@proofoftech/flowsafe 0.31.0 → 0.32.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/CHANGELOG.md +19 -0
- package/README.md +6 -0
- package/dist/agent-host/thread-topology.d.ts +1 -0
- package/dist/agent-host/thread-topology.d.ts.map +1 -1
- package/dist/agent-host/thread-topology.js +3 -2
- package/dist/agent-host/thread-topology.js.map +1 -1
- package/dist/approval-api/actor-context.d.ts +1 -0
- package/dist/approval-api/actor-context.d.ts.map +1 -1
- package/dist/approval-api/actor-context.js +12 -1
- package/dist/approval-api/actor-context.js.map +1 -1
- package/dist/approval-api/resource-ownership.d.ts +3 -0
- package/dist/approval-api/resource-ownership.d.ts.map +1 -1
- package/dist/approval-api/resource-ownership.js +14 -2
- package/dist/approval-api/resource-ownership.js.map +1 -1
- package/dist/do-runner/d1-storage.d.ts +6 -4
- package/dist/do-runner/d1-storage.d.ts.map +1 -1
- package/dist/do-runner/d1-storage.js +23 -32
- package/dist/do-runner/d1-storage.js.map +1 -1
- package/dist/do-runner/do-error-response.d.ts +1 -5
- package/dist/do-runner/do-error-response.d.ts.map +1 -1
- package/dist/do-runner/do-error-response.js +3 -6
- package/dist/do-runner/do-error-response.js.map +1 -1
- package/dist/do-runner/durable-object.d.ts.map +1 -1
- package/dist/do-runner/durable-object.js +60 -9
- package/dist/do-runner/durable-object.js.map +1 -1
- package/dist/do-runner/index.d.ts +6 -4
- package/dist/do-runner/index.d.ts.map +1 -1
- package/dist/do-runner/index.js +5 -3
- package/dist/do-runner/index.js.map +1 -1
- package/dist/do-runner/inventory.d.ts +6 -5
- package/dist/do-runner/inventory.d.ts.map +1 -1
- package/dist/do-runner/inventory.js +116 -26
- package/dist/do-runner/inventory.js.map +1 -1
- package/dist/do-runner/legacy-drain-classifier.d.ts +23 -0
- package/dist/do-runner/legacy-drain-classifier.d.ts.map +1 -0
- package/dist/do-runner/legacy-drain-classifier.js +77 -0
- package/dist/do-runner/legacy-drain-classifier.js.map +1 -0
- package/dist/do-runner/remote-step-expiry.d.ts +6 -0
- package/dist/do-runner/remote-step-expiry.d.ts.map +1 -0
- package/dist/do-runner/remote-step-expiry.js +5 -0
- package/dist/do-runner/remote-step-expiry.js.map +1 -0
- package/dist/do-runner/remote-step-journal.d.ts +27 -1
- package/dist/do-runner/remote-step-journal.d.ts.map +1 -1
- package/dist/do-runner/remote-step-journal.js +350 -2
- package/dist/do-runner/remote-step-journal.js.map +1 -1
- package/dist/do-runner/runtime.d.ts +19 -1
- package/dist/do-runner/runtime.d.ts.map +1 -1
- package/dist/do-runner/runtime.js +86 -16
- package/dist/do-runner/runtime.js.map +1 -1
- package/dist/do-runner/start-idempotency.d.ts +37 -16
- package/dist/do-runner/start-idempotency.d.ts.map +1 -1
- package/dist/do-runner/start-idempotency.js +280 -38
- package/dist/do-runner/start-idempotency.js.map +1 -1
- package/dist/do-runner/start-reservation-contract.d.ts +9 -5
- package/dist/do-runner/start-reservation-contract.d.ts.map +1 -1
- package/dist/do-runner/start-reservation-contract.js +18 -4
- package/dist/do-runner/start-reservation-contract.js.map +1 -1
- package/dist/do-runner/workflow-snapshot-row.d.ts +3 -0
- package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -1
- package/dist/do-runner/workflow-snapshot-row.js +28 -0
- package/dist/do-runner/workflow-snapshot-row.js.map +1 -1
- package/dist/host-kit/flowsafe-worker.d.ts +12 -2
- package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
- package/dist/host-kit/flowsafe-worker.js +167 -20
- package/dist/host-kit/flowsafe-worker.js.map +1 -1
- package/dist/host-kit/index.d.ts +1 -0
- package/dist/host-kit/index.d.ts.map +1 -1
- package/dist/host-kit/index.js +1 -0
- package/dist/host-kit/index.js.map +1 -1
- package/dist/host-kit/maintenance-capability.d.ts +1 -0
- package/dist/host-kit/maintenance-capability.d.ts.map +1 -1
- package/dist/host-kit/maintenance-capability.js +1 -0
- package/dist/host-kit/maintenance-capability.js.map +1 -1
- package/dist/host-kit/run-router.d.ts.map +1 -1
- package/dist/host-kit/run-router.js +10 -8
- package/dist/host-kit/run-router.js.map +1 -1
- package/package.json +2 -2
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { DoStatusError } from './do-status-error.js';
|
|
2
2
|
import { type StartExecutionIdentity } from './execution-admission.js';
|
|
3
|
-
import type
|
|
3
|
+
import { type ExecutionFenceStore, type ExecutionFenceWiring } from './execution-fence.js';
|
|
4
4
|
import { type StartReservation, type StartReservationOwner, type StartReservationReading, type StartTargetKind } from './start-reservation-contract.js';
|
|
5
|
-
export { decodeStartReservationAdmissionResult, START_IDEMPOTENCY_DDL, START_IDEMPOTENCY_RUN_INDEX_DDL, START_IDEMPOTENCY_STATE_INDEX_DDL, START_IDEMPOTENCY_TABLE, START_RESERVATION_STATES, START_TARGET_KINDS, type StartReservation, type StartReservationBinding, type StartReservationOwner, type StartReservationReading, type StartReservationState, type StartTargetKind, validateStartReservationAdmissionSchema, } from './start-reservation-contract.js';
|
|
5
|
+
export { BOUND_RESERVATION_SETTLEMENT_AGE_MS, decodeStartReservationAdmissionResult, isAbandonedReservation, START_IDEMPOTENCY_DDL, START_IDEMPOTENCY_RUN_INDEX_DDL, START_IDEMPOTENCY_STATE_INDEX_DDL, START_IDEMPOTENCY_TABLE, START_RESERVATION_STATES, START_TARGET_KINDS, type StartReservation, type StartReservationBinding, type StartReservationOwner, type StartReservationReading, type StartReservationState, type StartTargetKind, UNBOUND_RESERVATION_EXPIRY_MS, validateStartReservationAdmissionSchema, } from './start-reservation-contract.js';
|
|
6
6
|
export interface StartReservationRequest {
|
|
7
7
|
key: unknown;
|
|
8
8
|
owner: StartReservationOwner;
|
|
@@ -75,6 +75,13 @@ export declare class IdempotentStartPendingError extends DoStatusError {
|
|
|
75
75
|
};
|
|
76
76
|
constructor(reservation: StartReservation);
|
|
77
77
|
}
|
|
78
|
+
export declare class IdempotentStartAbortedError extends DoStatusError {
|
|
79
|
+
readonly status = 503;
|
|
80
|
+
readonly reason: {
|
|
81
|
+
readonly code: "IDEMPOTENT_START_ABORTED";
|
|
82
|
+
};
|
|
83
|
+
constructor();
|
|
84
|
+
}
|
|
78
85
|
/**
|
|
79
86
|
* The claim was taken, nothing persisted, and nothing is running.
|
|
80
87
|
*
|
|
@@ -132,20 +139,8 @@ export declare class StartIdempotencyUnsupportedError extends DoStatusError {
|
|
|
132
139
|
constructor();
|
|
133
140
|
}
|
|
134
141
|
/** Failures a start surface may reject while admitting or resolving a key. */
|
|
135
|
-
export type StartReservationRefusal = StartReservationOwnerMismatchError | StartReservationTargetMismatchError | IdempotentStartPendingError | IdempotentStartUnresolvableError | IdempotentStartAlreadySettledError | StartIdempotencyUnsupportedError | InvalidStartIdempotencyRequestError;
|
|
142
|
+
export type StartReservationRefusal = StartReservationOwnerMismatchError | StartReservationTargetMismatchError | IdempotentStartAbortedError | IdempotentStartPendingError | IdempotentStartUnresolvableError | IdempotentStartAlreadySettledError | StartIdempotencyUnsupportedError | InvalidStartIdempotencyRequestError;
|
|
136
143
|
/**
|
|
137
|
-
* Recognize the five reservation-decision refusals:
|
|
138
|
-
*
|
|
139
|
-
* - `IDEMPOTENT_START_OWNER_MISMATCH` (403)
|
|
140
|
-
* - `IDEMPOTENT_START_TARGET_MISMATCH` (409)
|
|
141
|
-
* - `IDEMPOTENT_START_PENDING` (503)
|
|
142
|
-
* - `IDEMPOTENT_START_UNRESOLVABLE` (409)
|
|
143
|
-
* - `IDEMPOTENT_START_ALREADY_SETTLED` (409)
|
|
144
|
-
*
|
|
145
|
-
* The guard also recognizes `IDEMPOTENT_START_UNSUPPORTED` keyed admission
|
|
146
|
-
* (503) and malformed reservation input (400,
|
|
147
|
-
* `INVALID_START_IDEMPOTENCY_REQUEST`).
|
|
148
|
-
*
|
|
149
144
|
* Unsupported wiring remains in this guard because the keyed request is
|
|
150
145
|
* intentionally refused at admission instead of being executed without its
|
|
151
146
|
* exactly-once guarantee. `StartReservationUnreadableError` is deliberately
|
|
@@ -174,6 +169,14 @@ export interface StartIdempotencyStatement {
|
|
|
174
169
|
}
|
|
175
170
|
/** How a surface is wired to the reservation store, or the typed opt-out. */
|
|
176
171
|
export type StartIdempotencyWiring = StartIdempotencyStore | 'none';
|
|
172
|
+
/**
|
|
173
|
+
* Position of the bound-reservation settlement pass: the `(updated_at, key)` of the
|
|
174
|
+
* last candidate it examined, which maintenance stores between passes.
|
|
175
|
+
*/
|
|
176
|
+
export interface BoundReservationSettlementCursor {
|
|
177
|
+
readonly updatedAt: number;
|
|
178
|
+
readonly key: string;
|
|
179
|
+
}
|
|
177
180
|
export declare function startIdempotencyFor(db: StartIdempotencyDatabase): StartIdempotencyStore;
|
|
178
181
|
/**
|
|
179
182
|
* A reservation exists but cannot be understood, or the table could not be
|
|
@@ -222,12 +225,28 @@ export declare class StartIdempotencyStore {
|
|
|
222
225
|
claimReservation(observed: StartReservationReading): Promise<StartReservationReading | undefined>;
|
|
223
226
|
/** Release only the exact unbound claim, without readback recovery. */
|
|
224
227
|
releaseReservation(observed: StartReservationReading): Promise<boolean>;
|
|
228
|
+
isExpiredUnboundReservation(reservation: StartReservationReading): boolean;
|
|
229
|
+
reviveUnboundReservation(observed: StartReservationReading): Promise<StartReservationReading | undefined>;
|
|
225
230
|
/** Associate an alias with an already-observed nonpending execution. */
|
|
226
231
|
associateReservation(observed: StartReservationReading, execution: StartExecutionIdentity): Promise<StartReservationReading>;
|
|
227
232
|
/** Bind a prepared start; only exact lost-write readback can recover. */
|
|
228
233
|
bindPreparedStart(observed: StartReservationReading, execution: StartExecutionIdentity): Promise<StartReservationReading>;
|
|
229
234
|
/** Settle every alias of this complete physical/logical execution. */
|
|
230
235
|
settleExecution(execution: StartExecutionIdentity): Promise<number>;
|
|
236
|
+
abandonUnboundReservations({ olderThanMs, key, fence, principal, }: {
|
|
237
|
+
olderThanMs: number;
|
|
238
|
+
key?: string;
|
|
239
|
+
fence: ExecutionFenceStore;
|
|
240
|
+
principal?: string;
|
|
241
|
+
}): Promise<number>;
|
|
242
|
+
settleOrphanedBoundReservations({ tablePrefix, olderThanMs, fence, settleAbsentWorkflowRuns, cursor, onPage, }: {
|
|
243
|
+
tablePrefix?: string;
|
|
244
|
+
olderThanMs: number;
|
|
245
|
+
fence: ExecutionFenceStore;
|
|
246
|
+
settleAbsentWorkflowRuns?: boolean;
|
|
247
|
+
cursor?: BoundReservationSettlementCursor;
|
|
248
|
+
onPage?: (settled: number, next: BoundReservationSettlementCursor | undefined) => void | Promise<void>;
|
|
249
|
+
}): Promise<number>;
|
|
231
250
|
/**
|
|
232
251
|
* Read one reservation. A PURE read: no lazy DDL, no upsert, nothing that
|
|
233
252
|
* would make consulting a key mutate the database — which is what lets a
|
|
@@ -269,7 +288,9 @@ export type IdempotentStartDecision<T> = {
|
|
|
269
288
|
reservation: StartReservationReading;
|
|
270
289
|
persisted: T;
|
|
271
290
|
};
|
|
272
|
-
export declare function beginIdempotentStart<T>(store: StartIdempotencyStore, request: StartReservationRequest, surface: IdempotentStartSurface<T>, fence?: ExecutionFenceWiring, mutationEpoch?: number
|
|
291
|
+
export declare function beginIdempotentStart<T>(store: StartIdempotencyStore, request: StartReservationRequest, surface: IdempotentStartSurface<T>, fence?: ExecutionFenceWiring, mutationEpoch?: number, options?: {
|
|
292
|
+
signal?: AbortSignal;
|
|
293
|
+
}): Promise<IdempotentStartDecision<T>>;
|
|
273
294
|
/**
|
|
274
295
|
* Resolve a surface's reservation wiring, refusing a key the host cannot
|
|
275
296
|
* honour.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"start-idempotency.d.ts","sourceRoot":"","sources":["../../src/do-runner/start-idempotency.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"start-idempotency.d.ts","sourceRoot":"","sources":["../../src/do-runner/start-idempotency.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAOL,KAAK,sBAAsB,EAC5B,MAAM,0BAA0B,CAA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AE,CAAC,CAAC;IAClB,QAAQ,CAAC,SAAS,EAAE,sBAAsB,CAAC;CAC5C,CAAC;AAEN,MAAM,WAAW,sBAAsB,CAAC,CAAC;IACvC,SAAS,CACP,WAAW,EAAE,uBAAuB,GACnC,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC;IAChD,IAAI,CAAC,WAAW,EAAE,uBAAuB,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CAC9D;AAED,MAAM,MAAM,uBAAuB,CAAC,CAAC,IACjC;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,WAAW,EAAE,uBAAuB,CAAA;CAAE,GACvD;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,WAAW,EAAE,uBAAuB,CAAC;IAAC,SAAS,EAAE,CAAC,CAAA;CAAE,CAAC;AAM3E,wBAAsB,oBAAoB,CAAC,CAAC,EAC1C,KAAK,EAAE,qBAAqB,EAC5B,OAAO,EAAE,uBAAuB,EAChC,OAAO,EAAE,sBAAsB,CAAC,CAAC,CAAC,EAClC,KAAK,CAAC,EAAE,oBAAoB,EAC5B,aAAa,CAAC,EAAE,MAAM,EACtB,OAAO,CAAC,EAAE;IAAE,MAAM,CAAC,EAAE,WAAW,CAAA;CAAE,GACjC,OAAO,CAAC,uBAAuB,CAAC,CAAC,CAAC,CAAC,CAoGrC;AA0HD;;;;;;;;;;GAUG;AACH,wBAAgB,uBAAuB,CACrC,MAAM,EAAE,sBAAsB,GAAG,SAAS,GACzC,qBAAqB,CAKvB"}
|
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
// SPDX-License-Identifier: Apache-2.0
|
|
2
2
|
// A missing result cannot establish whether a claimed start had effects.
|
|
3
|
+
import { EXECUTION_FENCE_TABLE } from '#deployment-identity-protocol';
|
|
3
4
|
import { isExecutionPrincipalId, isExecutionPrincipalKind, } from '../approval-api/principal-identity.js';
|
|
4
5
|
import { missingTableReadsEmpty } from './cause-chain.js';
|
|
5
6
|
import { DoStatusError } from './do-status-error.js';
|
|
6
|
-
import { InvalidExecutionIdentityError, normalizeMutationEpoch, normalizeStartExecutionIdentity, RunAdmissionConflictError, } from './execution-admission.js';
|
|
7
|
+
import { ExecutionFenceUnreadableError, InvalidExecutionIdentityError, normalizeMutationEpoch, normalizeStartExecutionIdentity, RunAdmissionConflictError, } from './execution-admission.js';
|
|
8
|
+
import { admitsDrainableExecution, captureExecutionFenceAdmissionSchema, ExecutionFencedError, executionFenceAdmissionSql, executionFenceAdmissionValues, } from './execution-fence.js';
|
|
7
9
|
import { isPathSafeId } from './path-safe-id.js';
|
|
8
|
-
import { admissionReservationFromRow, captureReservation, decodeStartReservationAdmissionResult, isStartTargetKind, ReservationSchemaError, reservationFromRow, reservationResultRows, reservationSchemaStage, START_IDEMPOTENCY_ADDITIONS, START_IDEMPOTENCY_COLUMNS, START_IDEMPOTENCY_DDL, START_IDEMPOTENCY_RUN_INDEX_DDL, START_IDEMPOTENCY_STATE_INDEX_DDL, START_IDEMPOTENCY_TABLE, START_TARGET_KINDS, sameReservationIdentity, validateStartReservationAdmissionSchema, } from './start-reservation-contract.js';
|
|
9
|
-
|
|
10
|
+
import { ABANDONABLE_RESERVATION_SQL, admissionReservationFromRow, BOUND_RESERVATION_SETTLEMENT_AGE_MS, captureReservation, decodeStartReservationAdmissionResult, isAbandonedReservation, isStartTargetKind, LEGACY_RESERVATION_SQL, ReservationSchemaError, reservationFromRow, reservationResultRows, reservationSchemaStage, START_IDEMPOTENCY_ADDITIONS, START_IDEMPOTENCY_COLUMNS, START_IDEMPOTENCY_DDL, START_IDEMPOTENCY_RUN_INDEX_DDL, START_IDEMPOTENCY_STATE_INDEX_DDL, START_IDEMPOTENCY_TABLE, START_TARGET_KINDS, sameReservationIdentity, UNBOUND_RESERVATION_EXPIRY_MS, validateStartReservationAdmissionSchema, } from './start-reservation-contract.js';
|
|
11
|
+
import { validateTablePrefix } from './table-prefix.js';
|
|
12
|
+
import { RUN_TERMINAL_SNAPSHOT_SQL, RUN_TERMINAL_STATUSES, } from './workflow-snapshot-row.js';
|
|
13
|
+
export { BOUND_RESERVATION_SETTLEMENT_AGE_MS, decodeStartReservationAdmissionResult, isAbandonedReservation, START_IDEMPOTENCY_DDL, START_IDEMPOTENCY_RUN_INDEX_DDL, START_IDEMPOTENCY_STATE_INDEX_DDL, START_IDEMPOTENCY_TABLE, START_RESERVATION_STATES, START_TARGET_KINDS, UNBOUND_RESERVATION_EXPIRY_MS, validateStartReservationAdmissionSchema, } from './start-reservation-contract.js';
|
|
10
14
|
function captureStartRequest(request) {
|
|
11
15
|
const key = assertKey(request.key);
|
|
12
16
|
const owner = assertOwner(request.owner);
|
|
@@ -94,6 +98,14 @@ export class IdempotentStartPendingError extends DoStatusError {
|
|
|
94
98
|
};
|
|
95
99
|
}
|
|
96
100
|
}
|
|
101
|
+
export class IdempotentStartAbortedError extends DoStatusError {
|
|
102
|
+
status = 503;
|
|
103
|
+
reason = { code: 'IDEMPOTENT_START_ABORTED' };
|
|
104
|
+
constructor() {
|
|
105
|
+
super('idempotent start admission was aborted');
|
|
106
|
+
this.name = 'IdempotentStartAbortedError';
|
|
107
|
+
}
|
|
108
|
+
}
|
|
97
109
|
/**
|
|
98
110
|
* The claim was taken, nothing persisted, and nothing is running.
|
|
99
111
|
*
|
|
@@ -163,18 +175,6 @@ export class StartIdempotencyUnsupportedError extends DoStatusError {
|
|
|
163
175
|
}
|
|
164
176
|
}
|
|
165
177
|
/**
|
|
166
|
-
* Recognize the five reservation-decision refusals:
|
|
167
|
-
*
|
|
168
|
-
* - `IDEMPOTENT_START_OWNER_MISMATCH` (403)
|
|
169
|
-
* - `IDEMPOTENT_START_TARGET_MISMATCH` (409)
|
|
170
|
-
* - `IDEMPOTENT_START_PENDING` (503)
|
|
171
|
-
* - `IDEMPOTENT_START_UNRESOLVABLE` (409)
|
|
172
|
-
* - `IDEMPOTENT_START_ALREADY_SETTLED` (409)
|
|
173
|
-
*
|
|
174
|
-
* The guard also recognizes `IDEMPOTENT_START_UNSUPPORTED` keyed admission
|
|
175
|
-
* (503) and malformed reservation input (400,
|
|
176
|
-
* `INVALID_START_IDEMPOTENCY_REQUEST`).
|
|
177
|
-
*
|
|
178
178
|
* Unsupported wiring remains in this guard because the keyed request is
|
|
179
179
|
* intentionally refused at admission instead of being executed without its
|
|
180
180
|
* exactly-once guarantee. `StartReservationUnreadableError` is deliberately
|
|
@@ -187,12 +187,22 @@ export class StartIdempotencyUnsupportedError extends DoStatusError {
|
|
|
187
187
|
export function isStartReservationRefusal(error) {
|
|
188
188
|
return (error instanceof StartReservationOwnerMismatchError ||
|
|
189
189
|
error instanceof StartReservationTargetMismatchError ||
|
|
190
|
+
error instanceof IdempotentStartAbortedError ||
|
|
190
191
|
error instanceof IdempotentStartPendingError ||
|
|
191
192
|
error instanceof IdempotentStartUnresolvableError ||
|
|
192
193
|
error instanceof IdempotentStartAlreadySettledError ||
|
|
193
194
|
error instanceof StartIdempotencyUnsupportedError ||
|
|
194
195
|
error instanceof InvalidStartIdempotencyRequestError);
|
|
195
196
|
}
|
|
197
|
+
const BOUND_SETTLEMENT_PAGE_SIZE = 90;
|
|
198
|
+
const BOUND_SETTLEMENT_MAX_PAGES = 4;
|
|
199
|
+
const SNAPSHOT_TABLE_SUFFIX = 'mastra_workflow_snapshot';
|
|
200
|
+
const SNAPSHOT_NAMESPACE_LIMIT = 64;
|
|
201
|
+
function orphanSettlementCandidates(prefixParameter) {
|
|
202
|
+
return `state = 'started' AND (
|
|
203
|
+
(start_token <> '' AND start_workflow_id IS NOT NULL AND start_table_prefix IS ${prefixParameter})
|
|
204
|
+
OR (${LEGACY_RESERVATION_SQL} AND run_id <> ''))`;
|
|
205
|
+
}
|
|
196
206
|
/**
|
|
197
207
|
* Rows affected by a write, read from D1's `{ meta: { changes } }` envelope.
|
|
198
208
|
* Restated here for the same reason execution-fence.ts restates it: every
|
|
@@ -260,6 +270,10 @@ export class StartReservationUnreadableError extends DoStatusError {
|
|
|
260
270
|
function isMissingReservationTable(error) {
|
|
261
271
|
return missingTableReadsEmpty(error, START_IDEMPOTENCY_TABLE);
|
|
262
272
|
}
|
|
273
|
+
function assertSettlementAge(age, minimum) {
|
|
274
|
+
if (!Number.isSafeInteger(age) || age < minimum)
|
|
275
|
+
throw new TypeError(`olderThanMs must be a safe integer of at least ${minimum}`);
|
|
276
|
+
}
|
|
263
277
|
function assertKey(key) {
|
|
264
278
|
if (!isPathSafeId(key)) {
|
|
265
279
|
throw new InvalidStartIdempotencyRequestError("idempotencyKey must be a URL-path-safe identifier (letters, digits, '.', '_', '~', '-'; 1-200 chars)");
|
|
@@ -446,7 +460,30 @@ export class StartIdempotencyStore {
|
|
|
446
460
|
}
|
|
447
461
|
/** Release only the exact unbound claim, without readback recovery. */
|
|
448
462
|
async releaseReservation(observed) {
|
|
449
|
-
|
|
463
|
+
return ((await this.#resetUnboundReservation(captureReservation(observed, 'started'))) !== undefined);
|
|
464
|
+
}
|
|
465
|
+
isExpiredUnboundReservation(reservation) {
|
|
466
|
+
return (reservation.binding.kind === 'unbound' &&
|
|
467
|
+
reservation.state !== 'terminal' &&
|
|
468
|
+
reservation.updatedAt <=
|
|
469
|
+
this.#reservationClock(reservation.key) - UNBOUND_RESERVATION_EXPIRY_MS);
|
|
470
|
+
}
|
|
471
|
+
async reviveUnboundReservation(observed) {
|
|
472
|
+
const reservation = captureReservation(observed, observed.state === 'terminal' ? 'terminal' : 'nonterminal');
|
|
473
|
+
if (!isAbandonedReservation(reservation) &&
|
|
474
|
+
!this.isExpiredUnboundReservation(reservation))
|
|
475
|
+
return undefined;
|
|
476
|
+
const revived = await this.#resetUnboundReservation(reservation);
|
|
477
|
+
if (revived) {
|
|
478
|
+
console.log(JSON.stringify({
|
|
479
|
+
type: 'start-reservation-revived',
|
|
480
|
+
key: revived.key,
|
|
481
|
+
runId: revived.runId,
|
|
482
|
+
}));
|
|
483
|
+
}
|
|
484
|
+
return revived;
|
|
485
|
+
}
|
|
486
|
+
async #resetUnboundReservation(reservation) {
|
|
450
487
|
const next = this.#nextReservationStamp(reservation);
|
|
451
488
|
await this.#requireReservationSchema(reservation.key);
|
|
452
489
|
let result;
|
|
@@ -457,7 +494,6 @@ export class StartIdempotencyStore {
|
|
|
457
494
|
AND owner_kind = ? AND owner_id = ?
|
|
458
495
|
AND target_kind = ? AND target_id = ? AND thread_id IS ?
|
|
459
496
|
AND created_at = ? AND updated_at = ? AND state = ?
|
|
460
|
-
AND state = 'started'
|
|
461
497
|
AND start_token = '' AND start_table_prefix IS NULL AND start_workflow_id IS NULL
|
|
462
498
|
RETURNING *`)
|
|
463
499
|
.bind(next, reservation.key, reservation.runId, reservation.owner.kind, reservation.owner.id, reservation.targetKind, reservation.targetId, reservation.threadId ?? null, reservation.createdAt, reservation.updatedAt, reservation.state)
|
|
@@ -469,8 +505,7 @@ export class StartIdempotencyStore {
|
|
|
469
505
|
});
|
|
470
506
|
}
|
|
471
507
|
try {
|
|
472
|
-
return
|
|
473
|
-
undefined);
|
|
508
|
+
return reservationMutationResult(result, reservation, 'reserved', next);
|
|
474
509
|
}
|
|
475
510
|
catch (error) {
|
|
476
511
|
throw new StartReservationUnreadableError(reservation.key, {
|
|
@@ -633,6 +668,190 @@ export class StartIdempotencyStore {
|
|
|
633
668
|
});
|
|
634
669
|
}
|
|
635
670
|
}
|
|
671
|
+
async abandonUnboundReservations({ olderThanMs, key, fence, principal = 'maintenance', }) {
|
|
672
|
+
assertSettlementAge(olderThanMs, UNBOUND_RESERVATION_EXPIRY_MS);
|
|
673
|
+
const safeKey = key === undefined ? undefined : assertKey(key);
|
|
674
|
+
if ((await this.#schemaStage()) !== 3)
|
|
675
|
+
return 0;
|
|
676
|
+
const now = this.#reservationClock(safeKey ?? 'abandon-unbound');
|
|
677
|
+
return this.#settleExpiredReservations(fence, {
|
|
678
|
+
bindings: [
|
|
679
|
+
now,
|
|
680
|
+
now - olderThanMs,
|
|
681
|
+
...(safeKey === undefined ? [] : [safeKey]),
|
|
682
|
+
],
|
|
683
|
+
eligibility: `state IN ('reserved', 'started') AND ${ABANDONABLE_RESERVATION_SQL}
|
|
684
|
+
${safeKey === undefined ? '' : 'AND key = ?3'}`,
|
|
685
|
+
audit: (row, observed) => ({
|
|
686
|
+
type: 'start-reservation-abandoned',
|
|
687
|
+
key: row.key,
|
|
688
|
+
ownerKind: row.owner.kind,
|
|
689
|
+
ownerId: row.owner.id,
|
|
690
|
+
targetKind: row.targetKind,
|
|
691
|
+
targetId: row.targetId,
|
|
692
|
+
ageMs: now - observed.updated_at,
|
|
693
|
+
principal,
|
|
694
|
+
}),
|
|
695
|
+
});
|
|
696
|
+
}
|
|
697
|
+
async settleOrphanedBoundReservations({ tablePrefix, olderThanMs, fence, settleAbsentWorkflowRuns = false, cursor, onPage, }) {
|
|
698
|
+
assertSettlementAge(olderThanMs, BOUND_RESERVATION_SETTLEMENT_AGE_MS);
|
|
699
|
+
const prefix = validateTablePrefix(tablePrefix)?.toLowerCase() ?? '';
|
|
700
|
+
if ((await this.#schemaStage()) !== 3)
|
|
701
|
+
return 0;
|
|
702
|
+
const now = this.#reservationClock('settle-orphaned-bound');
|
|
703
|
+
const cutoff = now - olderThanMs;
|
|
704
|
+
const snapshotTable = `${prefix}${SNAPSHOT_TABLE_SUFFIX}`;
|
|
705
|
+
const snapshotTablesSql = `SELECT lower(name) AS name FROM sqlite_schema
|
|
706
|
+
WHERE type IN ('table', 'view') AND lower(name) GLOB '*${SNAPSHOT_TABLE_SUFFIX}'`;
|
|
707
|
+
const { results: tables } = await this.#db
|
|
708
|
+
.prepare(`${snapshotTablesSql} LIMIT ${SNAPSHOT_NAMESPACE_LIMIT + 1}`)
|
|
709
|
+
.all();
|
|
710
|
+
if (!tables.length && !settleAbsentWorkflowRuns)
|
|
711
|
+
return 0;
|
|
712
|
+
if (tables.length > SNAPSHOT_NAMESPACE_LIMIT)
|
|
713
|
+
throw new Error('reservation settlement namespace overflow');
|
|
714
|
+
const names = tables.map(({ name }) => {
|
|
715
|
+
validateTablePrefix(name.slice(0, -SNAPSHOT_TABLE_SUFFIX.length));
|
|
716
|
+
return name;
|
|
717
|
+
});
|
|
718
|
+
let statusParameter = 6;
|
|
719
|
+
const terminal = RUN_TERMINAL_SNAPSHOT_SQL.replace(/\bsnapshot\b/g, 's.snapshot')
|
|
720
|
+
.replace(/\s{2,}/g, ' ')
|
|
721
|
+
.replaceAll('?', () => `?${statusParameter++}`);
|
|
722
|
+
// Legacy rows have no namespace, so a live snapshot in any prefix vetoes settlement.
|
|
723
|
+
const legacyRuns = names.map((name) => `SELECT 1 FROM "${name}" AS s WHERE s.run_id = r.run_id`);
|
|
724
|
+
const boundRun = names.includes(snapshotTable)
|
|
725
|
+
? `SELECT 1 FROM "${snapshotTable}" AS s
|
|
726
|
+
WHERE s.workflow_name = r.start_workflow_id AND s.run_id = r.run_id`
|
|
727
|
+
: undefined;
|
|
728
|
+
const snapshotExists = (predicate = '') => {
|
|
729
|
+
const legacy = legacyRuns
|
|
730
|
+
.map((run) => `EXISTS (${run}${predicate})`)
|
|
731
|
+
.join(' OR ');
|
|
732
|
+
const bound = boundRun ? `EXISTS (${boundRun}${predicate})` : '0';
|
|
733
|
+
return `(CASE WHEN r.start_token IS NULL THEN (${legacy || '0'}) ELSE ${bound} END)`;
|
|
734
|
+
};
|
|
735
|
+
const exists = snapshotExists();
|
|
736
|
+
const hasRunOrAbsenceProof = settleAbsentWorkflowRuns
|
|
737
|
+
? `(${exists} OR r.target_kind = 'workflow')`
|
|
738
|
+
: exists;
|
|
739
|
+
const liveRun = snapshotExists(` AND CASE WHEN json_valid(s.snapshot) THEN (${terminal}) IS NOT TRUE ELSE 1 END`);
|
|
740
|
+
const eligibleRun = `${hasRunOrAbsenceProof} AND NOT ${liveRun}
|
|
741
|
+
AND NOT EXISTS (${snapshotTablesSql} EXCEPT SELECT value FROM json_each(?5))`;
|
|
742
|
+
let settled = 0;
|
|
743
|
+
for (let page = 0; page < BOUND_SETTLEMENT_MAX_PAGES; page += 1) {
|
|
744
|
+
const result = await this.#db
|
|
745
|
+
.prepare(`SELECT key, updated_at FROM ${START_IDEMPOTENCY_TABLE}
|
|
746
|
+
WHERE updated_at <= ?1 AND ${orphanSettlementCandidates('?2')}
|
|
747
|
+
${cursor ? 'AND (updated_at, key) > (?3, ?4)' : ''}
|
|
748
|
+
ORDER BY updated_at, key LIMIT ${BOUND_SETTLEMENT_PAGE_SIZE}`)
|
|
749
|
+
.bind(cutoff, prefix, ...(cursor ? [cursor.updatedAt, cursor.key] : []))
|
|
750
|
+
.all();
|
|
751
|
+
const candidates = reservationResultRows(result).map((row) => {
|
|
752
|
+
if (!isPathSafeId(row.key) ||
|
|
753
|
+
typeof row.updated_at !== 'number' ||
|
|
754
|
+
!Number.isFinite(row.updated_at))
|
|
755
|
+
throw new Error('bound settlement candidate is malformed');
|
|
756
|
+
return { key: row.key, updatedAt: row.updated_at };
|
|
757
|
+
});
|
|
758
|
+
const last = candidates.at(-1);
|
|
759
|
+
if (last === undefined) {
|
|
760
|
+
if (cursor)
|
|
761
|
+
await onPage?.(0, undefined);
|
|
762
|
+
break;
|
|
763
|
+
}
|
|
764
|
+
const count = await this.#settleExpiredReservations(fence, {
|
|
765
|
+
bindings: [
|
|
766
|
+
now,
|
|
767
|
+
cutoff,
|
|
768
|
+
prefix,
|
|
769
|
+
JSON.stringify(candidates.map(({ key }) => key)),
|
|
770
|
+
JSON.stringify(names),
|
|
771
|
+
...(names.length ? RUN_TERMINAL_STATUSES : []),
|
|
772
|
+
],
|
|
773
|
+
candidateKeysParameter: '?4',
|
|
774
|
+
eligibility: `${orphanSettlementCandidates('?3')} AND ${eligibleRun}`,
|
|
775
|
+
runState: `CASE WHEN ${exists} THEN 'terminal' ELSE 'absent' END`,
|
|
776
|
+
audit: (row, observed) => ({
|
|
777
|
+
type: 'start-reservation-orphan-settled',
|
|
778
|
+
key: row.key,
|
|
779
|
+
runId: row.runId,
|
|
780
|
+
runState: observed.run_state,
|
|
781
|
+
ageMs: now - observed.updated_at,
|
|
782
|
+
}),
|
|
783
|
+
});
|
|
784
|
+
settled += count;
|
|
785
|
+
cursor =
|
|
786
|
+
candidates.length === BOUND_SETTLEMENT_PAGE_SIZE ? last : undefined;
|
|
787
|
+
await onPage?.(count, cursor);
|
|
788
|
+
if (!cursor)
|
|
789
|
+
break;
|
|
790
|
+
}
|
|
791
|
+
return settled;
|
|
792
|
+
}
|
|
793
|
+
async #settleExpiredReservations(fence, { bindings, eligibility, candidateKeysParameter, runState = 'NULL', audit, }) {
|
|
794
|
+
if (!fence.usesDatabase(this.#db))
|
|
795
|
+
throw new ExecutionFenceUnreadableError('reservation settlement fence uses a different database');
|
|
796
|
+
const observed = await fence.readForAdmission();
|
|
797
|
+
if (!admitsDrainableExecution(observed.reading))
|
|
798
|
+
throw new ExecutionFencedError(observed.reading.state);
|
|
799
|
+
const schema = await captureExecutionFenceAdmissionSchema(await this.#db
|
|
800
|
+
.prepare(`PRAGMA table_xinfo(${EXECUTION_FENCE_TABLE})`)
|
|
801
|
+
.all());
|
|
802
|
+
const semantic = executionFenceAdmissionValues(observed);
|
|
803
|
+
const values = [...bindings];
|
|
804
|
+
const bind = (value) => {
|
|
805
|
+
values.push(value);
|
|
806
|
+
return `?${values.length}`;
|
|
807
|
+
};
|
|
808
|
+
const gate = executionFenceAdmissionSql({
|
|
809
|
+
callerEpoch: bind(observed.reading.mutationEpoch),
|
|
810
|
+
semantic: semantic.map(bind),
|
|
811
|
+
schema: bind(schema),
|
|
812
|
+
statePredicate: "f.state IN ('open', 'draining')",
|
|
813
|
+
});
|
|
814
|
+
// CROSS JOIN makes the bounded list drive the snapshot checks.
|
|
815
|
+
const candidates = candidateKeysParameter
|
|
816
|
+
? `json_each(${candidateKeysParameter}) AS candidates
|
|
817
|
+
CROSS JOIN ${START_IDEMPOTENCY_TABLE} AS r ON r.key = candidates.value`
|
|
818
|
+
: `${START_IDEMPOTENCY_TABLE} AS r`;
|
|
819
|
+
// Materialize the pre-write timestamps for the audit in the same statement as the CAS.
|
|
820
|
+
const result = await this.#db
|
|
821
|
+
.prepare(`WITH eligible AS MATERIALIZED (
|
|
822
|
+
SELECT r.key, r.updated_at, ${runState} AS run_state FROM ${candidates}
|
|
823
|
+
WHERE updated_at <= ?2 AND ${eligibility} AND ${gate}
|
|
824
|
+
)
|
|
825
|
+
UPDATE ${START_IDEMPOTENCY_TABLE} SET state = 'terminal', updated_at = ?1
|
|
826
|
+
WHERE key IN (SELECT key FROM eligible)
|
|
827
|
+
RETURNING *,
|
|
828
|
+
(SELECT updated_at FROM eligible WHERE eligible.key = ${START_IDEMPOTENCY_TABLE}.key) AS previous_updated_at,
|
|
829
|
+
(SELECT run_state FROM eligible WHERE eligible.key = ${START_IDEMPOTENCY_TABLE}.key) AS run_state`)
|
|
830
|
+
.bind(...values)
|
|
831
|
+
.all();
|
|
832
|
+
const rows = reservationResultRows(result);
|
|
833
|
+
if (rows.length === 0) {
|
|
834
|
+
const after = await fence.readForAdmission();
|
|
835
|
+
if (!admitsDrainableExecution(after.reading))
|
|
836
|
+
throw new ExecutionFencedError(after.reading.state);
|
|
837
|
+
if (executionFenceAdmissionValues(after).some((value, index) => value !== semantic[index]))
|
|
838
|
+
throw new ExecutionFenceUnreadableError('execution fence changed during reservation settlement');
|
|
839
|
+
}
|
|
840
|
+
for (const raw of rows) {
|
|
841
|
+
const row = raw.run_id === ''
|
|
842
|
+
? reservationFromRow(raw, 3)
|
|
843
|
+
: admissionReservationFromRow(raw, 3);
|
|
844
|
+
const { previous_updated_at, run_state } = raw;
|
|
845
|
+
if (typeof previous_updated_at !== 'number' ||
|
|
846
|
+
!Number.isFinite(previous_updated_at) ||
|
|
847
|
+
(run_state !== null &&
|
|
848
|
+
run_state !== 'terminal' &&
|
|
849
|
+
run_state !== 'absent'))
|
|
850
|
+
throw new Error('reservation settlement returned an invalid observation');
|
|
851
|
+
console.log(JSON.stringify(audit(row, { updated_at: previous_updated_at, run_state })));
|
|
852
|
+
}
|
|
853
|
+
return rows.length;
|
|
854
|
+
}
|
|
636
855
|
#reservationClock(key) {
|
|
637
856
|
try {
|
|
638
857
|
const clock = this.#now();
|
|
@@ -811,7 +1030,12 @@ export class StartIdempotencyStore {
|
|
|
811
1030
|
return rows;
|
|
812
1031
|
}
|
|
813
1032
|
}
|
|
814
|
-
|
|
1033
|
+
function throwIfStartAborted(signal) {
|
|
1034
|
+
if (signal?.aborted)
|
|
1035
|
+
throw new IdempotentStartAbortedError();
|
|
1036
|
+
}
|
|
1037
|
+
export async function beginIdempotentStart(store, request, surface, fence, mutationEpoch, options) {
|
|
1038
|
+
const signal = options?.signal;
|
|
815
1039
|
const capturedRequest = captureStartRequest(request);
|
|
816
1040
|
const epoch = normalizeMutationEpoch(mutationEpoch);
|
|
817
1041
|
const { persisted, live } = surface;
|
|
@@ -835,7 +1059,9 @@ export async function beginIdempotentStart(store, request, surface, fence, mutat
|
|
|
835
1059
|
/* A failed observation cannot authorize nomination. */
|
|
836
1060
|
}
|
|
837
1061
|
}
|
|
1062
|
+
throwIfStartAborted(signal);
|
|
838
1063
|
const { reservation, created } = await store.reserve(capturedRequest);
|
|
1064
|
+
throwIfStartAborted(signal);
|
|
839
1065
|
let decision;
|
|
840
1066
|
// A creator can read back another caller's released reservation.
|
|
841
1067
|
if (created &&
|
|
@@ -843,12 +1069,17 @@ export async function beginIdempotentStart(store, request, surface, fence, mutat
|
|
|
843
1069
|
reservation.state === 'reserved' &&
|
|
844
1070
|
reservation.updatedAt === reservation.createdAt) {
|
|
845
1071
|
const claimed = await store.claimReservation(reservation);
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
1072
|
+
decision =
|
|
1073
|
+
claimed === undefined
|
|
1074
|
+
? await resolveLostClaim(store, reservation, capturedSurface, signal)
|
|
1075
|
+
: { kind: 'start', reservation: claimed };
|
|
849
1076
|
}
|
|
850
1077
|
else
|
|
851
|
-
decision = await resolveExistingReservation(store, reservation, capturedSurface, true);
|
|
1078
|
+
decision = await resolveExistingReservation(store, reservation, capturedSurface, true, signal);
|
|
1079
|
+
if (decision.kind === 'start' && signal?.aborted) {
|
|
1080
|
+
await store.releaseReservation(decision.reservation);
|
|
1081
|
+
throw new IdempotentStartAbortedError();
|
|
1082
|
+
}
|
|
852
1083
|
if (decision.kind === 'replay' &&
|
|
853
1084
|
proof !== undefined &&
|
|
854
1085
|
fence !== undefined &&
|
|
@@ -924,7 +1155,7 @@ function decodePersistedStart(value, row) {
|
|
|
924
1155
|
throw new StartReservationUnreadableError(row.key, { cause });
|
|
925
1156
|
}
|
|
926
1157
|
}
|
|
927
|
-
async function resolveExistingReservation(store, observed, surface, mayClaim) {
|
|
1158
|
+
async function resolveExistingReservation(store, observed, surface, mayClaim, signal) {
|
|
928
1159
|
if (observed.binding.kind === 'legacy') {
|
|
929
1160
|
if (observed.state === 'terminal')
|
|
930
1161
|
throw new IdempotentStartAlreadySettledError(observed);
|
|
@@ -933,6 +1164,8 @@ async function resolveExistingReservation(store, observed, surface, mayClaim) {
|
|
|
933
1164
|
const value = await surface.persisted(observed);
|
|
934
1165
|
if (value !== undefined) {
|
|
935
1166
|
const persisted = decodePersistedStart(value, observed);
|
|
1167
|
+
if (isAbandonedReservation(observed))
|
|
1168
|
+
throw new IdempotentStartPendingError(observed);
|
|
936
1169
|
if (observed.binding.kind === 'bound' &&
|
|
937
1170
|
!sameReservationExecution(observed, persisted.execution)) {
|
|
938
1171
|
if (observed.state === 'terminal')
|
|
@@ -946,21 +1179,30 @@ async function resolveExistingReservation(store, observed, surface, mayClaim) {
|
|
|
946
1179
|
reservation: observed,
|
|
947
1180
|
persisted: persisted.value,
|
|
948
1181
|
};
|
|
949
|
-
if (observed.state === 'terminal')
|
|
950
|
-
throw new IdempotentStartAlreadySettledError(observed);
|
|
951
1182
|
const reservation = await store.associateReservation(observed, persisted.execution);
|
|
952
1183
|
return { kind: 'replay', reservation, persisted: persisted.value };
|
|
953
1184
|
}
|
|
954
1185
|
}
|
|
955
|
-
else if (
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
if (
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
1186
|
+
else if (observed.binding.kind === 'unbound') {
|
|
1187
|
+
const revive = isAbandonedReservation(observed) ||
|
|
1188
|
+
store.isExpiredUnboundReservation(observed);
|
|
1189
|
+
if (revive || (mayClaim && observed.state === 'reserved')) {
|
|
1190
|
+
if (await surface.live(observed))
|
|
1191
|
+
throw new IdempotentStartPendingError(observed);
|
|
1192
|
+
throwIfStartAborted(signal);
|
|
1193
|
+
const candidate = revive
|
|
1194
|
+
? await store.reviveUnboundReservation(observed)
|
|
1195
|
+
: observed;
|
|
1196
|
+
if (!mayClaim)
|
|
1197
|
+
throw new IdempotentStartUnresolvableError(candidate ?? observed);
|
|
1198
|
+
if (candidate !== undefined) {
|
|
1199
|
+
throwIfStartAborted(signal);
|
|
1200
|
+
const claimed = await store.claimReservation(candidate);
|
|
1201
|
+
if (claimed !== undefined)
|
|
1202
|
+
return { kind: 'start', reservation: claimed };
|
|
1203
|
+
}
|
|
1204
|
+
return resolveLostClaim(store, observed, surface, signal);
|
|
1205
|
+
}
|
|
964
1206
|
}
|
|
965
1207
|
if (observed.state === 'terminal')
|
|
966
1208
|
throw new IdempotentStartAlreadySettledError(observed);
|
|
@@ -968,11 +1210,11 @@ async function resolveExistingReservation(store, observed, surface, mayClaim) {
|
|
|
968
1210
|
throw new IdempotentStartPendingError(observed);
|
|
969
1211
|
throw new IdempotentStartUnresolvableError(observed);
|
|
970
1212
|
}
|
|
971
|
-
async function resolveLostClaim(store, observed, surface) {
|
|
1213
|
+
async function resolveLostClaim(store, observed, surface, signal) {
|
|
972
1214
|
const current = await store.readForAdmission(observed.key);
|
|
973
1215
|
if (current === undefined || !sameReservationIdentity(current, observed))
|
|
974
1216
|
throw new StartReservationUnreadableError(observed.key);
|
|
975
|
-
return resolveExistingReservation(store, current, surface, false);
|
|
1217
|
+
return resolveExistingReservation(store, current, surface, false, signal);
|
|
976
1218
|
}
|
|
977
1219
|
/**
|
|
978
1220
|
* Resolve a surface's reservation wiring, refusing a key the host cannot
|