@substrat-run/control-plane-api 0.155.0 → 0.158.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/api.js CHANGED
@@ -9,7 +9,8 @@ import { auditedChange, withAuditedOutcomes } from './audited-change.js';
9
9
  import { BIND_EXPORT_BREAK_REFUSAL, CARRIED_AWAY_KEY, bindExportBreakRefusal, carriedAwayDump, dumpMetaValue, metaValueIn, crossVerticalHealth, exportBreakRefusal, isBindExportBreakRefusal, isExportBreakRefusal, isPrimaryScope, promoteReviewDigest, rebindReviewDigest, assertRebindReviewCurrent, migrationProgress, ulid, auditWarningOf, } from '@substrat-run/kernel';
10
10
  import { TENANT_HEADER, confinedTenant } from './auth.js';
11
11
  import { mintTenantToken } from './tenant-token.js';
12
- import { connectionGrantsForScope, transferScope } from './vertical-client.js';
12
+ import { beginTransfer, connectionGrantsForScope, transferScope } from './vertical-client.js';
13
+ import { COPY_JOB_MAX_MS, copyJobAt, copyJobHeld, copyJobId, copyJobLive, copyTagId, versionIdOfOrder, versionOrderOf, } from './copy-job.js';
13
14
  import { runningVersionOf, runningVersionStoresOf, scopeStoreReachOf, scopeStoresOf, unrouteScope } from './platform-scope-stores.js';
14
15
  import { STORE_REBUILD_REQUEST_SUBREQUESTS, runStoreFleetRebuild, storeRebuildBudget, storeRebuildStatus } from './store-rebuild.js';
15
16
  import { PUSH_HOLD_TTL_MS, runStoreDriverRollout, storeDriverRelease, storedReleaseLoader } from './store-releases.js';
@@ -26,7 +27,7 @@ import { NON_PROBLEM_REFUSAL, coded, mapError, relayed } from './errors.js';
26
27
  import { maskDump, maskRecords } from './mask.js';
27
28
  import { createPseudonymizer } from './pseudonymize.js';
28
29
  import { openDump, sealDump } from './seal.js';
29
- import { assertSandboxContract, verticalUploadBindings, migrationsDigestBindings, deployManifest, storedDeployManifest, pushedOwnerGrantProblems, pushedPermissionRegistry, deploymentRefFor, stableDeploymentRefFor, nextMigrationTag, upstreamStatusOf, } from './deploy.js';
30
+ import { assertSandboxContract, verticalUploadBindings, migrationsDigestBindings, deployManifest, storedDeployManifest, pushedOwnerGrantProblems, pushedModuleRegistryProblems, pushedPermissionRegistry, deploymentRefFor, stableDeploymentRefFor, nextMigrationTag, upstreamStatusOf, } from './deploy.js';
30
31
  /**
31
32
  * Answer with a problem document (#113 phase 4).
32
33
  *
@@ -408,6 +409,14 @@ const createPreviewBody = z.object({
408
409
  ttlHours: z.number().int().positive().max(720).nullable().optional(),
409
410
  surface: surfaceName.optional(),
410
411
  refresh: z.boolean().optional(),
412
+ // #2450 step 2: the caller can take a 202 and call again. A copy too large to finish in this
413
+ // request then moves in the background, and the 202 says how far it got; the same call, repeated,
414
+ // finishes the preview once it is done. A caller that does not say so is answered as before.
415
+ async: z.boolean().optional(),
416
+ // #2450: this call follows a 202 that named this call's own version, so it continues that copy and
417
+ // never starts one: it answers the copy's progress, finishes it once it is done, or says it is gone.
418
+ // A call after a 202 naming another push's copy (one being finished) is not a poll: it may start its own.
419
+ poll: z.boolean().optional(),
411
420
  });
412
421
  const listRolesQuery = z.object({
413
422
  tenantId: tenantIdSchema.optional(),
@@ -609,6 +618,8 @@ export const DEFAULT_MODEL_MARGIN_PERCENT = 20;
609
618
  * Cloudflare's `internal error; reference = <id>` shape (#559). */
610
619
  const UPSTREAM_REFERENCE = /\breference\s*=\s*([a-z0-9]+)/i;
