Ir para o conteúdo

Studio implementation handoff

Where to implement drafts as overlays, saves without GitHub, immutable delivery and fast rollback in Studio, with contracts and acceptance scenarios.

Esta página ainda não foi traduzida para o português — o conteúdo abaixo está em inglês.

This is the engineering handoff for the hosted site editor, written so implementation does not depend on the original discussion. It extends Studio's existing Fast Preview rather than introducing a second editing backend. The contracts below are its implementation defaults.

Read Content protocol, Keeping drafts current and Production delivery and rollback for the shared semantics. This page maps those decisions onto Studio, supplies operation sequences, and names the checks that demonstrate completion.

Decisions to preserve

  • Business users work with drafts. A draft is the blocks an editor changed, kept in Deco's storage; there are no draft branches, and creating branches or rebasing is never an editor task.
  • Successful autosave means a durable draft write. A save writes the whole blocks the editor changed into the draft and never calls GitHub, so a GitHub outage can't fail a save, and cannot prevent serving an already prepared release.
  • The editor's forms show the production branch, read through the GitHub API when the editor opens and in its background check (never in a save), with the draft on top. The preview renders the same draft over the latest release. A draft never records a base of its own. At Publish, any block the draft changed wins in full; there is no property merge.
  • Each saved block carries a precondition checked against the draft alone: "not in the draft yet" for a block the draft doesn't hold, else the draft's version the form loaded (a deletion the draft holds has a version too). A mismatch writes nothing and opens the editor's existing reconcile view from the draft's copy the refusal carries: values only one side changed merge on their own, the rest are asked value by value (per whole block for A/B tests and campaigns), and a block one side deleted gets one plain question. Never a dead-end message. An editor never conflicts with their own saves: the version after each save comes from that save's answer.
  • Studio validates no content: not on save, not in the browser, not at Publish. The only content check is deco check in the site's CI.
  • Production and versioned preview delivery read only prepared object-store assets. Neither a cache miss nor recovery contacts GitHub, Studio's editing API or its database.
  • A draft asset is an immutable overlay of changed blocks and tombstones, with no base revision. Preview uses its server's existing production content, captured once per client; publish still builds a complete snapshot.
  • A release asset is immutable. A channel manifest selects the current release. Rollback increases the channel generation while selecting an older revision; it does not decrease the generation or require a build.
  • Editing, publication and preparation are TypeScript control-plane work. The data plane is object storage/CDN with a minimal authorization layer when needed, independently deployable from Studio.
  • The portable protocol has seven methods: since deco-content 1.1 (@decocms/blocks 8.2.0), changes.list, changes.get and changes.discard compare a source with its base, which for a draft is the production branch. Since 1.2 (@decocms/blocks 8.8.0) the hosted storage is an overlay: it implements writeSnapshot() (the draft's own blocks, no GitHub), so blocks.apply checks ifMatch against the draft alone, and changes.list is the draft's own blocks. Draft lifecycle, publication, rollback and preview grants are separate Studio routes.

Existing Studio integration points

These are relative paths in the public Studio repository, not paths to add to Blocks. Recheck their current interfaces before implementation; the responsibilities below are the stable part of the map.

Existing moduleReuseChange or extend
apps/api/src/api/routes/decofile.tsOrganization/project authorization and the /rpc routeFor a request that only holds blocks.apply, gate on the cached v8 marker and never read the production branch. Add the publish review route
apps/api/src/hosted/draft-content-storage.tsThe protocol storage for a hosted draft; the layered read (production branch from GitHub, draft on top) for blocks.list, schema.get and changes.*Add writeSnapshot(): the draft's own files, no GitHub. In commit(), no schema, no production-branch reads, no dropping blocks equal to production: a put sets the whole block, a delete records a tombstone. changes() lists the draft's own names. No readSecretsPublicKey
apps/api/src/hosted/draft-store.tsConditional (If-Match) draft writes and slugsUnchanged: re-read and re-apply on a failed condition, so saves of different blocks are both kept
apps/api/src/hosted/release-objects.tsRelease object reads and writesThe latest release's commit, for the publish review
apps/api/src/hosted/publish.tsCommitting the draft's whole blocks on the production branch's headWhen the branch moves meanwhile, rebuild on the new head (bounded) instead of failing. Report the blocks a developer also changed; never block on them
apps/web/src/components/sections-editor/form-conflict-dialog.tsxThe reconcile view: theirs and yours, per fieldOpen it for every conflict of a save, a delete or a move, A/B tests and campaigns included (whole-block choice there)
apps/api/src/api/routes/github-webhook.tsExisting signed GitHub event intakeDurably enqueue push processing, deduplicate deliveries, trigger release preparation
apps/web/src/components/sections-editor/content-sync.tsSave queueEnd "saving" when the hosted write is confirmed; update the list of changes from the save's answer and refresh the preview outside the queue

Mount organization routes through Studio's existing org-scoped middleware and emit updates through its existing SSE delivery. Reuse durable workflow infrastructure for jobs and database-backed coordination. An in-process mutex or workflow-local map is not cross-replica serialization; the draft's conditional write is what serializes saves. Keep GitHub rate-limit handling and bounded fetch utilities for publishing.

The protocol now lives under @decocms/blocks/protocol, with shared keys, server, filesystem storage and conformance subpaths. The hosted storage adapter belongs in Studio; the SDK must not import the editing protocol at runtime.

Persisted state

Store these records through Studio's existing storage adapters and migrations. IDs are opaque; repository, organization and app-root scope are checked on every access. A repository can host several sites.

RecordMinimum persisted fields
Draftid, organization/project/site IDs, app root, draft object key, lifecycle state, last editor activity, latest preview overlay version. No base commit: the editor lays it over the production branch, the preview over the latest release
Repository observationrepo/ref scope, latest reconciled head, observed time; webhook delivery IDs recorded separately for deduplication
Releasesite ID, source repo/app root/commit, content revision, format, asset key, byte size and integrity digest, preparation state and timestamps
Channelsite/environment, monotonic generation, revision, automatic or held mode, desired manifest, last confirmed manifest generation
Promotion operationrequest key and digest, expected generation, source intent, target revision, durable result and storage-write recovery state
Audit eventactor, operation, before/after identifiers, blocks kept over a developer's change, timestamp; no tokens

Draft lifecycle is open → published or open → discarded. Release preparation is queued → preparing → ready or failed. A channel promotes only ready assets.

Commit SHA, per-block content hash, draft etag, content revision and channel generation are different identifiers. Never use a commit SHA as publication order, or an asset revision as authorization.

Hosted operation contracts

These routes are the Studio surface under /api/:org/sites/:siteId. Keep project/root authorization explicit. Use the existing protocol errors for protocol calls; lifecycle routes return ordinary HTTP errors and typed bodies.

OperationRequestResult
POST /draftsrequest key, optional display nameStable draft ID; reuse the default open draft where appropriate
GET /drafts/:ideditor sessionLifecycle state, the latest release its preview is laid over, preview readiness
POST /drafts/:id/rpcThe seven-method JSON-RPC protocolEndpoint bound to the draft; describe reports overlay: true
GET /drafts/:id/publish/revieweditor sessionThe draft's blocks a developer also changed on the production branch since the latest release
POST /drafts/:id/publishrequest key, expected draft etag, expected channel generationDurable operation ID; states distinguish awaiting checks, Git committed, preparing and promoted; reports the blocks the draft kept over a developer's change
POST /drafts/:id/discardrequest key, expected draft etagTerminal draft state; coordinated with in-flight saves
POST /drafts/:id/previewexact saved draft etag or prepared overlay versionPreparing status, or signed pointer to the exact prepared overlay with expiry
POST /channels/:channel/rollbackrequest key, expected generation, retained target revision, reasonNew generation and held channel state; no GitHub work in this operation
POST /channels/:channel/resumerequest key, expected generationExplicitly resume automatic mode and reconcile latest desired production; never resume merely because an event arrived
GET /operations/:ideditor sessionDurable status/result or bounded error with retry timing

A stale expected draft or generation is a conflict, not a silent overwrite. The managed editor sends ifMatch on every save: null for a block the draft doesn't hold, else the draft's version from changes.list or from its own last save's answer. A block the draft deletes is held: changes.list lists it as a delete with the tombstone version ("tombstone", TOMBSTONE_VERSION), and restoring it sends that version. The draft records a tombstone for every name it deletes, even one main doesn't have, since the save never reads main; the protocol allows that (Overlays). Until Studio depends on a @decocms/blocks release that exports TOMBSTONE_VERSION, its write storage still guards the tombstone at "tombstone", but the delete's answer and changes.list report null for it, so the editor sends "tombstone" for a block it knows the draft deletes.

A block someone else saved meanwhile is a Conflict, and the editor opens the reconcile view with their version and the editor's own, keeping what the editor typed. A block one side deleted gets one question instead: on an edit, "Keep my version" (saved over the deletion with ifMatch: "tombstone") or "Leave it deleted"; on a delete, "Delete anyway" or "Keep their version". Choosing theirs writes nothing more and shows one toast, "Kept their version" or "Left it deleted", in place of the save's success toast.

Event notifications invalidate editor reads; they do not replace durable status or the portable polling fallback. Never log signed preview pointers. The lifecycle response and SSE event report summaries, not the entire content map.

Save sequence

A save reads and writes only the draft object in Deco's storage.

save(draft, params):
  authorize (the site's v8 marker is cached; no GitHub call)
  read the draft object and its etag
  version of a block = content hash of the draft's block; a block the draft deletes is "tombstone"; any other is null
  check every ifMatch against those versions; a mismatch is a Conflict
  normalize set/delete (set wins); enforce names, shapes and sizes
  put each set block in whole; record each delete as a tombstone
  write the draft with If-Match: <etag>
  on a failed condition: reread and recheck every guard, then reapply, with bounded retries
  return the new versions ("tombstone" for each delete, which the draft records whether or not main has the name); enqueue overlay materialization

The save never reads the production branch, the latest release, the schema or GitHub. Its revision combines the last production-branch commit the editor read and the draft's etag, so it moves when either moves. There is no per-draft base pointer, no private snapshot of unreleased commits and no background base move.

Batch/coalescer logic retains each caller's identity and guards. Coalescing cannot cause one failed apply to partially write, or report another caller's unrelated mutation as its own result.

Reads are where GitHub comes in, at open and in the background check only: blocks.list and schema.get read the production branch and lay the draft on top. changes.list is the draft's own blocks; changes.get reads their "before" from the production branch. After a save, the editor updates its list of changes from the save's answer, with the "before" it loaded, instead of reading again.

Publication and materialization sequence

Publication is the only operation that writes to GitHub. It freezes the draft the editor confirmed, reads the production branch's head, and commits the draft's whole blocks and deletions on top of it, content files only. A tombstone of a name main doesn't have changes nothing, and the default commit message names only the deletions main had. If the branch moves before the commit lands, it reads the new head and builds the commit again, a bounded number of times; it never fails because a developer pushed. If another editor saves meanwhile, that later work stays in the draft as unpublished; don't claim it was included in the confirmed publication. Follow branch protection and required checks, using a PR when needed.

Before the editor confirms, the review lists each draft block whose production-branch version differs from the latest release's, the blocks a developer also changed: "Your developer also changed Footer. Publishing keeps your version." It never blocks; the whole draft block wins (see Publish: the whole draft block wins).

Schema compatibility and route diagnostics belong in deco check in CI. Studio adds no content validation: not on save, not in the browser and not at publish. Input syntax, operation limits, authorization and snapshot integrity are still enforced. Successful preparation does not certify compatibility with every deployed build; code-first rollout and selecting a compatible rollback target remain operational requirements.

prepare(site, commit):
  pin commit; reuse cached Git trees/blobs where available
  stream normalized entries into a canonical snapshot with byte limits
  compute revision; upload immutable asset and verify integrity
  record ready release and enqueue promotion intent
  never update a channel from the ingestion worker itself

Webhook receipt acknowledges only after durable enqueue. Deduplicate by provider delivery ID, and deduplicate preparation by site/app root/commit/format. A slow reconciliation sweep finds missed commits. Use the latest reconciled production head, not webhook arrival order; when several commits arrive, preparing only the newest is acceptable. Studio-initiated commits can enqueue directly, with webhook deduplication handling the later duplicate.

Define canonical content hashing once in Blocks and import it in the CLI and materializer: recursively sorted object keys in JavaScript code-unit order, preserved array order, compact UTF-8 JSON with no trailing newline, and SHA-256 over the canonical blocks map. Emit keys in that order in the serializer rather than relying on object insertion order, particularly for numeric-looking keys; use JSON string escaping and number encoding, including the normalization of negative zero to zero. The format is versioned, and the snapshot envelope's revision is excluded from its own hash. Incremental materialization must produce the same bytes as the reference serializer; ship shared golden fixtures before allowing promotion. Reject values JSON cannot represent. Protocol request digests use a separate domain prefix and canonical request body.

Release preparation, channel operations and rollback run in an independently deployed release-control service with its own durable state and credentials. The logical API namespace above may be routed to several services; rollback must not depend on the editing API being available. The delivery gateway remains read-only.

Use configured R2 storage and CDN as the initial deployment target; keep the asset contract portable. The control plane writes assets. The delivery gateway has only read access and locally verifies scoped credentials using deployed verification keys. It does not query Studio's database per request. Token rotation/revocation must have a documented bounded propagation policy; if revocation state is consulted, serve that state from the isolated storage plane too. Private caching always happens behind authorization and is scoped to site and format/revision.

Draft overlay preparation

The draft object already is an overlay: whole replacement entries for the blocks the editor saved, and tombstones for deletions. It records no base of its own; nothing is sent as a baseRevision or imposed on the servers that render drafts, which lay it over the latest release. Normalize filename aliases using the shared key rule. A block saved back to its released content stays in the overlay: the draft is what the editor saved.

Use the write bodies from autosave and their content hashes to update the overlay. Never crawl repository contents or rebuild a whole draft decofile merely to serve preview.

Upload new changed-block assets first. Then upload the complete immutable overlay manifest, whose set references block hashes and whose delete enumerates cumulative deletions. Reuse unchanged blob assets across saves. The grant authorizes this manifest and its referenced blobs. Enforce ordinary persistence guards before asset creation. The schema and blocks.list editor contract still describe the effective editable content; the overlay is a delivery optimization, not a replacement for that protocol shape.

At request time, capture the server's existing normal production snapshot, then fetch the overlay and only missing changed blobs. Build a read-through immutable view for lookup and enumeration. No production revision is downloaded or refreshed just to satisfy a draft. Bound caches of blobs, overlays and composed views; composed-view keys include the local production revision and overlay version. References and deletion handling use that same view for every resolve in the client. For non-HTTP consumers the client lifetime has the same capture rule.

Keep publication separate: it commits the draft on top of repository production and prepares a full release. A preview is not a promise that its inherited blocks match the later publication, especially during rollback holds when delivered content differs from Git.

Promotion, rollback and recovery

Use a durable per-channel lane with expected generations and stored desired manifests. It owns the only credential allowed to write channel objects. Preparation workers cannot promote directly. Every deliberate publish/resume/rollback gets a new ordered intent; superseded preparation may finish and retain its asset but cannot promote.

For an immutable ready target, store the next generation and desired manifest durably, then write the channel object and confirm it. The data plane considers the object authoritative. A lost storage-write response is reconciled by rereading the stored manifest. A retry of the same operation returns the same generation, rather than allocating another.

Only one writer may perform channel writes at a time. A database lease alone cannot fence an expired worker's outstanding object-store upload. For the initial R2 deployment, use a small promotion Worker with the R2 binding: put with onlyIf: { etagMatches: observedEtag } fences updates against the stored manifest; a failed condition returns null. Bootstrap with a conditional create, not an unconditional upload. R2 conditional operations document these primitives. Test them against the live provider as well as local emulation. A different provider adapter must supply equivalent conditional writes; do not ship a check-then-unconditional-put sequence. Stop promotion on an unresolved write instead of allowing two writers to race.

Rollback uses this same lane with a retained ready target and sets mode to held. Recovery, webhook replay and periodic reconciliation must respect the hold. Explicit resume creates a new intent against the latest production observation. Record the delivery/Git mismatch and offer a separate Git revert; GitHub downtime does not block rollback.

The SDK retains the greatest observed channel generation, discards stale asynchronous fetch completions, and accepts an older revision selected by a newer generation. In-flight page clients keep their original snapshot. Emit the cache-invalidation callback on generation changes even when content hashes repeat. Never substitute newer draft changes for an immutable overlay version. Apply it to the production captured by this client, after the release check a draft read makes first (it waits for that check, so the base is the latest release); do not fetch or await a base matching the overlay.

Initial defaults

Keep these values in versioned configuration; the protocol's own limits are fixed by @decocms/blocks and not advertised. They are starting defaults for implementation and load testing, not a guarantee that raw JSON byte size equals heap usage. Changing a public limit requires updating this table and its acceptance tests.

SettingInitial default
Production branch readsAt editor open and in the background check only, never in a save; the listing is cached per head commit
Preparation worker memory / accumulated read budget512 MiB container; 32 MiB input bytes per attempt, then checkpoint and yield; monitor actual heap and RSS
Protocol writes500 names, 1 MiB per entry, 8 MiB per request, 10 calls per batch
Schema / block-list / aggregate batch response16 MiB / 16 MiB / 32 MiB uncompressed; error instead of truncation
Prepared production snapshot8 MiB canonical block-map bytes; oversized historical sites need an explicit profiled tier before onboarding
Publish head-race retries3 attempts, jittered backoff; rate-limit responses wait for provider retry timing
Draft conditional-write retries3 attempts, jittered backoff; then Unavailable with retry timing
Editor activity heartbeat / active window30 seconds / 2 minutes
Hosted editor conditional fallback poll30 seconds and on focus; local protocol remains 2 seconds
Repository reconciliationEvery 5 minutes for connected sites; bounded concurrency and provider-budget-aware backoff
Channel manifest cacheAt most 5 seconds; generation-based ETag, no negative caching
Immutable revision cache1 year with immutable keys; authorize private access before using shared byte caches
SDK release poll60 seconds by default (5 seconds minimum, set with interval) with up to 1 second jitter, subject to the existing idle/Worker scheduling
Rollback retention30 days minimum; always retain live channel targets and explicit pins
Draft overlays / changed-blob cache8 MiB cumulative changed-block bytes per overlay; bounded cache, at most 3 composed views per site by default; unchanged production objects shared
Preview grants / discarded-draft cleanup1 hour grants; assets retained beyond every unexpired grant before cleanup

Track readiness lag, promotion lag, conditional-write retries per save, whole-block draft-win counts at publish, job RSS, publish head retries and held channels. Test the 8 MiB runtime limit with fallback, old/new revisions and concurrent pinned readers on the target hosts before rollout. A parser or serializer can still have high allocation overhead below the byte limit; lower concurrency or limits based on measurements.

The active-server propagation target at these defaults is preparation time plus up to roughly 75 seconds for manifest caching and polling/jitter, followed by any HTML cache delay. Scheduling and outages can extend it. Idle Workers have no elapsed-time guarantee until a request schedules refresh; their first response can serve the bundled fallback. Rollback follows the same rule.

Acceptance scenarios

ScenarioRequired evidence
Editor opens a new project and savesNo branch is created; the save is one conditional write to the draft object, with zero GitHub calls and no schema read
One editor saves the same block many timesNever a conflict: each save's guard is the version the previous save answered with
A developer's push changes the footer while the draft changes the titleThe forms show both on the next background check, the preview once the push is released: the footer from production, the title from the draft
Both change the same block, including different properties or deletionThe draft's whole block wins at Publish; the publish review names the block, and nothing blocks
Production moves while Publish runsPublish rebuilds on the new head and lands; the review's list still names the blocks kept
Two editors save the same blockThe second save, guarded with the version its form loaded, is a Conflict; nothing is overwritten, and the reconcile view opens
Two editors save different blocks on different replicas at onceThe conditional write fails for one; it rereads the draft, rechecks its guards and reapplies, so both blocks are kept
An A/B test or a campaign changed meanwhileThe reconcile view opens with a whole-version choice
Save response lost, worker restartedThe client rereads changes.list: a save that landed shows its version; nothing is applied twice
Block saved back to its production contentIt stays in changes.list until it's published or discarded
A draft saved before this designOpens and saves as is; no migration
GitHub unavailableSaving and previews continue for an open editor; opening the editor and the background check wait for GitHub; publishing pauses; prepared production assets and rollback continue serving
Webhook duplicated, missed or delivered out of orderIdempotent preparation and reconciliation; older events cannot regress production
Asset upload fails or is incompletePrevious manifest stays live; missing reads never fetch GitHub
Old job completes after rollbackChannel remains at the rollback generation in held mode
Manifest write succeeds but response is lostRetry reconciles the same generation; an expired writer cannot overwrite a newer one
SDK revision B fetch finishes after rollback to AThe higher-generation A remains selected; in-flight pages may finish on their pinned B
Old preview link used after another saveExact old overlay or draft error, never newer draft changes; inherited content follows local production
Local release changes while a draft rendersIn-flight client keeps its pair; next client uses the new local release without downloading another full draft
Draft deletes a block that exists in productionTombstone hides it from lookup and listing; absent override without a tombstone inherits production
Draft deletes a name main doesn't haveThe save records a tombstone without reading main; Publish commits nothing for it and its default message doesn't name it
An editor edits a block someone else deleted meanwhileOne question: "Keep my version" saves over the deletion with its tombstone version; "Leave it deleted" writes nothing
An editor creates a block under a name the draft deletesCreated over the deletion with its tombstone version; nothing is asked (the create edited nothing that was deleted)
An editor moves or deletes a block someone else changed meanwhileOne question: "Delete anyway" writes the whole move or delete over their version; "Keep their version" cancels all of it, so a move never lands as a copy
Two servers have different local release revisionsSame overlay intentionally produces different inherited content; composed caches cannot cross those base identities
Repeated saves change one previously edited blockFetch the small manifest and only changed-blob hashes missing from cache, not the full production or draft map
Private asset requested without a valid grantNo shared-cache bypass; tenant scope checked before bytes are served
Publish confirmed, then another save arrivesConfirmed content publishes; later save remains unpublished
GC runs during rollback or preview useChannel targets, pins, referenced uploads and unexpired grants survive
Max-sized snapshot and simultaneous readersMeasured peak memory stays within the runtime budget; preparation cannot OOM the API

Run portable protocol conformance against the filesystem and GitHub adapters. Add focused integration tests for provider head races, durable recovery and object-store fencing, and E2E tests extending Fast Preview's existing Git-sync and decofile suites. Include SDK generation/cache tests; a happy-path editor demo alone does not establish these guarantees.

Rollout order

  1. Ship the shared protocol subpaths and golden hashing fixtures.
  2. Make the hosted draft storage an overlay (writeSnapshot()): saves write whole blocks into the draft with conditional writes only, guarded against the draft, and stop calling GitHub. Version every block by its content hash. The forms keep reading the production branch at open and in the background check. Existing drafts keep working with no migration.
  3. Show "Saved" when the write is confirmed, update the list of changes from the save's answer, refresh the preview in the background, and route every save conflict to the reconcile view.
  4. Add the publish review (the blocks a developer also changed) and commit the whole draft blocks on top of the production branch's head, rebuilding when the head moves.
  5. Add complete production snapshot and draft-overlay materialization and a shadow delivery channel. Compare outputs with current control-plane reads without changing production traffic.
  6. Enable the isolated data plane for selected sites after cold-read, outage and memory tests. Keep the bundled last-good fallback; no data-plane GitHub fallback is allowed during rollout.
  7. Enable channel promotion, rollback/hold/resume and retention after race/recovery tests pass. Make save, preview-ready, Git-committed and promoted status visible in the editor.

Track these phases in the Studio and Deco API roadmap. Implementation is complete when the acceptance scenarios pass, a save makes no GitHub call, the deployed data plane cannot access GitHub, and operators can restore a retained release while GitHub and Studio's editing API are unavailable.