@abloatai/humans 0.59.2 → 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/README.md +1 -1
- package/dist/Ablo.d.ts +2 -10
- package/dist/Ablo.js +0 -1
- package/dist/client.d.ts +1 -48
- package/dist/humans.d.ts +1 -1
- package/dist/local/BaseSyncedStore.d.ts +5 -5
- package/dist/local/BaseSyncedStore.js +7 -7
- package/dist/local/Database.d.ts +2 -2
- package/dist/local/LazyReferenceCollection.d.ts +1 -1
- 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 +12 -36
- package/dist/local/SyncClient.js +50 -108
- package/dist/local/client/createModelOperations.d.ts +3 -27
- package/dist/local/client/createModelOperations.js +20 -21
- package/dist/local/client/options.d.ts +14 -39
- package/dist/local/client/reactiveEngine.d.ts +3 -9
- package/dist/local/client/reactiveEngine.js +6 -151
- package/dist/local/client/storeLifecycle.js +5 -1
- package/dist/local/fileUploads.d.ts +27 -0
- package/dist/local/fileUploads.js +55 -0
- package/dist/local/storeContract.d.ts +5 -5
- package/dist/local/stores/syncAction.d.ts +4 -4
- package/dist/local/sync/contextOnChange.js +1 -1
- package/dist/local/sync/createClaimStream.js +1 -1
- package/dist/local/sync/credentialLifecycle.d.ts +4 -5
- package/dist/local/sync/credentialLifecycle.js +4 -5
- package/dist/local/sync/deltaPipeline.js +12 -6
- package/dist/local/sync/schemas.d.ts +10 -10
- package/dist/local/sync/scopeGroups.d.ts +11 -0
- package/dist/local/sync/scopeGroups.js +75 -0
- package/dist/local/sync/wsFrameHandlers.d.ts +1 -1
- package/dist/local/transactions/localMutation.js +3 -3
- package/dist/local/transactions/mutations/MutationQueue.d.ts +4 -5
- 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 +9 -2
- 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/local/transactions/mutations/replayValidation.d.ts +15 -15
- package/dist/react/AbloProvider.d.ts +11 -86
- package/dist/react/AbloProvider.js +11 -163
- package/dist/react/ClientSideSuspense.d.ts +1 -1
- package/dist/react/DefaultFallback.d.ts +1 -1
- package/dist/react/createAbloReact.js +1 -1
- package/dist/react/useErrorListener.js +1 -1
- package/dist/react/useMutationFailureListener.js +1 -1
- package/dist/react.d.ts +1 -1
- package/dist/react.js +1 -1
- package/dist/surface.d.ts +3 -3
- package/dist/surface.js +1 -4
- package/package.json +3 -3
- package/src/Ablo.ts +5 -17
- package/src/client.ts +0 -51
- package/src/local/BaseSyncedStore.ts +14 -14
- 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 +73 -140
- package/src/local/client/createModelOperations.ts +30 -64
- package/src/local/client/options.ts +20 -43
- package/src/local/client/reactiveEngine.ts +7 -179
- package/src/local/client/storeLifecycle.ts +6 -1
- package/src/local/fileUploads.ts +97 -0
- package/src/local/storeContract.ts +5 -5
- package/src/local/sync/contextOnChange.ts +1 -1
- package/src/local/sync/createClaimStream.ts +1 -1
- package/src/local/sync/credentialLifecycle.ts +4 -5
- package/src/local/sync/deltaPipeline.ts +10 -6
- package/src/local/sync/scopeGroups.ts +91 -0
- package/src/local/sync/wsFrameHandlers.ts +0 -1
- 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/AbloProvider.tsx +17 -249
- package/src/react/useErrorListener.ts +1 -1
- package/src/react/useMutationFailureListener.ts +1 -1
- package/src/react.ts +1 -5
- package/src/surface.ts +1 -4
- package/dist/local/sync/participants.d.ts +0 -132
- package/dist/local/sync/participants.js +0 -342
- package/dist/local/transactions/mutations/pendingDrain.d.ts +0 -33
- package/dist/local/transactions/mutations/pendingDrain.js +0 -117
- package/src/local/sync/participants.ts +0 -564
- package/src/local/transactions/mutations/pendingDrain.ts +0 -169
|
@@ -1,342 +0,0 @@
|
|
|
1
|
-
import { scopeKindOf } from '@abloatai/transaction/schema/model';
|
|
2
|
-
import { AbloValidationError } from '@abloatai/transaction/errors';
|
|
3
|
-
import { subTarget, streamTarget, wireTarget, } from '@abloatai/transaction/coordination';
|
|
4
|
-
export function createParticipantManager(config) {
|
|
5
|
-
return {
|
|
6
|
-
async join(input, overrides) {
|
|
7
|
-
const options = normalizeJoinOptions(input, overrides);
|
|
8
|
-
const target = options.focus ?? options.target
|
|
9
|
-
? targetToEntityRef((options.focus ?? options.target))
|
|
10
|
-
: null;
|
|
11
|
-
const syncGroups = unique(resolveParticipantSyncGroups(options.scope ?? target ?? undefined, config.schema));
|
|
12
|
-
await config.ready();
|
|
13
|
-
// Not-connected joins surface through `sendClaim`'s diagnosed
|
|
14
|
-
// rejection below; a scopeless join needs no wire send at all.
|
|
15
|
-
const transport = config.transport;
|
|
16
|
-
const claimId = createParticipantClaimId();
|
|
17
|
-
if (syncGroups.length > 0) {
|
|
18
|
-
await transport.sendClaim(claimId, syncGroups, {
|
|
19
|
-
capabilityToken: options.capabilityToken,
|
|
20
|
-
// `ttl` is the spelling; `ttlSeconds` is the deprecated one, read
|
|
21
|
-
// second so a caller passing both gets the current name honored.
|
|
22
|
-
// eslint-disable-next-line @typescript-eslint/no-deprecated -- reading the deprecated alias IS the back-compat this line provides
|
|
23
|
-
ttlSeconds: parseParticipantTtlSeconds(options.ttl ?? options.ttlSeconds),
|
|
24
|
-
});
|
|
25
|
-
}
|
|
26
|
-
const participant = createJoinedParticipant({
|
|
27
|
-
target,
|
|
28
|
-
syncGroups,
|
|
29
|
-
claimId,
|
|
30
|
-
transport,
|
|
31
|
-
presence: config.presence,
|
|
32
|
-
claims: config.claims,
|
|
33
|
-
});
|
|
34
|
-
if (target && options.activity !== false) {
|
|
35
|
-
const activity = options.activity ?? 'reading';
|
|
36
|
-
if (activity === 'editing') {
|
|
37
|
-
participant.presence.editing(options.detail);
|
|
38
|
-
}
|
|
39
|
-
else if (activity === 'viewing') {
|
|
40
|
-
participant.presence.viewing(options.detail);
|
|
41
|
-
}
|
|
42
|
-
else {
|
|
43
|
-
participant.presence.reading(options.detail);
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
return participant;
|
|
47
|
-
},
|
|
48
|
-
};
|
|
49
|
-
}
|
|
50
|
-
export function resolveParticipantSyncGroups(scope, schema) {
|
|
51
|
-
if (!scope)
|
|
52
|
-
return [];
|
|
53
|
-
if (typeof scope === 'string')
|
|
54
|
-
return [scope];
|
|
55
|
-
if (Array.isArray(scope)) {
|
|
56
|
-
return scope.flatMap((entry) => typeof entry === 'string' ? [entry] : [syncGroupFromEntityRef(entry, schema)]);
|
|
57
|
-
}
|
|
58
|
-
const direct = scope;
|
|
59
|
-
if (isEntityScope(scope))
|
|
60
|
-
return [syncGroupFromEntityRef(scope, schema)];
|
|
61
|
-
if (typeof direct.syncGroup === 'string')
|
|
62
|
-
return [direct.syncGroup];
|
|
63
|
-
if (Array.isArray(direct.syncGroups)) {
|
|
64
|
-
return direct.syncGroups.filter((g) => typeof g === 'string');
|
|
65
|
-
}
|
|
66
|
-
const out = [];
|
|
67
|
-
for (const [key, value] of Object.entries(scope)) {
|
|
68
|
-
if (value === undefined)
|
|
69
|
-
continue;
|
|
70
|
-
if (Array.isArray(value)) {
|
|
71
|
-
for (const id of value)
|
|
72
|
-
out.push(syncGroupFromSchemaKey(key, id, schema));
|
|
73
|
-
}
|
|
74
|
-
else {
|
|
75
|
-
out.push(syncGroupFromSchemaKey(key, value, schema));
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
return out;
|
|
79
|
-
}
|
|
80
|
-
/**
|
|
81
|
-
* The group kind for a model, in the wire dialect every plane shares: a
|
|
82
|
-
* declared scope root wins; otherwise the lowercased typename — the same
|
|
83
|
-
* token the commit plane and claim targets use (`wireModel`). Never the
|
|
84
|
-
* camelCase schema key: the server validates inbound subscription groups
|
|
85
|
-
* against a lowercase-only grammar, so a key like `reportBlocks` would be
|
|
86
|
-
* rejected as malformed on subscribe — and even a lowercase key would put
|
|
87
|
-
* this client in a different group than a peer who resolved the same row
|
|
88
|
-
* through an entity ref, so the two would never see each other's claims.
|
|
89
|
-
*/
|
|
90
|
-
function groupKindForModel(def, key) {
|
|
91
|
-
return scopeKindOf(def, key) ?? (def.typename ?? key).toLowerCase();
|
|
92
|
-
}
|
|
93
|
-
export function syncGroupFromEntityRef(ref, schema) {
|
|
94
|
-
const match = findModelForEntityRef(ref, schema);
|
|
95
|
-
const kind = match
|
|
96
|
-
? groupKindForModel(match.def, match.key)
|
|
97
|
-
: ref.type.toLowerCase();
|
|
98
|
-
return `${kind}:${ref.id}`;
|
|
99
|
-
}
|
|
100
|
-
function syncGroupFromSchemaKey(schemaKey, id, schema) {
|
|
101
|
-
const def = schema?.models?.[schemaKey];
|
|
102
|
-
const kind = def ? groupKindForModel(def, schemaKey) : schemaKey.toLowerCase();
|
|
103
|
-
return `${kind}:${id}`;
|
|
104
|
-
}
|
|
105
|
-
function findModelForEntityRef(ref, schema) {
|
|
106
|
-
if (!schema?.models)
|
|
107
|
-
return null;
|
|
108
|
-
const wanted = ref.type.toLowerCase();
|
|
109
|
-
for (const [key, def] of Object.entries(schema.models)) {
|
|
110
|
-
const typename = def.typename ?? key;
|
|
111
|
-
if (typename.toLowerCase() === wanted || key.toLowerCase() === wanted) {
|
|
112
|
-
return { key, def };
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
return null;
|
|
116
|
-
}
|
|
117
|
-
export function parseParticipantTtlSeconds(value) {
|
|
118
|
-
if (typeof value === 'number' && Number.isFinite(value))
|
|
119
|
-
return value;
|
|
120
|
-
if (!value)
|
|
121
|
-
return undefined;
|
|
122
|
-
if (typeof value !== 'string')
|
|
123
|
-
return undefined;
|
|
124
|
-
const match = /^(\d+(?:\.\d+)?)(ms|s|m|h)?$/.exec(value.trim());
|
|
125
|
-
if (!match)
|
|
126
|
-
return undefined;
|
|
127
|
-
const amount = Number(match[1]);
|
|
128
|
-
const unit = match[2] ?? 's';
|
|
129
|
-
if (unit === 'ms')
|
|
130
|
-
return Math.max(1, Math.ceil(amount / 1000));
|
|
131
|
-
if (unit === 'm')
|
|
132
|
-
return Math.ceil(amount * 60);
|
|
133
|
-
if (unit === 'h')
|
|
134
|
-
return Math.ceil(amount * 3600);
|
|
135
|
-
return Math.ceil(amount);
|
|
136
|
-
}
|
|
137
|
-
export function createParticipantClaimId() {
|
|
138
|
-
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
|
139
|
-
return `participant:${crypto.randomUUID()}`;
|
|
140
|
-
}
|
|
141
|
-
return `participant:${Date.now()}:${Math.random().toString(36).slice(2)}`;
|
|
142
|
-
}
|
|
143
|
-
function normalizeJoinOptions(input, overrides) {
|
|
144
|
-
if (isTupleTarget(input) || isEntityScope(input)) {
|
|
145
|
-
return { ...overrides, target: input };
|
|
146
|
-
}
|
|
147
|
-
return { ...input, ...overrides };
|
|
148
|
-
}
|
|
149
|
-
function isTupleTarget(value) {
|
|
150
|
-
return (Array.isArray(value) &&
|
|
151
|
-
typeof value[0] === 'string' &&
|
|
152
|
-
typeof value[1] === 'string');
|
|
153
|
-
}
|
|
154
|
-
function isEntityScope(scope) {
|
|
155
|
-
return (typeof scope === 'object' &&
|
|
156
|
-
scope !== null &&
|
|
157
|
-
!Array.isArray(scope) &&
|
|
158
|
-
typeof scope.type === 'string' &&
|
|
159
|
-
typeof scope.id === 'string');
|
|
160
|
-
}
|
|
161
|
-
function targetToEntityRef(target) {
|
|
162
|
-
if (isTupleTarget(target))
|
|
163
|
-
return { type: target[0], id: target[1] };
|
|
164
|
-
return target;
|
|
165
|
-
}
|
|
166
|
-
function unique(values) {
|
|
167
|
-
return [...new Set(values)];
|
|
168
|
-
}
|
|
169
|
-
function createJoinedParticipant(args) {
|
|
170
|
-
const ownHandles = new Set();
|
|
171
|
-
let currentTarget = args.target;
|
|
172
|
-
let left = false;
|
|
173
|
-
const requireTarget = (target) => {
|
|
174
|
-
const resolved = target ? targetToEntityRef(target) : currentTarget;
|
|
175
|
-
if (!resolved) {
|
|
176
|
-
throw new AbloValidationError('Participant action requires a structured target', {
|
|
177
|
-
code: 'invalid_request',
|
|
178
|
-
});
|
|
179
|
-
}
|
|
180
|
-
return resolved;
|
|
181
|
-
};
|
|
182
|
-
const setFocus = (target, options) => {
|
|
183
|
-
currentTarget = targetToEntityRef(target);
|
|
184
|
-
if (options?.activity === 'editing') {
|
|
185
|
-
scopedPresence.editing(options.detail);
|
|
186
|
-
}
|
|
187
|
-
else if (options?.activity === 'viewing') {
|
|
188
|
-
scopedPresence.viewing(options.detail);
|
|
189
|
-
}
|
|
190
|
-
else if (options?.activity === 'reading') {
|
|
191
|
-
scopedPresence.reading(options.detail);
|
|
192
|
-
}
|
|
193
|
-
return joined;
|
|
194
|
-
};
|
|
195
|
-
const resolvePresenceAction = (targetOrDetail, detail) => {
|
|
196
|
-
if (typeof targetOrDetail === 'string' || targetOrDetail === undefined) {
|
|
197
|
-
return { target: requireTarget(), detail: targetOrDetail ?? detail };
|
|
198
|
-
}
|
|
199
|
-
return { target: requireTarget(targetOrDetail), detail };
|
|
200
|
-
};
|
|
201
|
-
const scopedPresence = {
|
|
202
|
-
get self() {
|
|
203
|
-
return args.presence.self;
|
|
204
|
-
},
|
|
205
|
-
get focus() {
|
|
206
|
-
return currentTarget;
|
|
207
|
-
},
|
|
208
|
-
get others() {
|
|
209
|
-
return args.presence.others.filter((entry) => presenceMatchesParticipant(entry, currentTarget, args.syncGroups));
|
|
210
|
-
},
|
|
211
|
-
update(activity) {
|
|
212
|
-
args.presence.update(activity);
|
|
213
|
-
},
|
|
214
|
-
reading(targetOrDetail, detail) {
|
|
215
|
-
const action = resolvePresenceAction(targetOrDetail, detail);
|
|
216
|
-
args.presence.update({
|
|
217
|
-
...activityFromTarget(action.target),
|
|
218
|
-
action: 'reading',
|
|
219
|
-
detail: action.detail,
|
|
220
|
-
});
|
|
221
|
-
},
|
|
222
|
-
viewing(targetOrDetail, detail) {
|
|
223
|
-
const action = resolvePresenceAction(targetOrDetail, detail);
|
|
224
|
-
args.presence.viewing(action.target, action.detail);
|
|
225
|
-
},
|
|
226
|
-
editing(targetOrDetail, detail) {
|
|
227
|
-
const action = resolvePresenceAction(targetOrDetail, detail);
|
|
228
|
-
args.presence.editing(action.target, action.detail);
|
|
229
|
-
},
|
|
230
|
-
idle() {
|
|
231
|
-
args.presence.idle();
|
|
232
|
-
},
|
|
233
|
-
onChange(listener) {
|
|
234
|
-
return args.presence.onChange(listener);
|
|
235
|
-
},
|
|
236
|
-
};
|
|
237
|
-
const track = (handle) => {
|
|
238
|
-
ownHandles.add(handle);
|
|
239
|
-
return {
|
|
240
|
-
object: 'claim',
|
|
241
|
-
id: handle.id,
|
|
242
|
-
description: handle.description,
|
|
243
|
-
target: handle.target,
|
|
244
|
-
async release() {
|
|
245
|
-
ownHandles.delete(handle);
|
|
246
|
-
await handle.release?.();
|
|
247
|
-
},
|
|
248
|
-
revoke() {
|
|
249
|
-
ownHandles.delete(handle);
|
|
250
|
-
handle.revoke?.();
|
|
251
|
-
},
|
|
252
|
-
[Symbol.asyncDispose]: async () => {
|
|
253
|
-
ownHandles.delete(handle);
|
|
254
|
-
await handle[Symbol.asyncDispose]?.();
|
|
255
|
-
},
|
|
256
|
-
};
|
|
257
|
-
};
|
|
258
|
-
const scopedClaims = {
|
|
259
|
-
get focus() {
|
|
260
|
-
return currentTarget;
|
|
261
|
-
},
|
|
262
|
-
get others() {
|
|
263
|
-
return args.claims.others.filter((claim) => currentTarget ? targetsOverlap(claim.target, currentTarget) : true);
|
|
264
|
-
},
|
|
265
|
-
claim(opts) {
|
|
266
|
-
return track(args.claims.claim(requireTarget(opts?.target), {
|
|
267
|
-
description: opts?.description,
|
|
268
|
-
ttl: opts?.ttl,
|
|
269
|
-
}));
|
|
270
|
-
},
|
|
271
|
-
onRejected(listener) {
|
|
272
|
-
return args.claims.onRejected(listener);
|
|
273
|
-
},
|
|
274
|
-
onChange(listener) {
|
|
275
|
-
return args.claims.onChange(listener);
|
|
276
|
-
},
|
|
277
|
-
};
|
|
278
|
-
const leave = () => {
|
|
279
|
-
if (left)
|
|
280
|
-
return;
|
|
281
|
-
left = true;
|
|
282
|
-
for (const handle of Array.from(ownHandles)) {
|
|
283
|
-
handle.revoke?.();
|
|
284
|
-
ownHandles.delete(handle);
|
|
285
|
-
}
|
|
286
|
-
args.presence.idle();
|
|
287
|
-
if (args.syncGroups.length > 0) {
|
|
288
|
-
args.transport.sendRelease(args.claimId);
|
|
289
|
-
}
|
|
290
|
-
};
|
|
291
|
-
const joined = {
|
|
292
|
-
get target() {
|
|
293
|
-
return currentTarget;
|
|
294
|
-
},
|
|
295
|
-
get focusTarget() {
|
|
296
|
-
return currentTarget;
|
|
297
|
-
},
|
|
298
|
-
syncGroups: [...args.syncGroups],
|
|
299
|
-
presence: scopedPresence,
|
|
300
|
-
claims: scopedClaims,
|
|
301
|
-
get peers() {
|
|
302
|
-
return scopedPresence.others;
|
|
303
|
-
},
|
|
304
|
-
get activeClaims() {
|
|
305
|
-
return scopedClaims.others;
|
|
306
|
-
},
|
|
307
|
-
focus: setFocus,
|
|
308
|
-
leave,
|
|
309
|
-
[Symbol.asyncDispose]: async () => {
|
|
310
|
-
leave();
|
|
311
|
-
},
|
|
312
|
-
};
|
|
313
|
-
return joined;
|
|
314
|
-
}
|
|
315
|
-
function activityFromTarget(target) {
|
|
316
|
-
return {
|
|
317
|
-
...wireTarget(target),
|
|
318
|
-
...subTarget(target),
|
|
319
|
-
};
|
|
320
|
-
}
|
|
321
|
-
function presenceMatchesParticipant(entry, target, syncGroups) {
|
|
322
|
-
if (syncGroups.some((g) => entry.syncGroups.includes(g)))
|
|
323
|
-
return true;
|
|
324
|
-
if (!target)
|
|
325
|
-
return true;
|
|
326
|
-
return targetsOverlap({
|
|
327
|
-
...streamTarget(entry.activity),
|
|
328
|
-
...subTarget(entry.activity),
|
|
329
|
-
}, target);
|
|
330
|
-
}
|
|
331
|
-
function targetsOverlap(a, b) {
|
|
332
|
-
if (a.type !== b.type || a.id !== b.id)
|
|
333
|
-
return false;
|
|
334
|
-
if (!hasSubtarget(a) || !hasSubtarget(b))
|
|
335
|
-
return true;
|
|
336
|
-
// Field is the floor: same field overlaps, different fields do not. Sub-field
|
|
337
|
-
// targeting returns when same-field concurrency (OT) is solved.
|
|
338
|
-
return !a.field || !b.field || a.field === b.field;
|
|
339
|
-
}
|
|
340
|
-
function hasSubtarget(target) {
|
|
341
|
-
return Boolean(target.field);
|
|
342
|
-
}
|
|
@@ -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
|
-
}
|