611
620
  const TENANT_ROUTES = [
621
+ { method: 'GET', re: /\/verticals\/[^/]+\/email-sender$/, pin: 'owner' },
622
+ { method: 'POST', re: /\/verticals\/[^/]+\/email-sender$/, pin: 'owner' },
612
623
  // One tenant's own path, route by route (#977). It used to be ONE catch-all entry per
613
624
  // method — `/tenants/<pin>/…` cannot address another tenant's row, so it looked safe —
614
625
  // but a path that is confined is not a route that is harmless: it reached entitlement
@@ -2734,6 +2745,209 @@ export function createControlPlaneApi(options) {
2734
2745
  };
2735
2746
  /** How many exports a carry tries before its source holds still long enough to bind (#1722 r12). */
2736
2747
  const CARRY_EXPORT_ATTEMPTS = 3;
2748
+ const COPY_POLL_SECONDS = 5;
2749
+ const copyingAnswer = (job) => ({
2750
+ copying: true,
2751
+ scopeId: job.spec.scopeId,
2752
+ versionId: job.spec.versionId,
2753
+ progress: { pages: job.pages, rows: job.rows, attempt: job.attempt },
2754
+ retryAfter: COPY_POLL_SECONDS,
2755
+ });
2756
+ /**
2757
+ * #2450: a push older than the one a preview's job is copying for is refused, never allowed to
2758
+ * replace it. Otherwise two CI runs for one preview would cancel each other's copy at every poll.
2759
+ * Older by `versionOrderOf`: when the registry recorded each version, whatever its id. Only a job
2760
+ * that can still land its push's data holds an older one off (`copyJobLive`): one that failed, was
2761
+ * cancelled or was left unfinished past its lease is replaced like any other.
2762
+ */
2763
+ const supersededRefusal = (job, mine, tag) => mine.order < job.spec.versionOrder && copyJobLive(job, Date.now())
2764
+ ? new ControlPlaneError(409, `a newer push (version ${job.spec.versionId}) to preview '${tag}' ` +
2765
+ `${job.status === 'copying' ? 'is copying its data' : 'is finishing its copy'}, so this push ` +
2766
+ `(version ${mine.versionId}) was superseded and did nothing`)
2767
+ : null;
2768
+ /**
2769
+ * #2450: a create for an older version than one another call (a poll included) to the same preview
2770
+ * marked within `PREVIEW_CREATE_BOUND_MS` (`CopyJobs.markNewest`). It covers the moments no job
2771
+ * record names the newer push: a newer push forgets the fork job it replaces, then reaps that row
2772
+ * and provisions its own; and the time after its copy has landed and its job is forgotten. Once the
2773
+ * mark's hold has run out, and no newer push's job is copying, an older version (a deliberate
2774
+ * re-preview) is taken like any other create.
2775
+ */
2776
+ const supersededByMark = (newest, mine, tag) => {
2777
+ const minutes = PREVIEW_CREATE_BOUND_MS / 60_000;
2778
+ return new ControlPlaneError(409, `a newer push (version ${versionIdOfOrder(newest)}) to preview '${tag}' called within the last ${minutes} min, ` +
2779
+ `so this push (version ${mine.versionId}) was superseded and did nothing. An older version is taken again ` +
2780
+ `${minutes} min after a newer push's last call, once no newer push's copy is running`);
2781
+ };
2782
+ /**
2783
+ * How long a call that claimed a done job holds it to finish it (#2450): twice the copy lease. The
2784
+ * holder renews the lease straight after claiming and can confirm the move only inside that lease,
2785
+ * so by the time its claim runs out it can no longer finish. One that died leaves the claim to run
2786
+ * out, and the next call then finds the lease gone, settles the move and frees the tag.
2787
+ */
2788
+ const copyClaimMs = 2 * copyLeaseMs;
2789
+ /**
2790
+ * Stop a preview's copy job and settle its move (#2450): a refresh, a delete, a newer push that
2791
+ * replaces it, or the job's own failure. The move's entries settle `retained`, so reap and erasure
2792
+ * reach both scripts; the stage it left is discarded best-effort, and goes with any later wipe.
2793
+ * `unlessFinishing` (a newer push): a done job another call has claimed is that call's to finish or
2794
+ * give up, so it is left alone, and the answer is false.
2795
+ */
2796
+ const settleJobMove = async (c, job, opts = {}) => {
2797
+ const jobs = options.copyJobs;
2798
+ if (!jobs)
2799
+ return true;
2800
+ // A step running right now writes nothing after this, and no call can claim the job after it:
2801
+ // its host keeps a cancel over a step's answer, and a claim takes only a done job.
2802
+ const latest = (await jobs.cancel(job.spec.id)) ?? job;
2803
+ if (opts.unlessFinishing && copyJobHeld(latest, Date.now()))
2804
+ return false;
2805
+ await settleJobEntries(c, job);
2806
+ await discardJobStages(job, latest);
2807
+ await jobs.forget(job.spec.id);
2808
+ return true;
2809
+ };
2810
+ /** A job's move, every entry settled `retained` (#2450), best-effort: a sweep settles what this misses. */
2811
+ const settleJobEntries = async (c, job) => {
2812
+ const { spec } = job;
2813
+ const actor = c.get('actor');
2814
+ const refs = spec.kind === 'carry' ? [spec.sourceRef, spec.destRef] : [spec.destRef];
2815
+ await Promise.allSettled(refs.map((ref) => c.var.admin.settleScopeScriptCopy(actor, spec.tenantId, spec.scopeId, ref, spec.moveId, 'retained')));
2816
+ };
2817
+ /**
2818
+ * Drop every stage these records of one job name at its destination (#2450), best-effort: once the
2819
+ * job is forgotten nothing else names them, and they would wait for a wipe of the scope there. A
2820
+ * stage that was loaded is gone already, and its discard changes nothing.
2821
+ */
2822
+ const discardJobStages = async (...records) => {
2823
+ const { spec } = records[0];
2824
+ const staged = records.flatMap((r) => [r.state?.stageId, r.done && !Array.isArray(r.done.dump) ? r.done.dump.stageId : undefined]);
2825
+ const dest = await options.resolveVerticalRef?.(spec.destRef).catch(() => undefined);
2826
+ for (const stageId of new Set(staged.filter((id) => id !== undefined))) {
2827
+ await dest?.discardStagedScope(spec.scopeId, stageId).catch(() => undefined);
2828
+ }
2829
+ };
2830
+ /**
2831
+ * Run the whole finish of a job this call claimed (#2450), from the lease's renewal on. However it
2832
+ * fails (a refusal, a fence that lapsed, a renewal or a resolve that threw outright), the job's move
2833
+ * settles `retained` and the stage it was to load is discarded: its caller forgets the job next,
2834
+ * after which nothing would, and a refused load keeps its stage.
2835
+ */
2836
+ const finishingJob = async (c, job, finish) => {
2837
+ try {
2838
+ return await finish();
2839
+ }
2840
+ catch (e) {
2841
+ await settleJobEntries(c, job);
2842
+ await discardJobStages(job);
2843
+ throw finishRefusal(c, job, e);
2844
+ }
2845
+ };
2846
+ /**
2847
+ * A finish of a claimed job that failed, as the route answers it (#2450). A refusal is answered as
2848
+ * itself. A fault (a 5xx: a load or a bind that failed past its own retries) is answered 409 naming
2849
+ * its status, as a job's own failure is (`refuseFailedJob`): the copy it finished is settled, and
2850
+ * only a new create starts it over, so it is no status to retry. The fault lands its ops-failure
2851
+ * row here, unless the step that met it recorded it.
2852
+ */
2853
+ const finishRefusal = (c, job, e) => {
2854
+ const { status, body } = mapError(e);
2855
+ if (status < 500)
2856
+ return e;
2857
+ if (!(typeof e === 'object' && e !== null && recordedCauses.has(e))) {
2858
+ recordCopyFault(c, job, 'finish', status, messageOfThrow(e), { cause: e });
2859
+ }
2860
+ return new ControlPlaneError(409, `the background copy failed with ${status} while it was finished: ${body.detail ?? 'internal error'}`);
2861
+ };
2862
+ /**
2863
+ * The ops-failure row of a fault a copy met (#2450), which the route answers 409 rather than as a
2864
+ * 5xx the backstop would record (#559). A 501 is a capability statement, not a fault, and none.
2865
+ */
2866
+ const recordCopyFault = (c, job, stage, status, message, opts = {}) => {
2867
+ if (status === 501)
2868
+ return;
2869
+ const entry = {
2870
+ actor: c.get('actor'),
2871
+ operation: 'preview.create',
2872
+ stage,
2873
+ tenantId: job.spec.tenantId,
2874
+ scopeId: job.spec.scopeId,
2875
+ vertical: job.spec.vertical,
2876
+ version: job.spec.versionId,
2877
+ status,
2878
+ message,
2879
+ };
2880
+ // A job's own record carries no throw: no cause, rather than an `undefined` one (`recordFailure`).
2881
+ if ('cause' in opts)
2882
+ recordFailure(entry, opts.cause);
2883
+ else
2884
+ recordFailure(entry);
2885
+ };
2886
+ /**
2887
+ * A preview's copy job (#2450), as of now (`copyJobAt`): one whose steps were lost past its
2888
+ * deadline reads as failed by it, so the route settles and answers it instead of waiting forever.
2889
+ */
2890
+ const readCopyJob = async (id) => {
2891
+ const job = await options.copyJobs?.get(id);
2892
+ return job ? copyJobAt(job, Date.now()) : null;
2893
+ };
2894
+ /**
2895
+ * Every copy job a preview has (#2450), settled: before it is reaped or replaced. `by` is a create
2896
+ * replacing it, which a newer push's live copy refuses (`supersededRefusal`) before anything is
2897
+ * settled; a delete passes none, and removes whatever is there.
2898
+ */
2899
+ const cancelPreviewJobs = async (c, preview, by) => {
2900
+ if (!options.copyJobs)
2901
+ return;
2902
+ const held = [];
2903
+ for (const kind of ['fork', 'carry']) {
2904
+ const job = await readCopyJob(copyJobId(kind, preview.id));
2905
+ if (job)
2906
+ held.push(job);
2907
+ }
2908
+ if (by) {
2909
+ for (const job of held) {
2910
+ const superseded = supersededRefusal(job, by.mine, by.tag);
2911
+ if (superseded)
2912
+ throw superseded;
2913
+ }
2914
+ }
2915
+ for (const job of held)
2916
+ await settleJobMove(c, job);
2917
+ };
2918
+ /**
2919
+ * Finish a carry a job copied (#2450): renew the move's lease, which the restore's fence then
2920
+ * counts from, and run the same `carryFinish` an in-request carry runs. A move the job can no
2921
+ * longer finish is refused. A finish that fails is settled (`finishingJob`) and forgets the job;
2922
+ * one that lands leaves it claimed, for the caller to forget once its bind has landed or failed:
2923
+ * until then the preview is still bound to the version this carry replaces, and a newer push that
2924
+ * found no job would carry from there.
2925
+ */
2926
+ const finishCarryJob = async (c, scope, versionId, job) => {
2927
+ const { spec } = job;
2928
+ const done = job.done;
2929
+ const actor = c.get('actor');
2930
+ try {
2931
+ return await finishingJob(c, job, async () => {
2932
+ const lease = await c.var.admin.renewScopeScriptCopy(actor, spec.tenantId, spec.scopeId, spec.moveId, { leaseMs: copyLeaseMs });
2933
+ const [source, dest] = await Promise.all([options.resolveVerticalRef?.(spec.sourceRef), options.resolveVerticalRef?.(spec.destRef)]);
2934
+ if (!lease || !source || !dest || !done || !spec.expected) {
2935
+ throw !lease
2936
+ ? new ControlPlaneError(409, `the copy of scope ${spec.scopeId} was settled before it could be loaded; nothing was moved`)
2937
+ : new ControlPlaneError(502, `the copy of scope ${spec.scopeId} could not reach both of its scripts to finish`);
2938
+ }
2939
+ const expected = spec.expected;
2940
+ return carryWith(c, scope, versionId, {
2941
+ moveId: spec.moveId, erasureEpoch: spec.erasureEpoch, from: spec.sourceRef, to: spec.destRef,
2942
+ source, dest, restoredStamp: spec.restoredStamp, leasedAt: lease.renewedAt, expected,
2943
+ }, async () => done);
2944
+ });
2945
+ }
2946
+ catch (e) {
2947
+ await options.copyJobs?.forget(spec.id).catch(() => undefined);
2948
+ throw e;
2949
+ }
2950
+ };
2737
2951
  /**
2738
2952
  * Carry a scope's data onto the script a version bind is about to route it to (#1710).
2739
2953
  * The caller binds only after this returns.
@@ -2782,6 +2996,16 @@ export function createControlPlaneApi(options) {
2782
2996
  * between lineages is `rebindScopeOntoVertical`'s job, behind its migration gate.
2783
2997
  */
2784
2998
  const carryOntoVersion = async (c, scope, versionId, opts = {}) => {
2999
+ const move = await carryBegin(c, scope, versionId, opts);
3000
+ if (!move)
3001
+ return null;
3002
+ // #2450: a page at a time into the destination's stage, so a scope of any size moves. The
3003
+ // stage moves neither the destination's load stamp nor its write revision, so the marker
3004
+ // `carryFinish` reads next still describes the store the restore commits into.
3005
+ return carryWith(c, scope, versionId, move, () => transferScope(move.source, move.dest, { from: scope.id }, { retry: retryTransient }));
3006
+ };
3007
+ /** The two ends a carry moves between, resolved and checked (`carryOntoVersion`), or null when nothing moves. */
3008
+ const carryEnds = async (c, scope, versionId, opts = {}) => {
2785
3009
  const resolveVersion = options.resolveVerticalVersion;
2786
3010
  if (!scope.vertical)
2787
3011
  return null;
@@ -2817,6 +3041,15 @@ export function createControlPlaneApi(options) {
2817
3041
  throw new ControlPlaneError(502, `cannot move scope ${scope.id} from '${from}' to '${to}': ${missing} could not be reached, ` +
2818
3042
  `so the version was not bound (#1710)`);
2819
3043
  }
3044
+ return { source, dest, from, to };
3045
+ };
3046
+ /** `carryOntoVersion`'s checks and its ledger entries, up to the copy (#2450): null when nothing moves. */
3047
+ const carryBegin = async (c, scope, versionId, opts = {}) => {
3048
+ const ends = await carryEnds(c, scope, versionId, opts);
3049
+ if (!ends)
3050
+ return null;
3051
+ const { source, dest, from, to } = ends;
3052
+ const actor = c.get('actor');
2820
3053
  // Before exporting or restoring anything, retain the script identity in the directory, so a
2821
3054
  // failed carry stays named for reap and erasure. Both entries are leased to this move: if this
2822
3055
  // request dies, a sweep settles them once the lease runs out, and the move can then no longer
@@ -2833,10 +3066,47 @@ export function createControlPlaneApi(options) {
2833
3066
  // cleanup. Name it before any bytes are restored so reap and erasure can find it.
2834
3067
  await c.var.admin.recordScopeScriptCopy(actor, scope.tenantId, scope.id, to, moveId, { role: 'destination', loadStamp: restoredStamp, leaseMs: copyLeaseMs });
2835
3068
  const erasureEpoch = await c.var.admin.scopeErasureEpoch(actor, scope.tenantId, scope.id);
2836
- // #2450: a page at a time into the destination's stage, so a scope of any size moves. The
2837
- // stage moves neither the destination's load stamp nor its write revision, so the marker read
2838
- // next still describes the store the restore below commits into.
2839
- const { dump, loadStamp: sourceStamp, revision: sourceRevision, meta } = await transferScope(source, dest, { from: scope.id }, { retry: retryTransient });
3069
+ return {
3070
+ moveId, erasureEpoch, from, to, source, dest, restoredStamp, leasedAt: recordedAt,
3071
+ expected: { versionId: scope.verticalVersionId ?? null, servingRef: scope.servingRef ?? null },
3072
+ };
3073
+ }
3074
+ catch (error) {
3075
+ await settleCarryRetained(c, scope, versionId, { moveId, from, to });
3076
+ throw error;
3077
+ }
3078
+ };
3079
+ /** Neither script of an unconfirmed move can be discarded: a retry or reap can still reach both. */
3080
+ const settleCarryRetained = async (c, scope, versionId, move) => {
3081
+ const actor = c.get('actor');
3082
+ // A crash leaves them pending and blocks key finalization.
3083
+ const settled = await Promise.allSettled([
3084
+ c.var.admin.settleScopeScriptCopy(actor, scope.tenantId, scope.id, move.from, move.moveId, 'retained'),
3085
+ c.var.admin.settleScopeScriptCopy(actor, scope.tenantId, scope.id, move.to, move.moveId, 'retained'),
3086
+ ]);
3087
+ for (const result of settled) {
3088
+ if (result.status === 'rejected')
3089
+ recordCarryCleanup(c, scope, versionId, 'copy-ledger', result.reason);
3090
+ }
3091
+ };
3092
+ /**
3093
+ * Finish a carry whose data `transfer` moves (#2450): the copy, then the #1722 checks and the
3094
+ * restore. Any failure settles both ends retained.
3095
+ */
3096
+ const carryWith = async (c, scope, versionId, move, transfer) => {
3097
+ try {
3098
+ return await carryFinish(c, scope, move, await transfer());
3099
+ }
3100
+ catch (error) {
3101
+ await settleCarryRetained(c, scope, versionId, move);
3102
+ throw error;
3103
+ }
3104
+ };
3105
+ const carryFinish = async (c, scope, move, transferred) => {
3106
+ const actor = c.get('actor');
3107
+ const { moveId, erasureEpoch, from, to, source, dest, restoredStamp } = move;
3108
+ const { dump, loadStamp: sourceStamp, revision: sourceRevision, meta } = transferred;
3109
+ {
2840
3110
  // What the destination holds now, read before the binding is checked again. The restore
2841
3111
  // sends it back and is refused if the store moved since: another carry into the same script
2842
3112
  // loaded it, or it went live under another carry's bind and took a write. That is a CI retry
@@ -2844,8 +3114,8 @@ export function createControlPlaneApi(options) {
2844
3114
  const destMarker = await retryTransient(() => dest.loadMarker(scope.id));
2845
3115
  const now = await c.var.admin.getScopeRecord(actor, scope.tenantId, scope.id);
2846
3116
  if (!now ||
2847
- (now.verticalVersionId ?? null) !== (scope.verticalVersionId ?? null) ||
2848
- (now.servingRef ?? null) !== (scope.servingRef ?? null)) {
3117
+ (now.verticalVersionId ?? null) !== move.expected.versionId ||
3118
+ (now.servingRef ?? null) !== move.expected.servingRef) {
2849
3119
  throw new ControlPlaneError(412, `scope ${scope.id} was re-pointed while its data was being copied out of '${from}', so nothing was ` +
2850
3120
  `moved or bound (#1722). Reload the scope and retry.`);
2851
3121
  }
@@ -2859,7 +3129,7 @@ export function createControlPlaneApi(options) {
2859
3129
  loadStamp: restoredStamp,
2860
3130
  ...(destMarker === 'unfenced' ? {} : { expect: destMarker }),
2861
3131
  // The store refuses this load once the move's lease can have run out (#1722).
2862
- fence: copyRestoreFence(moveId, recordedAt, copyLeaseMs, erasureEpoch),
3132
+ fence: copyRestoreFence(moveId, move.leasedAt, copyLeaseMs, erasureEpoch),
2863
3133
  });
2864
3134
  return {
2865
3135
  moveId,
@@ -2875,19 +3145,6 @@ export function createControlPlaneApi(options) {
2875
3145
  restoredStamp,
2876
3146
  };
2877
3147
  }
2878
- catch (error) {
2879
- // Neither script can be discarded based on this unconfirmed move. A retry or reap
2880
- // can still reach both. A crash leaves them pending and blocks key finalization.
2881
- const settled = await Promise.allSettled([
2882
- c.var.admin.settleScopeScriptCopy(actor, scope.tenantId, scope.id, from, moveId, 'retained'),
2883
- c.var.admin.settleScopeScriptCopy(actor, scope.tenantId, scope.id, to, moveId, 'retained'),
2884
- ]);
2885
- for (const result of settled) {
2886
- if (result.status === 'rejected')
2887
- recordCarryCleanup(c, scope, versionId, 'copy-ledger', result.reason);
2888
- }
2889
- throw error;
2890
- }
2891
3148
  };
2892
3149
  /**
2893
3150
  * Wipe one copy of a scope that no route reaches (#1722), without reaping it. Fenced where the
@@ -6391,13 +6648,19 @@ export function createControlPlaneApi(options) {
6391
6648
  const checked = storedDeployManifest.safeParse(raw);
6392
6649
  if (!checked.success)
6393
6650
  return refuseManifest(checked.error.issues[0]);
6651
+ if (checked.data.modules !== undefined && !checked.data.registry) {
6652
+ return refuseManifest({ path: ['registry'], message: 'required when modules are present' });
6653
+ }
6394
6654
  // #1869: a registry handed to this route now is NEW, so it answers to the push-time rule on
6395
6655
  // entity-grant shapes (no kernel namespace as an entity type), as `deployManifest` does.
6396
- // An absent registry stays accepted, as above.
6656
+ // A legacy manifest with neither modules nor registry stays accepted, as above.
6397
6657
  if (checked.data.registry) {
6398
6658
  const registry = pushedPermissionRegistry.safeParse(checked.data.registry);
6399
6659
  if (!registry.success)
6400
6660
  return refuseManifest(registry.error.issues[0], ['registry']);
6661
+ const moduleProblems = pushedModuleRegistryProblems(checked.data.modules, registry.data);
6662
+ if (moduleProblems.length > 0)
6663
+ return refuseManifest({ path: ['registry', 'permissions'], message: moduleProblems.join('; ') });
6401
6664
  }
6402
6665
  // #2430: an owner grant is a person's, so it holds no key the registry reserves.
6403
6666
  const ownerGrants = pushedOwnerGrantProblems(checked.data);
@@ -6602,12 +6865,21 @@ export function createControlPlaneApi(options) {
6602
6865
  await c.var.admin.setVerticalTenantProvisioner(c.get('actor'), slug, granted);
6603
6866
  return c.json({ slug, tenantProvisioner: granted });
6604
6867
  });
6605
- // Grant/revoke the EMAIL-SENDER capability (#303) — whether this vertical's scopes may POST to
6606
- // the /internal/email/send relay and have transactional mail sent for them. Staff-only (not in
6607
- // BUILDER_ROUTES): outbound authority is a platform decision, not the owner's. The relay handler
6608
- // reads the flag on every send.
6868
+ // Email sending is owner-managed from the dashboard; the registry grant applies to
6869
+ // every installation of this vertical. Tenant credentials must own the vertical.
6870
+ app.get('/verticals/:slug/email-sender', async (c) => {
6871
+ const slug = c.req.param('slug');
6872
+ if (await notOwned(c.get('principal'), slug))
6873
+ return refuse(c, 'forbidden', 'forbidden');
6874
+ const vertical = await verticalOf(c.get('actor'), slug);
6875
+ if (!vertical)
6876
+ return refuse(c, 'not_found', 'vertical not found');
6877
+ return c.json({ slug, emailSender: !!vertical.emailSender });
6878
+ });
6609
6879
  app.post('/verticals/:slug/email-sender', async (c) => {
6610
6880
  const slug = c.req.param('slug');
6881
+ if (await notOwned(c.get('principal'), slug))
6882
+ return refuse(c, 'forbidden', 'forbidden');
6611
6883
  const { granted } = z.object({ granted: z.boolean() }).parse(await c.req.json());
6612
6884
  await c.var.admin.setVerticalEmailSender(c.get('actor'), slug, granted);
6613
6885
  return c.json({ slug, emailSender: granted });
@@ -7104,7 +7376,14 @@ export function createControlPlaneApi(options) {
7104
7376
  const raw = form.get('manifest');
7105
7377
  if (typeof raw !== 'string')
7106
7378
  return refuse(c, 'validation_failed', 'missing manifest part');
7107
- const manifest = deployManifest.parse(JSON.parse(raw));
7379
+ const parsed = JSON.parse(raw);
7380
+ if (parsed !== null && typeof parsed === 'object' && 'modules' in parsed && !('registry' in parsed)) {
7381
+ return refuse(c, 'validation_failed', 'manifest registry: required when modules are present');
7382
+ }
7383
+ const manifest = deployManifest.parse(parsed);
7384
+ const moduleProblems = pushedModuleRegistryProblems(manifest.modules, manifest.registry);
7385
+ if (moduleProblems.length > 0)
7386
+ return refuse(c, 'validation_failed', `manifest registry.permissions: ${moduleProblems.join('; ')}`);
7108
7387
  // #2430: an owner grant is a person's, so it holds no key the registry reserves.
7109
7388
  const ownerGrants = pushedOwnerGrantProblems(manifest);
7110
7389
  if (ownerGrants.length > 0)
@@ -8319,6 +8598,31 @@ export function createControlPlaneApi(options) {
8319
8598
  source, opts) => {
8320
8599
  const actor = c.get('actor');
8321
8600
  const surface = opts.surface ?? 'app';
8601
+ // #2450 step 2: where a copy that outlasts this request may run — only for a caller that takes a
8602
+ // 202 and calls again, and on a host whose jobs can reach each end by its script.
8603
+ const jobs = opts.async && options.resolveVerticalRef ? options.copyJobs : undefined;
8604
+ // #2450: a call that continues the copy an earlier call of this push started. It never starts a
8605
+ // copy, reaps a row or forks one, so no answer lost or misread on the way back can turn into a
8606
+ // copy started over: only a new create (a new push) does that.
8607
+ const poll = jobs !== undefined && opts.poll === true;
8608
+ /** What a poll is answered when the copy it was waiting on is no longer there. */
8609
+ const copyGone = () => new ControlPlaneError(409, `the copy for preview '${opts.tag}' (version ${opts.versionId}) is no longer running: it failed, a newer push ` +
8610
+ `or a refresh replaced it, or the preview was deleted. Nothing was moved; a new create starts the copy over`);
8611
+ /**
8612
+ * A job's failure, as the route answers it. A refusal keeps the status and sentence the
8613
+ * synchronous copy would have answered. A fault the copy met (a 5xx: its deadline, an end it
8614
+ * could not reach, a stage it could not keep) is answered 409, naming that status: the call
8615
+ * reporting it did not fail, the copy did, earlier. A 502–504 reads to every client as a
8616
+ * gateway's, which it retries, though nothing about the copy will change. The fault is recorded
8617
+ * here, since its answer is no 5xx for the backstop to see (#559).
8618
+ */
8619
+ const refuseFailedJob = (job) => {
8620
+ const error = job.error ?? { status: 409, message: `the copy of scope ${job.spec.scopeId} was cancelled before it finished; nothing was moved` };
8621
+ if (error.status < 500)
8622
+ return new ControlPlaneError(error.status, error.message);
8623
+ recordCopyFault(c, job, 'copy', error.status, error.message);
8624
+ return new ControlPlaneError(409, `the background copy failed with ${error.status}: ${error.message}`);
8625
+ };
8322
8626
  // #527 guard: a preview MUST serve the version it just bound. Routing resolves
8323
8627
  // `COALESCE(scope.servingRef, version.deploymentRef)` (control-plane-do `readRoute`),
8324
8628
  // so a preview that still carries an inherited `serving_ref` — or otherwise resolves away
@@ -8344,6 +8648,19 @@ export function createControlPlaneApi(options) {
8344
8648
  // PUSHES THE DEADLINE FORWARD: without this a preview CI re-pushes to would be reaped 72h
8345
8649
  // after its first creation no matter how alive it is (preview-and-snapshots.md §9).
8346
8650
  const expiresAt = opts.ttlHours === null ? null : new Date(Date.now() + (opts.ttlHours ?? 72) * 3_600_000).toISOString();
8651
+ /**
8652
+ * #2450: a preview whose copy a job is running keeps its deadline counted from the latest call,
8653
+ * as a finished create's is, so a copy longer than the TTL is not met by the sweep's reap. Each
8654
+ * write is audited, so it is written only once the stored deadline has fallen more than
8655
+ * `PREVIEW_CREATE_BOUND_MS` behind this call's. Best-effort: the finish writes it again.
8656
+ */
8657
+ const keepAlive = async (row, moveId) => {
8658
+ const due = expiresAt === null
8659
+ ? row.expiresAt !== null
8660
+ : row.expiresAt === null || Date.parse(row.expiresAt) < Date.parse(expiresAt) - PREVIEW_CREATE_BOUND_MS;
8661
+ if (due)
8662
+ await c.var.admin.keepAlivePendingScopeCopy(actor, tenantId, row.id, moveId, row.status, row.expiresAt, expiresAt).catch(() => undefined);
8663
+ };
8347
8664
  // Residency (K-7/K-32): forking pins the copy's EXECUTION to the preview deployment.
8348
8665
  // Anything tighter than `global` cannot be honoured until Regional Services, so refuse
8349
8666
  // it here rather than record a residency claim with no mechanism (same gate as export).
@@ -8357,7 +8674,37 @@ export function createControlPlaneApi(options) {
8357
8674
  // every push is its own script, so the rebind first CARRIES the preview's data into
8358
8675
  // the new version's script (#1710). The preview's data then follows it from push to
8359
8676
  // push, and each push's migrations run forward over it (§4's rehearsal case).
8360
- const existing = (await c.var.admin.listScopes(actor, { tenantId, vertical: slug })).find((s) => s.kind === 'preview' && s.slug === previewSlug(slug, opts.tag));
8677
+ let existing = (await c.var.admin.listScopes(actor, { tenantId, vertical: slug })).find((s) => s.kind === 'preview' && s.slug === previewSlug(slug, opts.tag));
8678
+ // #2450 step 2: a fork a job is copying. While it copies, this call answers its progress, and
8679
+ // once it is done, this call finishes the preview. A failed job frees the tag with its error, so
8680
+ // a new create forks afresh; one a refresh or a newer push replaces is stopped, and its row
8681
+ // expired, so the code below reaps it at once.
8682
+ const forkJob = existing?.status === 'provisioning' ? await readCopyJob(copyJobId('fork', existing.id)) : null;
8683
+ // #2450: where this push stands against another's, on a host that runs copies as jobs.
8684
+ const incoming = options.copyJobs ? await c.var.admin.getVersion(actor, opts.versionId, slug) : undefined;
8685
+ if (options.copyJobs && !incoming)
8686
+ throw new ControlPlaneError(404, `unknown version ${opts.versionId} for vertical '${slug}'`);
8687
+ // Compared only where a job is found, which is only on such a host, where it was read.
8688
+ const mine = { versionId: opts.versionId, order: incoming ? versionOrderOf(incoming) : '' };
8689
+ // Every call marks its push the newest of this preview's, for as long as a create's request can
8690
+ // run, before it acts: an older one meanwhile is refused, whatever the rows and jobs say then. A
8691
+ // poll marks too, so the hold runs on past the push's last call however long its copy took.
8692
+ if (options.copyJobs) {
8693
+ const tagId = copyTagId(tenantId, previewSlug(slug, opts.tag));
8694
+ const newest = await options.copyJobs.markNewest(tagId, mine.order, PREVIEW_CREATE_BOUND_MS);
8695
+ if (newest > mine.order)
8696
+ throw supersededByMark(newest, mine, opts.tag);
8697
+ }
8698
+ // A poll goes on only to a fork job (below, where one for another version refuses it) or a live
8699
+ // preview (the carry, below). Anything else is a copy gone: never reaped, never forked afresh.
8700
+ // The row was listed before the job was read, so a call finishing the fork meanwhile (a poll
8701
+ // retried beside it) may have activated it since: it is read again before the copy is called gone.
8702
+ if (poll && !(existing && (forkJob || existing.status === 'active'))) {
8703
+ const fresh = existing ? await c.var.admin.getScopeRecord(actor, tenantId, existing.id) : undefined;
8704
+ if (fresh?.status !== 'active')
8705
+ throw copyGone();
8706
+ existing = fresh;
8707
+ }
8361
8708
  // A preview only HAS data once its two-phase create finished: the directory row lands
8362
8709
  // first as `provisioning` (K-31), the fork's export→restore runs, and `activateScope`
8363
8710
  // is the last step. So a row still at `provisioning` is a create that DIED mid-fork —
@@ -8375,7 +8722,7 @@ export function createControlPlaneApi(options) {
8375
8722
  // what a create in flight looks like, and reaping it wipes the scope that create is
8376
8723
  // restoring into. So a young one, not marked dead by its own frame, is refused instead.
8377
8724
  // `refresh` is the explicit ask to replace whatever is there, and still reaps.
8378
- if (existing && !opts.refresh && existing.status === 'provisioning') {
8725
+ if (existing && !forkJob && !opts.refresh && existing.status === 'provisioning') {
8379
8726
  const now = Date.now();
8380
8727
  const reclaimAt = previewReclaimAt(existing, now);
8381
8728
  if (now < reclaimAt) {
@@ -8440,6 +8787,179 @@ export function createControlPlaneApi(options) {
8440
8787
  // The `--<tag>` URL's base — the source's canonical hostname (fork) or the tenant-app
8441
8788
  // convention (clean-room). Computed once so reuse and fresh mint the same URL.
8442
8789
  const baseHostname = await previewBaseHostname(actor, source, tenantId, slug, surface);
8790
+ // The founding #559 case lands its durable row HERE, not in onError: the previews
8791
+ // route answers a ControlPlaneError directly (its own catch, never the app-level
8792
+ // recorder), and only this frame knows the preview's scopeId (`intoId`) — the key that lets
8793
+ // the console explain the stranded `provisioning` row this throw leaves behind.
8794
+ const restoreOrRecord = async (fn, intoId) => {
8795
+ try {
8796
+ await retryTransient(fn);
8797
+ }
8798
+ catch (e) {
8799
+ if (e instanceof ControlPlaneError && e.status >= 500 && e.status !== 501) {
8800
+ recordFailure({
8801
+ actor,
8802
+ operation: 'preview.create',
8803
+ stage: 'restore',
8804
+ tenantId,
8805
+ scopeId: intoId,
8806
+ vertical: slug,
8807
+ version: opts.versionId,
8808
+ status: e.status,
8809
+ message: e.message,
8810
+ }, e);
8811
+ }
8812
+ throw e;
8813
+ }
8814
+ };
8815
+ /**
8816
+ * #1722 for a fork (#2450): a source that a staff move carried to another script while the fork
8817
+ * read it was wiped where it was read, and its pages then read as the tombstone it left. A fork
8818
+ * never loads that, as a carry never does (`carryFinish`).
8819
+ */
8820
+ const refuseWipedSource = (meta, sourceId) => {
8821
+ if (dumpMetaValue(meta, CARRIED_AWAY_KEY) !== null) {
8822
+ throw new ControlPlaneError(412, `the source of preview '${opts.tag}' (scope ${sourceId}) was carried to another script and wiped while it ` +
8823
+ `was copied, so nothing was moved. Run the create again`);
8824
+ }
8825
+ };
8826
+ const abandonFork = async (previewId, fork, targetRef) => {
8827
+ // The fork stays named for reap and erasure; if this request had died instead, the sweep
8828
+ // would settle the entry once its lease ran out.
8829
+ if (fork && targetRef) {
8830
+ await c.var.admin.settleScopeScriptCopy(actor, tenantId, previewId, targetRef, fork.moveId, 'retained')
8831
+ .catch(() => undefined);
8832
+ }
8833
+ // Expire the row this create left behind, so the next create reaps it at once rather
8834
+ // than refusing it as in flight for the whole bound (#1920) — that next create is the
8835
+ // CLI's retry after a known-dead attempt (#1918). The row stays until then, or until
8836
+ // the GC sweep's next pass reaps it as expired; the #559 ops-failure row outlives both.
8837
+ // Best-effort: if this write fails too, the age bound still frees the tag.
8838
+ await c.var.admin
8839
+ .setScopeExpiresAt(actor, tenantId, previewId, new Date().toISOString())
8840
+ .catch(() => undefined);
8841
+ };
8842
+ const completeFork = async (p) => {
8843
+ await landFork(p);
8844
+ return servedFork(p);
8845
+ };
8846
+ /** A fork's data loaded, its row activated and the version bound: the fork has landed. */
8847
+ const landFork = async (p) => {
8848
+ try {
8849
+ if (p.load)
8850
+ await restoreOrRecord(p.load, p.previewId);
8851
+ await c.var.admin.activateScope(actor, tenantId, p.previewId);
8852
+ // Bind the PR version. A private vertical's push self-admitted, so this is accepted; a
8853
+ // preview scope also admits a pending version (#513), which is what a clean-room rehearsal
8854
+ // of not-yet-admitted code needs. It routes the row onto the fork, so it confirms the move.
8855
+ await c.var.admin.bindScopeVersion(actor, tenantId, p.previewId, opts.versionId, p.fork ? { confirmMove: { moveId: p.fork.moveId, source: 'retained' } } : undefined);
8856
+ }
8857
+ catch (e) {
8858
+ // A bind that committed and lost only its answer has landed the fork: abandoning it would
8859
+ // expire a row that serves this version. The carry draws the same line (`bindAfterCarry`'s caller).
8860
+ const now = await c.var.admin.getScopeRecord(actor, tenantId, p.previewId).catch(() => undefined);
8861
+ if (now?.status === 'active' && now.verticalVersionId === opts.versionId)
8862
+ return;
8863
+ await abandonFork(p.previewId, p.fork, p.targetRef);
8864
+ throw e;
8865
+ }
8866
+ };
8867
+ /** What follows a landed fork: its hostname, the #527 guard and its login. A fault here leaves it served. */
8868
+ const servedFork = async (p) => {
8869
+ const hostname = await bindPreviewHostname(c.var.admin, actor, baseHostname, tenantId, p.previewId, opts.tag, surface);
8870
+ await assertServesBoundVersion(p.previewId);
8871
+ const auth = await wireLogin(p.previewId, hostname, p.parent);
8872
+ return {
8873
+ scopeId: p.previewId,
8874
+ hostname,
8875
+ url: `https://${hostname}`,
8876
+ versionId: opts.versionId,
8877
+ reused: false,
8878
+ auth,
8879
+ notes: notesFor(p.parent),
8880
+ };
8881
+ };
8882
+ /**
8883
+ * Finish a fork a job copied (#2450): renew its lease, which the restore's fence then counts
8884
+ * from, and load the staged dump into the preview as an in-request fork would have. However it
8885
+ * fails before it has landed, its move is settled (`finishingJob`) and the row expired, so the
8886
+ * next create reaps it.
8887
+ */
8888
+ const finishForkJob = async (preview, job) => {
8889
+ const { spec } = job;
8890
+ const fork = { moveId: spec.moveId };
8891
+ const done = job.done;
8892
+ try {
8893
+ // The copy's part of the finish ends once the fork has landed: a fault after that (its
8894
+ // hostname, the guard, its login) is the served preview's, answered as itself.
8895
+ const landed = await finishingJob(c, job, async () => {
8896
+ let load;
8897
+ let parent;
8898
+ try {
8899
+ const lease = await c.var.admin.renewScopeScriptCopy(actor, tenantId, preview.id, spec.moveId, { leaseMs: copyLeaseMs });
8900
+ if (!lease || !target || !done || !preview.forkedFrom) {
8901
+ throw new ControlPlaneError(409, `the copy into preview '${opts.tag}' was settled before it could be loaded; nothing was moved`);
8902
+ }
8903
+ const forkedFrom = preview.forkedFrom;
8904
+ refuseWipedSource(done.meta, forkedFrom);
8905
+ parent = (await c.var.admin.getScopeRecord(actor, tenantId, forkedFrom)) ?? null;
8906
+ const lineage = copyLineageOf({ kind: preview.kind ?? '', forkedFrom });
8907
+ const fence = copyRestoreFence(spec.moveId, lease.renewedAt, copyLeaseMs, spec.erasureEpoch);
8908
+ load = () => target.restoreScope(tenantId, preview.id, done.dump, {
8909
+ sourceScopeId: forkedFrom, exact: true, ...(lineage ? { markCopy: lineage } : {}),
8910
+ loadStamp: spec.restoredStamp, fence,
8911
+ });
8912
+ }
8913
+ catch (e) {
8914
+ // Nothing was loaded: the row goes as a failed load leaves it (`landFork`).
8915
+ await abandonFork(preview.id, fork, spec.destRef);
8916
+ throw e;
8917
+ }
8918
+ const landing = { previewId: preview.id, parent, fork, targetRef: spec.destRef, load };
8919
+ await landFork(landing);
8920
+ return landing;
8921
+ });
8922
+ // Its row's deadline counts from this create, as every create's does: the copy may have
8923
+ // outlasted the one its first call set.
8924
+ await c.var.admin.setScopeExpiresAt(actor, tenantId, preview.id, expiresAt);
8925
+ return await servedFork(landed);
8926
+ }
8927
+ finally {
8928
+ await options.copyJobs?.forget(spec.id).catch(() => undefined);
8929
+ }
8930
+ };
8931
+ if (existing && forkJob) {
8932
+ // A refresh too: it replaces whatever is there but a newer push's copy, as the mark holds it off.
8933
+ const superseded = supersededRefusal(forkJob, mine, opts.tag);
8934
+ if (superseded)
8935
+ throw superseded;
8936
+ const replaced = opts.refresh || forkJob.spec.versionId !== opts.versionId;
8937
+ // A poll's own fork is this one or none: it replaces nothing.
8938
+ if (poll && replaced)
8939
+ throw copyGone();
8940
+ const row = existing;
8941
+ const inProgress = async () => {
8942
+ if (!jobs)
8943
+ throw new ControlPlaneError(409, `a create for preview '${opts.tag}' is in progress (its data is still being copied). Retry once it finishes`);
8944
+ await keepAlive(row, forkJob.spec.moveId);
8945
+ return copyingAnswer(forkJob);
8946
+ };
8947
+ if (!replaced && forkJob.status === 'copying')
8948
+ return inProgress();
8949
+ if (!replaced && forkJob.status === 'done') {
8950
+ // Only the call that claims a done job finishes it. Any other waits, and never renews,
8951
+ // settles or expires what that call is finishing (or has just finished).
8952
+ const claimed = await options.copyJobs?.claim(forkJob.spec.id, copyClaimMs);
8953
+ return claimed ? finishForkJob(existing, claimed) : inProgress();
8954
+ }
8955
+ // A newer push leaves a finish another call has claimed to that call; a refresh replaces it.
8956
+ if (!(await settleJobMove(c, forkJob, { unlessFinishing: !opts.refresh })))
8957
+ return inProgress();
8958
+ await c.var.admin.setScopeExpiresAt(actor, tenantId, existing.id, new Date().toISOString()).catch(() => undefined);
8959
+ if (!replaced)
8960
+ throw refuseFailedJob(forkJob);
8961
+ existing = (await c.var.admin.getScopeRecord(actor, tenantId, existing.id)) ?? existing;
8962
+ }
8443
8963
  // Found above, before any remote read, so an in-flight refusal costs one directory read.
8444
8964
  const stale = existing !== undefined && (opts.refresh || existing.status !== 'active');
8445
8965
  if (existing && !stale) {
@@ -8449,11 +8969,132 @@ export function createControlPlaneApi(options) {
8449
8969
  // `dropServingRef`: a preview provisioned before #527 inherited a serving_ref that is
8450
8970
  // cleared just below, so its route leaves the serving script too.
8451
8971
  let carried;
8972
+ /** The job this call claimed and finished, if any: forgotten once the bind below is over. */
8973
+ let finishedJob;
8974
+ const preview = existing;
8975
+ /** The row the bind below expects: as listed, or as a poll read it again (it may be bound since). */
8976
+ let carryScope = existing;
8452
8977
  try {
8453
- carried = await carryOntoVersion(c, existing, opts.versionId, { dropServingRef: true });
8978
+ // #2450 step 2: a carry a job is copying, for this push or an older one.
8979
+ const held = await readCopyJob(copyJobId('carry', preview.id));
8980
+ const inProgress = async (job) => {
8981
+ if (!jobs)
8982
+ throw new ControlPlaneError(409, `a push to preview '${opts.tag}' is still copying its data. Retry once it finishes`);
8983
+ await keepAlive(preview, job.spec.moveId);
8984
+ return copyingAnswer(job);
8985
+ };
8986
+ if (held && held.spec.versionId !== opts.versionId) {
8987
+ const superseded = supersededRefusal(held, mine, opts.tag);
8988
+ if (superseded)
8989
+ throw superseded;
8990
+ // A poll's own carry is not an older push's: it replaces nothing.
8991
+ if (poll)
8992
+ throw copyGone();
8993
+ // An older push's copy: this push replaces it, unless another call is finishing it.
8994
+ if (!(await settleJobMove(c, held, { unlessFinishing: true })))
8995
+ return inProgress(held);
8996
+ }
8997
+ else if (held) {
8998
+ if (held.status === 'copying')
8999
+ return inProgress(held);
9000
+ if (held.status !== 'done') {
9001
+ await settleJobMove(c, held);
9002
+ throw refuseFailedJob(held);
9003
+ }
9004
+ if (preview.verticalVersionId === opts.versionId &&
9005
+ (await carryEnds(c, preview, opts.versionId, { dropServingRef: true })) === null) {
9006
+ // Its bind landed and only the job's forget was lost: the preview serves this version
9007
+ // with nothing left to move, so the job goes and the preview is answered, never
9008
+ // finished again. A stage a holder still has is that holder's to load or discard.
9009
+ if (!copyJobHeld(held, Date.now()))
9010
+ await discardJobStages(held);
9011
+ await options.copyJobs?.forget(held.spec.id).catch(() => undefined);
9012
+ carried = null;
9013
+ }
9014
+ else {
9015
+ // Only the call that claims a done job finishes it; any other waits (see the fork's).
9016
+ const claimed = await options.copyJobs?.claim(held.spec.id, copyClaimMs);
9017
+ if (!claimed)
9018
+ return inProgress(held);
9019
+ carried = await finishCarryJob(c, preview, opts.versionId, claimed);
9020
+ finishedJob = claimed;
9021
+ }
9022
+ }
9023
+ if (carried === undefined && poll) {
9024
+ // A poll starts no carry. With no job left, either the one it waited on landed (the answer
9025
+ // that said so was lost) and the preview serves this version with nothing left to move,
9026
+ // which is answered again; or the copy is gone. Read on the row as it is now, not as it was
9027
+ // listed: a call finishing the carry (a poll retried beside this one) may have bound it since.
9028
+ const fresh = (await c.var.admin.getScopeRecord(actor, tenantId, preview.id)) ?? preview;
9029
+ const served = fresh.verticalVersionId === opts.versionId &&
9030
+ (await carryEnds(c, fresh, opts.versionId, { dropServingRef: true })) === null;
9031
+ if (!served)
9032
+ throw copyGone();
9033
+ carryScope = fresh;
9034
+ carried = null;
9035
+ }
9036
+ if (carried === undefined && jobs) {
9037
+ const move = await carryBegin(c, preview, opts.versionId, { dropServingRef: true });
9038
+ if (!move) {
9039
+ carried = null;
9040
+ }
9041
+ else {
9042
+ // The first page moves here; a carry that needs more moves in a job, and the preview
9043
+ // keeps serving its data from the old script until a later call finishes it.
9044
+ let begun;
9045
+ try {
9046
+ begun = await beginTransfer({ source: move.source, dest: move.dest }, { from: preview.id }, { retry: retryTransient, alwaysStage: true });
9047
+ }
9048
+ catch (e) {
9049
+ await settleCarryRetained(c, preview, opts.versionId, move);
9050
+ // The destination keeps one stage. Its refusal proves this call staged nothing:
9051
+ // another carry owns page zero, but may not have started its job yet. A visible
9052
+ // job gives the CLI its normal 202 poll; in the short gap before that, 503 makes
9053
+ // its existing first-call retry wait for the winning handler to finish.
9054
+ if (e instanceof ControlPlaneError && e.status === 409 &&
9055
+ e.message === 'a different staged load is in progress; retry after its copy finishes') {
9056
+ const winner = await readCopyJob(copyJobId('carry', preview.id));
9057
+ if (winner) {
9058
+ const superseded = supersededRefusal(winner, mine, opts.tag);
9059
+ if (superseded)
9060
+ throw superseded;
9061
+ return inProgress(winner);
9062
+ }
9063
+ throw new ControlPlaneError(503, `a carry to preview '${opts.tag}' is staging its first page; retry`);
9064
+ }
9065
+ throw e;
9066
+ }
9067
+ if ('state' in begun) {
9068
+ const job = await jobs.start({
9069
+ id: copyJobId('carry', preview.id), kind: 'carry', tenantId, vertical: slug, scopeId: preview.id,
9070
+ versionId: opts.versionId, versionOrder: mine.order,
9071
+ moveId: move.moveId, sourceRef: move.from, destRef: move.to, actor, leaseMs: copyLeaseMs,
9072
+ erasureEpoch: move.erasureEpoch, restoredStamp: move.restoredStamp, expected: move.expected,
9073
+ startedAt: Date.now(), deadline: Date.now() + COPY_JOB_MAX_MS,
9074
+ }, begun.state);
9075
+ // Another call started this preview's job first: this call's move is not the job's, so
9076
+ // its entries settle and its own stage is discarded. The store checks that stage ID,
9077
+ // leaving the winner's stage alone. A newer push's job refuses this one now, as its
9078
+ // next call would; an older one's is replaced by that next call.
9079
+ if (job.spec.moveId !== move.moveId) {
9080
+ await settleCarryRetained(c, preview, opts.versionId, move);
9081
+ await move.dest.discardStagedScope(preview.id, begun.state.stageId).catch(() => undefined);
9082
+ const superseded = supersededRefusal(job, mine, opts.tag);
9083
+ if (superseded)
9084
+ throw superseded;
9085
+ }
9086
+ return copyingAnswer(job);
9087
+ }
9088
+ const done = begun.done;
9089
+ carried = await carryWith(c, preview, opts.versionId, move, async () => done);
9090
+ }
9091
+ }
9092
+ if (carried === undefined)
9093
+ carried = await carryOntoVersion(c, preview, opts.versionId, { dropServingRef: true });
8454
9094
  }
8455
9095
  catch (e) {
8456
- if (e instanceof ControlPlaneError && e.status >= 500 && e.status !== 501) {
9096
+ if (e instanceof ControlPlaneError && e.status >= 500 && e.status !== 501 &&
9097
+ !(e.status === 503 && e.message.includes('is staging its first page; retry'))) {
8457
9098
  recordFailure({
8458
9099
  actor,
8459
9100
  operation: 'preview.create',
@@ -8473,10 +9114,28 @@ export function createControlPlaneApi(options) {
8473
9114
  // #527 has its inherited serving_ref cleared, so routing follows the bound version (its
8474
9115
  // per-version script) and not the prod serving script; the OFF positions are re-asserted
8475
9116
  // there (#1674); and the copy left in the old script is wiped.
8476
- await bindAfterCarry(c, existing, opts.versionId, carried, {
8477
- clearServingRef: true,
8478
- recarry: () => carryOntoVersion(c, existing, opts.versionId, { dropServingRef: true }),
8479
- });
9117
+ try {
9118
+ const scope = carryScope;
9119
+ await bindAfterCarry(c, scope, opts.versionId, carried, {
9120
+ clearServingRef: true,
9121
+ recarry: () => carryOntoVersion(c, scope, opts.versionId, { dropServingRef: true }),
9122
+ });
9123
+ }
9124
+ catch (e) {
9125
+ // A job's bind that failed is that copy's end, as its load's is (`finishRefusal`). A fault
9126
+ // after the bind landed (re-asserting the switches, the source's settle) is the served
9127
+ // preview's, answered as itself: a retry finds the preview serving this version.
9128
+ if (!finishedJob)
9129
+ throw e;
9130
+ const now = await c.var.admin.getScopeRecord(actor, tenantId, existing.id).catch(() => undefined);
9131
+ throw now?.verticalVersionId === opts.versionId ? e : finishRefusal(c, finishedJob, e);
9132
+ }
9133
+ finally {
9134
+ // #2450: a job this call finished stays claimed until its bind has landed or failed, so a
9135
+ // newer push polling meanwhile waits, rather than carry from the binding this one replaces.
9136
+ if (finishedJob)
9137
+ await options.copyJobs?.forget(finishedJob.spec.id).catch(() => undefined);
9138
+ }
8480
9139
  // Renew (or clear) the preview's GC deadline so a reused preview does not silently die.
8481
9140
  await c.var.admin.setScopeExpiresAt(actor, tenantId, existing.id, expiresAt);
8482
9141
  const hostname = await bindPreviewHostname(c.var.admin, actor, baseHostname, tenantId, existing.id, opts.tag, surface);
@@ -8515,42 +9174,22 @@ export function createControlPlaneApi(options) {
8515
9174
  // A marked row is also the GC sweep's to reap (its `expiresAt` has passed), so the sweep
8516
9175
  // can get there between the lookup above and this reap. Gone is what the reap wanted.
8517
9176
  if (existing && stale) {
9177
+ // #2450: a job still copying holds a live lease, which a reap waits on; stop it first. A newer
9178
+ // push's copy is not this create's to stop, a refresh's included: it refuses instead.
9179
+ await cancelPreviewJobs(c, existing, { mine, tag: opts.tag });
8518
9180
  await reapPreview(c, existing).catch((e) => {
8519
9181
  if (errorCodeOf(e) !== 'not_found')
8520
9182
  throw e;
8521
9183
  });
8522
9184
  }
8523
9185
  const previewId = scopeIdSchema.parse(ulid());
8524
- // The founding #559 case lands its durable row HERE, not in onError: the previews
8525
- // route answers a ControlPlaneError directly (its own catch, never the app-level
8526
- // recorder), and only this frame knows the preview's scopeId — the key that lets
8527
- // the console explain the stranded `provisioning` row this throw leaves behind.
8528
- const restoreOrRecord = async (fn) => {
8529
- try {
8530
- await retryTransient(fn);
8531
- }
8532
- catch (e) {
8533
- if (e instanceof ControlPlaneError && e.status >= 500 && e.status !== 501) {
8534
- recordFailure({
8535
- actor,
8536
- operation: 'preview.create',
8537
- stage: 'restore',
8538
- tenantId,
8539
- scopeId: previewId,
8540
- vertical: slug,
8541
- version: opts.versionId,
8542
- status: e.status,
8543
- message: e.message,
8544
- }, e);
8545
- }
8546
- throw e;
8547
- }
8548
- };
8549
9186
  let row;
8550
9187
  /** `fenced`: the ledger stamp and lease of this fork's restore (#1722), when it has one. */
8551
9188
  let restore;
8552
9189
  /** #2450: the fork's data, moved into the preview's copy once the ledger names it. */
8553
9190
  let forkData = null;
9191
+ /** #2450 step 2: a source a job can page from, when this create may run in the background. */
9192
+ let forkPaged = null;
8554
9193
  /** #2009: the directory's classification of the row below, which every restore of it carries. */
8555
9194
  const markCopyOfRow = () => {
8556
9195
  const lineage = copyLineageOf({ kind: row.kind ?? '', forkedFrom: row.forkedFrom ?? null });
@@ -8564,6 +9203,12 @@ export function createControlPlaneApi(options) {
8564
9203
  if (!target) {
8565
9204
  throw new ControlPlaneError(501, 'preview needs dispatch resolution for the PR version');
8566
9205
  }
9206
+ // #2450 step 2: what a job needs to move the fork's pages after this request, by reference.
9207
+ if (sourceClient && jobs) {
9208
+ const sourceRef = await routeOf(c, source);
9209
+ if (sourceRef)
9210
+ forkPaged = { source: sourceClient, sourceRef, sourceScopeId: source.id };
9211
+ }
8567
9212
  const canonical = await c.var.admin.exportScope(actor, tenantId, source.id);
8568
9213
  // #2450: from a vertical, the fork's data moves a page at a time into the preview's own stage
8569
9214
  // there, so a scope of any size forks. Unstamped, as the whole export was: a fork writes
@@ -8571,7 +9216,11 @@ export function createControlPlaneApi(options) {
8571
9216
  // (K-31: no copied data without a record) and ahead of the restore's own retries, so a
8572
9217
  // restore blip reloads the same stage and an export fault is not recorded as a restore's.
8573
9218
  forkData = sourceClient
8574
- ? async () => (await transferScope(sourceClient, target, { from: source.id, to: previewId }, { retry: retryTransient, stamp: false })).dump
9219
+ ? async () => {
9220
+ const moved = await transferScope(sourceClient, target, { from: source.id, to: previewId }, { retry: retryTransient, stamp: false });
9221
+ refuseWipedSource(moved.meta, source.id);
9222
+ return moved.dump;
9223
+ }
8575
9224
  : async () => canonical.tables;
8576
9225
  // Directory row FIRST as `provisioning` (K-31 two-phase): a crash before the data
8577
9226
  // copy leaves an inert row that — carrying `forkedFrom` + `expiresAt` — the GC sweep
@@ -8623,6 +9272,7 @@ export function createControlPlaneApi(options) {
8623
9272
  ? ((await c.var.admin.getVersion(actor, opts.versionId, slug))?.deploymentRef ?? null)
8624
9273
  : null;
8625
9274
  let fork = null;
9275
+ let load = null;
8626
9276
  try {
8627
9277
  // Inside the try: a host writes the directory row FIRST and then migrates, projects and
8628
9278
  // seats, so a provision that throws can leave a `provisioning` row too. A provision
@@ -8631,6 +9281,7 @@ export function createControlPlaneApi(options) {
8631
9281
  await c.var.host.provisionScope(actor, row);
8632
9282
  if (restore) {
8633
9283
  let fenced = {};
9284
+ let move = null;
8634
9285
  if (targetRef) {
8635
9286
  const moveId = ulid();
8636
9287
  const restoredStamp = ulid();
@@ -8638,48 +9289,44 @@ export function createControlPlaneApi(options) {
8638
9289
  await c.var.admin.recordScopeScriptCopy(actor, tenantId, previewId, targetRef, moveId, { role: 'destination', loadStamp: restoredStamp, leaseMs: copyLeaseMs });
8639
9290
  fork = { moveId };
8640
9291
  const erasureEpoch = await c.var.admin.scopeErasureEpoch(actor, tenantId, previewId);
9292
+ move = { moveId, restoredStamp, erasureEpoch };
8641
9293
  fenced = { loadStamp: restoredStamp, fence: copyRestoreFence(moveId, recordedAt, copyLeaseMs, erasureEpoch) };
8642
9294
  }
8643
- const load = restore;
8644
- const dump = forkData ? await forkData() : undefined;
8645
- await restoreOrRecord(() => load(fenced, dump));
9295
+ const restoreWith = restore;
9296
+ let dump;
9297
+ if (forkPaged && jobs && move && targetRef && target) {
9298
+ // #2450 step 2: the first page moves here. A fork that needs more moves in a job, and a
9299
+ // later call to this route finishes it (`finishForkJob`); the row stays `provisioning`.
9300
+ const begun = await beginTransfer({ source: forkPaged.source, dest: target }, { from: forkPaged.sourceScopeId, to: previewId }, { retry: retryTransient, stamp: false, alwaysStage: true });
9301
+ if ('state' in begun) {
9302
+ const job = await jobs.start({
9303
+ id: copyJobId('fork', previewId), kind: 'fork', tenantId, vertical: slug, scopeId: previewId,
9304
+ versionId: opts.versionId, versionOrder: mine.order,
9305
+ moveId: move.moveId, sourceRef: forkPaged.sourceRef, destRef: targetRef, actor, leaseMs: copyLeaseMs,
9306
+ erasureEpoch: move.erasureEpoch, restoredStamp: move.restoredStamp,
9307
+ startedAt: Date.now(), deadline: Date.now() + COPY_JOB_MAX_MS,
9308
+ }, begun.state);
9309
+ // A job id names the preview, which this create just minted, so no other call can
9310
+ // hold it; a job answered for another move would be a defect, not a race.
9311
+ if (job.spec.moveId !== move.moveId) {
9312
+ throw new ControlPlaneError(500, `preview ${previewId} already had a copy job for another move`);
9313
+ }
9314
+ return copyingAnswer(job);
9315
+ }
9316
+ refuseWipedSource(begun.done.meta, forkPaged.sourceScopeId);
9317
+ dump = begun.done.dump;
9318
+ }
9319
+ else {
9320
+ dump = forkData ? await forkData() : undefined;
9321
+ }
9322
+ load = () => restoreWith(fenced, dump);
8646
9323
  }
8647
- await c.var.admin.activateScope(actor, tenantId, previewId);
8648
- // Bind the PR version. A private vertical's push self-admitted, so this is accepted; a
8649
- // preview scope also admits a pending version (#513), which is what a clean-room rehearsal
8650
- // of not-yet-admitted code needs. It routes the row onto the fork, so it confirms the move.
8651
- await c.var.admin.bindScopeVersion(actor, tenantId, previewId, opts.versionId, fork ? { confirmMove: { moveId: fork.moveId, source: 'retained' } } : undefined);
8652
9324
  }
8653
9325
  catch (e) {
8654
- // The fork stays named for reap and erasure; if this request had died instead, the sweep
8655
- // would settle the entry once its lease ran out.
8656
- const unbound = fork;
8657
- if (unbound && targetRef) {
8658
- await c.var.admin.settleScopeScriptCopy(actor, tenantId, previewId, targetRef, unbound.moveId, 'retained')
8659
- .catch(() => undefined);
8660
- }
8661
- // Expire the row this create left behind, so the next create reaps it at once rather
8662
- // than refusing it as in flight for the whole bound (#1920) — that next create is the
8663
- // CLI's retry after a known-dead attempt (#1918). The row stays until then, or until
8664
- // the GC sweep's next pass reaps it as expired; the #559 ops-failure row outlives both.
8665
- // Best-effort: if this write fails too, the age bound still frees the tag.
8666
- await c.var.admin
8667
- .setScopeExpiresAt(actor, tenantId, previewId, new Date().toISOString())
8668
- .catch(() => undefined);
9326
+ await abandonFork(previewId, fork, targetRef);
8669
9327
  throw e;
8670
9328
  }
8671
- const hostname = await bindPreviewHostname(c.var.admin, actor, baseHostname, tenantId, previewId, opts.tag, surface);
8672
- await assertServesBoundVersion(previewId);
8673
- const auth = await wireLogin(previewId, hostname, source);
8674
- return {
8675
- scopeId: previewId,
8676
- hostname,
8677
- url: `https://${hostname}`,
8678
- versionId: opts.versionId,
8679
- reused: false,
8680
- auth,
8681
- notes: notesFor(source),
8682
- };
9329
+ return completeFork({ previewId, parent: source, fork, targetRef, load });
8683
9330
  };
8684
9331
  // The owning tenant of a builder's OWN vertical — the gate every preview route shares. A
8685
9332
  // preview forks THIS tenant's own scope and binds the version onto that fork (never an
@@ -8733,6 +9380,11 @@ export function createControlPlaneApi(options) {
8733
9380
  }
8734
9381
  try {
8735
9382
  const out = await orchestratedPreview(c, tenantId, slug, source, body);
9383
+ // #2450 step 2: the copy runs on; the same call, repeated, finishes the preview.
9384
+ if ('copying' in out) {
9385
+ c.header('Retry-After', String(out.retryAfter));
9386
+ return c.json(out, 202);
9387
+ }
8736
9388
  return c.json(out, out.reused ? 200 : 201);
8737
9389
  }
8738
9390
  catch (e) {
@@ -8780,6 +9432,8 @@ export function createControlPlaneApi(options) {
8780
9432
  if (!preview)
8781
9433
  return c.json({ deleted: null, note: `no preview '${tag}' for '${slug}'` });
8782
9434
  try {
9435
+ // #2450: a copy still running holds a live lease, which the reap waits on; stop it first.
9436
+ await cancelPreviewJobs(c, preview);
8783
9437
  // Storage-before-row, the same ordering as the fork hard-delete: wipe the DO in the
8784
9438
  // PR version's deployment, then deleteSnapshot (fork-only re-check, hostnames + row,
8785
9439
  // audit). A crash between the two converges on retry.