@abloatai/humans 0.60.0 → 0.61.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/local/BaseSyncedStore.js +5 -5
- package/dist/local/Model.js +46 -56
- package/dist/local/NetworkMonitor.js +2 -0
- package/dist/local/RuntimeContext.js +2 -0
- package/dist/local/SyncClient.d.ts +5 -29
- package/dist/local/SyncClient.js +26 -99
- package/dist/local/client/createModelOperations.js +6 -4
- package/dist/local/fileUploads.d.ts +27 -0
- package/dist/local/fileUploads.js +55 -0
- package/dist/local/stores/syncAction.d.ts +1 -1
- package/dist/local/sync/contextOnChange.js +1 -1
- package/dist/local/sync/createClaimStream.js +1 -1
- package/dist/local/sync/deltaPipeline.js +12 -6
- package/dist/local/sync/schemas.d.ts +2 -2
- package/dist/local/transactions/localMutation.js +3 -3
- package/dist/local/transactions/mutations/MutationQueue.d.ts +1 -2
- package/dist/local/transactions/mutations/MutationQueue.js +25 -51
- package/dist/local/transactions/mutations/batchProcessing.js +23 -10
- package/dist/local/transactions/mutations/commitPayload.d.ts +8 -1
- package/dist/local/transactions/mutations/commitTransport.js +3 -1
- package/dist/local/transactions/mutations/executionSelection.d.ts +0 -1
- package/dist/local/transactions/mutations/executionSelection.js +9 -17
- package/dist/local/transactions/mutations/failureHandling.js +9 -0
- package/dist/local/transactions/mutations/localMutation.js +3 -3
- package/dist/local/transactions/mutations/queueCoalescing.js +8 -0
- package/dist/react/useErrorListener.js +1 -1
- package/dist/react/useMutationFailureListener.js +1 -1
- package/package.json +3 -4
- package/src/local/BaseSyncedStore.ts +5 -5
- package/src/local/Model.ts +45 -55
- package/src/local/NetworkMonitor.ts +2 -0
- package/src/local/RuntimeContext.ts +2 -0
- package/src/local/SyncClient.ts +33 -127
- package/src/local/client/createModelOperations.ts +9 -6
- package/src/local/fileUploads.ts +97 -0
- package/src/local/sync/contextOnChange.ts +1 -1
- package/src/local/sync/createClaimStream.ts +1 -1
- package/src/local/sync/deltaPipeline.ts +10 -6
- package/src/local/transactions/localMutation.ts +3 -3
- package/src/local/transactions/mutations/MutationQueue.ts +24 -53
- package/src/local/transactions/mutations/batchProcessing.ts +25 -10
- package/src/local/transactions/mutations/commitPayload.ts +11 -1
- package/src/local/transactions/mutations/commitTransport.ts +2 -2
- package/src/local/transactions/mutations/executionSelection.ts +9 -15
- package/src/local/transactions/mutations/failureHandling.ts +10 -0
- package/src/local/transactions/mutations/localMutation.ts +3 -3
- package/src/local/transactions/mutations/queueCoalescing.ts +6 -0
- package/src/react/useErrorListener.ts +1 -1
- package/src/react/useMutationFailureListener.ts +1 -1
- package/dist/local/transactions/mutations/pendingDrain.d.ts +0 -33
- package/dist/local/transactions/mutations/pendingDrain.js +0 -117
- package/src/local/transactions/mutations/pendingDrain.ts +0 -169
|
@@ -4,8 +4,12 @@ export function takeNextExecutionBatch(
|
|
|
4
4
|
executionQueue: QueuedMutation[],
|
|
5
5
|
maxBatchSize: number,
|
|
6
6
|
): { batch: QueuedMutation[]; remaining: QueuedMutation[] } {
|
|
7
|
+
// Cancellation, delta confirmation, and failure settlement can all make a
|
|
8
|
+
// queued reference terminal before its scheduler callback runs. Terminal or
|
|
9
|
+
// currently executing rows have no authority to cross the dispatch boundary.
|
|
10
|
+
const pendingQueue = executionQueue.filter((tx) => tx.status === 'pending');
|
|
7
11
|
const retryGroups = new Map<string, Map<string, QueuedMutation>>();
|
|
8
|
-
for (const tx of
|
|
12
|
+
for (const tx of pendingQueue) {
|
|
9
13
|
const envelope = tx.commitEnvelope;
|
|
10
14
|
if (!envelope) continue;
|
|
11
15
|
const group = retryGroups.get(envelope.idempotencyKey) ?? new Map<string, QueuedMutation>();
|
|
@@ -16,27 +20,17 @@ export function takeNextExecutionBatch(
|
|
|
16
20
|
const members = [...byId.values()];
|
|
17
21
|
const expectedCount = members[0]?.commitEnvelope?.operationCount;
|
|
18
22
|
if (expectedCount === undefined || members.length !== expectedCount) continue;
|
|
19
|
-
const remaining =
|
|
23
|
+
const remaining = pendingQueue.filter((tx) => tx.commitEnvelope?.idempotencyKey !== idempotencyKey);
|
|
20
24
|
members.sort((a, b) => (a.commitEnvelope?.operationIndex ?? 0) - (b.commitEnvelope?.operationIndex ?? 0));
|
|
21
25
|
return { batch: members, remaining };
|
|
22
26
|
}
|
|
23
|
-
const fresh =
|
|
27
|
+
const fresh = pendingQueue.filter((tx) => !tx.commitEnvelope);
|
|
24
28
|
const firstFresh = fresh[0];
|
|
25
|
-
if (!firstFresh) return { batch: [], remaining:
|
|
29
|
+
if (!firstFresh) return { batch: [], remaining: pendingQueue };
|
|
26
30
|
const explicitIndex = fresh.findIndex((tx) => typeof tx.writeOptions?.idempotencyKey === 'string');
|
|
27
31
|
const selected = explicitIndex === 0
|
|
28
32
|
? [firstFresh]
|
|
29
33
|
: fresh.slice(0, Math.min(maxBatchSize, explicitIndex > 0 ? explicitIndex : fresh.length));
|
|
30
34
|
const selectedIds = new Set(selected.map((tx) => tx.id));
|
|
31
|
-
return { batch: selected, remaining:
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
export function takePendingDrainBatch(pending: QueuedMutation[], maxBatchSize: number): QueuedMutation[] {
|
|
35
|
-
const first = pending[0];
|
|
36
|
-
if (!first) return [];
|
|
37
|
-
const envelope = first.commitEnvelope;
|
|
38
|
-
if (envelope) return pending.filter((tx) => tx.commitEnvelope?.idempotencyKey === envelope.idempotencyKey);
|
|
39
|
-
if (typeof first.writeOptions?.idempotencyKey === 'string') return [first];
|
|
40
|
-
const explicitIndex = pending.findIndex((tx) => typeof tx.writeOptions?.idempotencyKey === 'string');
|
|
41
|
-
return pending.slice(0, Math.min(maxBatchSize, explicitIndex > 0 ? explicitIndex : pending.length));
|
|
35
|
+
return { batch: selected, remaining: pendingQueue.filter((tx) => !selectedIds.has(tx.id)) };
|
|
42
36
|
}
|
|
@@ -44,6 +44,16 @@ export async function handleFailure(
|
|
|
44
44
|
transaction: QueuedMutation,
|
|
45
45
|
error: Error,
|
|
46
46
|
): Promise<void> {
|
|
47
|
+
// The dispatch owner may lose its acknowledgement while an authoritative
|
|
48
|
+
// delta concurrently completes the same transaction. Completion is
|
|
49
|
+
// terminal: a late catch path must not turn that row back into `pending`
|
|
50
|
+
// and schedule a second seal after its durable sources were cleaned up.
|
|
51
|
+
if (
|
|
52
|
+
transaction.status === 'completed' ||
|
|
53
|
+
transaction.status === 'failed' ||
|
|
54
|
+
transaction.status === 'rolled_back' ||
|
|
55
|
+
transaction.status === 'awaiting_delta'
|
|
56
|
+
) return;
|
|
47
57
|
transaction.attempts++;
|
|
48
58
|
|
|
49
59
|
// Check whether this is a permanent error that should not be retried.
|
|
@@ -43,9 +43,9 @@ export function createLocalMutationPort(emitter: OptimisticEmitter): LocalMutati
|
|
|
43
43
|
const updates = new Map<string, OptimisticUpdateEntry>();
|
|
44
44
|
return {
|
|
45
45
|
updates,
|
|
46
|
-
applyCreate: (model, transaction) => applyOptimisticCreate(updates, emitter, model, transaction),
|
|
47
|
-
applyUpdate: (model, transaction) => applyOptimisticUpdate(updates, emitter, model, transaction),
|
|
48
|
-
applyDelete: (model, transaction) => applyOptimisticDelete(updates, emitter, model, transaction),
|
|
46
|
+
applyCreate: (model, transaction) => { applyOptimisticCreate(updates, emitter, model, transaction); },
|
|
47
|
+
applyUpdate: (model, transaction) => { applyOptimisticUpdate(updates, emitter, model, transaction); },
|
|
48
|
+
applyDelete: (model, transaction) => { applyOptimisticDelete(updates, emitter, model, transaction); },
|
|
49
49
|
rollback: (transaction, reason, error) => rollbackOptimistic(updates, emitter, transaction, reason, error),
|
|
50
50
|
};
|
|
51
51
|
}
|
|
@@ -12,6 +12,12 @@ export interface QueueCoalescingContext {
|
|
|
12
12
|
}
|
|
13
13
|
|
|
14
14
|
export function enqueueTransaction(ctx: QueueCoalescingContext, transaction: QueuedMutation): void {
|
|
15
|
+
// Only the pending state may cross into the execution owner. A late timer,
|
|
16
|
+
// reconnect callback, or stale staging callback must not resurrect a row
|
|
17
|
+
// that is already executing or terminal, and repeated triggers must not put
|
|
18
|
+
// the same source mutation into the queue twice.
|
|
19
|
+
if (transaction.status !== 'pending') return;
|
|
20
|
+
if (ctx.executionQueue.some((candidate) => candidate.id === transaction.id)) return;
|
|
15
21
|
ctx.ensureDerivedFields(transaction);
|
|
16
22
|
const modelKey = `${transaction.modelName}:${transaction.modelId}`;
|
|
17
23
|
if (transaction.type === 'update' && transaction.attempts === 0 && !transaction.commitEnvelope) {
|
|
@@ -16,7 +16,7 @@ export function useErrorListener(listener: (error: Error) => void): void {
|
|
|
16
16
|
const listenerRef = useRef(listener);
|
|
17
17
|
listenerRef.current = listener;
|
|
18
18
|
useEffect(
|
|
19
|
-
() => context.subscribeError((error) => listenerRef.current(error)),
|
|
19
|
+
() => context.subscribeError((error) => { listenerRef.current(error); }),
|
|
20
20
|
[context],
|
|
21
21
|
);
|
|
22
22
|
}
|
|
@@ -29,6 +29,6 @@ export function useMutationFailureListener(
|
|
|
29
29
|
useEffect(() => {
|
|
30
30
|
const engine = context.engine;
|
|
31
31
|
if (!engine) return;
|
|
32
|
-
return engine.onMutationFailure((payload) => listenerRef.current(payload));
|
|
32
|
+
return engine.onMutationFailure((payload) => { listenerRef.current(payload); });
|
|
33
33
|
}, [context, context.engine]);
|
|
34
34
|
}
|
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
import type { RuntimeContext } from '../../RuntimeContext.js';
|
|
2
|
-
import type { QueuedMutation } from './commitPayload.js';
|
|
3
|
-
import type { MutationStore } from './MutationStore.js';
|
|
4
|
-
import type { OptimisticUpdateEntry } from './localMutation.js';
|
|
5
|
-
import type { MutationCommitResult } from '@abloatai/transaction/commit';
|
|
6
|
-
import type { DurableCommitEnvelope } from '@abloatai/transaction/commit';
|
|
7
|
-
export interface PendingDrainContext {
|
|
8
|
-
readonly runtime: RuntimeContext;
|
|
9
|
-
readonly config: {
|
|
10
|
-
deltaConfirmationTimeout: number;
|
|
11
|
-
};
|
|
12
|
-
readonly store: MutationStore;
|
|
13
|
-
readonly executionQueue: QueuedMutation[];
|
|
14
|
-
readonly optimisticUpdates: Map<string, OptimisticUpdateEntry>;
|
|
15
|
-
readonly assertDurableReplayOpen: () => void;
|
|
16
|
-
readonly processCommitLane: () => Promise<void>;
|
|
17
|
-
readonly takePendingDrainBatch: (pending: QueuedMutation[]) => QueuedMutation[];
|
|
18
|
-
readonly ensureCommitEnvelope: (batch: QueuedMutation[]) => string;
|
|
19
|
-
readonly ensureDerivedFields: (transaction: QueuedMutation) => void;
|
|
20
|
-
readonly sourceMutationIdsFor: (batch: readonly QueuedMutation[]) => string[];
|
|
21
|
-
readonly sealDurableCommit: (input: Parameters<typeof import('./commitTransport.js').sealDurableCommit>[1]) => Promise<DurableCommitEnvelope>;
|
|
22
|
-
readonly assertEnvelopeInsideReplayWindow: (envelope: DurableCommitEnvelope) => void;
|
|
23
|
-
readonly parseMutationCommitResult: (value: Awaited<ReturnType<import('../../interfaces/index.js').MutationExecutor['commit']>>) => MutationCommitResult;
|
|
24
|
-
readonly dispatchCommitBounded: (...args: Parameters<import('../../interfaces/index.js').MutationExecutor['commit']>) => ReturnType<import('../../interfaces/index.js').MutationExecutor['commit']>;
|
|
25
|
-
readonly persistDurableCommitAcceptance: (envelope: DurableCommitEnvelope, result: MutationCommitResult) => Promise<DurableCommitEnvelope>;
|
|
26
|
-
readonly removeDurableCommit: (idempotencyKey: string) => Promise<void>;
|
|
27
|
-
readonly scheduleReplicationLagTimeout: (transactionId: string, clientTxId?: string, correlationId?: string) => void;
|
|
28
|
-
readonly scheduleDeltaConfirmationTimeout: (transaction: QueuedMutation, timeoutMs: number) => void;
|
|
29
|
-
readonly enqueue: (transaction: QueuedMutation) => void;
|
|
30
|
-
readonly recentDeltaCorrelations: Map<string, number>;
|
|
31
|
-
readonly emit: (event: string, payload: object) => boolean;
|
|
32
|
-
}
|
|
33
|
-
export declare function drainPendingConfirmations(ctx: PendingDrainContext): Promise<void>;
|
|
@@ -1,117 +0,0 @@
|
|
|
1
|
-
import { applyWriteOptions, collectQueuedReads, TX_TYPE_TO_MUTATION_OP } from './commitPayload.js';
|
|
2
|
-
export async function drainPendingConfirmations(ctx) {
|
|
3
|
-
ctx.assertDurableReplayOpen();
|
|
4
|
-
// Kick the commit lane too: atomic envelopes from `commits.create()` may
|
|
5
|
-
// have been left at the head of the lane while the connection was down.
|
|
6
|
-
// Fire-and-forget; processCommitLane serializes itself.
|
|
7
|
-
void ctx.processCommitLane();
|
|
8
|
-
// Collect pending transactions in created order
|
|
9
|
-
const pending = ctx.store.getByStatus('pending').sort((a, b) => a.createdAt - b.createdAt);
|
|
10
|
-
if (pending.length === 0)
|
|
11
|
-
return;
|
|
12
|
-
const pendingIds = new Set(pending.map((tx) => tx.id));
|
|
13
|
-
// These rows may already be waiting behind the normal batch timer. The
|
|
14
|
-
// reconnect fast path takes ownership of them for this attempt so the same
|
|
15
|
-
// transaction cannot dispatch concurrently through both paths.
|
|
16
|
-
const retainedQueue = ctx.executionQueue.filter((tx) => !pendingIds.has(tx.id));
|
|
17
|
-
ctx.executionQueue.splice(0, ctx.executionQueue.length, ...retainedQueue);
|
|
18
|
-
const remaining = [...pending];
|
|
19
|
-
while (remaining.length > 0) {
|
|
20
|
-
const batch = ctx.takePendingDrainBatch(remaining);
|
|
21
|
-
if (batch.length === 0)
|
|
22
|
-
break;
|
|
23
|
-
const batchIds = new Set(batch.map((tx) => tx.id));
|
|
24
|
-
const nextRemaining = remaining.filter((tx) => !batchIds.has(tx.id));
|
|
25
|
-
try {
|
|
26
|
-
const idempotencyKey = ctx.ensureCommitEnvelope(batch);
|
|
27
|
-
const projectedOperations = batch.map((tx) => {
|
|
28
|
-
ctx.ensureDerivedFields(tx);
|
|
29
|
-
return applyWriteOptions({
|
|
30
|
-
type: TX_TYPE_TO_MUTATION_OP[tx.type],
|
|
31
|
-
model: tx.modelKey,
|
|
32
|
-
id: tx.modelId,
|
|
33
|
-
input: tx.type === 'create' || tx.type === 'update' ? tx.data || {} : undefined,
|
|
34
|
-
transactionId: tx.id,
|
|
35
|
-
}, tx);
|
|
36
|
-
});
|
|
37
|
-
const durableEnvelope = await ctx.sealDurableCommit({
|
|
38
|
-
idempotencyKey,
|
|
39
|
-
origin: 'model_batch',
|
|
40
|
-
operations: projectedOperations,
|
|
41
|
-
sourceMutationIds: ctx.sourceMutationIdsFor(batch),
|
|
42
|
-
commitOptions: { reads: collectQueuedReads(batch) },
|
|
43
|
-
createdAt: Math.min(...batch.map((transaction) => transaction.createdAt)),
|
|
44
|
-
sealedAt: batch[0]?.commitEnvelope?.sealedAt ?? Date.now(),
|
|
45
|
-
sequence: batch[0]?.commitEnvelope?.sequence,
|
|
46
|
-
});
|
|
47
|
-
ctx.assertEnvelopeInsideReplayWindow(durableEnvelope);
|
|
48
|
-
const result = ctx.parseMutationCommitResult(await ctx.dispatchCommitBounded(durableEnvelope.operations, {
|
|
49
|
-
idempotencyKey,
|
|
50
|
-
...(durableEnvelope.commitOptions.reads !== undefined
|
|
51
|
-
? { reads: durableEnvelope.commitOptions.reads }
|
|
52
|
-
: {}),
|
|
53
|
-
}));
|
|
54
|
-
await ctx.persistDurableCommitAcceptance(durableEnvelope, result);
|
|
55
|
-
if (result.status === 'queued') {
|
|
56
|
-
// Reconnect flushes use the same accepted-vs-confirmed contract as
|
|
57
|
-
// the normal lane. A queued source receipt retains the envelope and
|
|
58
|
-
// waits for exact correlation; it is never promoted by the reconnect
|
|
59
|
-
// shortcut itself.
|
|
60
|
-
for (const tx of batch) {
|
|
61
|
-
tx.requiresCorrelatedDelta = true;
|
|
62
|
-
tx.syncIdNeededForCompletion = undefined;
|
|
63
|
-
tx.correlationId = result.correlationId;
|
|
64
|
-
const echoSyncId = result.correlationId
|
|
65
|
-
? ctx.recentDeltaCorrelations.get(result.correlationId)
|
|
66
|
-
: undefined;
|
|
67
|
-
if (echoSyncId !== undefined) {
|
|
68
|
-
ctx.store.updateStatus(tx.id, 'completed');
|
|
69
|
-
ctx.emit('transaction:completed', tx);
|
|
70
|
-
ctx.emit(`transaction:completed:${tx.id}`, tx);
|
|
71
|
-
ctx.optimisticUpdates.delete(tx.id);
|
|
72
|
-
continue;
|
|
73
|
-
}
|
|
74
|
-
ctx.store.updateStatus(tx.id, 'awaiting_delta');
|
|
75
|
-
ctx.scheduleReplicationLagTimeout(tx.id, idempotencyKey, result.correlationId);
|
|
76
|
-
ctx.scheduleDeltaConfirmationTimeout(tx, ctx.config.deltaConfirmationTimeout);
|
|
77
|
-
}
|
|
78
|
-
if (batch.every((tx) => tx.status === 'completed')) {
|
|
79
|
-
await ctx.removeDurableCommit(idempotencyKey);
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
else {
|
|
83
|
-
await ctx.removeDurableCommit(idempotencyKey);
|
|
84
|
-
// Mark this request envelope as completed before moving to the next.
|
|
85
|
-
for (const tx of batch) {
|
|
86
|
-
ctx.store.updateStatus(tx.id, 'completed');
|
|
87
|
-
ctx.emit('transaction:completed', tx);
|
|
88
|
-
ctx.emit(`transaction:completed:${tx.id}`, tx);
|
|
89
|
-
ctx.optimisticUpdates.delete(tx.id);
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
ctx.runtime.logger.debug('txn:commit', 0, {
|
|
93
|
-
count: batch.length,
|
|
94
|
-
lastSyncId: result.lastSyncId,
|
|
95
|
-
});
|
|
96
|
-
remaining.splice(0, remaining.length, ...nextRemaining);
|
|
97
|
-
}
|
|
98
|
-
catch (err) {
|
|
99
|
-
// If one request fails, hand it and every later request back to the
|
|
100
|
-
// normal lane. Their envelopes stay attached for safe retry.
|
|
101
|
-
const networkUnavailable = !ctx.runtime.onlineStatus.isOnline();
|
|
102
|
-
const isNetworkError = err instanceof Error &&
|
|
103
|
-
(err.message.includes('Failed to fetch') ||
|
|
104
|
-
err.message.includes('Network request failed') ||
|
|
105
|
-
err.message.includes('NetworkError'));
|
|
106
|
-
if (!networkUnavailable || !isNetworkError) {
|
|
107
|
-
ctx.runtime.observability.breadcrumb('Batch flush fallback failed', 'sync.transaction', 'warning', {
|
|
108
|
-
error: err instanceof Error ? err.message : String(err),
|
|
109
|
-
});
|
|
110
|
-
}
|
|
111
|
-
for (const tx of [...batch, ...nextRemaining]) {
|
|
112
|
-
ctx.enqueue(tx);
|
|
113
|
-
}
|
|
114
|
-
return;
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
}
|
|
@@ -1,169 +0,0 @@
|
|
|
1
|
-
import type { RuntimeContext } from '../../RuntimeContext.js';
|
|
2
|
-
import type { QueuedMutation } from './commitPayload.js';
|
|
3
|
-
import type { MutationStore } from './MutationStore.js';
|
|
4
|
-
import type { OptimisticUpdateEntry } from './localMutation.js';
|
|
5
|
-
import type { MutationCommitResult } from '@abloatai/transaction/commit';
|
|
6
|
-
import type { DurableCommitEnvelope } from '@abloatai/transaction/commit';
|
|
7
|
-
import { applyWriteOptions, collectQueuedReads, TX_TYPE_TO_MUTATION_OP } from './commitPayload.js';
|
|
8
|
-
|
|
9
|
-
export interface PendingDrainContext {
|
|
10
|
-
readonly runtime: RuntimeContext;
|
|
11
|
-
readonly config: { deltaConfirmationTimeout: number };
|
|
12
|
-
readonly store: MutationStore;
|
|
13
|
-
readonly executionQueue: QueuedMutation[];
|
|
14
|
-
readonly optimisticUpdates: Map<string, OptimisticUpdateEntry>;
|
|
15
|
-
readonly assertDurableReplayOpen: () => void;
|
|
16
|
-
readonly processCommitLane: () => Promise<void>;
|
|
17
|
-
readonly takePendingDrainBatch: (pending: QueuedMutation[]) => QueuedMutation[];
|
|
18
|
-
readonly ensureCommitEnvelope: (batch: QueuedMutation[]) => string;
|
|
19
|
-
readonly ensureDerivedFields: (transaction: QueuedMutation) => void;
|
|
20
|
-
readonly sourceMutationIdsFor: (batch: readonly QueuedMutation[]) => string[];
|
|
21
|
-
readonly sealDurableCommit: (input: Parameters<typeof import('./commitTransport.js').sealDurableCommit>[1]) => Promise<DurableCommitEnvelope>;
|
|
22
|
-
readonly assertEnvelopeInsideReplayWindow: (envelope: DurableCommitEnvelope) => void;
|
|
23
|
-
readonly parseMutationCommitResult: (value: Awaited<ReturnType<import('../../interfaces/index.js').MutationExecutor['commit']>>) => MutationCommitResult;
|
|
24
|
-
readonly dispatchCommitBounded: (...args: Parameters<import('../../interfaces/index.js').MutationExecutor['commit']>) => ReturnType<import('../../interfaces/index.js').MutationExecutor['commit']>;
|
|
25
|
-
readonly persistDurableCommitAcceptance: (envelope: DurableCommitEnvelope, result: MutationCommitResult) => Promise<DurableCommitEnvelope>;
|
|
26
|
-
readonly removeDurableCommit: (idempotencyKey: string) => Promise<void>;
|
|
27
|
-
readonly scheduleReplicationLagTimeout: (transactionId: string, clientTxId?: string, correlationId?: string) => void;
|
|
28
|
-
readonly scheduleDeltaConfirmationTimeout: (transaction: QueuedMutation, timeoutMs: number) => void;
|
|
29
|
-
readonly enqueue: (transaction: QueuedMutation) => void;
|
|
30
|
-
readonly recentDeltaCorrelations: Map<string, number>;
|
|
31
|
-
readonly emit: (event: string, payload: object) => boolean;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
export async function drainPendingConfirmations(ctx: PendingDrainContext): Promise<void> {
|
|
35
|
-
ctx.assertDurableReplayOpen();
|
|
36
|
-
// Kick the commit lane too: atomic envelopes from `commits.create()` may
|
|
37
|
-
// have been left at the head of the lane while the connection was down.
|
|
38
|
-
// Fire-and-forget; processCommitLane serializes itself.
|
|
39
|
-
void ctx.processCommitLane();
|
|
40
|
-
|
|
41
|
-
// Collect pending transactions in created order
|
|
42
|
-
const pending = ctx.store.getByStatus('pending').sort((a, b) => a.createdAt - b.createdAt);
|
|
43
|
-
if (pending.length === 0) return;
|
|
44
|
-
const pendingIds = new Set(pending.map((tx) => tx.id));
|
|
45
|
-
// These rows may already be waiting behind the normal batch timer. The
|
|
46
|
-
// reconnect fast path takes ownership of them for this attempt so the same
|
|
47
|
-
// transaction cannot dispatch concurrently through both paths.
|
|
48
|
-
const retainedQueue = ctx.executionQueue.filter(
|
|
49
|
-
(tx) => !pendingIds.has(tx.id),
|
|
50
|
-
);
|
|
51
|
-
ctx.executionQueue.splice(
|
|
52
|
-
0,
|
|
53
|
-
ctx.executionQueue.length,
|
|
54
|
-
...retainedQueue,
|
|
55
|
-
);
|
|
56
|
-
|
|
57
|
-
const remaining = [...pending];
|
|
58
|
-
while (remaining.length > 0) {
|
|
59
|
-
const batch = ctx.takePendingDrainBatch(remaining);
|
|
60
|
-
if (batch.length === 0) break;
|
|
61
|
-
const batchIds = new Set(batch.map((tx) => tx.id));
|
|
62
|
-
const nextRemaining = remaining.filter((tx) => !batchIds.has(tx.id));
|
|
63
|
-
|
|
64
|
-
try {
|
|
65
|
-
const idempotencyKey = ctx.ensureCommitEnvelope(batch);
|
|
66
|
-
const projectedOperations = batch.map((tx) => {
|
|
67
|
-
ctx.ensureDerivedFields(tx);
|
|
68
|
-
return applyWriteOptions(
|
|
69
|
-
{
|
|
70
|
-
type: TX_TYPE_TO_MUTATION_OP[tx.type],
|
|
71
|
-
model: tx.modelKey,
|
|
72
|
-
id: tx.modelId,
|
|
73
|
-
input: tx.type === 'create' || tx.type === 'update' ? tx.data || {} : undefined,
|
|
74
|
-
transactionId: tx.id,
|
|
75
|
-
},
|
|
76
|
-
tx,
|
|
77
|
-
);
|
|
78
|
-
});
|
|
79
|
-
const durableEnvelope = await ctx.sealDurableCommit({
|
|
80
|
-
idempotencyKey,
|
|
81
|
-
origin: 'model_batch',
|
|
82
|
-
operations: projectedOperations,
|
|
83
|
-
sourceMutationIds: ctx.sourceMutationIdsFor(batch),
|
|
84
|
-
commitOptions: { reads: collectQueuedReads(batch) },
|
|
85
|
-
createdAt: Math.min(...batch.map((transaction) => transaction.createdAt)),
|
|
86
|
-
sealedAt: batch[0]?.commitEnvelope?.sealedAt ?? Date.now(),
|
|
87
|
-
sequence: batch[0]?.commitEnvelope?.sequence,
|
|
88
|
-
});
|
|
89
|
-
ctx.assertEnvelopeInsideReplayWindow(durableEnvelope);
|
|
90
|
-
const result = ctx.parseMutationCommitResult(
|
|
91
|
-
await ctx.dispatchCommitBounded(durableEnvelope.operations, {
|
|
92
|
-
idempotencyKey,
|
|
93
|
-
...(durableEnvelope.commitOptions.reads !== undefined
|
|
94
|
-
? { reads: durableEnvelope.commitOptions.reads }
|
|
95
|
-
: {}),
|
|
96
|
-
}),
|
|
97
|
-
);
|
|
98
|
-
await ctx.persistDurableCommitAcceptance(durableEnvelope, result);
|
|
99
|
-
if (result.status === 'queued') {
|
|
100
|
-
// Reconnect flushes use the same accepted-vs-confirmed contract as
|
|
101
|
-
// the normal lane. A queued source receipt retains the envelope and
|
|
102
|
-
// waits for exact correlation; it is never promoted by the reconnect
|
|
103
|
-
// shortcut itself.
|
|
104
|
-
for (const tx of batch) {
|
|
105
|
-
tx.requiresCorrelatedDelta = true;
|
|
106
|
-
tx.syncIdNeededForCompletion = undefined;
|
|
107
|
-
tx.correlationId = result.correlationId;
|
|
108
|
-
const echoSyncId = result.correlationId
|
|
109
|
-
? ctx.recentDeltaCorrelations.get(result.correlationId)
|
|
110
|
-
: undefined;
|
|
111
|
-
if (echoSyncId !== undefined) {
|
|
112
|
-
ctx.store.updateStatus(tx.id, 'completed');
|
|
113
|
-
ctx.emit('transaction:completed', tx);
|
|
114
|
-
ctx.emit(`transaction:completed:${tx.id}`, tx);
|
|
115
|
-
ctx.optimisticUpdates.delete(tx.id);
|
|
116
|
-
continue;
|
|
117
|
-
}
|
|
118
|
-
ctx.store.updateStatus(tx.id, 'awaiting_delta');
|
|
119
|
-
ctx.scheduleReplicationLagTimeout(
|
|
120
|
-
tx.id,
|
|
121
|
-
idempotencyKey,
|
|
122
|
-
result.correlationId,
|
|
123
|
-
);
|
|
124
|
-
ctx.scheduleDeltaConfirmationTimeout(
|
|
125
|
-
tx,
|
|
126
|
-
ctx.config.deltaConfirmationTimeout,
|
|
127
|
-
);
|
|
128
|
-
}
|
|
129
|
-
if (batch.every((tx) => tx.status === 'completed')) {
|
|
130
|
-
await ctx.removeDurableCommit(idempotencyKey);
|
|
131
|
-
}
|
|
132
|
-
} else {
|
|
133
|
-
await ctx.removeDurableCommit(idempotencyKey);
|
|
134
|
-
// Mark this request envelope as completed before moving to the next.
|
|
135
|
-
for (const tx of batch) {
|
|
136
|
-
ctx.store.updateStatus(tx.id, 'completed');
|
|
137
|
-
ctx.emit('transaction:completed', tx);
|
|
138
|
-
ctx.emit(`transaction:completed:${tx.id}`, tx);
|
|
139
|
-
ctx.optimisticUpdates.delete(tx.id);
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
ctx.runtime.logger.debug('txn:commit', 0, {
|
|
143
|
-
count: batch.length,
|
|
144
|
-
lastSyncId: result.lastSyncId,
|
|
145
|
-
});
|
|
146
|
-
remaining.splice(0, remaining.length, ...nextRemaining);
|
|
147
|
-
} catch (err) {
|
|
148
|
-
// If one request fails, hand it and every later request back to the
|
|
149
|
-
// normal lane. Their envelopes stay attached for safe retry.
|
|
150
|
-
const networkUnavailable = !ctx.runtime.onlineStatus.isOnline();
|
|
151
|
-
const isNetworkError =
|
|
152
|
-
err instanceof Error &&
|
|
153
|
-
(err.message.includes('Failed to fetch') ||
|
|
154
|
-
err.message.includes('Network request failed') ||
|
|
155
|
-
err.message.includes('NetworkError'));
|
|
156
|
-
|
|
157
|
-
if (!networkUnavailable || !isNetworkError) {
|
|
158
|
-
ctx.runtime.observability.breadcrumb('Batch flush fallback failed', 'sync.transaction', 'warning', {
|
|
159
|
-
error: err instanceof Error ? err.message : String(err),
|
|
160
|
-
});
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
for (const tx of [...batch, ...nextRemaining]) {
|
|
164
|
-
ctx.enqueue(tx);
|
|
165
|
-
}
|
|
166
|
-
return;
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
}
|