payload-canvas 0.1.0 → 0.2.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 +202 -26
- package/dist/admin/editor/Canvas.js +30 -8
- package/dist/admin/editor/Editor.js +2 -0
- package/dist/admin/editor/Inspector.js +14 -7
- package/dist/admin/editor/Outline.js +15 -9
- package/dist/admin/editor/Overlay.js +2 -1
- package/dist/admin/editor/actions.d.ts +5 -0
- package/dist/admin/editor/actions.js +23 -1
- package/dist/admin/editor/counts.d.ts +6 -0
- package/dist/admin/editor/counts.js +10 -0
- package/dist/admin/editor/dnd/displace.js +3 -1
- package/dist/admin/editor/editor.scss +53 -0
- package/dist/admin/editor/inline.d.ts +12 -0
- package/dist/admin/editor/inline.js +48 -3
- package/dist/admin/editor/insert/spots.js +4 -2
- package/dist/admin/editor/live/useMultiplayer.js +8 -2
- package/dist/admin/editor/media/ImageEditor.js +21 -15
- package/dist/admin/editor/media/actions.d.ts +13 -9
- package/dist/admin/editor/media/actions.js +67 -28
- package/dist/admin/editor/media/model.d.ts +8 -0
- package/dist/admin/editor/media/model.js +14 -6
- package/dist/admin/editor/menu/blockMenu.js +13 -8
- package/dist/admin/editor/regions/RegionOverlay.d.ts +18 -0
- package/dist/admin/editor/regions/RegionOverlay.js +44 -0
- package/dist/admin/editor/regions/RegionPane.d.ts +5 -0
- package/dist/admin/editor/regions/RegionPane.js +26 -0
- package/dist/admin/editor/regions/RegionRows.d.ts +1 -0
- package/dist/admin/editor/regions/RegionRows.js +23 -0
- package/dist/admin/editor/regions/controller.d.ts +73 -0
- package/dist/admin/editor/regions/controller.js +231 -0
- package/dist/admin/editor/regions/select.d.ts +17 -0
- package/dist/admin/editor/regions/select.js +31 -0
- package/dist/admin/editor/runtime.d.ts +6 -0
- package/dist/admin/editor/runtime.js +49 -4
- package/dist/admin/editor/sections/controller.d.ts +6 -2
- package/dist/admin/editor/sections/controller.js +9 -3
- package/dist/admin/editor/shortcuts.js +11 -4
- package/dist/admin/editor/storage.d.ts +7 -0
- package/dist/admin/editor/storage.js +15 -0
- package/dist/admin/editor/store.d.ts +39 -0
- package/dist/admin/editor/store.js +106 -2
- package/dist/admin/editor/templates/Bindable.js +1 -1
- package/dist/admin/editor/templates/SamplePicker.js +1 -1
- package/dist/admin/editor/topbar/DocumentActions.js +38 -5
- package/dist/admin/editor/topbar/closeSave.d.ts +50 -0
- package/dist/admin/editor/topbar/closeSave.js +90 -0
- package/dist/admin/editor/topbar/document.d.ts +10 -2
- package/dist/admin/editor/topbar/document.js +9 -1
- package/dist/admin/editor/topbar/drawerLabels.d.ts +22 -0
- package/dist/admin/editor/topbar/drawerLabels.js +69 -0
- package/dist/admin/editor/topbar/problems.d.ts +9 -0
- package/dist/admin/editor/topbar/problems.js +15 -1
- package/dist/admin/editor/topbar/settingsDrawer.js +88 -4
- package/dist/admin/editor/topbar/settingsFocus.d.ts +11 -0
- package/dist/admin/editor/topbar/settingsFocus.js +46 -0
- package/dist/admin/editor/ui/payloadA11y.d.ts +17 -0
- package/dist/admin/editor/ui/payloadA11y.js +12 -5
- package/dist/admin/editor/valueStore.d.ts +2 -0
- package/dist/admin/editor/valueStore.js +6 -0
- package/dist/core/dropTarget.js +3 -1
- package/dist/core/index.d.ts +2 -0
- package/dist/core/index.js +2 -0
- package/dist/core/payloadBlocks.d.ts +53 -0
- package/dist/core/payloadBlocks.js +391 -0
- package/dist/core/regions.d.ts +63 -0
- package/dist/core/regions.js +239 -0
- package/dist/core/types.d.ts +53 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/live/document.d.ts +9 -1
- package/dist/live/document.js +57 -17
- package/dist/live/draftAccess.d.ts +36 -0
- package/dist/live/draftAccess.js +146 -0
- package/dist/live/endpoints.d.ts +11 -2
- package/dist/live/endpoints.js +120 -10
- package/dist/live/fieldChecks.d.ts +3 -3
- package/dist/live/fieldsGuard.d.ts +56 -2
- package/dist/live/fieldsGuard.js +107 -11
- package/dist/live/index.d.ts +2 -0
- package/dist/live/index.js +2 -0
- package/dist/live/regions.d.ts +89 -0
- package/dist/live/regions.js +401 -0
- package/dist/live/runtime.d.ts +1 -1
- package/dist/live/runtime.js +5 -2
- package/dist/live/session.d.ts +74 -9
- package/dist/live/session.js +655 -123
- package/dist/live/storage.d.ts +97 -0
- package/dist/live/storage.js +269 -0
- package/dist/live/types.d.ts +64 -0
- package/dist/live/writeGate.d.ts +72 -0
- package/dist/live/writeGate.js +478 -0
- package/dist/mcp/index.js +56 -12
- package/dist/plugin/hook.d.ts +44 -6
- package/dist/plugin/hook.js +176 -20
- package/dist/plugin/index.d.ts +23 -1
- package/dist/plugin/index.js +172 -10
- package/dist/plugin/references.d.ts +4 -2
- package/dist/plugin/references.js +2 -0
- package/dist/plugin/sectionsBuilder.js +3 -3
- package/dist/protocol/index.d.ts +28 -2
- package/dist/react/canvas/BuilderCanvas.js +198 -8
- package/dist/react/canvas/frame.d.ts +70 -0
- package/dist/react/canvas/frame.js +66 -0
- package/dist/react/canvas/inline/dom.d.ts +7 -1
- package/dist/react/canvas/inline/dom.js +19 -9
- package/dist/react/canvas/inline/mapper.d.ts +26 -0
- package/dist/react/canvas/inline/mapper.js +59 -32
- package/dist/react/canvas/inline/session.d.ts +7 -1
- package/dist/react/canvas/inline/session.js +6 -2
- package/dist/react/canvas/measure.js +26 -1
- package/dist/react/index.d.ts +2 -0
- package/dist/react/index.js +2 -0
- package/dist/react/render/LayoutOutlet.d.ts +11 -0
- package/dist/react/render/LayoutOutlet.js +16 -0
- package/dist/react/render/canvasFrame.d.ts +46 -0
- package/dist/react/render/canvasFrame.js +59 -0
- package/dist/react/render/canvasServer.d.ts +13 -0
- package/dist/react/render/canvasServer.js +3 -0
- package/dist/react/render/canvasServerTypes.d.ts +17 -0
- package/dist/react/render/regions.d.ts +13 -0
- package/dist/react/render/regions.js +8 -0
- package/dist/react/server.d.ts +2 -1
- package/dist/react/server.js +1 -0
- package/package.json +1 -1
package/dist/live/session.js
CHANGED
|
@@ -8,11 +8,15 @@
|
|
|
8
8
|
//
|
|
9
9
|
// In-process only: with more than one app server, route each document to one server (sticky
|
|
10
10
|
// routing), because the session state lives in memory.
|
|
11
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
11
12
|
import { sameJson } from '../core/fieldSemantics.js';
|
|
12
13
|
import { indexLayout, normalizeLayout } from '../core/tree.js';
|
|
13
14
|
import { validateLayout } from '../core/validate.js';
|
|
14
15
|
import { actorFromUser, payloadErrorMessage, resolveOperations, splitLayoutErrors } from './apply.js';
|
|
15
16
|
import { createKeyedMutex } from './mutex.js';
|
|
17
|
+
import { sameValue } from './fieldsGuard.js';
|
|
18
|
+
import { JSON_CODEC } from './storage.js';
|
|
19
|
+
import { writeKey } from './writeGate.js';
|
|
16
20
|
/** The actor of the commits that bring hook changes from a save to the editors. */
|
|
17
21
|
export const FIELD_HOOKS_ACTOR = { type: 'user', id: 'system:field-hooks', label: 'Field hooks' };
|
|
18
22
|
/** Session key of a document. */
|
|
@@ -84,6 +88,19 @@ export function sanitizeAwareness(value) {
|
|
|
84
88
|
...(field ? { field } : {}),
|
|
85
89
|
};
|
|
86
90
|
}
|
|
91
|
+
/**
|
|
92
|
+
* True when two reads of the document's other fields hold exactly the same values (`sameJson`),
|
|
93
|
+
* `updatedAt` included: an access rule may read any of them, so a save that changed only
|
|
94
|
+
* `updatedAt` is a change too. Not the form comparison of fieldsGuard.ts (`sameValue`): it treats
|
|
95
|
+
* '' and null, or 1 and '1', as one value, and two documents with one id and timestamp as equal.
|
|
96
|
+
*/
|
|
97
|
+
function sameFields(a, b) {
|
|
98
|
+
return sameJson(a, b);
|
|
99
|
+
}
|
|
100
|
+
/** How often `withCurrentDoc` runs a check while saves keep changing the document. */
|
|
101
|
+
const CURRENT_DOC_TRIES = 3;
|
|
102
|
+
/** How often a session save reads the stored layout while outside saves keep changing it. */
|
|
103
|
+
const EXTERNAL_SYNC_TRIES = 3;
|
|
87
104
|
const realTimers = {
|
|
88
105
|
now: () => Date.now(),
|
|
89
106
|
// Unref'd: session timers never keep a process alive. The shutdown flush saves unsaved work.
|
|
@@ -94,8 +111,24 @@ const realTimers = {
|
|
|
94
111
|
const HOOK_CHANGES_KEY = 'builderHookChanges';
|
|
95
112
|
/** `context` flag of reads that need every locale (`ALL_LOCALES_CONTEXT` in plugin/hook.ts). */
|
|
96
113
|
const ALL_LOCALES_KEY = 'builderAllLocales';
|
|
97
|
-
|
|
98
|
-
|
|
114
|
+
/** Adds the row ids of the session's stored value to its own rows. */
|
|
115
|
+
function rememberRows(session) {
|
|
116
|
+
for (const id of codecOfTarget(session.target).rowIds?.(session.stored) ?? [])
|
|
117
|
+
session.ownRowIds.add(id);
|
|
118
|
+
}
|
|
119
|
+
/** The answer of a session save that found nothing left to write. */
|
|
120
|
+
const SKIPPED = Symbol('skipped');
|
|
121
|
+
/**
|
|
122
|
+
* The session save waits: a reset action owns the layout until its save or rollback finishes, or
|
|
123
|
+
* a committed save's hook changes are not in the layout yet (`session.adopting`).
|
|
124
|
+
*/
|
|
125
|
+
const PAUSED = Symbol('paused');
|
|
126
|
+
/** How a session's field stores its layout. */
|
|
127
|
+
const codecOfTarget = (target) => target.codec ?? JSON_CODEC;
|
|
128
|
+
/** The prop hook changes the save hook recorded for the session's document (per document, see plugin/hook.ts). */
|
|
129
|
+
function hookChangesIn(context, target) {
|
|
130
|
+
const entries = context[HOOK_CHANGES_KEY];
|
|
131
|
+
const value = (entries && typeof entries === 'object' ? entries[writeKey(target.collection, target.id)] : undefined);
|
|
99
132
|
if (!value || typeof value !== 'object' || !value.input || !value.output)
|
|
100
133
|
return null;
|
|
101
134
|
return { input: value.input, output: value.output };
|
|
@@ -171,9 +204,17 @@ export function createSessionManager(options = {}) {
|
|
|
171
204
|
const logSize = options.logSize ?? 500;
|
|
172
205
|
const retryDelays = options.retryDelaysMs?.length ? options.retryDelaysMs : [2000, 5000, 15_000, 30_000];
|
|
173
206
|
const logger = options.logger ?? { error: (message, error) => console.error(message, error) };
|
|
207
|
+
const gate = options.gate ?? null;
|
|
174
208
|
const sessions = new Map();
|
|
175
209
|
const loading = new Map();
|
|
176
210
|
const mutex = createKeyedMutex();
|
|
211
|
+
const resetMutex = createKeyedMutex();
|
|
212
|
+
const activeActions = new Map();
|
|
213
|
+
/**
|
|
214
|
+
* The reset action (its `activeActions` entry) that runs the current save (`resetFor`'s `save`),
|
|
215
|
+
* also in work that save started: it counts as that action's own only while that action runs.
|
|
216
|
+
*/
|
|
217
|
+
const actionSave = new AsyncLocalStorage();
|
|
177
218
|
let tokens = 0;
|
|
178
219
|
// ---- loading ----------------------------------------------------------
|
|
179
220
|
const load = async (target, store) => {
|
|
@@ -185,47 +226,69 @@ export function createSessionManager(options = {}) {
|
|
|
185
226
|
}
|
|
186
227
|
let pending = loading.get(key);
|
|
187
228
|
if (!pending) {
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
doc
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
229
|
+
let invalidated = false;
|
|
230
|
+
const promise = (async () => {
|
|
231
|
+
for (;;) {
|
|
232
|
+
while (activeActions.has(key))
|
|
233
|
+
await activeActions.get(key);
|
|
234
|
+
invalidated = false;
|
|
235
|
+
// The session state is shared by everyone, so it is read without one user's field access.
|
|
236
|
+
// Each request checks its own document access before it connects or commits.
|
|
237
|
+
const doc = await store.findByID({
|
|
238
|
+
collection: target.collection,
|
|
239
|
+
id: target.id,
|
|
240
|
+
depth: 0,
|
|
241
|
+
draft: target.drafts,
|
|
242
|
+
overrideAccess: true,
|
|
243
|
+
// Every locale: the session holds the stored layout with its translations.
|
|
244
|
+
context: { [ALL_LOCALES_KEY]: true },
|
|
245
|
+
});
|
|
246
|
+
// An action may have started and finished while this read was in flight.
|
|
247
|
+
if (invalidated)
|
|
248
|
+
continue;
|
|
249
|
+
const layout = codecOfTarget(target).decode(doc[target.field]);
|
|
250
|
+
const { [target.field]: _layout, ...rest } = doc;
|
|
251
|
+
const session = {
|
|
252
|
+
key,
|
|
253
|
+
sessionId: globalThis.crypto.randomUUID().slice(0, 8),
|
|
254
|
+
target,
|
|
255
|
+
store,
|
|
256
|
+
layout,
|
|
257
|
+
doc: rest,
|
|
258
|
+
seq: 0,
|
|
259
|
+
log: [],
|
|
260
|
+
knownBlocking: null,
|
|
261
|
+
members: new Map(),
|
|
262
|
+
user: null,
|
|
263
|
+
persistedSeq: 0,
|
|
264
|
+
completedWrites: 0,
|
|
265
|
+
firstDirtyAt: null,
|
|
266
|
+
persistTimer: null,
|
|
267
|
+
persisting: null,
|
|
268
|
+
failures: 0,
|
|
269
|
+
saveError: null,
|
|
270
|
+
evictTimer: null,
|
|
271
|
+
externalPending: false,
|
|
272
|
+
externalGen: 0,
|
|
273
|
+
unsaved: [],
|
|
274
|
+
stored: doc[target.field],
|
|
275
|
+
ownRowIds: codecOfTarget(target).rowIds?.(doc[target.field]) ?? new Set(),
|
|
276
|
+
writing: false,
|
|
277
|
+
docRefresh: null,
|
|
278
|
+
docGen: 0,
|
|
279
|
+
docFailed: false,
|
|
280
|
+
docVersion: 0,
|
|
281
|
+
adopting: null,
|
|
282
|
+
};
|
|
283
|
+
sessions.set(key, session);
|
|
284
|
+
return session;
|
|
285
|
+
}
|
|
224
286
|
})();
|
|
287
|
+
pending = { promise, invalidate: () => { invalidated = true; } };
|
|
225
288
|
loading.set(key, pending);
|
|
226
|
-
void
|
|
289
|
+
void promise.then(() => loading.delete(key), () => loading.delete(key));
|
|
227
290
|
}
|
|
228
|
-
const session = await pending;
|
|
291
|
+
const session = await pending.promise;
|
|
229
292
|
session.store = store;
|
|
230
293
|
return session;
|
|
231
294
|
};
|
|
@@ -253,6 +316,7 @@ export function createSessionManager(options = {}) {
|
|
|
253
316
|
at: new Date(timers.now()).toISOString(),
|
|
254
317
|
...(typeof info.updatedAt === 'string' ? { updatedAt: info.updatedAt } : {}),
|
|
255
318
|
...(typeof info.status === 'string' ? { status: info.status } : {}),
|
|
319
|
+
...(info.fields && info.fields.length > 0 ? { fields: [...info.fields] } : {}),
|
|
256
320
|
});
|
|
257
321
|
const sessionEvent = (session, self, reset = false) => ({
|
|
258
322
|
type: 'session',
|
|
@@ -265,7 +329,7 @@ export function createSessionManager(options = {}) {
|
|
|
265
329
|
...(reset ? { reset: true } : {}),
|
|
266
330
|
});
|
|
267
331
|
// ---- persistence ------------------------------------------------------
|
|
268
|
-
const dirty = (session) => session.seq > session.persistedSeq;
|
|
332
|
+
const dirty = (session) => session.seq > session.persistedSeq || session.externalPending;
|
|
269
333
|
const cancelEvict = (session) => {
|
|
270
334
|
if (session.evictTimer === null)
|
|
271
335
|
return;
|
|
@@ -273,11 +337,11 @@ export function createSessionManager(options = {}) {
|
|
|
273
337
|
session.evictTimer = null;
|
|
274
338
|
};
|
|
275
339
|
const maybeEvict = (session) => {
|
|
276
|
-
if (session.members.size > 0 || dirty(session) || session.persisting || session.evictTimer !== null)
|
|
340
|
+
if (session.members.size > 0 || dirty(session) || session.persisting || activeActions.has(session.key) || session.evictTimer !== null)
|
|
277
341
|
return;
|
|
278
342
|
session.evictTimer = timers.set(() => {
|
|
279
343
|
session.evictTimer = null;
|
|
280
|
-
if (session.members.size > 0 || dirty(session) || session.persisting)
|
|
344
|
+
if (session.members.size > 0 || dirty(session) || session.persisting || activeActions.has(session.key))
|
|
281
345
|
return;
|
|
282
346
|
if (sessions.get(session.key) === session)
|
|
283
347
|
sessions.delete(session.key);
|
|
@@ -311,36 +375,113 @@ export function createSessionManager(options = {}) {
|
|
|
311
375
|
const persist = (session) => {
|
|
312
376
|
if (session.persisting)
|
|
313
377
|
return session.persisting;
|
|
378
|
+
if (activeActions.has(session.key))
|
|
379
|
+
return Promise.resolve();
|
|
314
380
|
if (!dirty(session)) {
|
|
315
381
|
session.firstDirtyAt = null;
|
|
316
382
|
maybeEvict(session);
|
|
317
383
|
return Promise.resolve();
|
|
318
384
|
}
|
|
319
|
-
const {
|
|
385
|
+
const { target } = session;
|
|
320
386
|
session.firstDirtyAt = null;
|
|
321
387
|
// The save hook records here what the props' hooks changed (plugin/hook.ts). The Local API
|
|
322
388
|
// without `req` uses this object as the request context.
|
|
323
389
|
const context = { builderSession: true };
|
|
390
|
+
const codec = codecOfTarget(target);
|
|
391
|
+
let seq = session.seq;
|
|
392
|
+
/** The layout the save sent. */
|
|
393
|
+
let sent = session.layout;
|
|
394
|
+
/**
|
|
395
|
+
* A Payload blocks field whose stored value differs from what the save sent (Payload's hooks
|
|
396
|
+
* changed values or blocks): the session took the stored value as its base.
|
|
397
|
+
*/
|
|
398
|
+
let rebased = false;
|
|
399
|
+
/** The save itself. Reads the layout only now: with the gate, after every save before it committed. */
|
|
400
|
+
const save = async (req) => {
|
|
401
|
+
if (activeActions.has(session.key))
|
|
402
|
+
return PAUSED;
|
|
403
|
+
// A save outside the session changed the stored value meanwhile: take it first. A newer outside
|
|
404
|
+
// save during the read leaves it pending: read again, never write on the older base.
|
|
405
|
+
for (let tries = 0; session.externalPending; tries++) {
|
|
406
|
+
if (tries === EXTERNAL_SYNC_TRIES)
|
|
407
|
+
throw Object.assign(new Error('The stored layout kept changing during the save.'), { status: 409 });
|
|
408
|
+
await syncExternal(session);
|
|
409
|
+
if (activeActions.has(session.key))
|
|
410
|
+
return PAUSED;
|
|
411
|
+
}
|
|
412
|
+
// The stored document holds hook changes the layout does not have yet: never write over them.
|
|
413
|
+
// Not waited for here: the session lock they need may wait for this write gate.
|
|
414
|
+
if (session.adopting)
|
|
415
|
+
return PAUSED;
|
|
416
|
+
// A save outside the session stored this layout while this one waited (Publish): nothing to write.
|
|
417
|
+
if (!dirty(session))
|
|
418
|
+
return SKIPPED;
|
|
419
|
+
seq = session.seq;
|
|
420
|
+
const layout = session.layout;
|
|
421
|
+
sent = layout;
|
|
422
|
+
const problems = codec.problems(layout);
|
|
423
|
+
if (problems.length > 0)
|
|
424
|
+
throw Object.assign(new Error(problems.join(' ')), { status: 422 });
|
|
425
|
+
session.writing = true;
|
|
426
|
+
try {
|
|
427
|
+
return await write(layout, req);
|
|
428
|
+
}
|
|
429
|
+
finally {
|
|
430
|
+
session.writing = false;
|
|
431
|
+
}
|
|
432
|
+
};
|
|
433
|
+
const write = async (layout, req) => {
|
|
434
|
+
const saved = await session.store.update({
|
|
435
|
+
collection: target.collection,
|
|
436
|
+
id: target.id,
|
|
437
|
+
data: { [target.field]: codec.encode(layout, session.stored) },
|
|
438
|
+
depth: 0,
|
|
439
|
+
draft: target.drafts,
|
|
440
|
+
...(target.drafts && target.autosave ? { autosave: true } : {}),
|
|
441
|
+
context,
|
|
442
|
+
user: session.user,
|
|
443
|
+
overrideAccess: false,
|
|
444
|
+
// Never blocked by Payload's document lock; the save hook keeps the lock (fieldsGuard.ts).
|
|
445
|
+
overrideLock: true,
|
|
446
|
+
// The same request as the gate's hold: the update joins it.
|
|
447
|
+
...(req ? { req } : {}),
|
|
448
|
+
});
|
|
449
|
+
session.completedWrites += 1;
|
|
450
|
+
if (codec.kind === 'payload-blocks') {
|
|
451
|
+
// Still holding the gate, so no other save lands in between. What Payload's hooks stored
|
|
452
|
+
// (other values, added, removed or moved blocks) becomes the session's base, with the
|
|
453
|
+
// commits made during the save on top. The read also gives the other fields.
|
|
454
|
+
const doc = await refreshDoc(session);
|
|
455
|
+
const before = session.stored;
|
|
456
|
+
session.stored = doc[target.field];
|
|
457
|
+
rememberRows(session);
|
|
458
|
+
if (!sameValue(codec.encode(sent, before), doc[target.field])) {
|
|
459
|
+
await rebaseOn(session, doc, seq);
|
|
460
|
+
rebased = true;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
else {
|
|
464
|
+
// The collection's hooks may change other fields in this save too: read them again.
|
|
465
|
+
refreshDoc(session);
|
|
466
|
+
}
|
|
467
|
+
return saved;
|
|
468
|
+
};
|
|
324
469
|
const run = (async () => {
|
|
325
470
|
try {
|
|
326
|
-
const
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
user: session.user,
|
|
335
|
-
overrideAccess: false,
|
|
336
|
-
// Never blocked by Payload's document lock; the save hook keeps the lock (fieldsGuard.ts).
|
|
337
|
-
overrideLock: true,
|
|
338
|
-
});
|
|
471
|
+
const req = {};
|
|
472
|
+
const saved = gate ? await gate.run(writeKey(target.collection, target.id), req, () => save(req)) : await save();
|
|
473
|
+
if (saved === PAUSED)
|
|
474
|
+
return;
|
|
475
|
+
if (saved === SKIPPED) {
|
|
476
|
+
clearFailure(session);
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
339
479
|
session.persistedSeq = Math.max(session.persistedSeq, seq);
|
|
480
|
+
session.unsaved = session.unsaved.filter((entry) => entry.seq > session.persistedSeq);
|
|
340
481
|
clearFailure(session);
|
|
341
482
|
const info = { updatedAt: saved?.updatedAt, status: saved?._status };
|
|
342
|
-
deliver(session, savedEvent(seq, info));
|
|
343
|
-
const changes = hookChangesIn(context);
|
|
483
|
+
deliver(session, savedEvent(rebased ? session.persistedSeq : seq, info));
|
|
484
|
+
const changes = hookChangesIn(context, target);
|
|
344
485
|
if (changes)
|
|
345
486
|
queueAdopt(session, { ...changes, seq }, info);
|
|
346
487
|
}
|
|
@@ -360,8 +501,13 @@ export function createSessionManager(options = {}) {
|
|
|
360
501
|
})();
|
|
361
502
|
const done = run.then(() => {
|
|
362
503
|
session.persisting = null;
|
|
363
|
-
if (dirty(session)) {
|
|
364
|
-
|
|
504
|
+
if (dirty(session) && !activeActions.has(session.key)) {
|
|
505
|
+
const adopting = session.adopting;
|
|
506
|
+
if (session.failures === 0 && adopting) {
|
|
507
|
+
// Saves again once the hook changes are in the layout.
|
|
508
|
+
void adopting.then(() => markDirty(session));
|
|
509
|
+
}
|
|
510
|
+
else if (session.failures === 0) {
|
|
365
511
|
// Commits arrived during the save.
|
|
366
512
|
session.firstDirtyAt ??= timers.now();
|
|
367
513
|
schedulePersist(session);
|
|
@@ -375,6 +521,165 @@ export function createSessionManager(options = {}) {
|
|
|
375
521
|
session.persisting = done;
|
|
376
522
|
return done;
|
|
377
523
|
};
|
|
524
|
+
// ---- saves outside the session ------------------------------------------
|
|
525
|
+
/** The stored document, every value (the session holds values some editors may not read). */
|
|
526
|
+
const readStored = (session) => session.store.findByID({
|
|
527
|
+
collection: session.target.collection,
|
|
528
|
+
id: session.target.id,
|
|
529
|
+
depth: 0,
|
|
530
|
+
draft: session.target.drafts,
|
|
531
|
+
overrideAccess: true,
|
|
532
|
+
context: { [ALL_LOCALES_KEY]: true },
|
|
533
|
+
});
|
|
534
|
+
/**
|
|
535
|
+
* The document's other fields from a stored document, unless a newer read already set them.
|
|
536
|
+
* `docVersion` counts changes of their values: only a read that finds every value exactly as it
|
|
537
|
+
* was (`updatedAt` included) leaves a check that ran meanwhile valid.
|
|
538
|
+
*/
|
|
539
|
+
const setDoc = (session, doc, gen) => {
|
|
540
|
+
if (gen !== session.docGen)
|
|
541
|
+
return;
|
|
542
|
+
const { [session.target.field]: _layout, ...rest } = doc;
|
|
543
|
+
if (!sameFields(session.doc, rest))
|
|
544
|
+
session.docVersion += 1;
|
|
545
|
+
session.doc = rest;
|
|
546
|
+
session.docFailed = false;
|
|
547
|
+
};
|
|
548
|
+
/**
|
|
549
|
+
* Reads the stored document again after a committed save (a region, the settings drawer, REST,
|
|
550
|
+
* the session's own save): its other fields may change who may read what. No gate, no lock: a
|
|
551
|
+
* plain read, so it can run while a save holds the gate or a commit holds the lock. A failed read
|
|
552
|
+
* marks the fields as untrusted (`docFailed`) until a newer read works.
|
|
553
|
+
*/
|
|
554
|
+
const refreshDoc = (session) => {
|
|
555
|
+
const gen = ++session.docGen;
|
|
556
|
+
const stored = readStored(session);
|
|
557
|
+
const read = stored
|
|
558
|
+
.then((doc) => setDoc(session, doc, gen), (error) => {
|
|
559
|
+
if (gen !== session.docGen)
|
|
560
|
+
return;
|
|
561
|
+
session.docFailed = true;
|
|
562
|
+
logger.error(`[websiteBuilder] Could not read ${session.key} again after a save.`, error);
|
|
563
|
+
})
|
|
564
|
+
.finally(() => {
|
|
565
|
+
if (session.docRefresh === read)
|
|
566
|
+
session.docRefresh = null;
|
|
567
|
+
});
|
|
568
|
+
session.docRefresh = read;
|
|
569
|
+
return stored;
|
|
570
|
+
};
|
|
571
|
+
/**
|
|
572
|
+
* The session's doc once the reads after committed saves are done. After a failed read it reads
|
|
573
|
+
* once more; when that fails too, it throws.
|
|
574
|
+
*/
|
|
575
|
+
const freshDoc = async (session) => {
|
|
576
|
+
for (let retried = false;; retried = true) {
|
|
577
|
+
while (session.docRefresh)
|
|
578
|
+
await session.docRefresh;
|
|
579
|
+
if (!session.docFailed)
|
|
580
|
+
return session.doc;
|
|
581
|
+
if (retried)
|
|
582
|
+
throw new Error(`The document ${session.key} could not be read after a save.`);
|
|
583
|
+
refreshDoc(session);
|
|
584
|
+
}
|
|
585
|
+
};
|
|
586
|
+
/**
|
|
587
|
+
* `check` on the doc as stored when it returns: the reads of saves that committed meanwhile are
|
|
588
|
+
* awaited, and when they changed a value the check runs again (at most CURRENT_DOC_TRIES times).
|
|
589
|
+
*/
|
|
590
|
+
const withCurrent = async (session, check) => {
|
|
591
|
+
for (let i = 0; i < CURRENT_DOC_TRIES; i++) {
|
|
592
|
+
const doc = await freshDoc(session);
|
|
593
|
+
const version = session.docVersion;
|
|
594
|
+
const value = await check(doc);
|
|
595
|
+
await freshDoc(session);
|
|
596
|
+
if (session.docVersion === version)
|
|
597
|
+
return value;
|
|
598
|
+
}
|
|
599
|
+
throw new Error(`The document ${session.key} kept changing during an access check.`);
|
|
600
|
+
};
|
|
601
|
+
/**
|
|
602
|
+
* Makes a stored document the session's base: its layout as stored, then the session's unsaved
|
|
603
|
+
* commits on top (each operation that still applies). Every editor gets the new state; the
|
|
604
|
+
* session id stays, so editors rebase their unsent changes instead of dropping them.
|
|
605
|
+
* `savedSeq`: the session's own save that stored this document (its commits up to that seq are
|
|
606
|
+
* in it). `outside`: a read for saves outside the session, with the session id and `externalGen`
|
|
607
|
+
* from when it started. Throws when the stored value cannot be read as a layout. The document's
|
|
608
|
+
* other fields come from the read every committed save starts (`refreshDoc`), not from here.
|
|
609
|
+
*/
|
|
610
|
+
const rebaseOn = async (session, doc, savedSeq, outside) => {
|
|
611
|
+
const { target } = session;
|
|
612
|
+
const base = codecOfTarget(target).decode(doc[target.field]);
|
|
613
|
+
await mutex.run(session.key, async () => {
|
|
614
|
+
if (sessions.get(session.key) !== session)
|
|
615
|
+
return;
|
|
616
|
+
// Outside reads wait for the action's outcome. A read from before a reset, or from before a
|
|
617
|
+
// newer outside save, is repeated: it never takes that save's place.
|
|
618
|
+
if (outside && (activeActions.has(session.key) || session.sessionId !== outside.sessionId || session.externalGen !== outside.gen)) {
|
|
619
|
+
session.externalPending = true;
|
|
620
|
+
markDirty(session);
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
if (outside)
|
|
624
|
+
session.externalPending = false;
|
|
625
|
+
session.stored = doc[target.field];
|
|
626
|
+
rememberRows(session);
|
|
627
|
+
if (savedSeq !== undefined)
|
|
628
|
+
session.persistedSeq = Math.max(session.persistedSeq, savedSeq);
|
|
629
|
+
let layout = base;
|
|
630
|
+
const pending = [];
|
|
631
|
+
for (const entry of session.unsaved) {
|
|
632
|
+
if (entry.seq <= session.persistedSeq)
|
|
633
|
+
continue;
|
|
634
|
+
const ops = [];
|
|
635
|
+
for (const op of entry.ops) {
|
|
636
|
+
const result = resolveOperations(layout, [op]);
|
|
637
|
+
if (!result.ok)
|
|
638
|
+
continue;
|
|
639
|
+
layout = result.layout;
|
|
640
|
+
ops.push(...result.ops);
|
|
641
|
+
}
|
|
642
|
+
if (ops.length > 0)
|
|
643
|
+
pending.push({ seq: entry.seq, ops });
|
|
644
|
+
}
|
|
645
|
+
session.unsaved = pending;
|
|
646
|
+
session.layout = layout;
|
|
647
|
+
session.seq += 1;
|
|
648
|
+
session.knownBlocking = null;
|
|
649
|
+
// The commit log no longer leads to this state: a reconnect gets a fresh session.
|
|
650
|
+
session.log = [];
|
|
651
|
+
if (pending.length === 0)
|
|
652
|
+
session.persistedSeq = session.seq;
|
|
653
|
+
else
|
|
654
|
+
markDirty(session);
|
|
655
|
+
for (const member of session.members.values()) {
|
|
656
|
+
if (!member.send)
|
|
657
|
+
continue;
|
|
658
|
+
try {
|
|
659
|
+
member.send(sessionEvent(session, member.info), eventId(session));
|
|
660
|
+
}
|
|
661
|
+
catch {
|
|
662
|
+
// A closed stream must not stop the others.
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
});
|
|
666
|
+
};
|
|
667
|
+
/**
|
|
668
|
+
* Takes a stored layout that a save outside the session wrote (a Payload blocks field: the Edit
|
|
669
|
+
* view, REST and the Local API write the field itself).
|
|
670
|
+
*/
|
|
671
|
+
const syncExternal = async (session) => {
|
|
672
|
+
if (activeActions.has(session.key))
|
|
673
|
+
return;
|
|
674
|
+
const outside = { sessionId: session.sessionId, gen: session.externalGen };
|
|
675
|
+
try {
|
|
676
|
+
await rebaseOn(session, await readStored(session), undefined, outside);
|
|
677
|
+
}
|
|
678
|
+
catch (error) {
|
|
679
|
+
session.externalPending = true;
|
|
680
|
+
throw error;
|
|
681
|
+
}
|
|
682
|
+
};
|
|
378
683
|
// ---- hook changes ------------------------------------------------------
|
|
379
684
|
/**
|
|
380
685
|
* Applies what the props' hooks changed in a save as one commit of FIELD_HOOKS_ACTOR, through
|
|
@@ -390,7 +695,9 @@ export function createSessionManager(options = {}) {
|
|
|
390
695
|
const resolved = resolveOperations(session.layout, ops);
|
|
391
696
|
if (!resolved.ok)
|
|
392
697
|
return;
|
|
393
|
-
|
|
698
|
+
// Another session's seq says nothing about this one: its changes are saved again.
|
|
699
|
+
const sameSession = changes.sessionId === undefined || changes.sessionId === session.sessionId;
|
|
700
|
+
const clean = sameSession && session.seq === changes.seq && session.persistedSeq >= changes.seq;
|
|
394
701
|
session.layout = resolved.layout;
|
|
395
702
|
session.seq += 1;
|
|
396
703
|
session.knownBlocking = null;
|
|
@@ -404,25 +711,140 @@ export function createSessionManager(options = {}) {
|
|
|
404
711
|
deliver(session, savedEvent(session.seq, info));
|
|
405
712
|
}
|
|
406
713
|
else {
|
|
714
|
+
session.unsaved.push({ seq: session.seq, ops: resolved.ops });
|
|
407
715
|
markDirty(session);
|
|
408
716
|
}
|
|
409
717
|
};
|
|
410
|
-
/**
|
|
718
|
+
/**
|
|
719
|
+
* Queues `adopt` behind the commits in flight. Never awaited by a save. A reset waits for it
|
|
720
|
+
* (`session.adopting`): the changes belong to the state the reset replaces.
|
|
721
|
+
*/
|
|
411
722
|
const queueAdopt = (session, changes, info) => {
|
|
412
|
-
|
|
723
|
+
const queued = mutex
|
|
724
|
+
.run(session.key, async () => {
|
|
725
|
+
// Under the mutex: the next task finds no adoption queued before it.
|
|
726
|
+
if (session.adopting === queued)
|
|
727
|
+
session.adopting = null;
|
|
728
|
+
adopt(session, changes, info);
|
|
729
|
+
})
|
|
730
|
+
.catch((error) => {
|
|
413
731
|
logger.error(`[websiteBuilder] Could not apply the field hook changes of ${session.key}.`, error);
|
|
414
732
|
});
|
|
733
|
+
session.adopting = queued;
|
|
415
734
|
};
|
|
416
735
|
const markDirty = (session) => {
|
|
417
736
|
session.firstDirtyAt ??= timers.now();
|
|
418
737
|
// A save in flight reschedules itself when it ends. While saves fail, the backoff timer stays:
|
|
419
738
|
// new commits do not hammer a broken database.
|
|
420
|
-
if (session.persisting)
|
|
739
|
+
if (session.persisting || activeActions.has(session.key))
|
|
421
740
|
return;
|
|
422
741
|
if (session.failures > 0 && session.persistTimer !== null)
|
|
423
742
|
return;
|
|
424
743
|
schedulePersist(session);
|
|
425
744
|
};
|
|
745
|
+
// ---- reset (Revert, Restore) ---------------------------------------------
|
|
746
|
+
/**
|
|
747
|
+
* Changes an open session's state as a whole (`change`), then sends every editor a fresh
|
|
748
|
+
* `session` event with `reset: true` and a new session id: commits made on the old state can no
|
|
749
|
+
* longer be replayed or rebased. A save in flight must not land after the caller's save of the
|
|
750
|
+
* new layout: it is awaited outside the mutex (a save may need the mutex itself, it takes a save
|
|
751
|
+
* from outside first). So are the queued hook changes of saves that committed before: the state
|
|
752
|
+
* the reset replaces (and puts back when the action fails) holds them. `change` also gets the
|
|
753
|
+
* session's state from before anything here changed it (`prior.dirty`: it had unsaved commits).
|
|
754
|
+
* False when no session is open.
|
|
755
|
+
*/
|
|
756
|
+
const replaceState = async (key, change) => {
|
|
757
|
+
for (;;) {
|
|
758
|
+
// A load holds the mutex while it waits for this action. It will read the final document.
|
|
759
|
+
const open = sessions.get(key);
|
|
760
|
+
if (!open)
|
|
761
|
+
return false;
|
|
762
|
+
const running = open.persisting ?? open.adopting;
|
|
763
|
+
if (running) {
|
|
764
|
+
await running;
|
|
765
|
+
continue;
|
|
766
|
+
}
|
|
767
|
+
const done = await mutex.run(key, async () => {
|
|
768
|
+
const session = sessions.get(key);
|
|
769
|
+
if (!session)
|
|
770
|
+
return false;
|
|
771
|
+
// A save started, or hook changes were queued, while this waited for the mutex: wait for
|
|
772
|
+
// them outside, then try again.
|
|
773
|
+
if (session.persisting || session.adopting)
|
|
774
|
+
return null;
|
|
775
|
+
// Before the seq below moves on (that alone would make the session look unsaved).
|
|
776
|
+
const prior = { dirty: dirty(session) };
|
|
777
|
+
if (session.persistTimer !== null)
|
|
778
|
+
timers.clear(session.persistTimer);
|
|
779
|
+
session.persistTimer = null;
|
|
780
|
+
session.firstDirtyAt = null;
|
|
781
|
+
clearFailure(session);
|
|
782
|
+
session.sessionId = globalThis.crypto.randomUUID().slice(0, 8);
|
|
783
|
+
session.seq += 1;
|
|
784
|
+
session.log = [];
|
|
785
|
+
session.knownBlocking = null;
|
|
786
|
+
change(session, prior);
|
|
787
|
+
for (const member of session.members.values()) {
|
|
788
|
+
if (!member.send)
|
|
789
|
+
continue;
|
|
790
|
+
try {
|
|
791
|
+
member.send(sessionEvent(session, member.info, true), eventId(session));
|
|
792
|
+
}
|
|
793
|
+
catch {
|
|
794
|
+
// A closed stream must not stop the others.
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
return true;
|
|
798
|
+
});
|
|
799
|
+
if (done !== null)
|
|
800
|
+
return done;
|
|
801
|
+
}
|
|
802
|
+
};
|
|
803
|
+
/** A new layout that the caller saves next (Revert, Restore): no unsaved commits. */
|
|
804
|
+
const resetTo = (session, layout, stored) => {
|
|
805
|
+
session.layout = codecOfTarget(session.target).kind === 'json' ? normalizeLayout(layout) : layout;
|
|
806
|
+
session.unsaved = [];
|
|
807
|
+
// The value the caller stores next: what the next save builds on.
|
|
808
|
+
if (stored !== undefined) {
|
|
809
|
+
session.stored = stored;
|
|
810
|
+
rememberRows(session);
|
|
811
|
+
}
|
|
812
|
+
session.persistedSeq = session.seq;
|
|
813
|
+
};
|
|
814
|
+
/**
|
|
815
|
+
* The state before a reset whose save failed: its layout, stored value and unsaved commits, still
|
|
816
|
+
* unsaved (the next save stores them), never counted as saved.
|
|
817
|
+
*/
|
|
818
|
+
const putBack = (session, undo) => {
|
|
819
|
+
// A guarded outside save may have stored the reset layout before the action failed.
|
|
820
|
+
const needsSave = undo.dirty || session.completedWrites > undo.completedWrites || session.externalPending;
|
|
821
|
+
session.layout = undo.layout;
|
|
822
|
+
session.stored = undo.stored;
|
|
823
|
+
session.unsaved = undo.unsaved;
|
|
824
|
+
session.persistedSeq = needsSave ? undo.persistedSeq : session.seq;
|
|
825
|
+
if (needsSave)
|
|
826
|
+
markDirty(session);
|
|
827
|
+
};
|
|
828
|
+
const resetAction = (key, change) => resetMutex.run(key, async () => {
|
|
829
|
+
let resume;
|
|
830
|
+
const action = new Promise((resolve) => { resume = resolve; });
|
|
831
|
+
activeActions.set(key, action);
|
|
832
|
+
loading.get(key)?.invalidate();
|
|
833
|
+
try {
|
|
834
|
+
return await change(action);
|
|
835
|
+
}
|
|
836
|
+
finally {
|
|
837
|
+
activeActions.delete(key);
|
|
838
|
+
resume();
|
|
839
|
+
const session = sessions.get(key);
|
|
840
|
+
if (session) {
|
|
841
|
+
if (dirty(session))
|
|
842
|
+
markDirty(session);
|
|
843
|
+
else
|
|
844
|
+
maybeEvict(session);
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
});
|
|
426
848
|
// ---- AI collaborators -------------------------------------------------
|
|
427
849
|
const touchAi = (session, actor, changedId) => {
|
|
428
850
|
const clientId = `ai:${actor.id}`;
|
|
@@ -478,7 +900,10 @@ export function createSessionManager(options = {}) {
|
|
|
478
900
|
}
|
|
479
901
|
}
|
|
480
902
|
const firstLogged = session.log[0]?.seq ?? session.seq + 1;
|
|
481
|
-
|
|
903
|
+
// A Payload blocks field never replays old commits: they may hold values that are gone now
|
|
904
|
+
// and that this user may not read. The reconnect gets the current state instead.
|
|
905
|
+
const replayed = codecOfTarget(target).kind === 'json' &&
|
|
906
|
+
after !== undefined &&
|
|
482
907
|
Number.isInteger(after.seq) &&
|
|
483
908
|
(after.sessionId === undefined || after.sessionId === session.sessionId) &&
|
|
484
909
|
after.seq <= session.seq &&
|
|
@@ -545,19 +970,48 @@ export function createSessionManager(options = {}) {
|
|
|
545
970
|
else {
|
|
546
971
|
ops = args.ops;
|
|
547
972
|
}
|
|
548
|
-
|
|
973
|
+
let resolved = resolveOperations(session.layout, ops, blocks, args.localization);
|
|
549
974
|
if (!resolved.ok) {
|
|
550
975
|
maybeEvict(session);
|
|
551
976
|
return reject(409, resolved.error);
|
|
552
977
|
}
|
|
978
|
+
// The field's own rules for what it stores (copied rows of a Payload blocks field get new
|
|
979
|
+
// ids). Editors get these operations, so every copy of the layout matches.
|
|
980
|
+
const prepared = codecOfTarget(session.target).prepare?.(session.layout, resolved.ops, session.ownRowIds);
|
|
981
|
+
if (prepared && prepared !== resolved.ops) {
|
|
982
|
+
resolved = resolveOperations(session.layout, prepared, blocks, args.localization);
|
|
983
|
+
if (!resolved.ok) {
|
|
984
|
+
maybeEvict(session);
|
|
985
|
+
return reject(409, resolved.error);
|
|
986
|
+
}
|
|
987
|
+
}
|
|
553
988
|
if (args.access) {
|
|
554
|
-
// No other commit runs meanwhile (mutex), and hook changes queue behind this one.
|
|
555
|
-
|
|
989
|
+
// No other commit runs meanwhile (mutex), and hook changes queue behind this one. The
|
|
990
|
+
// document's other fields as stored now: a save that commits during the check runs it again.
|
|
991
|
+
const access = args.access;
|
|
992
|
+
const { layout: before } = session;
|
|
993
|
+
const after = resolved.layout;
|
|
994
|
+
const changes = resolved.ops;
|
|
995
|
+
let denied;
|
|
996
|
+
try {
|
|
997
|
+
denied = await withCurrent(session, (doc) => access({ before, after, ops: changes, doc }));
|
|
998
|
+
}
|
|
999
|
+
catch (error) {
|
|
1000
|
+
logger.error(`[websiteBuilder] Could not check access for a commit to ${session.key}.`, error);
|
|
1001
|
+
maybeEvict(session);
|
|
1002
|
+
return reject(503, 'The document could not be checked. Try again.');
|
|
1003
|
+
}
|
|
556
1004
|
if (denied) {
|
|
557
1005
|
maybeEvict(session);
|
|
558
1006
|
return reject(403, denied);
|
|
559
1007
|
}
|
|
560
1008
|
}
|
|
1009
|
+
// What the field cannot store is refused, never saved in part (a Payload blocks field).
|
|
1010
|
+
const storageProblems = codecOfTarget(session.target).problems(resolved.layout);
|
|
1011
|
+
if (storageProblems.length > 0) {
|
|
1012
|
+
maybeEvict(session);
|
|
1013
|
+
return reject(422, storageProblems.join(' '));
|
|
1014
|
+
}
|
|
561
1015
|
const validateOptions = { localization: args.localization ?? null };
|
|
562
1016
|
session.knownBlocking ??= new Set(splitLayoutErrors(validateLayout(session.layout, blocks, validateOptions)).blocking.map(errorKey));
|
|
563
1017
|
const known = session.knownBlocking;
|
|
@@ -583,6 +1037,7 @@ export function createSessionManager(options = {}) {
|
|
|
583
1037
|
session.log.push(event);
|
|
584
1038
|
if (session.log.length > logSize)
|
|
585
1039
|
session.log.splice(0, session.log.length - logSize);
|
|
1040
|
+
session.unsaved.push({ seq: session.seq, ops: resolved.ops });
|
|
586
1041
|
const afterCommit = actor.type === 'ai' ? touchAi(session, actor, lastChangedId(resolved.ops)) : null;
|
|
587
1042
|
deliver(session, event, eventId(session));
|
|
588
1043
|
afterCommit?.();
|
|
@@ -623,15 +1078,39 @@ export function createSessionManager(options = {}) {
|
|
|
623
1078
|
return true;
|
|
624
1079
|
},
|
|
625
1080
|
peek(collection, id) {
|
|
626
|
-
const
|
|
627
|
-
|
|
1081
|
+
const key = channelKey(collection, id);
|
|
1082
|
+
const session = sessions.get(key);
|
|
1083
|
+
if (!session)
|
|
1084
|
+
return null;
|
|
1085
|
+
const action = activeActions.get(key);
|
|
1086
|
+
const resetting = action !== undefined && actionSave.getStore() !== action;
|
|
1087
|
+
return {
|
|
1088
|
+
sessionId: session.sessionId,
|
|
1089
|
+
seq: session.seq,
|
|
1090
|
+
layout: session.layout,
|
|
1091
|
+
doc: session.doc,
|
|
1092
|
+
...(resetting ? { resetting: true } : {}),
|
|
1093
|
+
...(session.adopting ? { adopting: true } : {}),
|
|
1094
|
+
};
|
|
628
1095
|
},
|
|
629
|
-
markSaved(collection, id, seq, info) {
|
|
1096
|
+
markSaved(collection, id, seq, info = {}) {
|
|
630
1097
|
const session = sessions.get(channelKey(collection, id));
|
|
631
|
-
|
|
632
|
-
// newest version. Then the session must save again, so it stays dirty.
|
|
633
|
-
if (!session || session.persisting)
|
|
1098
|
+
if (!session)
|
|
634
1099
|
return;
|
|
1100
|
+
session.completedWrites += 1;
|
|
1101
|
+
// A committed save from outside: its other fields are read again.
|
|
1102
|
+
refreshDoc(session);
|
|
1103
|
+
// A session save that is writing may finish after this save and store an older layout as the
|
|
1104
|
+
// newest version. Then the session must save again, so it stays dirty. Editors still hear
|
|
1105
|
+
// of the save (its time, its status and the other fields it changed), with the seq already
|
|
1106
|
+
// saved. A session save that only waits for the gate checks again when it gets it.
|
|
1107
|
+
// A save that read an earlier session (before a reset, or before the session closed and opened
|
|
1108
|
+
// again) holds none of this session's commits: its seq says nothing about them.
|
|
1109
|
+
const earlier = info.sessionId !== undefined && info.sessionId !== session.sessionId;
|
|
1110
|
+
if (earlier || (session.persisting && session.writing)) {
|
|
1111
|
+
deliver(session, savedEvent(session.persistedSeq, info));
|
|
1112
|
+
return;
|
|
1113
|
+
}
|
|
635
1114
|
session.persistedSeq = Math.max(session.persistedSeq, seq);
|
|
636
1115
|
deliver(session, savedEvent(Math.min(seq, session.seq), info));
|
|
637
1116
|
if (dirty(session))
|
|
@@ -648,6 +1127,37 @@ export function createSessionManager(options = {}) {
|
|
|
648
1127
|
if (session)
|
|
649
1128
|
queueAdopt(session, changes);
|
|
650
1129
|
},
|
|
1130
|
+
externalSaved(collection, id, info) {
|
|
1131
|
+
const session = sessions.get(channelKey(collection, id));
|
|
1132
|
+
if (!session)
|
|
1133
|
+
return;
|
|
1134
|
+
session.completedWrites += 1;
|
|
1135
|
+
// Every committed save from outside, also one that left the layout alone (a region, the
|
|
1136
|
+
// settings drawer, REST): its other fields may change who may read what.
|
|
1137
|
+
refreshDoc(session);
|
|
1138
|
+
deliver(session, savedEvent(session.persistedSeq, info));
|
|
1139
|
+
if (!info.layoutChanged)
|
|
1140
|
+
return;
|
|
1141
|
+
session.externalGen += 1;
|
|
1142
|
+
session.externalPending = true;
|
|
1143
|
+
if (activeActions.has(session.key))
|
|
1144
|
+
return;
|
|
1145
|
+
// Now, so open editors see the change at once (the next save takes it too, see `persist`).
|
|
1146
|
+
const take = () => (session.externalPending ? syncExternal(session) : Promise.resolve());
|
|
1147
|
+
void (gate ? gate.run(writeKey(collection, id), {}, take) : take()).catch((error) => {
|
|
1148
|
+
session.externalPending = true;
|
|
1149
|
+
markDirty(session);
|
|
1150
|
+
logger.error(`[websiteBuilder] Could not take the saved layout of ${session.key} into the live session.`, error);
|
|
1151
|
+
});
|
|
1152
|
+
},
|
|
1153
|
+
async currentDoc(collection, id) {
|
|
1154
|
+
const session = sessions.get(channelKey(collection, id));
|
|
1155
|
+
return session ? freshDoc(session) : null;
|
|
1156
|
+
},
|
|
1157
|
+
async withCurrentDoc(collection, id, check) {
|
|
1158
|
+
const session = sessions.get(channelKey(collection, id));
|
|
1159
|
+
return session ? { value: await withCurrent(session, check) } : null;
|
|
1160
|
+
},
|
|
651
1161
|
broadcast(collection, id, event) {
|
|
652
1162
|
const session = sessions.get(channelKey(collection, id));
|
|
653
1163
|
if (!session)
|
|
@@ -655,62 +1165,84 @@ export function createSessionManager(options = {}) {
|
|
|
655
1165
|
deliver(session, event);
|
|
656
1166
|
return true;
|
|
657
1167
|
},
|
|
658
|
-
|
|
1168
|
+
reset(collection, id, layout, stored) {
|
|
659
1169
|
const key = channelKey(collection, id);
|
|
660
|
-
return
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
1170
|
+
return resetAction(key, () => replaceState(key, (session) => resetTo(session, layout, stored)));
|
|
1171
|
+
},
|
|
1172
|
+
async resetFor(collection, id, layout, stored, save) {
|
|
1173
|
+
const key = channelKey(collection, id);
|
|
1174
|
+
return resetAction(key, async (action) => {
|
|
1175
|
+
// A save that holds the write gate now started before this action: its commit and its hook
|
|
1176
|
+
// changes belong to the state the reset replaces, and puts back when `save` fails. The gate
|
|
1177
|
+
// is only passed, never held across `save`. Guarded saves that come after are refused.
|
|
1178
|
+
if (gate)
|
|
1179
|
+
await gate.run(writeKey(collection, id), {}, async () => { });
|
|
1180
|
+
let before = null;
|
|
1181
|
+
await replaceState(key, (session, prior) => {
|
|
1182
|
+
before = {
|
|
1183
|
+
layout: session.layout,
|
|
1184
|
+
stored: session.stored,
|
|
1185
|
+
unsaved: session.unsaved,
|
|
1186
|
+
persistedSeq: session.persistedSeq,
|
|
1187
|
+
completedWrites: session.completedWrites,
|
|
1188
|
+
dirty: prior.dirty,
|
|
1189
|
+
};
|
|
1190
|
+
resetTo(session, layout, stored);
|
|
1191
|
+
});
|
|
1192
|
+
try {
|
|
1193
|
+
// Its own updates may store the reset layout; other guarded saves are refused.
|
|
1194
|
+
return await actionSave.run(action, save);
|
|
1195
|
+
}
|
|
1196
|
+
catch (error) {
|
|
1197
|
+
// Set inside the reset (a closure): no open session leaves it null.
|
|
1198
|
+
const undo = before;
|
|
1199
|
+
if (undo)
|
|
1200
|
+
await replaceState(key, (session) => putBack(session, undo));
|
|
1201
|
+
throw error;
|
|
688
1202
|
}
|
|
689
|
-
return true;
|
|
690
1203
|
});
|
|
691
1204
|
},
|
|
692
1205
|
async flush(collection, id) {
|
|
693
|
-
const
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
1206
|
+
const key = channelKey(collection, id);
|
|
1207
|
+
for (;;) {
|
|
1208
|
+
while (activeActions.has(key))
|
|
1209
|
+
await activeActions.get(key);
|
|
1210
|
+
const session = sessions.get(key);
|
|
1211
|
+
if (!session)
|
|
1212
|
+
return { ok: true };
|
|
1213
|
+
// Hook changes of a committed save first (outside every lock): the layout must hold them
|
|
1214
|
+
// before it is saved or published.
|
|
1215
|
+
if (session.adopting) {
|
|
1216
|
+
await session.adopting;
|
|
1217
|
+
continue;
|
|
1218
|
+
}
|
|
1219
|
+
if (session.persisting)
|
|
1220
|
+
await session.persisting;
|
|
1221
|
+
if (activeActions.has(key) || session.adopting)
|
|
1222
|
+
continue;
|
|
1223
|
+
const save = async () => {
|
|
1224
|
+
if (session.persistTimer !== null)
|
|
1225
|
+
timers.clear(session.persistTimer);
|
|
1226
|
+
session.persistTimer = null;
|
|
1227
|
+
// A manual save counts as one more try for the backoff.
|
|
1228
|
+
await persist(session);
|
|
1229
|
+
};
|
|
708
1230
|
await save();
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
1231
|
+
if (activeActions.has(key) || session.adopting)
|
|
1232
|
+
continue;
|
|
1233
|
+
// A save that started before the last commits leaves them dirty: save once more.
|
|
1234
|
+
if (dirty(session) && session.failures === 0)
|
|
1235
|
+
await save();
|
|
1236
|
+
if (activeActions.has(key) || session.adopting)
|
|
1237
|
+
continue;
|
|
1238
|
+
if (!dirty(session))
|
|
1239
|
+
return { ok: true };
|
|
1240
|
+
return { ok: false, error: session.saveError?.message ?? 'The draft could not be saved.' };
|
|
1241
|
+
}
|
|
712
1242
|
},
|
|
713
1243
|
async flushAll() {
|
|
1244
|
+
while (activeActions.size > 0)
|
|
1245
|
+
await Promise.all(activeActions.values());
|
|
714
1246
|
await Promise.all([...sessions.values()].map((s) => this.flush(s.target.collection, s.target.id)));
|
|
715
1247
|
},
|
|
716
1248
|
unsaved: () => [...sessions.values()].filter(dirty).length,
|