@agentshouse/mdruntime 0.1.0-c2c52158b7381 → 0.1.0-c2d73b235d7d7
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 +24 -20
- package/dist/acceptance.d.ts +3 -0
- package/dist/acceptance.d.ts.map +1 -0
- package/dist/acceptance.js +328 -0
- package/dist/act-lanes.d.ts +30 -0
- package/dist/act-lanes.d.ts.map +1 -0
- package/dist/act-lanes.js +225 -0
- package/dist/actions.d.ts +26 -0
- package/dist/actions.d.ts.map +1 -0
- package/dist/actions.js +345 -0
- package/dist/adapter.d.ts +315 -122
- package/dist/adapter.d.ts.map +1 -1
- package/dist/attached-model.d.ts +4 -11
- package/dist/attached-model.d.ts.map +1 -1
- package/dist/attached-model.js +33 -49
- package/dist/{binary.d.ts → attachment.d.ts} +8 -9
- package/dist/attachment.d.ts.map +1 -0
- package/dist/attachment.js +15 -0
- package/dist/authored.d.ts +88 -0
- package/dist/authored.d.ts.map +1 -0
- package/dist/authored.js +345 -0
- package/dist/bootstrap.d.ts +30 -11
- package/dist/bootstrap.d.ts.map +1 -1
- package/dist/bootstrap.js +305 -140
- package/dist/cell.d.ts +6 -0
- package/dist/cell.d.ts.map +1 -0
- package/dist/cell.js +9 -0
- package/dist/chain.d.ts +12 -0
- package/dist/chain.d.ts.map +1 -0
- package/dist/chain.js +67 -0
- package/dist/change-set.d.ts +10 -16
- package/dist/change-set.d.ts.map +1 -1
- package/dist/change-set.js +17 -90
- package/dist/change.d.ts +7 -2
- package/dist/change.d.ts.map +1 -1
- package/dist/change.js +7 -2
- package/dist/chat-types.d.ts +3 -0
- package/dist/chat-types.d.ts.map +1 -0
- package/dist/chat-types.js +11 -0
- package/dist/client.d.ts +53 -31
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +66 -29
- package/dist/collection.d.ts +33 -21
- package/dist/collection.d.ts.map +1 -1
- package/dist/collection.js +57 -366
- package/dist/column.d.ts +5 -0
- package/dist/column.d.ts.map +1 -0
- package/dist/column.js +9 -0
- package/dist/compile.d.ts +19 -0
- package/dist/compile.d.ts.map +1 -0
- package/dist/compile.js +755 -0
- package/dist/connection.d.ts +6 -142
- package/dist/connection.d.ts.map +1 -1
- package/dist/connection.js +117 -4210
- package/dist/context.d.ts +2 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/{chat/context.js → context.js} +2 -5
- package/dist/conversation-live.d.ts +150 -0
- package/dist/conversation-live.d.ts.map +1 -0
- package/dist/conversation-live.js +260 -0
- package/dist/conversation-row.d.ts +55 -0
- package/dist/conversation-row.d.ts.map +1 -0
- package/dist/conversation-row.js +82 -0
- package/dist/conversation.d.ts +84 -54
- package/dist/conversation.d.ts.map +1 -1
- package/dist/conversation.js +1043 -823
- package/dist/declaration.d.ts +10 -0
- package/dist/declaration.d.ts.map +1 -0
- package/dist/declaration.js +24 -0
- package/dist/discovery.d.ts +12 -0
- package/dist/discovery.d.ts.map +1 -0
- package/dist/discovery.js +175 -0
- package/dist/download.d.ts +6 -0
- package/dist/download.d.ts.map +1 -0
- package/dist/download.js +42 -0
- package/dist/durability.d.ts +20 -4
- package/dist/durability.d.ts.map +1 -1
- package/dist/durability.js +12 -0
- package/dist/entry.d.ts +30 -3
- package/dist/entry.d.ts.map +1 -1
- package/dist/entry.js +135 -41
- package/dist/expectation.d.ts +26 -13
- package/dist/expectation.d.ts.map +1 -1
- package/dist/expectation.js +72 -19
- package/dist/failure.d.ts +3 -0
- package/dist/failure.d.ts.map +1 -1
- package/dist/failure.js +8 -0
- package/dist/figures.d.ts +49 -0
- package/dist/figures.d.ts.map +1 -0
- package/dist/figures.js +199 -0
- package/dist/file.d.ts +2 -11
- package/dist/file.d.ts.map +1 -1
- package/dist/file.js +7 -4
- package/dist/holdings.d.ts +29 -0
- package/dist/holdings.d.ts.map +1 -0
- package/dist/holdings.js +95 -0
- package/dist/host.d.ts +25 -8
- package/dist/host.d.ts.map +1 -1
- package/dist/host.js +157 -61
- package/dist/house-query.d.ts +24 -0
- package/dist/house-query.d.ts.map +1 -0
- package/dist/house-query.js +102 -0
- package/dist/identity.d.ts +1 -3
- package/dist/identity.d.ts.map +1 -1
- package/dist/identity.js +1 -7
- package/dist/index.d.ts +49 -19
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +25 -8
- package/dist/install.d.ts +60 -0
- package/dist/install.d.ts.map +1 -0
- package/dist/install.js +537 -0
- package/dist/lifecycle.d.ts +7 -0
- package/dist/lifecycle.d.ts.map +1 -0
- package/dist/lifecycle.js +292 -0
- package/dist/linked-file.d.ts +7 -0
- package/dist/linked-file.d.ts.map +1 -0
- package/dist/linked-file.js +16 -0
- package/dist/listing.d.ts +60 -0
- package/dist/listing.d.ts.map +1 -0
- package/dist/listing.js +168 -0
- package/dist/live.d.ts +39 -0
- package/dist/live.d.ts.map +1 -0
- package/dist/live.js +223 -0
- package/dist/loaded.d.ts +7 -0
- package/dist/loaded.d.ts.map +1 -0
- package/dist/loaded.js +46 -0
- package/dist/locks.d.ts +7 -0
- package/dist/locks.d.ts.map +1 -0
- package/dist/locks.js +34 -0
- package/dist/lost.d.ts +5 -0
- package/dist/lost.d.ts.map +1 -0
- package/dist/lost.js +49 -0
- package/dist/media.d.ts +24 -0
- package/dist/media.d.ts.map +1 -0
- package/dist/media.js +365 -0
- package/dist/memory.d.ts +22 -8
- package/dist/memory.d.ts.map +1 -1
- package/dist/memory.js +311 -120
- package/dist/messages.d.ts +67 -0
- package/dist/messages.d.ts.map +1 -0
- package/dist/messages.js +180 -0
- package/dist/modal.d.ts +2 -0
- package/dist/modal.d.ts.map +1 -0
- package/dist/modal.js +11 -0
- package/dist/model.d.ts +15 -15
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +11 -22
- package/dist/models.d.ts +10 -0
- package/dist/models.d.ts.map +1 -0
- package/dist/models.js +153 -0
- package/dist/name.d.ts +0 -1
- package/dist/name.d.ts.map +1 -1
- package/dist/name.js +3 -7
- package/dist/observation.d.ts +40 -10
- package/dist/observation.d.ts.map +1 -1
- package/dist/observation.js +265 -44
- package/dist/online.d.ts +7 -0
- package/dist/online.d.ts.map +1 -0
- package/dist/online.js +29 -0
- package/dist/opened.d.ts +6 -6
- package/dist/opened.d.ts.map +1 -1
- package/dist/opened.js +7 -7
- package/dist/opening.d.ts +4 -0
- package/dist/opening.d.ts.map +1 -0
- package/dist/opening.js +71 -0
- package/dist/outcome.d.ts +46 -16
- package/dist/outcome.d.ts.map +1 -1
- package/dist/outcome.js +51 -7
- package/dist/overlay.d.ts +24 -11
- package/dist/overlay.d.ts.map +1 -1
- package/dist/overlay.js +138 -193
- package/dist/page-metadata.d.ts +8 -0
- package/dist/page-metadata.d.ts.map +1 -0
- package/dist/page-metadata.js +19 -0
- package/dist/parts.d.ts +7 -0
- package/dist/parts.d.ts.map +1 -0
- package/dist/parts.js +36 -0
- package/dist/paths.d.ts +2 -0
- package/dist/paths.d.ts.map +1 -1
- package/dist/paths.js +26 -0
- package/dist/preparation.d.ts +46 -0
- package/dist/preparation.d.ts.map +1 -0
- package/dist/preparation.js +344 -0
- package/dist/presence.d.ts +58 -0
- package/dist/presence.d.ts.map +1 -0
- package/dist/presence.js +231 -0
- package/dist/queries.d.ts +16 -0
- package/dist/queries.d.ts.map +1 -0
- package/dist/queries.js +330 -0
- package/dist/query.d.ts +22 -209
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +3 -494
- package/dist/{chat/questions.d.ts → questions.d.ts} +6 -7
- package/dist/questions.d.ts.map +1 -0
- package/dist/{chat/questions.js → questions.js} +14 -8
- package/dist/queue.d.ts +40 -0
- package/dist/queue.d.ts.map +1 -0
- package/dist/queue.js +482 -0
- package/dist/reach.d.ts +31 -15
- package/dist/reach.d.ts.map +1 -1
- package/dist/reach.js +385 -176
- package/dist/react.d.ts +27 -3
- package/dist/react.d.ts.map +1 -1
- package/dist/react.js +33 -1
- package/dist/{chat/read.d.ts → read.d.ts} +2 -0
- package/dist/read.d.ts.map +1 -0
- package/dist/{chat/read.js → read.js} +4 -0
- package/dist/readiness.d.ts +36 -21
- package/dist/readiness.d.ts.map +1 -1
- package/dist/readiness.js +20 -18
- package/dist/reads.d.ts +38 -10
- package/dist/reads.d.ts.map +1 -1
- package/dist/reads.js +174 -83
- package/dist/recovery.d.ts +4 -0
- package/dist/recovery.d.ts.map +1 -1
- package/dist/recovery.js +59 -2
- package/dist/refresh.d.ts +18 -15
- package/dist/refresh.d.ts.map +1 -1
- package/dist/refresh.js +145 -79
- package/dist/refusal.d.ts +5 -0
- package/dist/refusal.d.ts.map +1 -0
- package/dist/refusal.js +55 -0
- package/dist/replica.d.ts +45 -38
- package/dist/replica.d.ts.map +1 -1
- package/dist/replica.js +319 -229
- package/dist/retried.d.ts +30 -0
- package/dist/retried.d.ts.map +1 -0
- package/dist/retried.js +72 -0
- package/dist/room-draft.d.ts +53 -13
- package/dist/room-draft.d.ts.map +1 -1
- package/dist/room-draft.js +405 -115
- package/dist/room-drafts.d.ts +24 -0
- package/dist/room-drafts.d.ts.map +1 -0
- package/dist/room-drafts.js +222 -0
- package/dist/room-list.d.ts +10 -0
- package/dist/room-list.d.ts.map +1 -0
- package/dist/room-list.js +47 -0
- package/dist/rows.d.ts +40 -32
- package/dist/rows.d.ts.map +1 -1
- package/dist/rows.js +72 -123
- package/dist/run-tables.d.ts +25 -0
- package/dist/run-tables.d.ts.map +1 -0
- package/dist/run-tables.js +98 -0
- package/dist/running.d.ts +5 -0
- package/dist/running.d.ts.map +1 -0
- package/dist/running.js +10 -0
- package/dist/runs.d.ts +27 -0
- package/dist/runs.d.ts.map +1 -0
- package/dist/runs.js +92 -0
- package/dist/runtime.d.ts +38 -0
- package/dist/runtime.d.ts.map +1 -0
- package/dist/runtime.js +1 -0
- package/dist/save.d.ts +45 -87
- package/dist/save.d.ts.map +1 -1
- package/dist/save.js +402 -286
- package/dist/saves.d.ts +34 -0
- package/dist/saves.d.ts.map +1 -0
- package/dist/saves.js +464 -0
- package/dist/search.d.ts +12 -95
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +10 -317
- package/dist/seed.d.ts +11 -2
- package/dist/seed.d.ts.map +1 -1
- package/dist/seed.js +71 -1
- package/dist/selector.d.ts +3 -0
- package/dist/selector.d.ts.map +1 -0
- package/dist/selector.js +22 -0
- package/dist/shared.d.ts +1 -10
- package/dist/shared.d.ts.map +1 -1
- package/dist/shared.js +13 -135
- package/dist/shown.d.ts +35 -0
- package/dist/shown.d.ts.map +1 -0
- package/dist/shown.js +327 -0
- package/dist/socket/admission.d.ts +7 -0
- package/dist/socket/admission.d.ts.map +1 -0
- package/dist/socket/admission.js +39 -0
- package/dist/socket/answers.d.ts +6 -0
- package/dist/socket/answers.d.ts.map +1 -0
- package/dist/socket/answers.js +20 -0
- package/dist/socket/lanes.d.ts +28 -0
- package/dist/socket/lanes.d.ts.map +1 -0
- package/dist/socket/lanes.js +103 -0
- package/dist/socket/reads.d.ts +10 -0
- package/dist/socket/reads.d.ts.map +1 -0
- package/dist/socket/reads.js +31 -0
- package/dist/socket/session.d.ts +41 -0
- package/dist/socket/session.d.ts.map +1 -0
- package/dist/socket/session.js +26 -0
- package/dist/socket.d.ts +70 -0
- package/dist/socket.d.ts.map +1 -0
- package/dist/socket.js +172 -0
- package/dist/source.d.ts +96 -0
- package/dist/source.d.ts.map +1 -0
- package/dist/source.js +149 -0
- package/dist/status.d.ts +4 -5
- package/dist/status.d.ts.map +1 -1
- package/dist/status.js +3 -7
- package/dist/store/installs.d.ts +30 -0
- package/dist/store/installs.d.ts.map +1 -0
- package/dist/store/installs.js +40 -0
- package/dist/store/readiness.d.ts +11 -0
- package/dist/store/readiness.d.ts.map +1 -0
- package/dist/store/readiness.js +68 -0
- package/dist/store/records.d.ts +234 -0
- package/dist/store/records.d.ts.map +1 -0
- package/dist/store/records.js +474 -0
- package/dist/store/room-held.d.ts +8 -0
- package/dist/store/room-held.d.ts.map +1 -0
- package/dist/store/room-held.js +17 -0
- package/dist/store/rooms-shown.d.ts +8 -0
- package/dist/store/rooms-shown.d.ts.map +1 -0
- package/dist/store/rooms-shown.js +13 -0
- package/dist/store/space.d.ts +11 -0
- package/dist/store/space.d.ts.map +1 -0
- package/dist/store/space.js +41 -0
- package/dist/store/watchers.d.ts +17 -0
- package/dist/store/watchers.d.ts.map +1 -0
- package/dist/store/watchers.js +56 -0
- package/dist/store/writes.d.ts +24 -0
- package/dist/store/writes.d.ts.map +1 -0
- package/dist/store/writes.js +125 -0
- package/dist/store.d.ts +115 -160
- package/dist/store.d.ts.map +1 -1
- package/dist/store.js +171 -762
- package/dist/stored.d.ts +181 -0
- package/dist/stored.d.ts.map +1 -0
- package/dist/stored.js +807 -0
- package/dist/surface.d.ts +100 -0
- package/dist/surface.d.ts.map +1 -0
- package/dist/surface.js +258 -0
- package/dist/sync.d.ts +21 -0
- package/dist/sync.d.ts.map +1 -0
- package/dist/sync.js +557 -0
- package/dist/tables.d.ts +362 -204
- package/dist/tables.d.ts.map +1 -1
- package/dist/tables.js +378 -264
- package/dist/tallies.d.ts +18 -0
- package/dist/tallies.d.ts.map +1 -0
- package/dist/tallies.js +128 -0
- package/dist/transfer.d.ts +0 -5
- package/dist/transfer.d.ts.map +1 -1
- package/dist/turn.d.ts +1 -1
- package/dist/turn.d.ts.map +1 -1
- package/dist/turn.js +28 -20
- package/dist/validation.d.ts +31 -0
- package/dist/validation.d.ts.map +1 -0
- package/dist/validation.js +144 -0
- package/dist/windows.d.ts +1 -11
- package/dist/windows.d.ts.map +1 -1
- package/dist/windows.js +2 -70
- package/dist/wire.d.ts +89 -17
- package/dist/wire.d.ts.map +1 -1
- package/dist/wire.js +38 -15
- package/package.json +16 -20
- package/AGENTS.md +0 -308
- package/dist/attempt.d.ts +0 -16
- package/dist/attempt.d.ts.map +0 -1
- package/dist/attempt.js +0 -70
- package/dist/binary.d.ts.map +0 -1
- package/dist/binary.js +0 -8
- package/dist/chat/acts.d.ts +0 -33
- package/dist/chat/acts.d.ts.map +0 -1
- package/dist/chat/acts.js +0 -36
- package/dist/chat/context.d.ts +0 -3
- package/dist/chat/context.d.ts.map +0 -1
- package/dist/chat/earlier.d.ts +0 -10
- package/dist/chat/earlier.d.ts.map +0 -1
- package/dist/chat/earlier.js +0 -54
- package/dist/chat/house.d.ts +0 -25
- package/dist/chat/house.d.ts.map +0 -1
- package/dist/chat/house.js +0 -38
- package/dist/chat/input.d.ts +0 -11
- package/dist/chat/input.d.ts.map +0 -1
- package/dist/chat/input.js +0 -92
- package/dist/chat/kit.d.ts +0 -61
- package/dist/chat/kit.d.ts.map +0 -1
- package/dist/chat/kit.js +0 -123
- package/dist/chat/lasting.d.ts +0 -6
- package/dist/chat/lasting.d.ts.map +0 -1
- package/dist/chat/lasting.js +0 -19
- package/dist/chat/list.d.ts +0 -28
- package/dist/chat/list.d.ts.map +0 -1
- package/dist/chat/list.js +0 -103
- package/dist/chat/markdown.d.ts +0 -21
- package/dist/chat/markdown.d.ts.map +0 -1
- package/dist/chat/markdown.js +0 -246
- package/dist/chat/message.d.ts +0 -7
- package/dist/chat/message.d.ts.map +0 -1
- package/dist/chat/message.js +0 -237
- package/dist/chat/messages.d.ts +0 -29
- package/dist/chat/messages.d.ts.map +0 -1
- package/dist/chat/messages.js +0 -190
- package/dist/chat/name.d.ts +0 -7
- package/dist/chat/name.d.ts.map +0 -1
- package/dist/chat/name.js +0 -37
- package/dist/chat/opened.d.ts +0 -12
- package/dist/chat/opened.d.ts.map +0 -1
- package/dist/chat/opened.js +0 -19
- package/dist/chat/overlay.d.ts +0 -32
- package/dist/chat/overlay.d.ts.map +0 -1
- package/dist/chat/overlay.js +0 -103
- package/dist/chat/parts.d.ts +0 -58
- package/dist/chat/parts.d.ts.map +0 -1
- package/dist/chat/parts.js +0 -120
- package/dist/chat/pieces.d.ts +0 -62
- package/dist/chat/pieces.d.ts.map +0 -1
- package/dist/chat/pieces.js +0 -1110
- package/dist/chat/process.d.ts +0 -20
- package/dist/chat/process.d.ts.map +0 -1
- package/dist/chat/process.js +0 -32
- package/dist/chat/provider.d.ts +0 -68
- package/dist/chat/provider.d.ts.map +0 -1
- package/dist/chat/provider.js +0 -619
- package/dist/chat/question.d.ts +0 -9
- package/dist/chat/question.d.ts.map +0 -1
- package/dist/chat/question.js +0 -69
- package/dist/chat/questions.d.ts.map +0 -1
- package/dist/chat/read.d.ts.map +0 -1
- package/dist/chat/ready.d.ts +0 -37
- package/dist/chat/ready.d.ts.map +0 -1
- package/dist/chat/ready.js +0 -93
- package/dist/chat/room-file.d.ts +0 -8
- package/dist/chat/room-file.d.ts.map +0 -1
- package/dist/chat/room-file.js +0 -72
- package/dist/chat/steady.d.ts +0 -3
- package/dist/chat/steady.d.ts.map +0 -1
- package/dist/chat/steady.js +0 -26
- package/dist/chat/style.d.ts +0 -4
- package/dist/chat/style.d.ts.map +0 -1
- package/dist/chat/style.js +0 -306
- package/dist/chat.d.ts +0 -15
- package/dist/chat.d.ts.map +0 -1
- package/dist/chat.js +0 -8
- package/dist/fence.d.ts +0 -6
- package/dist/fence.d.ts.map +0 -1
- package/dist/fence.js +0 -10
- package/dist/log.d.ts +0 -5
- package/dist/log.d.ts.map +0 -1
- package/dist/log.js +0 -14
- package/dist/read-side.d.ts +0 -27
- package/dist/read-side.d.ts.map +0 -1
- package/dist/read-side.js +0 -1179
package/dist/connection.js
CHANGED
|
@@ -1,4224 +1,131 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import { createLog } from './log.js';
|
|
18
|
-
import { binaryRecord } from './binary.js';
|
|
19
|
-
import { openedFiles } from './opened.js';
|
|
20
|
-
import { ABSENT_TARGET, absentBinary, absentReference, binaryAnswer, binaryLinkAnswer, calledResult, failure, historyAnswer, LOCKED_UNREADABLE, lockedRoom, undeclared, UNCERTAIN, UNREADABLE, } from './outcome.js';
|
|
1
|
+
import { notReadyWaitMs } from '@agentshouse/mdmodel';
|
|
2
|
+
import { submitLater } from './acceptance.js';
|
|
3
|
+
import { invokeAction, called, readConversationHistory, resendLater } from './actions.js';
|
|
4
|
+
import { builtInModel, NO_ROOM_TYPES } from './attached-model.js';
|
|
5
|
+
import { createLiveConversations } from './conversation-live.js';
|
|
6
|
+
import { writeRule } from './declaration.js';
|
|
7
|
+
import { refusedForSpace } from './durability.js';
|
|
8
|
+
import { uncaught } from './failure.js';
|
|
9
|
+
import { createFigures } from './figures.js';
|
|
10
|
+
import { scheduleCurrency, spaceFreed, start } from './lifecycle.js';
|
|
11
|
+
import { createLiveQueries } from './live.js';
|
|
12
|
+
import { open } from './opening.js';
|
|
13
|
+
import { deliverOwedReadiness, filled, prepare } from './preparation.js';
|
|
14
|
+
import { createPresence } from './presence.js';
|
|
15
|
+
import { answeredPlan, figuresCover, roomTallies } from './queries.js';
|
|
16
|
+
import { readAnswers } from './reads.js';
|
|
21
17
|
import { createRecovery } from './recovery.js';
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
27
|
-
import {
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
import { FencedMap } from './fence.js';
|
|
31
|
-
import { keysIn, tallying } from './shared.js';
|
|
32
|
-
import { finished, inChunks, ROW_WEIGHT, stepped, yielded } from './turn.js';
|
|
33
|
-
import { identityTime, roomDraftRevision } from './identity.js';
|
|
34
|
-
import { beneath, normalize } from './paths.js';
|
|
35
|
-
import { openRuntimeStore, } from './store.js';
|
|
36
|
-
import { unconfirmed } from './transfer.js';
|
|
37
|
-
import { governs, holds, narrowed, planReach, } from './reach.js';
|
|
38
|
-
function roomsAlone(plan) {
|
|
39
|
-
return (plan.reach === null &&
|
|
40
|
-
plan.root.types === null &&
|
|
41
|
-
plan.root.where === null &&
|
|
42
|
-
plan.root.pathPrefix === null &&
|
|
43
|
-
plan.paths === null &&
|
|
44
|
-
plan.hop === null &&
|
|
45
|
-
plan.backlinks === null);
|
|
18
|
+
import { createRetries } from './retried.js';
|
|
19
|
+
import { publishChangeSet, show } from './shown.js';
|
|
20
|
+
import { createSocket } from './socket.js';
|
|
21
|
+
import { createStore } from './store.js';
|
|
22
|
+
import { composedRuntime } from './surface.js';
|
|
23
|
+
import { adopt, discover } from './sync.js';
|
|
24
|
+
function writable(room) {
|
|
25
|
+
return room !== undefined && room.operations.write.length > 0;
|
|
46
26
|
}
|
|
47
|
-
function within(root, path) {
|
|
48
|
-
return root === '' || beneath(root, path);
|
|
49
|
-
}
|
|
50
|
-
function declaredSelection(room) {
|
|
51
|
-
const selection = room.typedSelection;
|
|
52
|
-
if (selection === undefined)
|
|
53
|
-
return true;
|
|
54
|
-
if (!Array.isArray(selection.roots) || selection.roots.length === 0)
|
|
55
|
-
return false;
|
|
56
|
-
return selection.roots.every((root, index) => validRoot(root) &&
|
|
57
|
-
root !== '' &&
|
|
58
|
-
selection.roots.every((other, at) => at === index || !within(other, root)));
|
|
59
|
-
}
|
|
60
|
-
const OPENING_LANE = 'opening';
|
|
61
|
-
const CONVERSATION_LANE = 'conversations';
|
|
62
|
-
const ROOM_READS = 256;
|
|
63
27
|
const ROOM_ATTEMPTS = 16;
|
|
64
|
-
// A Room that locks offline stays readable this long after the connection drops, so a laptop waking or changing network keeps working while a disconnected device locks soon after.
|
|
65
|
-
const LOCK_GRACE_MS = 120_000;
|
|
66
|
-
function operationOf(input) {
|
|
67
|
-
const operation = input?.operation_id;
|
|
68
|
-
return typeof operation === 'string' ? operation : null;
|
|
69
|
-
}
|
|
70
|
-
const outside = new Map();
|
|
71
|
-
function outsideOf(roots) {
|
|
72
|
-
const key = JSON.stringify(roots);
|
|
73
|
-
const held = outside.get(key);
|
|
74
|
-
if (held !== undefined)
|
|
75
|
-
return held;
|
|
76
|
-
const counted = (path) => (roots.some((root) => beneath(root, path)) ? 0 : 1);
|
|
77
|
-
const made = {
|
|
78
|
-
documents: (path) => (markdownPath(path) ? counted(path) : 0),
|
|
79
|
-
binaries: counted,
|
|
80
|
-
};
|
|
81
|
-
outside.set(key, made);
|
|
82
|
-
return made;
|
|
83
|
-
}
|
|
84
|
-
function abandonedOn(signal) {
|
|
85
|
-
return new Promise((resolve) => {
|
|
86
|
-
if (signal.aborted)
|
|
87
|
-
resolve(null);
|
|
88
|
-
else
|
|
89
|
-
signal.addEventListener('abort', () => resolve(null), { once: true });
|
|
90
|
-
});
|
|
91
|
-
}
|
|
92
|
-
function roomLane(locator) {
|
|
93
|
-
return `room ${locator}`;
|
|
94
|
-
}
|
|
95
|
-
function pendingKey(locator, id) {
|
|
96
|
-
return `${locator}\u0000${id}`;
|
|
97
|
-
}
|
|
98
28
|
export function composeRuntime(options) {
|
|
99
|
-
const
|
|
100
|
-
const roomTypes =
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
const
|
|
105
|
-
const
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
const replicas = new FencedMap(isFenced);
|
|
111
|
-
const queuesWithoutReplica = new FencedMap(isFenced);
|
|
112
|
-
const pendings = new Map();
|
|
113
|
-
const seeds = new Map();
|
|
114
|
-
const seedWatchers = new Map();
|
|
115
|
-
const roomDrafts = new FencedMap(isFenced);
|
|
116
|
-
const presentations = new Map();
|
|
117
|
-
let limits = [];
|
|
118
|
-
let capabilities = [];
|
|
119
|
-
const rooms = new FencedMap(isFenced);
|
|
120
|
-
const counted = new Map();
|
|
121
|
-
const unreadable = new Set();
|
|
122
|
-
const isModelFenced = (key) => isFenced(key.slice(key.indexOf(' ') + 1));
|
|
123
|
-
const models = new FencedMap(isModelFenced);
|
|
124
|
-
const liveModels = new FencedMap(isModelFenced);
|
|
125
|
-
const invalidModels = new Set();
|
|
126
|
-
const discovered = new Map();
|
|
127
|
-
const reads = doorReads(options.adapter, (locator) => discovered.get(locator), () => generation);
|
|
128
|
-
let roomsListed = false;
|
|
129
|
-
const scopedRefusals = new Map();
|
|
130
|
-
const sourceRefusals = new Map();
|
|
131
|
-
const declarationRefusals = new Set();
|
|
132
|
-
function modelKey(locator, attached) {
|
|
133
|
-
return `${attached} ${locator}`;
|
|
134
|
-
}
|
|
135
|
-
function modelOf(locator, attached = 'collection') {
|
|
136
|
-
return models.get(modelKey(locator, attached)) ?? NO_MODEL;
|
|
137
|
-
}
|
|
138
|
-
function savedModel(locator, attached) {
|
|
139
|
-
return invalidModels.has(modelKey(locator, attached))
|
|
140
|
-
? { status: 'unavailable', reason: 'revoked' }
|
|
141
|
-
: modelOf(locator, attached);
|
|
142
|
-
}
|
|
143
|
-
function compositionFor(record) {
|
|
144
|
-
return compositionOf({
|
|
145
|
-
...record,
|
|
146
|
-
model: savedModel(record.locator, 'collection'),
|
|
147
|
-
selectionModel: savedModel(record.locator, 'typed-selection'),
|
|
148
|
-
});
|
|
149
|
-
}
|
|
150
|
-
let refusal = null;
|
|
151
|
-
let storageLoss = null;
|
|
152
|
-
let status = STARTING;
|
|
153
|
-
let shown = STARTING;
|
|
154
|
-
let discoveryPaused = false;
|
|
155
|
-
let closed = false;
|
|
156
|
-
let stopping = false;
|
|
157
|
-
let withdrawStream;
|
|
158
|
-
const announced = new Map();
|
|
159
|
-
let underway = null;
|
|
160
|
-
let streamed = null;
|
|
161
|
-
let handed = false;
|
|
162
|
-
const recovery = (options.recovery ?? createRecovery()).scope(ROOM_ATTEMPTS);
|
|
163
|
-
const repairing = new Set();
|
|
164
|
-
const calling = new Set();
|
|
165
|
-
const repairable = new Map();
|
|
166
|
-
let outcomeRetention = null;
|
|
167
|
-
const answering = new Map();
|
|
168
|
-
let complete = false;
|
|
169
|
-
let recorded = false;
|
|
170
|
-
const stale = new Set();
|
|
171
|
-
let generation = 0;
|
|
172
|
-
let discovering = null;
|
|
173
|
-
let opened = null;
|
|
174
|
-
const owed = new Set();
|
|
175
|
-
const reloadsDue = new Map();
|
|
176
|
-
const lanes = new Map();
|
|
177
|
-
let roomReads = { generation, free: ROOM_READS, waiting: [] };
|
|
178
|
-
const working = new Set();
|
|
179
|
-
let mutations = Promise.resolve();
|
|
180
|
-
const roomListeners = new Set();
|
|
181
|
-
const refusalListeners = new Set();
|
|
182
|
-
const storageLossListeners = new Set();
|
|
183
|
-
const statusListeners = new Set();
|
|
184
|
-
const queueSubscriptions = new Set();
|
|
185
|
-
const roomDraftListeners = new Set();
|
|
186
|
-
const presentationListeners = new Set();
|
|
187
|
-
const readSide = createReadSide();
|
|
188
|
-
let withdrawConversations;
|
|
189
|
-
let currencyQueued = null;
|
|
190
|
-
let socketOpen = false;
|
|
191
|
-
const confirmed = new Set();
|
|
192
|
-
let lockGrace = null;
|
|
193
|
-
const lockListeners = new Set();
|
|
194
|
-
let serviceMode = 'open';
|
|
195
|
-
let haltedRefusal = false;
|
|
196
|
-
let openSignals = 0;
|
|
197
|
-
const serviceModeListeners = new Set();
|
|
198
|
-
let member = null;
|
|
199
|
-
const memberListeners = new Set();
|
|
200
|
-
const prepared = new Set();
|
|
201
|
-
const projecting = new Set();
|
|
202
|
-
const unpreparedDemand = new Set();
|
|
203
|
-
const unindexable = new Set();
|
|
204
|
-
let preparing = false;
|
|
205
|
-
let targets = {};
|
|
206
|
-
let persistence = options.shell.persistence;
|
|
207
|
-
let capacity = null;
|
|
208
|
-
const paused = new Set();
|
|
209
|
-
let rechecking = null;
|
|
210
|
-
const readinessWatches = new Set();
|
|
211
|
-
let readinessQueued = false;
|
|
212
|
-
const catching = new Set();
|
|
213
|
-
const transfers = new FencedMap(isFenced);
|
|
214
|
-
const conversations = createConversationStore({
|
|
215
|
-
agents: declaredAgents,
|
|
216
|
-
documents: ({ locator }) => rowsQuery(planOf({ rooms: [locator], select: { fields: 'all' } }, roomFacts())),
|
|
217
|
-
call: (name, input) => invokeAction(name, input),
|
|
218
|
-
durably,
|
|
219
|
-
stream: () => options.adapter.conversations,
|
|
220
|
-
publish: publishChangeSet,
|
|
221
|
-
online: () => connectionOf() !== 'unreachable' && refusal === null,
|
|
222
|
-
closed: () => closed,
|
|
223
|
-
unanswered: resendLater,
|
|
224
|
-
expired: (operation) => pastHorizon(operation),
|
|
225
|
-
});
|
|
226
|
-
const searchIndex = createSearchIndex({
|
|
227
|
-
room: (room) => readSide.room(room),
|
|
228
|
-
document: (room, path) => readSide.document(room, path),
|
|
229
|
-
});
|
|
230
|
-
const roomsToIndex = new Set();
|
|
231
|
-
const conversationsToIndex = new Set();
|
|
232
|
-
let indexing = false;
|
|
233
|
-
const journal = createLog();
|
|
234
|
-
const keptFiles = openedFiles(options.database, isFenced);
|
|
235
|
-
let notifyReady = () => { };
|
|
236
|
-
const ready = new Promise((resolve) => {
|
|
237
|
-
notifyReady = resolve;
|
|
238
|
-
});
|
|
239
|
-
function rememberRoomDraft(record) {
|
|
240
|
-
const room = roomDrafts.get(record.locator) ?? new Map();
|
|
241
|
-
room.set(record.path, record);
|
|
242
|
-
roomDrafts.set(record.locator, room);
|
|
243
|
-
}
|
|
244
|
-
function forgetRoomDraft(locator, path) {
|
|
245
|
-
const room = roomDrafts.get(locator);
|
|
246
|
-
if (room === undefined)
|
|
247
|
-
return;
|
|
248
|
-
room.delete(path);
|
|
249
|
-
if (room.size === 0)
|
|
250
|
-
roomDrafts.delete(locator);
|
|
251
|
-
}
|
|
252
|
-
function roomDraftOf(record) {
|
|
253
|
-
return structuredClone({
|
|
254
|
-
room: record.locator,
|
|
255
|
-
path: record.path,
|
|
256
|
-
revision: record.revision,
|
|
257
|
-
parts: record.parts,
|
|
258
|
-
changedUnderneath: underneath(record.parts, record.path, replicas.get(record.locator)?.visible),
|
|
259
|
-
returned: record.returned,
|
|
260
|
-
});
|
|
261
|
-
}
|
|
262
|
-
function snapshotRoomDrafts() {
|
|
263
|
-
const records = [...roomDrafts.values()].flatMap((room) => [...room.values()]);
|
|
264
|
-
records.sort((left, right) => {
|
|
265
|
-
if (left.locator !== right.locator)
|
|
266
|
-
return left.locator < right.locator ? -1 : 1;
|
|
267
|
-
if (left.path !== right.path)
|
|
268
|
-
return left.path < right.path ? -1 : 1;
|
|
269
|
-
return 0;
|
|
270
|
-
});
|
|
271
|
-
return records.map(roomDraftOf);
|
|
272
|
-
}
|
|
273
|
-
function publishRoomDrafts(waitingOnly) {
|
|
274
|
-
if (closed)
|
|
275
|
-
return;
|
|
276
|
-
const value = snapshotRoomDrafts();
|
|
277
|
-
for (const listener of roomDraftListeners) {
|
|
278
|
-
if (waitingOnly && listener.ready)
|
|
279
|
-
continue;
|
|
280
|
-
listener.ready = true;
|
|
281
|
-
listener.notify(value);
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
function presentationOf(app) {
|
|
285
|
-
const value = presentations.get(app);
|
|
286
|
-
return value === undefined ? null : structuredClone(value);
|
|
287
|
-
}
|
|
288
|
-
function keepPresentation(app, next) {
|
|
289
|
-
return exclusive(async () => {
|
|
290
|
-
const local = await openLocal();
|
|
291
|
-
const stored = next(presentations.get(app));
|
|
292
|
-
await local.present({ app, value: stored });
|
|
293
|
-
presentations.set(app, stored);
|
|
294
|
-
publishChangeSet(changeSet('', null, null, { presentation: app }));
|
|
295
|
-
});
|
|
296
|
-
}
|
|
297
|
-
function emitPresentation(app) {
|
|
298
|
-
if (closed)
|
|
299
|
-
return;
|
|
300
|
-
for (const listener of presentationListeners) {
|
|
301
|
-
if (listener.app === app && listener.ready)
|
|
302
|
-
listener.notify(presentationOf(app));
|
|
303
|
-
}
|
|
304
|
-
}
|
|
305
|
-
function pending() {
|
|
306
|
-
return (!localSaves &&
|
|
307
|
-
(queuesWithoutReplica.size > 0 ||
|
|
308
|
-
[...replicas.values()].some((replica) => replica.queue.length > 0)));
|
|
309
|
-
}
|
|
310
|
-
function attention() {
|
|
311
|
-
const attentionRequired = [];
|
|
312
|
-
for (const record of [...roomDrafts.values()].flatMap((room) => [...room.values()])) {
|
|
313
|
-
if (record.returned === null)
|
|
314
|
-
continue;
|
|
315
|
-
attentionRequired.push({
|
|
316
|
-
room: record.locator,
|
|
317
|
-
path: record.path,
|
|
318
|
-
returned: structuredClone(record.returned),
|
|
319
|
-
});
|
|
320
|
-
}
|
|
321
|
-
for (const [room, refusal] of sourceRefusals)
|
|
322
|
-
attentionRequired.push({ room, refusal: structuredClone(refusal) });
|
|
323
|
-
attentionRequired.sort((left, right) => {
|
|
324
|
-
if (left.room !== right.room)
|
|
325
|
-
return left.room < right.room ? -1 : 1;
|
|
326
|
-
if ('refusal' in left || 'refusal' in right) {
|
|
327
|
-
if ('refusal' in left && 'refusal' in right)
|
|
328
|
-
return 0;
|
|
329
|
-
return 'refusal' in left ? -1 : 1;
|
|
330
|
-
}
|
|
331
|
-
if (left.path !== right.path)
|
|
332
|
-
return left.path < right.path ? -1 : 1;
|
|
333
|
-
return 0;
|
|
334
|
-
});
|
|
335
|
-
let reset = null;
|
|
336
|
-
for (const { submission } of pendings.values()) {
|
|
337
|
-
if (submission.state !== 'reset')
|
|
338
|
-
continue;
|
|
339
|
-
if (reset === null || submission.reset < reset)
|
|
340
|
-
reset = submission.reset;
|
|
341
|
-
}
|
|
342
|
-
return { attentionRequired, reset };
|
|
343
|
-
}
|
|
344
|
-
function documentsIn(locator) {
|
|
345
|
-
const replica = replicas.get(locator);
|
|
346
|
-
return replica === undefined ? 0 : finished(counting(replica));
|
|
347
|
-
}
|
|
348
|
-
function* counting(replica) {
|
|
349
|
-
const weighed = outsideOf(replica.confirmed.record.typedSelection?.roots ?? []);
|
|
350
|
-
return ((yield* tallying(replica.visible.documents, weighed.documents)) +
|
|
351
|
-
(yield* tallying(replica.visible.binaries, weighed.binaries)));
|
|
352
|
-
}
|
|
353
|
-
function listed() {
|
|
354
|
-
return structuredClone([...rooms.values()].map((room) => {
|
|
355
|
-
const documents = documentsIn(room.locator);
|
|
356
|
-
counted.set(room.locator, documents);
|
|
357
|
-
return locked(room.locator)
|
|
358
|
-
? {
|
|
359
|
-
...room,
|
|
360
|
-
model: modelTypes(NO_MODEL),
|
|
361
|
-
typedSelection: null,
|
|
362
|
-
documents: 0,
|
|
363
|
-
locked: true,
|
|
364
|
-
}
|
|
365
|
-
: { ...room, documents, locked: false };
|
|
366
|
-
}));
|
|
367
|
-
}
|
|
368
|
-
function locked(locator) {
|
|
369
|
-
return rooms.get(locator)?.replica.offline === 'locked' && !confirmed.has(locator);
|
|
370
|
-
}
|
|
371
|
-
function lockedRooms() {
|
|
372
|
-
return [...rooms.keys()].filter(locked).sort();
|
|
373
|
-
}
|
|
374
|
-
function relocked(before) {
|
|
375
|
-
const after = lockedRooms();
|
|
376
|
-
if (JSON.stringify(after) === JSON.stringify(before))
|
|
377
|
-
return;
|
|
378
|
-
journal.record(`locked ${after.length}`);
|
|
379
|
-
emitRooms();
|
|
380
|
-
for (const notify of [...lockListeners])
|
|
381
|
-
notify();
|
|
382
|
-
}
|
|
383
|
-
function confirmLocks(listed) {
|
|
384
|
-
if (!socketOpen)
|
|
385
|
-
return;
|
|
386
|
-
for (const room of listed) {
|
|
387
|
-
if (room.replica.admission === 'admitted')
|
|
388
|
-
confirmed.add(room.locator);
|
|
389
|
-
}
|
|
390
|
-
}
|
|
391
|
-
function connectionLost() {
|
|
392
|
-
if (lockGrace !== null || closed)
|
|
393
|
-
return;
|
|
394
|
-
lockGrace = setTimeout(() => {
|
|
395
|
-
lockGrace = null;
|
|
396
|
-
if (socketOpen || closed)
|
|
397
|
-
return;
|
|
398
|
-
const before = lockedRooms();
|
|
399
|
-
confirmed.clear();
|
|
400
|
-
relocked(before);
|
|
401
|
-
}, LOCK_GRACE_MS);
|
|
402
|
-
}
|
|
403
|
-
function connectionLive() {
|
|
404
|
-
if (lockGrace !== null)
|
|
405
|
-
clearTimeout(lockGrace);
|
|
406
|
-
lockGrace = null;
|
|
407
|
-
}
|
|
408
|
-
function watchLocks(notify) {
|
|
409
|
-
lockListeners.add(notify);
|
|
410
|
-
return () => {
|
|
411
|
-
lockListeners.delete(notify);
|
|
412
|
-
};
|
|
413
|
-
}
|
|
414
|
-
function roomFacts(reach = null) {
|
|
415
|
-
const held = [...rooms.values()]
|
|
416
|
-
.filter((room) => holds(reach, room.locator))
|
|
417
|
-
.map((room) => {
|
|
418
|
-
const governed = governs(reach, room);
|
|
419
|
-
const attached = [
|
|
420
|
-
...(governed.collection ? [modelOf(room.locator)] : []),
|
|
421
|
-
...(governed.selection ? [modelOf(room.locator, 'typed-selection')] : []),
|
|
422
|
-
];
|
|
423
|
-
return {
|
|
424
|
-
locator: room.locator,
|
|
425
|
-
available: attached.every((model) => model.status !== 'unavailable'),
|
|
426
|
-
types: attached.flatMap((model) => model.status === 'unavailable' ? [] : Object.values(model.types)),
|
|
427
|
-
};
|
|
428
|
-
});
|
|
429
|
-
return { listed: roomsListed, rooms: held };
|
|
430
|
-
}
|
|
431
|
-
function emitRooms() {
|
|
432
|
-
readSide.recover();
|
|
433
|
-
queueReadiness();
|
|
434
|
-
const value = listed();
|
|
435
|
-
for (const listener of roomListeners)
|
|
436
|
-
listener(value);
|
|
437
|
-
}
|
|
438
|
-
function emitRefusal() {
|
|
439
|
-
queueReadiness();
|
|
440
|
-
for (const listener of refusalListeners)
|
|
441
|
-
listener(refusal);
|
|
442
|
-
}
|
|
443
|
-
function emitStorageLoss() {
|
|
444
|
-
queueReadiness();
|
|
445
|
-
for (const listener of storageLossListeners)
|
|
446
|
-
listener(storageLoss);
|
|
447
|
-
}
|
|
448
|
-
function emitMember() {
|
|
449
|
-
for (const listener of memberListeners)
|
|
450
|
-
listener(member);
|
|
451
|
-
}
|
|
452
|
-
function moveTo(next) {
|
|
453
|
-
if (closed)
|
|
454
|
-
return;
|
|
455
|
-
status = next;
|
|
456
|
-
show();
|
|
457
|
-
}
|
|
458
|
-
function show() {
|
|
459
|
-
if (closed)
|
|
460
|
-
return;
|
|
461
|
-
queueReadiness();
|
|
462
|
-
const next = status.state === 'synced' && !conversations.current()
|
|
463
|
-
? { ...status, state: 'syncing' }
|
|
464
|
-
: status;
|
|
465
|
-
if (same(shown, next))
|
|
466
|
-
return;
|
|
467
|
-
shown = next;
|
|
468
|
-
for (const listener of statusListeners)
|
|
469
|
-
listener(shown);
|
|
470
|
-
}
|
|
471
|
-
function entryOf(locator, batch) {
|
|
472
|
-
if (localSaves)
|
|
473
|
-
return Object.freeze({ batch, state: 'local' });
|
|
474
|
-
const state = pendings.get(pendingKey(locator, batch.id));
|
|
475
|
-
if (state?.accepted !== undefined) {
|
|
476
|
-
return Object.freeze({ batch, state: 'accepted', roomVersion: state.accepted });
|
|
477
|
-
}
|
|
478
|
-
return Object.freeze({ batch, ...(state?.submission ?? { state: 'waiting' }) });
|
|
479
|
-
}
|
|
480
|
-
function entriesOf(locator) {
|
|
481
|
-
return (replicas.get(locator)?.queue ?? queuesWithoutReplica.get(locator) ?? []).map((batch) => entryOf(locator, batch));
|
|
482
|
-
}
|
|
483
|
-
function emitQueue(locator) {
|
|
484
|
-
const entries = entriesOf(locator);
|
|
485
|
-
for (const subscription of queueSubscriptions) {
|
|
486
|
-
if (subscription.locator === locator)
|
|
487
|
-
subscription.notify(entries);
|
|
488
|
-
}
|
|
489
|
-
}
|
|
490
|
-
function applyChangeSet(set) {
|
|
491
|
-
const held = {
|
|
492
|
-
...set,
|
|
493
|
-
documents: set.documents.filter(({ locator }) => prepared.has(locator) || projecting.has(locator)),
|
|
494
|
-
};
|
|
495
|
-
const applied = readSide.apply(held, () => searchIndex.changed(held));
|
|
496
|
-
if (applied instanceof Promise)
|
|
497
|
-
void applied.catch(unpublished);
|
|
498
|
-
}
|
|
499
|
-
function unpublished(error) {
|
|
500
|
-
journal.record(`publication failed ${error instanceof Error ? error.name : 'unknown'}`);
|
|
501
|
-
}
|
|
502
|
-
async function referenced(locator) {
|
|
503
|
-
for (;;) {
|
|
504
|
-
const record = replicas.get(locator)?.confirmed.record;
|
|
505
|
-
if (record === undefined || closed)
|
|
506
|
-
return;
|
|
507
|
-
const held = { text: record.documents, binaries: record.binaries };
|
|
508
|
-
const composition = compositionOf(record);
|
|
509
|
-
if (referencesIndexed(held, composition))
|
|
510
|
-
return;
|
|
511
|
-
await indexReferrers(held, composition);
|
|
512
|
-
}
|
|
513
|
-
}
|
|
514
|
-
async function prepareReplica(locator) {
|
|
515
|
-
await referenced(locator);
|
|
516
|
-
const replica = replicas.get(locator);
|
|
517
|
-
if (replica === undefined || closed || prepared.has(locator))
|
|
518
|
-
return;
|
|
519
|
-
const visible = replica.visible;
|
|
520
|
-
const entered = [];
|
|
521
|
-
projecting.add(locator);
|
|
522
|
-
try {
|
|
523
|
-
await inChunks(await stepped(keysIn(visible.documents, visible.binaries)), (path) => ROW_WEIGHT + (visible.documents[path]?.length ?? 0), (chunk) => {
|
|
524
|
-
const current = replicas.get(locator);
|
|
525
|
-
if (current === undefined || closed)
|
|
526
|
-
return;
|
|
527
|
-
const set = entering(locator, current, chunk);
|
|
528
|
-
entered.push(set);
|
|
529
|
-
return readSide.apply(set);
|
|
530
|
-
});
|
|
531
|
-
if (!replicas.has(locator) || closed)
|
|
532
|
-
return;
|
|
533
|
-
prepared.add(locator);
|
|
534
|
-
}
|
|
535
|
-
finally {
|
|
536
|
-
projecting.delete(locator);
|
|
537
|
-
}
|
|
538
|
-
conversations.changed(mergeChangeSets(entered));
|
|
539
|
-
readSide.recover();
|
|
540
|
-
queueReadiness();
|
|
541
|
-
}
|
|
542
|
-
function unprepared() {
|
|
543
|
-
return [...unpreparedDemand, ...replicas.keys()].find((locator) => !prepared.has(locator) && !unindexable.has(locator));
|
|
544
|
-
}
|
|
545
|
-
function unbuilt(locator, error) {
|
|
546
|
-
unindexable.add(locator);
|
|
547
|
-
journal.record(`index failed ${locator} ${error instanceof Error ? error.name : 'unknown'}`);
|
|
548
|
-
queueReadiness();
|
|
549
|
-
}
|
|
550
|
-
function prepare(locators = []) {
|
|
551
|
-
for (const locator of locators)
|
|
552
|
-
unpreparedDemand.add(locator);
|
|
553
|
-
if (preparing)
|
|
554
|
-
return;
|
|
555
|
-
preparing = true;
|
|
556
|
-
void (async () => {
|
|
557
|
-
try {
|
|
558
|
-
for (let waiting = unprepared(); waiting !== undefined; waiting = unprepared()) {
|
|
559
|
-
await yielded();
|
|
560
|
-
if (closed)
|
|
561
|
-
return;
|
|
562
|
-
unpreparedDemand.delete(waiting);
|
|
563
|
-
await prepareReplica(waiting).catch((error) => unbuilt(waiting, error));
|
|
564
|
-
}
|
|
565
|
-
}
|
|
566
|
-
finally {
|
|
567
|
-
preparing = false;
|
|
568
|
-
}
|
|
569
|
-
})();
|
|
570
|
-
}
|
|
571
|
-
function roomsOfReach(reach) {
|
|
572
|
-
return new Set([...reach.rooms, ...reach.documents.map(roomOfKey)]);
|
|
573
|
-
}
|
|
574
|
-
function reachedRooms(plan) {
|
|
575
|
-
const reached = plan.reach === null ? null : roomsOfReach(plan.reach);
|
|
576
|
-
const named = plan.rooms ??
|
|
577
|
-
(reached === null
|
|
578
|
-
? [...new Set([...rooms.keys(), ...replicas.keys(), ...queuesWithoutReplica.keys()])]
|
|
579
|
-
: [...reached]);
|
|
580
|
-
return [...new Set(named)]
|
|
581
|
-
.filter((locator) => (reached === null || reached.has(locator)) && !plan.locked.includes(locator))
|
|
582
|
-
.sort();
|
|
583
|
-
}
|
|
584
|
-
function awaited(locator) {
|
|
585
|
-
return (!roomsListed ||
|
|
586
|
-
(rooms.has(locator) && discovered.get(locator)?.replica.admission === 'admitted'));
|
|
587
|
-
}
|
|
588
|
-
function covered(plan) {
|
|
589
|
-
const locators = reachedRooms(plan);
|
|
590
|
-
if (locators.length === 0 && plan.rooms === null && plan.reach === null && !roomsListed) {
|
|
591
|
-
return { pending: [] };
|
|
592
|
-
}
|
|
593
|
-
const pending = [];
|
|
594
|
-
const coverage = [];
|
|
595
|
-
const overlay = [];
|
|
596
|
-
for (const locator of locators) {
|
|
597
|
-
const replica = replicas.get(locator);
|
|
598
|
-
if (replica === undefined) {
|
|
599
|
-
if (awaited(locator))
|
|
600
|
-
pending.push({ room: locator, awaits: 'acquisition' });
|
|
601
|
-
continue;
|
|
602
|
-
}
|
|
603
|
-
if (!prepared.has(locator)) {
|
|
604
|
-
pending.push({ room: locator, awaits: 'preparation' });
|
|
605
|
-
continue;
|
|
606
|
-
}
|
|
607
|
-
coverage.push({
|
|
608
|
-
room: locator,
|
|
609
|
-
generation: replica.confirmed.record.transfer,
|
|
610
|
-
current: !(catching.has(locator) || owed.has(locator) || transfers.has(locator)),
|
|
611
|
-
});
|
|
612
|
-
for (const batch of replica.queue)
|
|
613
|
-
overlay.push(batch.id);
|
|
614
|
-
}
|
|
615
|
-
if (pending.length > 0)
|
|
616
|
-
return { pending };
|
|
617
|
-
return { coverage: { rooms: coverage, indexes: [], overlay } };
|
|
618
|
-
}
|
|
619
|
-
function awaitPreparation(cover) {
|
|
620
|
-
if (!('pending' in cover))
|
|
621
|
-
return;
|
|
622
|
-
const waiting = cover.pending.filter(({ awaits }) => awaits === 'preparation');
|
|
623
|
-
if (waiting.length > 0)
|
|
624
|
-
prepare(waiting.map(({ room }) => room));
|
|
625
|
-
}
|
|
626
|
-
function requiredRooms(given) {
|
|
627
|
-
const reach = planReach(given);
|
|
628
|
-
if (reach === null)
|
|
629
|
-
return { listed: roomsListed, rooms: [...rooms.keys()].sort() };
|
|
630
|
-
const named = [...roomsOfReach(reach)].sort();
|
|
631
|
-
if (roomsListed)
|
|
632
|
-
return { listed: true, rooms: named.filter((room) => rooms.has(room)) };
|
|
633
|
-
return { listed: named.every((room) => replicas.has(room)), rooms: named };
|
|
634
|
-
}
|
|
635
|
-
function roomState(locator, search) {
|
|
636
|
-
if (sourceRefusals.has(locator))
|
|
637
|
-
return 'refused';
|
|
638
|
-
const listedRoom = discovered.get(locator);
|
|
639
|
-
if (roomsListed &&
|
|
640
|
-
(listedRoom === undefined ||
|
|
641
|
-
listedRoom.replica.admission !== 'admitted' ||
|
|
642
|
-
unreadable.has(locator)))
|
|
643
|
-
return 'unadmitted';
|
|
644
|
-
if (!replicas.has(locator))
|
|
645
|
-
return 'acquiring';
|
|
646
|
-
if (!prepared.has(locator))
|
|
647
|
-
return 'preparing';
|
|
648
|
-
if (search && !searchIndex.rooms().has(locator))
|
|
649
|
-
return 'indexing';
|
|
650
|
-
return 'complete';
|
|
651
|
-
}
|
|
652
|
-
function conversationCoverage(reach, search) {
|
|
653
|
-
const declared = reach === null || reach.conversations;
|
|
654
|
-
if (!declared || options.adapter.conversations === undefined || declaredAgents() === undefined)
|
|
655
|
-
return 'undeclared';
|
|
656
|
-
if (!conversations.known() || !conversations.current())
|
|
657
|
-
return 'acquiring';
|
|
658
|
-
if (!search)
|
|
659
|
-
return 'complete';
|
|
660
|
-
const unindexed = conversations
|
|
661
|
-
.searchable()
|
|
662
|
-
.filter((one) => conversations.acquired(one) && !searchIndex.conversations().has(one));
|
|
663
|
-
if (unindexed.length === 0)
|
|
664
|
-
return 'complete';
|
|
665
|
-
index([], unindexed);
|
|
666
|
-
return 'indexing';
|
|
667
|
-
}
|
|
668
|
-
function connectionOf() {
|
|
669
|
-
if (socketOpen)
|
|
670
|
-
return 'connected';
|
|
671
|
-
if (status.providerUnreachable)
|
|
672
|
-
return 'unreachable';
|
|
673
|
-
return options.adapter.roomStream === undefined && status.lastCompleted !== null
|
|
674
|
-
? 'connected'
|
|
675
|
-
: 'connecting';
|
|
676
|
-
}
|
|
677
|
-
function refusedIn(locators) {
|
|
678
|
-
return locators.flatMap((room) => {
|
|
679
|
-
const held = sourceRefusals.get(room);
|
|
680
|
-
if (held === undefined)
|
|
681
|
-
return [];
|
|
682
|
-
const { file, location } = held.fields;
|
|
683
|
-
return [
|
|
684
|
-
{
|
|
685
|
-
room,
|
|
686
|
-
file: typeof file === 'string' ? file : '',
|
|
687
|
-
rule: held.code,
|
|
688
|
-
location: typeof location === 'string' ? location : null,
|
|
689
|
-
},
|
|
690
|
-
];
|
|
691
|
-
});
|
|
692
|
-
}
|
|
693
|
-
function readinessFor(port, reach) {
|
|
694
|
-
const required = requiredRooms(reach);
|
|
695
|
-
const search = port.search === 'required';
|
|
696
|
-
const coverage = required.rooms.map((room) => ({ room, state: roomState(room, search) }));
|
|
697
|
-
const building = (state) => coverage
|
|
698
|
-
.filter((room) => room.state === state && !unindexable.has(room.room))
|
|
699
|
-
.map(({ room }) => room);
|
|
700
|
-
const preparing = building('preparing');
|
|
701
|
-
if (preparing.length > 0)
|
|
702
|
-
prepare(preparing);
|
|
703
|
-
const indexing = building('indexing');
|
|
704
|
-
if (indexing.length > 0)
|
|
705
|
-
index(indexing, []);
|
|
706
|
-
return readinessOf({
|
|
707
|
-
code: port.code,
|
|
708
|
-
coverage: {
|
|
709
|
-
listed: required.listed,
|
|
710
|
-
rooms: coverage,
|
|
711
|
-
conversations: conversationCoverage(reach, search),
|
|
712
|
-
search: search ? 'required' : 'unused',
|
|
713
|
-
},
|
|
714
|
-
persistence,
|
|
715
|
-
connection: connectionOf(),
|
|
716
|
-
house: refusal !== null ? 'refused' : writesHeld() ? 'write-halted' : 'open',
|
|
717
|
-
capacity: capacity !== null &&
|
|
718
|
-
coverage.some(({ room, state }) => paused.has(room) || !SETTLED_ROOMS.has(state))
|
|
719
|
-
? capacity
|
|
720
|
-
: port.capacity,
|
|
721
|
-
refused: refusedIn(required.rooms),
|
|
722
|
-
lost: storageLoss !== null,
|
|
723
|
-
established: targets[port.target]?.established === true,
|
|
724
|
-
});
|
|
725
|
-
}
|
|
726
|
-
function establish(name) {
|
|
727
|
-
targets = { ...targets, [name]: { established: true } };
|
|
728
|
-
queueReadiness();
|
|
729
|
-
void durably((local) => local.keepTargets(targets)).catch(() => {
|
|
730
|
-
journal.record(`target record failed ${name}`);
|
|
731
|
-
});
|
|
732
|
-
}
|
|
733
|
-
function deliverReadiness(watch) {
|
|
734
|
-
if (!readinessWatches.has(watch))
|
|
735
|
-
return;
|
|
736
|
-
const readiness = readinessFor(watch.port, watch.reach);
|
|
737
|
-
if (readiness.ready && targets[watch.port.target]?.established !== true) {
|
|
738
|
-
establish(watch.port.target);
|
|
739
|
-
}
|
|
740
|
-
const shown = JSON.stringify(readiness);
|
|
741
|
-
if (shown === watch.last)
|
|
742
|
-
return;
|
|
743
|
-
watch.last = shown;
|
|
744
|
-
watch.deliver(structuredClone(readiness));
|
|
745
|
-
}
|
|
746
|
-
function queueReadiness() {
|
|
747
|
-
if (readinessQueued || closed || readinessWatches.size === 0)
|
|
748
|
-
return;
|
|
749
|
-
readinessQueued = true;
|
|
750
|
-
queueMicrotask(() => {
|
|
751
|
-
readinessQueued = false;
|
|
752
|
-
if (closed)
|
|
753
|
-
return;
|
|
754
|
-
for (const watch of [...readinessWatches])
|
|
755
|
-
deliverReadiness(watch);
|
|
756
|
-
});
|
|
757
|
-
}
|
|
758
|
-
function watchReadiness(port, reach, deliver) {
|
|
759
|
-
const watch = { port, reach, deliver, last: null };
|
|
760
|
-
readinessWatches.add(watch);
|
|
761
|
-
void openLocal().then(() => deliverReadiness(watch), () => deliverReadiness(watch));
|
|
762
|
-
return () => {
|
|
763
|
-
readinessWatches.delete(watch);
|
|
764
|
-
};
|
|
765
|
-
}
|
|
766
|
-
function layerBytes(layer) {
|
|
767
|
-
let bytes = 0;
|
|
768
|
-
for (const [path, text] of Object.entries(layer.documents))
|
|
769
|
-
bytes += (path.length + text.length) * 2;
|
|
770
|
-
return bytes;
|
|
771
|
-
}
|
|
772
|
-
function grownBy(next, previous) {
|
|
773
|
-
if (previous === undefined)
|
|
774
|
-
return layerBytes(next);
|
|
775
|
-
const documents = Object.fromEntries(Object.entries(next.documents).filter(([path, text]) => previous.documents[path] !== text));
|
|
776
|
-
return layerBytes({ ...next, documents });
|
|
777
|
-
}
|
|
778
|
-
function exceeded(error) {
|
|
779
|
-
return (typeof error === 'object' &&
|
|
780
|
-
error !== null &&
|
|
781
|
-
error.name === 'QuotaExceededError');
|
|
782
|
-
}
|
|
783
|
-
async function estimated() {
|
|
784
|
-
const estimate = options.shell.estimate === undefined ? null : await options.shell.estimate();
|
|
785
|
-
return estimate === null ? null : Math.max(0, estimate.total - estimate.usage);
|
|
786
|
-
}
|
|
787
|
-
function pause(locator, cause) {
|
|
788
|
-
paused.add(locator);
|
|
789
|
-
capacity = cause;
|
|
790
|
-
journal.record(`capacity ${cause.cause} ${locator} ${cause.needed} ${cause.available ?? '-'}`);
|
|
791
|
-
queueReadiness();
|
|
792
|
-
if (rechecking !== null)
|
|
793
|
-
return;
|
|
794
|
-
// A paused preparation measures the browser's space again each minute, so space freed elsewhere resumes it without a retry.
|
|
795
|
-
rechecking = setInterval(() => {
|
|
796
|
-
void recheck();
|
|
797
|
-
}, 60_000);
|
|
798
|
-
}
|
|
799
|
-
async function recheck() {
|
|
800
|
-
const held = capacity;
|
|
801
|
-
if (held === null || closed)
|
|
802
|
-
return;
|
|
803
|
-
const available = await estimated().catch(() => null);
|
|
804
|
-
if (available === null || available < (held.needed ?? 0))
|
|
805
|
-
return;
|
|
806
|
-
if (held.cause === 'storage-exceeded' &&
|
|
807
|
-
(held.available === null || available <= held.available))
|
|
808
|
-
return;
|
|
809
|
-
resume();
|
|
810
|
-
}
|
|
811
|
-
function resume() {
|
|
812
|
-
if (rechecking !== null)
|
|
813
|
-
clearInterval(rechecking);
|
|
814
|
-
rechecking = null;
|
|
815
|
-
if (paused.size === 0 && capacity === null)
|
|
816
|
-
return;
|
|
817
|
-
paused.clear();
|
|
818
|
-
capacity = null;
|
|
819
|
-
journal.record('capacity resumed');
|
|
820
|
-
queueReadiness();
|
|
821
|
-
if (!closed && authorization !== undefined)
|
|
822
|
-
void sync('unstreamed');
|
|
823
|
-
}
|
|
824
|
-
async function reclaimed(local) {
|
|
825
|
-
const unreferenced = [...transfers.keys()].filter((locator) => !discovered.has(locator));
|
|
826
|
-
for (const locator of unreferenced) {
|
|
827
|
-
await local.abandon(locator);
|
|
828
|
-
transfers.delete(locator);
|
|
829
|
-
}
|
|
830
|
-
if (unreferenced.length > 0)
|
|
831
|
-
journal.record(`capacity reclaimed ${unreferenced.length}`);
|
|
832
|
-
return unreferenced.length > 0;
|
|
833
|
-
}
|
|
834
|
-
async function admitted(local, locator, needed) {
|
|
835
|
-
if (paused.has(locator))
|
|
836
|
-
return false;
|
|
837
|
-
let available = await estimated().catch(() => null);
|
|
838
|
-
if (available === null || available >= needed)
|
|
839
|
-
return true;
|
|
840
|
-
if (await reclaimed(local))
|
|
841
|
-
available = await estimated().catch(() => null);
|
|
842
|
-
if (available === null || available >= needed)
|
|
843
|
-
return true;
|
|
844
|
-
pause(locator, { cause: 'insufficient-space', needed, available });
|
|
845
|
-
return false;
|
|
846
|
-
}
|
|
847
|
-
async function exceededOn(locator, bytes) {
|
|
848
|
-
const available = await estimated().catch(() => null);
|
|
849
|
-
pause(locator, { cause: 'storage-exceeded', needed: bytes, available });
|
|
850
|
-
}
|
|
851
|
-
function seedRoomHeld(room, version) {
|
|
852
|
-
return prepared.has(room) && reachedBy(room, version);
|
|
853
|
-
}
|
|
854
|
-
function seedHeld(at) {
|
|
855
|
-
return Object.entries(at).every(([room, version]) => (roomsListed && !rooms.has(room)) || seedRoomHeld(room, version));
|
|
856
|
-
}
|
|
857
|
-
function seedApplies(plan) {
|
|
858
|
-
const seed = seeds.get(plan.key);
|
|
859
|
-
if (seed === undefined)
|
|
860
|
-
return null;
|
|
861
|
-
if (!seedHeld(seed.at))
|
|
862
|
-
return seed;
|
|
863
|
-
seeds.delete(plan.key);
|
|
864
|
-
return null;
|
|
865
|
-
}
|
|
866
|
-
function seedBehind(plan, cover) {
|
|
867
|
-
const seed = seedApplies(plan);
|
|
868
|
-
if (seed === null || 'pending' in cover)
|
|
869
|
-
return cover;
|
|
870
|
-
return {
|
|
871
|
-
pending: Object.entries(seed.at)
|
|
872
|
-
.filter(([room, version]) => !seedRoomHeld(room, version))
|
|
873
|
-
.map(([room]) => ({ room, awaits: 'acquisition' })),
|
|
874
|
-
};
|
|
875
|
-
}
|
|
876
|
-
function seed(entry) {
|
|
877
|
-
if (seedHeld(entry.at))
|
|
878
|
-
return;
|
|
879
|
-
for (const { query, rows } of entry.queries) {
|
|
880
|
-
const key = queryKey(query);
|
|
881
|
-
seeds.set(key, { rows, at: entry.at });
|
|
882
|
-
for (const shown of seedWatchers.get(key) ?? [])
|
|
883
|
-
shown();
|
|
884
|
-
}
|
|
885
|
-
}
|
|
886
|
-
async function rowsQuery(plan) {
|
|
887
|
-
const before = covered(plan);
|
|
888
|
-
awaitPreparation(before);
|
|
889
|
-
const seeded = seedApplies(plan);
|
|
890
|
-
if (seeded !== null)
|
|
891
|
-
return seededResult(seeded).result;
|
|
892
|
-
if ('pending' in before)
|
|
893
|
-
return before;
|
|
894
|
-
const { rows, at: cover } = await readSide.query(plan, () => covered(plan));
|
|
895
|
-
awaitPreparation(cover);
|
|
896
|
-
if ('pending' in cover)
|
|
897
|
-
return cover;
|
|
898
|
-
return { ...rows, coverage: cover.coverage };
|
|
899
|
-
}
|
|
900
|
-
async function indexConversation(conversation) {
|
|
901
|
-
searchIndex.indexMessages(conversation, [], false);
|
|
902
|
-
let after = null;
|
|
903
|
-
for (;;) {
|
|
904
|
-
const batch = await durably((local) => local.messagesAfter(conversation, after));
|
|
905
|
-
if (closed)
|
|
906
|
-
return;
|
|
907
|
-
searchIndex.indexMessages(conversation, batch.map(({ identity, text }) => ({ conversation, identity, text })), batch.length === 0);
|
|
908
|
-
if (batch.length === 0)
|
|
909
|
-
return;
|
|
910
|
-
after = batch[batch.length - 1].identity;
|
|
911
|
-
}
|
|
912
|
-
}
|
|
913
|
-
function indexNext() {
|
|
914
|
-
const room = [...roomsToIndex].find((locator) => !searchIndex.rooms().has(locator) && !unindexable.has(locator));
|
|
915
|
-
if (room !== undefined) {
|
|
916
|
-
roomsToIndex.delete(room);
|
|
917
|
-
return () => prepared.has(room)
|
|
918
|
-
? searchIndex.indexRoom(room).catch((error) => unbuilt(room, error))
|
|
919
|
-
: undefined;
|
|
920
|
-
}
|
|
921
|
-
const conversation = [...conversationsToIndex].find((one) => !searchIndex.conversations().has(one));
|
|
922
|
-
if (conversation === undefined)
|
|
923
|
-
return null;
|
|
924
|
-
conversationsToIndex.delete(conversation);
|
|
925
|
-
return () => indexConversation(conversation);
|
|
926
|
-
}
|
|
927
|
-
function index(rooms, named) {
|
|
928
|
-
for (const room of rooms)
|
|
929
|
-
roomsToIndex.add(room);
|
|
930
|
-
for (const conversation of named)
|
|
931
|
-
conversationsToIndex.add(conversation);
|
|
932
|
-
if (indexing)
|
|
933
|
-
return;
|
|
934
|
-
indexing = true;
|
|
935
|
-
void (async () => {
|
|
936
|
-
try {
|
|
937
|
-
for (let unit = indexNext(); unit !== null && !closed; unit = indexNext()) {
|
|
938
|
-
await yielded();
|
|
939
|
-
await unit();
|
|
940
|
-
queueReadiness();
|
|
941
|
-
}
|
|
942
|
-
}
|
|
943
|
-
finally {
|
|
944
|
-
indexing = false;
|
|
945
|
-
}
|
|
946
|
-
})().catch(() => { });
|
|
947
|
-
}
|
|
948
|
-
function publishChangeSet(set) {
|
|
949
|
-
applyChangeSet(set);
|
|
950
|
-
if (set.rooms.length > 0 ||
|
|
951
|
-
[...new Set(set.documents.map(({ locator }) => locator))].some((locator) => rooms.has(locator) && counted.get(locator) !== documentsIn(locator)))
|
|
952
|
-
emitRooms();
|
|
953
|
-
for (const locator of set.queues)
|
|
954
|
-
emitQueue(locator);
|
|
955
|
-
if (set.drafts.length > 0 ||
|
|
956
|
-
set.documents.some((change) => roomDrafts.get(change.locator)?.has(change.path) === true)) {
|
|
957
|
-
publishRoomDrafts(false);
|
|
958
|
-
}
|
|
959
|
-
for (const app of set.presentations)
|
|
960
|
-
emitPresentation(app);
|
|
961
|
-
conversations.changed(set);
|
|
962
|
-
}
|
|
963
|
-
async function refuse(reason, provider = null) {
|
|
964
|
-
discoveryPaused = true;
|
|
965
|
-
try {
|
|
966
|
-
if (reason === 'revoked-authorization') {
|
|
967
|
-
await exclusive(async () => {
|
|
968
|
-
const revoked = { status: 'unavailable', reason: 'revoked' };
|
|
969
|
-
try {
|
|
970
|
-
const local = await openLocal();
|
|
971
|
-
await local.revokeModels([...replicas.values()].map((replica) => replica.confirmed.record));
|
|
972
|
-
}
|
|
973
|
-
catch {
|
|
974
|
-
journal.record('model revocation persistence failed');
|
|
975
|
-
}
|
|
976
|
-
const keys = new Set(models.keys());
|
|
977
|
-
for (const locator of rooms.keys()) {
|
|
978
|
-
keys.add(modelKey(locator, 'collection'));
|
|
979
|
-
keys.add(modelKey(locator, 'typed-selection'));
|
|
980
|
-
}
|
|
981
|
-
for (const key of keys) {
|
|
982
|
-
invalidModels.add(key);
|
|
983
|
-
models.set(key, revoked);
|
|
984
|
-
liveModels.delete(key);
|
|
985
|
-
}
|
|
986
|
-
const revocations = [];
|
|
987
|
-
for (const locator of [...rooms.keys()]) {
|
|
988
|
-
const before = replicas.get(locator) ?? null;
|
|
989
|
-
const after = before === null
|
|
990
|
-
? null
|
|
991
|
-
: await stepped(replicating(await confirmedOf({ ...before.confirmed.record, model: revoked, selectionModel: revoked }, before.confirmed), before.queue, before));
|
|
992
|
-
const set = await stepped(changing(locator, before, after, { room: true }));
|
|
993
|
-
revocations.push([locator, before, after, set]);
|
|
994
|
-
}
|
|
995
|
-
const changed = [];
|
|
996
|
-
for (const [locator, before, after, set] of revocations) {
|
|
997
|
-
const room = rooms.get(locator);
|
|
998
|
-
if (room === undefined || (replicas.get(locator) ?? null) !== before)
|
|
999
|
-
continue;
|
|
1000
|
-
if (after !== null)
|
|
1001
|
-
replicas.set(locator, after);
|
|
1002
|
-
rooms.set(locator, {
|
|
1003
|
-
...room,
|
|
1004
|
-
model: modelTypes(revoked),
|
|
1005
|
-
typedSelection: room.typedSelection === null
|
|
1006
|
-
? null
|
|
1007
|
-
: { ...room.typedSelection, model: modelTypes(revoked) },
|
|
1008
|
-
});
|
|
1009
|
-
changed.push(set);
|
|
1010
|
-
}
|
|
1011
|
-
publishChangeSet(mergeChangeSets(changed));
|
|
1012
|
-
});
|
|
1013
|
-
}
|
|
1014
|
-
}
|
|
1015
|
-
finally {
|
|
1016
|
-
refusal = {
|
|
1017
|
-
code: reason,
|
|
1018
|
-
retryable: false,
|
|
1019
|
-
reauthorizationOffered: reason === 'revoked-authorization',
|
|
1020
|
-
refusal: provider,
|
|
1021
|
-
};
|
|
1022
|
-
journal.record(`connection refused ${reason}`);
|
|
1023
|
-
emitRefusal();
|
|
1024
|
-
}
|
|
1025
|
-
}
|
|
1026
|
-
function list(room, synchronizationAvailable) {
|
|
1027
|
-
const selection = room.typedSelection ?? null;
|
|
1028
|
-
rooms.set(room.locator, {
|
|
1029
|
-
name: room.name,
|
|
1030
|
-
locator: room.locator,
|
|
1031
|
-
handle: room.handle,
|
|
1032
|
-
operations: room.operations,
|
|
1033
|
-
replica: room.replica,
|
|
1034
|
-
model: modelTypes(modelOf(room.locator)),
|
|
1035
|
-
typedSelection: selection === null
|
|
1036
|
-
? null
|
|
1037
|
-
: {
|
|
1038
|
-
roots: selection.roots,
|
|
1039
|
-
model: modelTypes(modelOf(room.locator, 'typed-selection')),
|
|
1040
|
-
},
|
|
1041
|
-
providerOwnedPaths: room.providerOwnedPaths,
|
|
1042
|
-
roomVersion: replicas.get(room.locator)?.confirmed.record.roomVersion ?? null,
|
|
1043
|
-
synchronizationAvailable,
|
|
1044
|
-
refusal: scopedRefusals.get(room.locator) ?? sourceRefusals.get(room.locator) ?? null,
|
|
1045
|
-
});
|
|
1046
|
-
}
|
|
1047
|
-
async function applyDiscovery(found, started, covered) {
|
|
1048
|
-
const lockedBefore = lockedRooms();
|
|
1049
|
-
for (const room of found) {
|
|
1050
|
-
const fence = fences.get(room.locator);
|
|
1051
|
-
if (fence !== undefined && fence.erased && fence.at < started)
|
|
1052
|
-
fences.delete(room.locator);
|
|
1053
|
-
}
|
|
1054
|
-
await loseRooms(found
|
|
1055
|
-
.filter((room) => room.replica.admission !== 'admitted' && heldLocally(room.locator))
|
|
1056
|
-
.map((room) => room.locator));
|
|
1057
|
-
const listed = found.filter((room) => !fences.has(room.locator));
|
|
1058
|
-
const listedLocators = new Set(listed.map((room) => room.locator));
|
|
1059
|
-
for (const locator of listedLocators)
|
|
1060
|
-
scopedRefusals.delete(locator);
|
|
1061
|
-
if (covered === undefined)
|
|
1062
|
-
discovered.clear();
|
|
1063
|
-
else
|
|
1064
|
-
for (const locator of covered)
|
|
1065
|
-
discovered.delete(locator);
|
|
1066
|
-
for (const room of listed)
|
|
1067
|
-
discovered.set(room.locator, room);
|
|
1068
|
-
const unlisted = unlistedHeld(new Set(found.map((room) => room.locator))).filter((locator) => covered === undefined || covered.includes(locator));
|
|
1069
|
-
if (options.adapter.exhaustiveDiscovery === true)
|
|
1070
|
-
await loseRooms(unlisted);
|
|
1071
|
-
else
|
|
1072
|
-
unlistedKept(unlisted);
|
|
1073
|
-
for (const room of listed) {
|
|
1074
|
-
const held = replicas.get(room.locator)?.confirmed.record;
|
|
1075
|
-
if (held !== undefined && held.replica.selection !== room.replica.selection) {
|
|
1076
|
-
list(held, false);
|
|
1077
|
-
continue;
|
|
1078
|
-
}
|
|
1079
|
-
list(room, room.replica.admission === 'admitted' && !unreadable.has(room.locator));
|
|
1080
|
-
}
|
|
1081
|
-
confirmLocks(listed);
|
|
1082
|
-
roomsListed = true;
|
|
1083
|
-
emitRooms();
|
|
1084
|
-
relocked(lockedBefore);
|
|
1085
|
-
return listed;
|
|
1086
|
-
}
|
|
1087
|
-
function heldLocally(locator) {
|
|
1088
|
-
return (replicas.has(locator) ||
|
|
1089
|
-
roomDrafts.has(locator) ||
|
|
1090
|
-
transfers.has(locator) ||
|
|
1091
|
-
queuesWithoutReplica.has(locator));
|
|
1092
|
-
}
|
|
1093
|
-
function unlistedHeld(listed) {
|
|
1094
|
-
return [
|
|
1095
|
-
...new Set([
|
|
1096
|
-
...rooms.keys(),
|
|
1097
|
-
...roomDrafts.keys(),
|
|
1098
|
-
...transfers.keys(),
|
|
1099
|
-
...queuesWithoutReplica.keys(),
|
|
1100
|
-
]),
|
|
1101
|
-
].filter((locator) => !listed.has(locator));
|
|
1102
|
-
}
|
|
1103
|
-
function unlistedKept(unlisted) {
|
|
1104
|
-
for (const locator of unlisted) {
|
|
1105
|
-
const held = replicas.get(locator)?.confirmed.record;
|
|
1106
|
-
if (held !== undefined)
|
|
1107
|
-
list(held, false);
|
|
1108
|
-
else
|
|
1109
|
-
rooms.delete(locator);
|
|
1110
|
-
}
|
|
1111
|
-
}
|
|
1112
|
-
function fence(locators) {
|
|
1113
|
-
const fresh = [...new Set(locators)].filter((locator) => !fences.has(locator));
|
|
1114
|
-
const removed = fresh.map((locator) => ({
|
|
1115
|
-
locator,
|
|
1116
|
-
shown: prepared.has(locator) || projecting.has(locator) ? (replicas.get(locator) ?? null) : null,
|
|
1117
|
-
drafts: [...(roomDrafts.get(locator)?.keys() ?? [])],
|
|
1118
|
-
}));
|
|
1119
|
-
for (const locator of fresh) {
|
|
1120
|
-
fences.set(locator, { at: discoveries, erased: false });
|
|
1121
|
-
lastFenced.set(locator, ++fencings);
|
|
1122
|
-
confirmed.delete(locator);
|
|
1123
|
-
for (const batch of replicas.get(locator)?.queue ?? queuesWithoutReplica.get(locator) ?? [])
|
|
1124
|
-
pendings.delete(pendingKey(locator, batch.id));
|
|
1125
|
-
replicas.delete(locator);
|
|
1126
|
-
queuesWithoutReplica.delete(locator);
|
|
1127
|
-
rooms.delete(locator);
|
|
1128
|
-
roomDrafts.delete(locator);
|
|
1129
|
-
transfers.delete(locator);
|
|
1130
|
-
catching.delete(locator);
|
|
1131
|
-
discovered.delete(locator);
|
|
1132
|
-
announced.delete(locator);
|
|
1133
|
-
unreadable.delete(locator);
|
|
1134
|
-
stale.delete(locator);
|
|
1135
|
-
repairable.delete(locator);
|
|
1136
|
-
unindexable.delete(locator);
|
|
1137
|
-
paused.delete(locator);
|
|
1138
|
-
prepared.delete(locator);
|
|
1139
|
-
scopedRefusals.delete(locator);
|
|
1140
|
-
sourceRefusals.delete(locator);
|
|
1141
|
-
declarationRefusals.delete(locator);
|
|
1142
|
-
for (const attached of ['collection', 'typed-selection']) {
|
|
1143
|
-
const key = modelKey(locator, attached);
|
|
1144
|
-
models.delete(key);
|
|
1145
|
-
liveModels.delete(key);
|
|
1146
|
-
invalidModels.delete(key);
|
|
1147
|
-
}
|
|
1148
|
-
journal.record(`room lost ${locator}`);
|
|
1149
|
-
}
|
|
1150
|
-
if (fresh.length === 0)
|
|
1151
|
-
return fresh;
|
|
1152
|
-
searchIndex.forget(fresh);
|
|
1153
|
-
const withdrawn = readSide.apply(stepped(withdrawing(removed)), (set) => conversations.changed(set));
|
|
1154
|
-
if (withdrawn instanceof Promise)
|
|
1155
|
-
void withdrawn.catch(unpublished);
|
|
1156
|
-
publishChangeSet(mergeChangeSets(removed.map(({ locator, drafts }) => changeSet(locator, null, null, { room: true, queue: true, drafts }))));
|
|
1157
|
-
readSide.recover();
|
|
1158
|
-
moveTo({ ...status, ...attention() });
|
|
1159
|
-
return fresh;
|
|
1160
|
-
}
|
|
1161
|
-
function* withdrawing(removed) {
|
|
1162
|
-
const sets = [];
|
|
1163
|
-
for (const { locator, shown } of removed)
|
|
1164
|
-
sets.push(yield* changing(locator, shown, null));
|
|
1165
|
-
return mergeChangeSets(sets);
|
|
1166
|
-
}
|
|
1167
|
-
async function erased(local, locators) {
|
|
1168
|
-
await local.erase(locators);
|
|
1169
|
-
for (const locator of locators) {
|
|
1170
|
-
const held = fences.get(locator);
|
|
1171
|
-
if (held !== undefined)
|
|
1172
|
-
held.erased = true;
|
|
1173
|
-
}
|
|
1174
|
-
}
|
|
1175
|
-
async function loseRooms(locators) {
|
|
1176
|
-
const fresh = fence(locators);
|
|
1177
|
-
if (fresh.length === 0)
|
|
1178
|
-
return;
|
|
1179
|
-
await durably(async (local) => {
|
|
1180
|
-
await erased(local, fresh);
|
|
1181
|
-
await unpair(local);
|
|
1182
|
-
});
|
|
1183
|
-
}
|
|
1184
|
-
function restored(key, persisted) {
|
|
1185
|
-
const prior = models.get(key);
|
|
1186
|
-
if (prior !== undefined &&
|
|
1187
|
-
prior.status !== 'unavailable' &&
|
|
1188
|
-
(persisted.status === 'unavailable' || !sameModel(prior.snapshot, persisted.snapshot))) {
|
|
1189
|
-
invalidModels.add(key);
|
|
1190
|
-
}
|
|
1191
|
-
const model = persisted.status === 'unavailable' ||
|
|
1192
|
-
liveModels.get(key) === JSON.stringify(persisted.snapshot)
|
|
1193
|
-
? persisted
|
|
1194
|
-
: cached(persisted);
|
|
1195
|
-
models.set(key, model);
|
|
1196
|
-
if (model.status === 'unavailable') {
|
|
1197
|
-
liveModels.delete(key);
|
|
1198
|
-
invalidModels.delete(key);
|
|
1199
|
-
}
|
|
1200
|
-
return model;
|
|
1201
|
-
}
|
|
1202
|
-
async function hydrate(opened) {
|
|
1203
|
-
const [records, queues, kept, presented, held, chatDrafts, lastCompleted, declared, named, known, staged, heldTargets,] = await Promise.all([
|
|
1204
|
-
opened.all(),
|
|
1205
|
-
opened.queues(),
|
|
1206
|
-
opened.roomDrafts(),
|
|
1207
|
-
opened.presentation(),
|
|
1208
|
-
opened.conversations(),
|
|
1209
|
-
opened.chatDrafts(),
|
|
1210
|
-
opened.lastCompleted(),
|
|
1211
|
-
opened.providerLimits(),
|
|
1212
|
-
opened.capabilities(),
|
|
1213
|
-
opened.member(),
|
|
1214
|
-
opened.transfers(),
|
|
1215
|
-
opened.targets(),
|
|
1216
|
-
]);
|
|
1217
|
-
const queuedBatches = new Map(queues.map((queue) => [queue.locator, queue.pending.map(({ batch }) => batch)]));
|
|
1218
|
-
const previousReplicas = new Map(replicas);
|
|
1219
|
-
const read = new Map();
|
|
1220
|
-
for (const record of records) {
|
|
1221
|
-
const model = restored(modelKey(record.locator, 'collection'), record.model);
|
|
1222
|
-
const selectionModel = restored(modelKey(record.locator, 'typed-selection'), record.selectionModel);
|
|
1223
|
-
const prior = previousReplicas.get(record.locator);
|
|
1224
|
-
const confirmed = await confirmedOf({ ...record, model, selectionModel }, prior?.confirmed);
|
|
1225
|
-
const replica = await stepped(replicating(confirmed, queuedBatches.get(record.locator) ?? [], prior));
|
|
1226
|
-
await stepped(counting(replica));
|
|
1227
|
-
read.set(record.locator, replica);
|
|
1228
|
-
}
|
|
1229
|
-
const sets = new Map();
|
|
1230
|
-
for (const locator of new Set([...previousReplicas.keys(), ...read.keys()])) {
|
|
1231
|
-
sets.set(locator, await stepped(changing(locator, previousReplicas.get(locator) ?? null, read.get(locator) ?? null)));
|
|
1232
|
-
}
|
|
1233
|
-
targets = heldTargets;
|
|
1234
|
-
transfers.clear();
|
|
1235
|
-
for (const record of staged)
|
|
1236
|
-
transfers.set(record.locator, record);
|
|
1237
|
-
limits = declared;
|
|
1238
|
-
capabilities = named;
|
|
1239
|
-
member = known;
|
|
1240
|
-
roomDrafts.clear();
|
|
1241
|
-
for (const record of kept)
|
|
1242
|
-
rememberRoomDraft(record);
|
|
1243
|
-
presentations.clear();
|
|
1244
|
-
for (const record of presented)
|
|
1245
|
-
presentations.set(record.app, record.value);
|
|
1246
|
-
conversations.hydrate(held, chatDrafts);
|
|
1247
|
-
pendings.clear();
|
|
1248
|
-
for (const queue of queues) {
|
|
1249
|
-
for (const { batch, state } of queue.pending) {
|
|
1250
|
-
pendings.set(pendingKey(queue.locator, batch.id), state);
|
|
1251
|
-
}
|
|
1252
|
-
}
|
|
1253
|
-
replicas.clear();
|
|
1254
|
-
queuesWithoutReplica.clear();
|
|
1255
|
-
for (const [locator, queue] of queuedBatches) {
|
|
1256
|
-
if (!read.has(locator))
|
|
1257
|
-
queuesWithoutReplica.set(locator, queue);
|
|
1258
|
-
}
|
|
1259
|
-
for (const record of records) {
|
|
1260
|
-
if (fences.has(record.locator))
|
|
1261
|
-
continue;
|
|
1262
|
-
const replica = read.get(record.locator);
|
|
1263
|
-
const { model, selectionModel } = replica.confirmed.record;
|
|
1264
|
-
replicas.set(record.locator, replica);
|
|
1265
|
-
const existing = rooms.get(record.locator);
|
|
1266
|
-
if (existing === undefined)
|
|
1267
|
-
list(record, false);
|
|
1268
|
-
else {
|
|
1269
|
-
rooms.set(record.locator, {
|
|
1270
|
-
...existing,
|
|
1271
|
-
roomVersion: record.roomVersion,
|
|
1272
|
-
operations: record.operations,
|
|
1273
|
-
replica: record.replica,
|
|
1274
|
-
model: modelTypes(model),
|
|
1275
|
-
typedSelection: record.typedSelection === null
|
|
1276
|
-
? null
|
|
1277
|
-
: {
|
|
1278
|
-
roots: record.typedSelection.roots,
|
|
1279
|
-
model: modelTypes(selectionModel),
|
|
1280
|
-
},
|
|
1281
|
-
});
|
|
1282
|
-
}
|
|
1283
|
-
}
|
|
1284
|
-
return {
|
|
1285
|
-
lastCompleted,
|
|
1286
|
-
locators: new Set([...queuedBatches.keys(), ...replicas.keys()]),
|
|
1287
|
-
read: mergeChangeSets([...sets].flatMap(([locator, set]) => (fences.has(locator) ? [] : [set]))),
|
|
1288
|
-
};
|
|
1289
|
-
}
|
|
1290
|
-
async function readState(opened) {
|
|
1291
|
-
const { lastCompleted, locators, read } = await hydrate(opened);
|
|
1292
|
-
applyChangeSet(read);
|
|
1293
|
-
prepare();
|
|
1294
|
-
if (replicas.size > 0)
|
|
1295
|
-
emitRooms();
|
|
1296
|
-
if (member !== null)
|
|
1297
|
-
emitMember();
|
|
1298
|
-
for (const locator of locators)
|
|
1299
|
-
emitQueue(locator);
|
|
1300
|
-
publishRoomDrafts(false);
|
|
1301
|
-
return lastCompleted;
|
|
1302
|
-
}
|
|
1303
|
-
async function open() {
|
|
1304
|
-
if (closed)
|
|
1305
|
-
throw new Error('runtime closed');
|
|
1306
|
-
const opened = await openRuntimeStore(isFenced, options.database);
|
|
1307
|
-
store = opened;
|
|
1308
|
-
const interrupted = await opened.fences();
|
|
1309
|
-
for (const locator of interrupted) {
|
|
1310
|
-
fences.set(locator, { at: discoveries, erased: false });
|
|
1311
|
-
lastFenced.set(locator, ++fencings);
|
|
1312
|
-
}
|
|
1313
|
-
const kept = options.shell.generation;
|
|
1314
|
-
const storedGeneration = await opened.generation();
|
|
1315
|
-
const loss = detectStorageLoss(storedGeneration, kept);
|
|
1316
|
-
const generation = nextGeneration(storedGeneration, kept);
|
|
1317
|
-
if (generation !== storedGeneration)
|
|
1318
|
-
await opened.rememberGeneration(generation);
|
|
1319
|
-
if (generation !== kept)
|
|
1320
|
-
await options.shell.keepGeneration(generation);
|
|
1321
|
-
if (loss !== null) {
|
|
1322
|
-
storageLoss = loss;
|
|
1323
|
-
emitStorageLoss();
|
|
1324
|
-
}
|
|
1325
|
-
const lastCompleted = await readState(opened);
|
|
1326
|
-
if (interrupted.length > 0)
|
|
1327
|
-
await erased(opened, interrupted);
|
|
1328
|
-
moveTo({ ...status, lastCompleted, ...attention() });
|
|
1329
|
-
void exclusive(() => unpair(opened)).catch(() => {
|
|
1330
|
-
journal.record('unpair failed');
|
|
1331
|
-
});
|
|
1332
|
-
return opened;
|
|
1333
|
-
}
|
|
1334
|
-
function durably(work) {
|
|
1335
|
-
return exclusive(async () => {
|
|
1336
|
-
const local = await openLocal();
|
|
1337
|
-
return work(local);
|
|
1338
|
-
});
|
|
1339
|
-
}
|
|
1340
|
-
function openLocal() {
|
|
1341
|
-
opening ??= open().catch((error) => {
|
|
1342
|
-
opening = undefined;
|
|
1343
|
-
throw error;
|
|
1344
|
-
});
|
|
1345
|
-
return opening;
|
|
1346
|
-
}
|
|
1347
|
-
function exclusive(work) {
|
|
1348
|
-
const next = mutations.then(work, work);
|
|
1349
|
-
mutations = next.then(() => undefined, () => undefined);
|
|
1350
|
-
return next;
|
|
1351
|
-
}
|
|
1352
|
-
function withdrawable(locator) {
|
|
1353
|
-
return (batch) => {
|
|
1354
|
-
const state = pendings.get(pendingKey(locator, batch.id));
|
|
1355
|
-
return state !== undefined && state.submission.state !== 'submitted' && !state.lost;
|
|
1356
|
-
};
|
|
1357
|
-
}
|
|
1358
|
-
function landedWhole(locator, batch, confirmed, current) {
|
|
1359
|
-
if (!landed(batch, confirmed, current))
|
|
1360
|
-
return false;
|
|
1361
|
-
const partner = partnerOf(batch, locator);
|
|
1362
|
-
if (partner === null)
|
|
1363
|
-
return true;
|
|
1364
|
-
const other = replicas.get(partner);
|
|
1365
|
-
const half = other?.queue.find((one) => one.id === batch.id);
|
|
1366
|
-
return other !== undefined && half !== undefined && landed(half, other.confirmed);
|
|
1367
|
-
}
|
|
1368
|
-
function carriedBack(locator, unlanded, written) {
|
|
1369
|
-
const back = new Map();
|
|
1370
|
-
const taken = [];
|
|
1371
|
-
for (const batch of unlanded) {
|
|
1372
|
-
const between = batch.between;
|
|
1373
|
-
if (between === undefined)
|
|
1374
|
-
continue;
|
|
1375
|
-
const source = between.source.room;
|
|
1376
|
-
const destination = between.destination.room;
|
|
1377
|
-
for (const { path: to } of pendings.get(pendingKey(destination, batch.id))?.drafts ?? []) {
|
|
1378
|
-
const record = roomDrafts.get(destination)?.get(to);
|
|
1379
|
-
const path = between.moves.find((move) => move.to === to)?.path;
|
|
1380
|
-
if (record === undefined || path === undefined)
|
|
1381
|
-
continue;
|
|
1382
|
-
const [into, key] = source === locator ? [written, path] : [back, documentKey(source, path)];
|
|
1383
|
-
const existing = into.get(key) ?? roomDrafts.get(source)?.get(path);
|
|
1384
|
-
taken.push({ locator: destination, path: to });
|
|
1385
|
-
into.set(key, {
|
|
1386
|
-
locator: source,
|
|
1387
|
-
path,
|
|
1388
|
-
revision: roomDraftRevision(),
|
|
1389
|
-
parts: returnedInto(existing?.parts, record.parts),
|
|
1390
|
-
returned: existing?.returned ?? null,
|
|
1391
|
-
});
|
|
1392
|
-
}
|
|
1393
|
-
}
|
|
1394
|
-
const records = [...back.values()];
|
|
1395
|
-
const elsewhere = taken.filter((one) => one.locator !== locator);
|
|
1396
|
-
const rooms = new Set([...records, ...elsewhere].map((one) => one.locator));
|
|
1397
|
-
return {
|
|
1398
|
-
taken: taken.filter((one) => one.locator === locator).map(({ path }) => path),
|
|
1399
|
-
writes: [...rooms].map((room) => ({
|
|
1400
|
-
locator: room,
|
|
1401
|
-
roomDrafts: records.filter((record) => record.locator === room),
|
|
1402
|
-
consumedRoomDrafts: elsewhere.filter((one) => one.locator === room).map(({ path }) => path),
|
|
1403
|
-
})),
|
|
1404
|
-
changes: [...rooms].map((room) => changeSet(room, null, null, {
|
|
1405
|
-
drafts: [...records, ...elsewhere]
|
|
1406
|
-
.filter((one) => one.locator === room)
|
|
1407
|
-
.map(({ path }) => path),
|
|
1408
|
-
})),
|
|
1409
|
-
remember() {
|
|
1410
|
-
for (const one of taken)
|
|
1411
|
-
forgetRoomDraft(one.locator, one.path);
|
|
1412
|
-
for (const record of records)
|
|
1413
|
-
rememberRoomDraft(record);
|
|
1414
|
-
},
|
|
1415
|
-
};
|
|
1416
|
-
}
|
|
1417
|
-
async function settle(local, locator, before, confirmed, queue, settling = {}) {
|
|
1418
|
-
const previousQueue = before?.queue ?? queuesWithoutReplica.get(locator) ?? [];
|
|
1419
|
-
const { withdrawn, kept } = await stepped(standing(confirmed, queue, withdrawable(locator), localSaves));
|
|
1420
|
-
const founded = kept.filter((batch) => !queue.includes(batch));
|
|
1421
|
-
const queueChanged = kept.length !== previousQueue.length || founded.length > 0;
|
|
1422
|
-
const unqueued = withdrawn.map((batch) => ({
|
|
1423
|
-
batch,
|
|
1424
|
-
landed: landedWhole(locator, batch, confirmed),
|
|
1425
|
-
}));
|
|
1426
|
-
const returning = [
|
|
1427
|
-
...[...unqueued].reverse().map(({ batch, landed }) => ({
|
|
1428
|
-
batch,
|
|
1429
|
-
returned: localSaves || landed ? null : returnedBy('withdrawn'),
|
|
1430
|
-
})),
|
|
1431
|
-
...(settling.leaving === undefined ? [] : [settling.leaving]),
|
|
1432
|
-
];
|
|
1433
|
-
const written = new Map();
|
|
1434
|
-
for (const { batch, returned } of returning) {
|
|
1435
|
-
if (returned === null || batch.between?.destination.room === locator)
|
|
1436
|
-
continue;
|
|
1437
|
-
for (const saved of pendings.get(pendingKey(locator, batch.id))?.drafts ?? []) {
|
|
1438
|
-
const existing = written.get(saved.path) ?? roomDrafts.get(locator)?.get(saved.path);
|
|
1439
|
-
written.set(saved.path, {
|
|
1440
|
-
locator,
|
|
1441
|
-
path: saved.path,
|
|
1442
|
-
revision: roomDraftRevision(),
|
|
1443
|
-
parts: returnedInto(existing?.parts, saved.parts),
|
|
1444
|
-
returned,
|
|
1445
|
-
});
|
|
1446
|
-
}
|
|
1447
|
-
}
|
|
1448
|
-
const carried = carriedBack(locator, [
|
|
1449
|
-
...[...unqueued].reverse().flatMap(({ batch, landed }) => (landed ? [] : [batch])),
|
|
1450
|
-
...(settling.leaving === undefined || settling.leaving.returned === null
|
|
1451
|
-
? []
|
|
1452
|
-
: [settling.leaving.batch]),
|
|
1453
|
-
], written);
|
|
1454
|
-
await local.keepAuthored({
|
|
1455
|
-
locator,
|
|
1456
|
-
queue: kept,
|
|
1457
|
-
founded,
|
|
1458
|
-
roomDrafts: [...written.values()],
|
|
1459
|
-
consumedRoomDrafts: carried.taken,
|
|
1460
|
-
}, ...carried.writes);
|
|
1461
|
-
const staying = new Set(kept.map((batch) => batch.id));
|
|
1462
|
-
for (const batch of previousQueue) {
|
|
1463
|
-
if (!staying.has(batch.id))
|
|
1464
|
-
pendings.delete(pendingKey(locator, batch.id));
|
|
1465
|
-
}
|
|
1466
|
-
for (const record of written.values())
|
|
1467
|
-
rememberRoomDraft(record);
|
|
1468
|
-
carried.remember();
|
|
1469
|
-
const drafts = [...written.keys(), ...carried.taken];
|
|
1470
|
-
try {
|
|
1471
|
-
await local.write({
|
|
1472
|
-
next: confirmed.record,
|
|
1473
|
-
previous: before?.confirmed.record ?? null,
|
|
1474
|
-
...(settling.stored === undefined ? {} : { stored: settling.stored }),
|
|
1475
|
-
});
|
|
1476
|
-
}
|
|
1477
|
-
catch (error) {
|
|
1478
|
-
const held = before === undefined ? null : await stepped(replicating(before.confirmed, kept, before));
|
|
1479
|
-
const set = await stepped(changing(locator, before ?? null, held, { queue: queueChanged, drafts }));
|
|
1480
|
-
if (held !== null)
|
|
1481
|
-
replicas.set(locator, held);
|
|
1482
|
-
else if (kept.length > 0)
|
|
1483
|
-
queuesWithoutReplica.set(locator, kept);
|
|
1484
|
-
else
|
|
1485
|
-
queuesWithoutReplica.delete(locator);
|
|
1486
|
-
publishChangeSet(mergeChangeSets([set, ...carried.changes]));
|
|
1487
|
-
moveTo({ ...status, ...attention() });
|
|
1488
|
-
throw error;
|
|
1489
|
-
}
|
|
1490
|
-
const changed = { room: settling.room, queue: queueChanged, drafts };
|
|
1491
|
-
const next = await stepped(replicating(confirmed, kept, before));
|
|
1492
|
-
await stepped(counting(next));
|
|
1493
|
-
const set = await stepped(changing(locator, before ?? null, next, changed));
|
|
1494
|
-
return () => {
|
|
1495
|
-
queuesWithoutReplica.delete(locator);
|
|
1496
|
-
for (const { batch, landed } of unqueued) {
|
|
1497
|
-
const outcome = localSaves ? 'dropped' : landed ? 'landed' : 'withdrawn';
|
|
1498
|
-
journal.record(`outcome ${locator} ${batch.id} ${outcome}`);
|
|
1499
|
-
}
|
|
1500
|
-
replicas.set(locator, next);
|
|
1501
|
-
return mergeChangeSets([
|
|
1502
|
-
heldChange(locator, before ?? null, next, set, changed),
|
|
1503
|
-
...carried.changes,
|
|
1504
|
-
]);
|
|
1505
|
-
};
|
|
1506
|
-
}
|
|
1507
|
-
function heldChange(locator, before, next, set, changed) {
|
|
1508
|
-
const held = replicas.get(locator) ?? null;
|
|
1509
|
-
return held === next ? set : changeSet(locator, before, held, changed);
|
|
1510
|
-
}
|
|
1511
|
-
function adoptModels(locator, record) {
|
|
1512
|
-
for (const [attached, model] of [
|
|
1513
|
-
['collection', record.model],
|
|
1514
|
-
['typed-selection', record.selectionModel],
|
|
1515
|
-
]) {
|
|
1516
|
-
const key = modelKey(locator, attached);
|
|
1517
|
-
models.set(key, model);
|
|
1518
|
-
invalidModels.delete(key);
|
|
1519
|
-
if (model.status === 'current')
|
|
1520
|
-
liveModels.set(key, JSON.stringify(model.snapshot));
|
|
1521
|
-
else if (model.status === 'unavailable')
|
|
1522
|
-
liveModels.delete(key);
|
|
1523
|
-
}
|
|
1524
|
-
}
|
|
1525
|
-
function remodel(locator, answers, held) {
|
|
1526
|
-
const taken = (answer, previous, attached) => {
|
|
1527
|
-
if (answer === undefined)
|
|
1528
|
-
return previous;
|
|
1529
|
-
const { state, refused } = attachedModel(answer, previous, attached === 'collection' ? roomTypes : NO_ROOM_TYPES);
|
|
1530
|
-
if (refused !== null) {
|
|
1531
|
-
const where = refused.location === undefined ? '' : ` ${refused.location}`;
|
|
1532
|
-
journal.record(`model invalid ${locator} ${attached} ${refused.identity} ${refused.rule}${where}`);
|
|
1533
|
-
}
|
|
1534
|
-
models.set(modelKey(locator, attached), state);
|
|
1535
|
-
return state;
|
|
1536
|
-
};
|
|
1537
|
-
return {
|
|
1538
|
-
collection: taken(answers?.collection, held.collection, 'collection'),
|
|
1539
|
-
selection: taken(answers?.selection, held.selection, 'typed-selection'),
|
|
1540
|
-
};
|
|
1541
|
-
}
|
|
1542
|
-
function publish(local, room, confirmed, landing, live) {
|
|
1543
|
-
const { base, stored } = landing;
|
|
1544
|
-
return exclusive(async () => {
|
|
1545
|
-
if (stored !== undefined) {
|
|
1546
|
-
await indexReferrers({ text: confirmed.record.documents, binaries: confirmed.record.binaries }, compositionOf(confirmed.record));
|
|
1547
|
-
}
|
|
1548
|
-
if (!live()) {
|
|
1549
|
-
caughtUpTo(room.locator);
|
|
1550
|
-
return true;
|
|
1551
|
-
}
|
|
1552
|
-
const prior = replicas.get(room.locator);
|
|
1553
|
-
if (base !== undefined &&
|
|
1554
|
-
(prior?.confirmed.record.roomVersion !== base.record.roomVersion ||
|
|
1555
|
-
prior.confirmed.record.revisions !== base.record.revisions)) {
|
|
1556
|
-
return false;
|
|
1557
|
-
}
|
|
1558
|
-
adoptModels(room.locator, confirmed.record);
|
|
1559
|
-
const queue = prior?.queue ?? queuesWithoutReplica.get(room.locator) ?? [];
|
|
1560
|
-
const roomVersion = confirmed.record.roomVersion;
|
|
1561
|
-
const accepted = queue.filter((batch) => {
|
|
1562
|
-
const accepted = pendings.get(pendingKey(room.locator, batch.id))?.accepted;
|
|
1563
|
-
return (accepted !== undefined && options.adapter.reached(room.locator, roomVersion, accepted));
|
|
1564
|
-
});
|
|
1565
|
-
let settled;
|
|
1566
|
-
try {
|
|
1567
|
-
settled = await settle(local, room.locator, prior, confirmed, queue.filter((batch) => !accepted.includes(batch)), { room: true, ...(stored === undefined ? {} : { stored }) });
|
|
1568
|
-
}
|
|
1569
|
-
catch (error) {
|
|
1570
|
-
if (!exceeded(error))
|
|
1571
|
-
throw error;
|
|
1572
|
-
await exceededOn(room.locator, grownBy(confirmed.record, prior?.confirmed.record));
|
|
1573
|
-
caughtUpTo(room.locator);
|
|
1574
|
-
return true;
|
|
1575
|
-
}
|
|
1576
|
-
const set = settled();
|
|
1577
|
-
if (stored !== undefined) {
|
|
1578
|
-
transfers.delete(room.locator);
|
|
1579
|
-
catching.delete(room.locator);
|
|
1580
|
-
}
|
|
1581
|
-
for (const batch of accepted)
|
|
1582
|
-
pendings.delete(pendingKey(room.locator, batch.id));
|
|
1583
|
-
stale.delete(room.locator);
|
|
1584
|
-
unindexable.delete(room.locator);
|
|
1585
|
-
if (unreadable.delete(room.locator))
|
|
1586
|
-
scopedRefusals.delete(room.locator);
|
|
1587
|
-
sourceRefusals.delete(room.locator);
|
|
1588
|
-
declarationRefusals.delete(room.locator);
|
|
1589
|
-
list(room, true);
|
|
1590
|
-
if (prior === undefined)
|
|
1591
|
-
prepared.add(room.locator);
|
|
1592
|
-
publishChangeSet(set);
|
|
1593
|
-
await unpair(local);
|
|
1594
|
-
moveTo({ ...status, ...attention() });
|
|
1595
|
-
options.adapter.roomStream?.published(room.locator, roomVersion);
|
|
1596
|
-
if (accepted.length > 0 && (replicas.get(room.locator)?.queue.length ?? 0) > 0) {
|
|
1597
|
-
submitLater(room.locator);
|
|
1598
|
-
}
|
|
1599
|
-
return true;
|
|
1600
|
-
});
|
|
1601
|
-
}
|
|
1602
|
-
async function savedRoom(locator) {
|
|
1603
|
-
const local = await openLocal();
|
|
1604
|
-
await referenced(locator);
|
|
1605
|
-
const replica = replicas.get(locator);
|
|
1606
|
-
const room = rooms.get(locator);
|
|
1607
|
-
if (replica === undefined || room === undefined) {
|
|
1608
|
-
throw runtimeError('room-not-held', `No Local Replica for ${locator}`);
|
|
1609
|
-
}
|
|
1610
|
-
return { local, replica, room };
|
|
1611
|
-
}
|
|
1612
|
-
async function saveRoomDrafts(locator, named, writtenBy) {
|
|
1613
|
-
const target = await savedRoom(locator);
|
|
1614
|
-
const saved = [];
|
|
1615
|
-
for (const { path, revision } of named) {
|
|
1616
|
-
const record = roomDrafts.get(locator)?.get(path);
|
|
1617
|
-
if (record === undefined || record.revision !== revision) {
|
|
1618
|
-
return { outcome: 'refused', code: 'stale', retryable: false, file: path };
|
|
1619
|
-
}
|
|
1620
|
-
if (!saved.some((draft) => draft.path === path))
|
|
1621
|
-
saved.push({ path, parts: record.parts });
|
|
1622
|
-
}
|
|
1623
|
-
return committed(locator, target, saved, new Set(saved.map(({ path }) => path)), writtenBy);
|
|
1624
|
-
}
|
|
1625
|
-
async function saveParts(locator, named, writtenBy) {
|
|
1626
|
-
const read = named.map(({ path, parts }) => ({ path, parts: readParts(parts) }));
|
|
1627
|
-
if (read.some(({ path }, at) => path === '' ||
|
|
1628
|
-
normalize(path) !== path ||
|
|
1629
|
-
read.findIndex((one) => one.path === path) !== at)) {
|
|
1630
|
-
throw runtimeError('room-draft-malformed');
|
|
1631
|
-
}
|
|
1632
|
-
const target = await savedRoom(locator);
|
|
1633
|
-
const saved = [];
|
|
1634
|
-
const files = [];
|
|
1635
|
-
for (const { path, parts } of read) {
|
|
1636
|
-
const file = parts.file === undefined
|
|
1637
|
-
? undefined
|
|
1638
|
-
: await heldFile(parts.file.blob, binaryBase(target.replica.visible, path));
|
|
1639
|
-
if (parts.file !== undefined && file !== undefined) {
|
|
1640
|
-
files.push({ key: file.localId, blob: parts.file.blob });
|
|
1641
|
-
}
|
|
1642
|
-
saved.push({ path, parts: held(undefined, parts, file) });
|
|
1643
|
-
}
|
|
1644
|
-
return committed(locator, target, saved, new Set(), writtenBy, files);
|
|
1645
|
-
}
|
|
1646
|
-
function carriedDrafts(locator, saved, consumed) {
|
|
1647
|
-
const holding = roomDrafts.get(locator);
|
|
1648
|
-
return new Map(saved.flatMap(({ path, parts }) => {
|
|
1649
|
-
const record = holding?.get(path);
|
|
1650
|
-
if (parts.move === undefined || record === undefined || consumed.has(path))
|
|
1651
|
-
return [];
|
|
1652
|
-
const to = moveTarget(parts.move);
|
|
1653
|
-
if (to === path || holding?.has(to) === true)
|
|
1654
|
-
return [];
|
|
1655
|
-
return [[path, { ...record, path: to, revision: roomDraftRevision() }]];
|
|
1656
|
-
}));
|
|
1657
|
-
}
|
|
1658
|
-
function sideOf(locator, replica, room) {
|
|
1659
|
-
const record = replica.confirmed.record;
|
|
1660
|
-
return {
|
|
1661
|
-
room: locator,
|
|
1662
|
-
handle: room.handle,
|
|
1663
|
-
baseRoomVersion: record.roomVersion,
|
|
1664
|
-
composition: compositionFor(record),
|
|
1665
|
-
operations: room.operations,
|
|
1666
|
-
providerOwnedPaths: room.providerOwnedPaths,
|
|
1667
|
-
visible: replica.visible,
|
|
1668
|
-
queued: queuedDocuments(replica.queue),
|
|
1669
|
-
clean: {
|
|
1670
|
-
text: record.documents,
|
|
1671
|
-
binaries: record.binaries,
|
|
1672
|
-
composition: compositionOf(record),
|
|
1673
|
-
},
|
|
1674
|
-
};
|
|
1675
|
-
}
|
|
1676
|
-
function movedInto(locator, saved) {
|
|
1677
|
-
const into = saved.find(({ parts }) => parts.move?.room !== undefined && parts.move.room !== locator);
|
|
1678
|
-
return into?.parts.move?.room ?? null;
|
|
1679
|
-
}
|
|
1680
|
-
async function committedMove(locator, destination, { local, replica, room }, saved, consumed, writtenBy, files) {
|
|
1681
|
-
const mixed = saved.find(({ parts }) => Object.keys(parts).length !== 1 || parts.move?.room !== destination);
|
|
1682
|
-
if (mixed !== undefined) {
|
|
1683
|
-
return { outcome: 'refused', code: 'mixed-room-move', retryable: false, file: mixed.path };
|
|
1684
|
-
}
|
|
1685
|
-
const changed = saved.flatMap(({ path, parts }) => changedParts(path, underneath(parts, path, replica.visible)));
|
|
1686
|
-
if (changed.length > 0)
|
|
1687
|
-
return { outcome: 'refused', code: 'changed-underneath', retryable: false, parts: changed };
|
|
1688
|
-
await referenced(destination);
|
|
1689
|
-
const target = replicas.get(destination);
|
|
1690
|
-
const listedRoom = rooms.get(destination);
|
|
1691
|
-
if (target === undefined || listedRoom === undefined) {
|
|
1692
|
-
throw runtimeError('room-not-held', `No Local Replica for ${destination}`);
|
|
1693
|
-
}
|
|
1694
|
-
const built = await buildMove({
|
|
1695
|
-
source: sideOf(locator, replica, room),
|
|
1696
|
-
destination: sideOf(destination, target, listedRoom),
|
|
1697
|
-
moves: saved.map(({ path, parts }) => ({ path, to: moveTarget(parts.move) })),
|
|
1698
|
-
providerLimits: limits,
|
|
1699
|
-
local: localSaves,
|
|
1700
|
-
...(writtenBy === undefined ? {} : { writtenBy }),
|
|
1701
|
-
});
|
|
1702
|
-
if (built.kind === 'refused')
|
|
1703
|
-
return { outcome: 'refused', ...built.refusal };
|
|
1704
|
-
const id = built.leaving.id;
|
|
1705
|
-
const carrying = saved.flatMap(({ path, parts }) => {
|
|
1706
|
-
const record = roomDrafts.get(locator)?.get(path);
|
|
1707
|
-
const to = moveTarget(parts.move);
|
|
1708
|
-
if (record === undefined || consumed.has(path) || roomDrafts.get(destination)?.has(to)) {
|
|
1709
|
-
return [];
|
|
1710
|
-
}
|
|
1711
|
-
const moved = {
|
|
1712
|
-
...record,
|
|
1713
|
-
locator: destination,
|
|
1714
|
-
path: to,
|
|
1715
|
-
revision: roomDraftRevision(),
|
|
1716
|
-
};
|
|
1717
|
-
return [{ from: path, record: moved }];
|
|
1718
|
-
});
|
|
1719
|
-
const carried = carrying.map(({ record }) => record);
|
|
1720
|
-
const marked = carried.map(({ path }) => ({ path, parts: {} }));
|
|
1721
|
-
const left = [...consumed, ...carrying.map(({ from }) => from)];
|
|
1722
|
-
const leavingQueue = [...replica.queue, built.leaving];
|
|
1723
|
-
const arrivingQueue = [...target.queue, built.arriving];
|
|
1724
|
-
let fencedRoom;
|
|
1725
|
-
try {
|
|
1726
|
-
fencedRoom = await local.saveAuthored(files, {
|
|
1727
|
-
locator,
|
|
1728
|
-
queue: leavingQueue,
|
|
1729
|
-
saved: new Map([[id, saved]]),
|
|
1730
|
-
consumedRoomDrafts: left,
|
|
1731
|
-
}, {
|
|
1732
|
-
locator: destination,
|
|
1733
|
-
queue: arrivingQueue,
|
|
1734
|
-
saved: new Map([[id, marked]]),
|
|
1735
|
-
roomDrafts: carried,
|
|
1736
|
-
});
|
|
1737
|
-
}
|
|
1738
|
-
catch {
|
|
1739
|
-
return { outcome: 'refused', code: 'durable-write', retryable: true };
|
|
1740
|
-
}
|
|
1741
|
-
if (fencedRoom !== null) {
|
|
1742
|
-
throw runtimeError('room-not-held', `No Local Replica for ${fencedRoom}`);
|
|
1743
|
-
}
|
|
1744
|
-
const nextSource = await stepped(replicating(replica.confirmed, leavingQueue, replica));
|
|
1745
|
-
const nextDestination = await stepped(replicating(target.confirmed, arrivingQueue, target));
|
|
1746
|
-
const sets = [
|
|
1747
|
-
await stepped(changing(locator, replica, nextSource, { queue: true, drafts: left })),
|
|
1748
|
-
await stepped(changing(destination, target, nextDestination, {
|
|
1749
|
-
queue: true,
|
|
1750
|
-
drafts: carried.map(({ path }) => path),
|
|
1751
|
-
})),
|
|
1752
|
-
];
|
|
1753
|
-
if (fences.has(locator) || fences.has(destination)) {
|
|
1754
|
-
throw runtimeError('room-not-held', `No Local Replica for ${locator}`);
|
|
1755
|
-
}
|
|
1756
|
-
pendings.set(pendingKey(locator, id), {
|
|
1757
|
-
drafts: saved,
|
|
1758
|
-
submission: { state: 'waiting' },
|
|
1759
|
-
lost: false,
|
|
1760
|
-
});
|
|
1761
|
-
pendings.set(pendingKey(destination, id), {
|
|
1762
|
-
drafts: marked,
|
|
1763
|
-
submission: { state: 'waiting' },
|
|
1764
|
-
lost: false,
|
|
1765
|
-
});
|
|
1766
|
-
for (const path of left)
|
|
1767
|
-
forgetRoomDraft(locator, path);
|
|
1768
|
-
for (const record of carried)
|
|
1769
|
-
rememberRoomDraft(record);
|
|
1770
|
-
replicas.set(locator, nextSource);
|
|
1771
|
-
replicas.set(destination, nextDestination);
|
|
1772
|
-
publishChangeSet(mergeChangeSets(sets));
|
|
1773
|
-
queuedSave(locator);
|
|
1774
|
-
return { outcome: 'saved', identifier: id };
|
|
1775
|
-
}
|
|
1776
|
-
function queuedSave(locator) {
|
|
1777
|
-
if (!localSaves)
|
|
1778
|
-
recorded = false;
|
|
1779
|
-
moveTo({ ...(localSaves ? status : saving(status)), ...attention() });
|
|
1780
|
-
submitLater(locator);
|
|
1781
|
-
}
|
|
1782
|
-
async function committed(locator, target, saved, consumed, writtenBy, files = []) {
|
|
1783
|
-
const into = movedInto(locator, saved);
|
|
1784
|
-
if (into !== null) {
|
|
1785
|
-
return committedMove(locator, into, target, saved, consumed, writtenBy, files);
|
|
1786
|
-
}
|
|
1787
|
-
const { local, replica, room } = target;
|
|
1788
|
-
const changed = saved.flatMap(({ path, parts }) => changedParts(path, underneath(parts, path, replica.visible)));
|
|
1789
|
-
if (changed.length > 0)
|
|
1790
|
-
return { outcome: 'refused', code: 'changed-underneath', retryable: false, parts: changed };
|
|
1791
|
-
const parts = saved.map(({ path, parts }) => changesOf(path, parts));
|
|
1792
|
-
const changes = parts.flatMap(({ changes }) => changes);
|
|
1793
|
-
const visibleOver = function* (queue) {
|
|
1794
|
-
return (yield* replicating(replica.confirmed, queue, replica)).visible;
|
|
1795
|
-
};
|
|
1796
|
-
const requeue = await stepped(requeuing(replica.queue, changes, replica.visible, withdrawable(locator), visibleOver));
|
|
1797
|
-
if (requeue.kind === 'refused')
|
|
1798
|
-
return { outcome: 'refused', ...requeue.refusal };
|
|
1799
|
-
const foreign = [...requeue.withdrawn.keys()].some((origin) => {
|
|
1800
|
-
const writer = replica.queue.find((batch) => batch.id === origin)?.writtenBy;
|
|
1801
|
-
return writer?.app !== writtenBy?.app || writer?.release !== writtenBy?.release;
|
|
1802
|
-
});
|
|
1803
|
-
if (foreign) {
|
|
1804
|
-
return {
|
|
1805
|
-
outcome: 'refused',
|
|
1806
|
-
code: 'unknown-revision',
|
|
1807
|
-
retryable: false,
|
|
1808
|
-
file: [...requeue.queued].at(-1),
|
|
1809
|
-
};
|
|
1810
|
-
}
|
|
1811
|
-
const withdrawing = requeue.withdrawn.size > 0;
|
|
1812
|
-
const input = {
|
|
1813
|
-
local: localSaves,
|
|
1814
|
-
baseRoomVersion: replica.confirmed.record.roomVersion,
|
|
1815
|
-
composition: compositionFor(replica.confirmed.record),
|
|
1816
|
-
operations: room.operations,
|
|
1817
|
-
providerOwnedPaths: room.providerOwnedPaths,
|
|
1818
|
-
providerLimits: limits,
|
|
1819
|
-
handle: room.handle,
|
|
1820
|
-
visible: replica.visible,
|
|
1821
|
-
changes,
|
|
1822
|
-
bases: parts.flatMap(({ bases }) => bases),
|
|
1823
|
-
queued: queuedDocuments(replica.queue),
|
|
1824
|
-
writtenBy,
|
|
1825
|
-
clean: {
|
|
1826
|
-
text: replica.confirmed.record.documents,
|
|
1827
|
-
binaries: replica.confirmed.record.binaries,
|
|
1828
|
-
composition: compositionOf(replica.confirmed.record),
|
|
1829
|
-
},
|
|
1830
|
-
};
|
|
1831
|
-
const checked = withdrawing
|
|
1832
|
-
? await buildBatch({ ...input, queued: new Set([...input.queued, ...requeue.queued]) })
|
|
1833
|
-
: null;
|
|
1834
|
-
if (checked?.kind === 'refused')
|
|
1835
|
-
return { outcome: 'refused', ...checked.refusal };
|
|
1836
|
-
const owners = [...requeue.owners].flatMap((origin) => {
|
|
1837
|
-
const batch = requeue.withdrawn.get(origin);
|
|
1838
|
-
return batch === undefined || batch === null ? [] : [{ origin, batch }];
|
|
1839
|
-
});
|
|
1840
|
-
if (owners.length > 1) {
|
|
1841
|
-
return {
|
|
1842
|
-
outcome: 'refused',
|
|
1843
|
-
code: 'unknown-revision',
|
|
1844
|
-
retryable: false,
|
|
1845
|
-
file: [...requeue.queued].at(-1),
|
|
1846
|
-
};
|
|
1847
|
-
}
|
|
1848
|
-
const built = !withdrawing
|
|
1849
|
-
? await buildBatch(input)
|
|
1850
|
-
: requeue.changes.length === 0
|
|
1851
|
-
? null
|
|
1852
|
-
: await buildBatch({
|
|
1853
|
-
...input,
|
|
1854
|
-
visible: (await stepped(replicating(replica.confirmed, requeue.queue, replica)))
|
|
1855
|
-
.visible,
|
|
1856
|
-
changes: requeue.changes,
|
|
1857
|
-
queued: queuedDocuments(requeue.queue),
|
|
1858
|
-
});
|
|
1859
|
-
if (built?.kind === 'refused')
|
|
1860
|
-
return { outcome: 'refused', ...built.refusal };
|
|
1861
|
-
const [owner] = owners;
|
|
1862
|
-
const join = built === null || owner === undefined
|
|
1863
|
-
? null
|
|
1864
|
-
: joined(requeue.queue, owner.batch, built.batch);
|
|
1865
|
-
if (join?.kind === 'refused')
|
|
1866
|
-
return { outcome: 'refused', ...join.refusal };
|
|
1867
|
-
const withdrawn = new Map(requeue.withdrawn);
|
|
1868
|
-
if (join !== null && owner !== undefined)
|
|
1869
|
-
withdrawn.set(owner.origin, join.batch);
|
|
1870
|
-
const drafted = new Map();
|
|
1871
|
-
for (const [origin, replaced] of withdrawn) {
|
|
1872
|
-
if (replaced === null)
|
|
1873
|
-
continue;
|
|
1874
|
-
const carried = withdrawnDrafts(pendings.get(pendingKey(locator, origin))?.drafts ?? [], changes);
|
|
1875
|
-
drafted.set(replaced.id, replaced === join?.batch
|
|
1876
|
-
? [
|
|
1877
|
-
...carried.map((held) => joinedDraft(held, saved)),
|
|
1878
|
-
...saved.filter((draft) => !carried.some((held) => held.path === draft.path)),
|
|
1879
|
-
]
|
|
1880
|
-
: carried);
|
|
1881
|
-
}
|
|
1882
|
-
if (built !== null && join === null)
|
|
1883
|
-
drafted.set(built.batch.id, saved);
|
|
1884
|
-
const batches = join !== null ? join.queue : built === null ? requeue.queue : [...requeue.queue, built.batch];
|
|
1885
|
-
for (const replaced of withdrawn.values()) {
|
|
1886
|
-
if (replaced === null || !batches.includes(replaced))
|
|
1887
|
-
continue;
|
|
1888
|
-
const limited = await stepped(limiting(batches, replaced, limits, visibleOver));
|
|
1889
|
-
if (limited !== null)
|
|
1890
|
-
return { outcome: 'refused', ...limited };
|
|
1891
|
-
}
|
|
1892
|
-
const carried = carriedDrafts(locator, saved, consumed);
|
|
1893
|
-
const left = [...consumed, ...carried.keys()];
|
|
1894
|
-
const arrived = [...carried.values()];
|
|
1895
|
-
let fencedRoom;
|
|
1896
|
-
try {
|
|
1897
|
-
fencedRoom = await local.saveAuthored(files, {
|
|
1898
|
-
locator,
|
|
1899
|
-
queue: batches,
|
|
1900
|
-
saved: drafted,
|
|
1901
|
-
consumedRoomDrafts: left,
|
|
1902
|
-
roomDrafts: arrived,
|
|
1903
|
-
});
|
|
1904
|
-
}
|
|
1905
|
-
catch {
|
|
1906
|
-
return { outcome: 'refused', code: 'durable-write', retryable: true };
|
|
1907
|
-
}
|
|
1908
|
-
if (fencedRoom !== null) {
|
|
1909
|
-
throw runtimeError('room-not-held', `No Local Replica for ${fencedRoom}`);
|
|
1910
|
-
}
|
|
1911
|
-
const next = await stepped(replicating(replica.confirmed, batches, replica));
|
|
1912
|
-
const set = await stepped(changing(locator, replica, next, {
|
|
1913
|
-
queue: true,
|
|
1914
|
-
drafts: [...left, ...arrived.map(({ path }) => path)],
|
|
1915
|
-
}));
|
|
1916
|
-
if (fences.has(locator))
|
|
1917
|
-
throw runtimeError('room-not-held', `No Local Replica for ${locator}`);
|
|
1918
|
-
for (const origin of withdrawn.keys())
|
|
1919
|
-
pendings.delete(pendingKey(locator, origin));
|
|
1920
|
-
for (const [id, drafts] of drafted) {
|
|
1921
|
-
pendings.set(pendingKey(locator, id), {
|
|
1922
|
-
drafts,
|
|
1923
|
-
submission: { state: 'waiting' },
|
|
1924
|
-
lost: false,
|
|
1925
|
-
});
|
|
1926
|
-
}
|
|
1927
|
-
for (const path of left)
|
|
1928
|
-
forgetRoomDraft(locator, path);
|
|
1929
|
-
for (const record of arrived)
|
|
1930
|
-
rememberRoomDraft(record);
|
|
1931
|
-
replicas.set(locator, next);
|
|
1932
|
-
publishChangeSet(set);
|
|
1933
|
-
queuedSave(locator);
|
|
1934
|
-
const identifier = join?.batch.id ??
|
|
1935
|
-
built?.batch.id ??
|
|
1936
|
-
[...requeue.withdrawn].map(([origin, replaced]) => replaced?.id ?? origin).at(-1);
|
|
1937
|
-
return { outcome: 'saved', identifier };
|
|
1938
|
-
}
|
|
1939
|
-
async function mark(local, locator, batch, submission, lost) {
|
|
1940
|
-
const partner = partnerOf(batch, locator);
|
|
1941
|
-
for (const held of partner === null ? [locator] : [locator, partner]) {
|
|
1942
|
-
const state = pendings.get(pendingKey(held, batch.id));
|
|
1943
|
-
if (!continuing() ||
|
|
1944
|
-
state === undefined ||
|
|
1945
|
-
(JSON.stringify(state.submission) === JSON.stringify(submission) && state.lost === lost)) {
|
|
1946
|
-
continue;
|
|
1947
|
-
}
|
|
1948
|
-
await local.submit(held, batch.id, submission, lost);
|
|
1949
|
-
if (fences.has(held))
|
|
1950
|
-
continue;
|
|
1951
|
-
pendings.set(pendingKey(held, batch.id), { ...state, submission, lost });
|
|
1952
|
-
const replica = replicas.get(held);
|
|
1953
|
-
if (replica !== undefined)
|
|
1954
|
-
publishChangeSet(changeSet(held, replica, replica, { queue: true }));
|
|
1955
|
-
}
|
|
1956
|
-
moveTo({ ...status, ...attention() });
|
|
1957
|
-
}
|
|
1958
|
-
async function keepUpload(local, locator, identifier, upload) {
|
|
1959
|
-
if (!continuing())
|
|
1960
|
-
throw new Error('connection refused');
|
|
1961
|
-
await local.keepUpload(locator, identifier, upload);
|
|
1962
|
-
if (fences.has(locator))
|
|
1963
|
-
throw runtimeError('room-not-held', `No Local Replica for ${locator}`);
|
|
1964
|
-
const key = pendingKey(locator, identifier);
|
|
1965
|
-
pendings.set(key, { ...pendings.get(key), upload });
|
|
1966
|
-
if (!continuing())
|
|
1967
|
-
throw new Error('connection refused');
|
|
1968
|
-
}
|
|
1969
|
-
async function readHistory(locator, path, query = {}) {
|
|
1970
|
-
if (closed || refusal !== null)
|
|
1971
|
-
return UNCERTAIN;
|
|
1972
|
-
try {
|
|
1973
|
-
await ensureAuthorization();
|
|
1974
|
-
}
|
|
1975
|
-
catch {
|
|
1976
|
-
return UNCERTAIN;
|
|
1977
|
-
}
|
|
1978
|
-
if (closed || authorization === undefined || refusal !== null)
|
|
1979
|
-
return UNCERTAIN;
|
|
1980
|
-
const since = fencings;
|
|
1981
|
-
const transfer = ['transfer', 'history', locator, path];
|
|
1982
|
-
if (query.revision !== undefined)
|
|
1983
|
-
transfer.push(query.revision);
|
|
1984
|
-
if (query.pageToken !== undefined)
|
|
1985
|
-
transfer.push(query.pageToken);
|
|
1986
|
-
journal.record(transfer.join(' '));
|
|
1987
|
-
try {
|
|
1988
|
-
const result = await options.adapter.history(authorization, {
|
|
1989
|
-
locator,
|
|
1990
|
-
path,
|
|
1991
|
-
...(query.revision === undefined ? {} : { revision: query.revision }),
|
|
1992
|
-
...(query.pageToken === undefined ? {} : { pageToken: query.pageToken }),
|
|
1993
|
-
});
|
|
1994
|
-
journal.record(`outcome history ${result.kind}`);
|
|
1995
|
-
if (fencedSince(locator, since))
|
|
1996
|
-
return failure({ kind: 'room-not-readable', locator });
|
|
1997
|
-
if (result.kind === 'scoped-refusal') {
|
|
1998
|
-
const room = replicas.get(result.locator)?.confirmed.record;
|
|
1999
|
-
if (room !== undefined)
|
|
2000
|
-
await scoped(result, room, await openLocal());
|
|
2001
|
-
}
|
|
2002
|
-
if (result.kind === 'revoked-authorization')
|
|
2003
|
-
await refuse('revoked-authorization');
|
|
2004
|
-
return historyAnswer(result);
|
|
2005
|
-
}
|
|
2006
|
-
catch {
|
|
2007
|
-
journal.record('outcome history transport-uncertainty');
|
|
2008
|
-
return UNCERTAIN;
|
|
2009
|
-
}
|
|
2010
|
-
}
|
|
2011
|
-
function located(room, path, destination) {
|
|
2012
|
-
const crossing = roomTarget(destination);
|
|
2013
|
-
if (crossing === null) {
|
|
2014
|
-
const named = target(path, destination);
|
|
2015
|
-
return named === null || !rooms.has(room) ? null : { room, path: named };
|
|
2016
|
-
}
|
|
2017
|
-
const held = [...rooms.values()].find((listed) => listed.handle === crossing.handle);
|
|
2018
|
-
return held === undefined ? null : { room: held.locator, path: crossing.path };
|
|
2019
|
-
}
|
|
2020
|
-
async function resolveReference(room, path, destination) {
|
|
2021
|
-
if (roomTarget(destination) === null && target(path, destination) === null) {
|
|
2022
|
-
return ABSENT_TARGET;
|
|
2023
|
-
}
|
|
2024
|
-
const at = located(room, path, destination);
|
|
2025
|
-
if (at === null)
|
|
2026
|
-
return UNREADABLE;
|
|
2027
|
-
if (locked(at.room))
|
|
2028
|
-
return LOCKED_UNREADABLE;
|
|
2029
|
-
const visible = replicas.get(at.room)?.visible;
|
|
2030
|
-
if (visible?.documents[at.path] !== undefined || visible?.binaries[at.path] !== undefined) {
|
|
2031
|
-
return { kind: 'document', ...at };
|
|
2032
|
-
}
|
|
2033
|
-
const history = await readHistory(at.room, at.path);
|
|
2034
|
-
if (history.kind === 'no-history' || history.kind === 'revision')
|
|
2035
|
-
return ABSENT_TARGET;
|
|
2036
|
-
if (history.kind !== 'history')
|
|
2037
|
-
return history;
|
|
2038
|
-
const [last] = history.revisions;
|
|
2039
|
-
if (last === undefined)
|
|
2040
|
-
return ABSENT_TARGET;
|
|
2041
|
-
return history.deleted === true
|
|
2042
|
-
? { kind: 'deleted', ...at, revision: last }
|
|
2043
|
-
: { kind: 'document', ...at };
|
|
2044
|
-
}
|
|
2045
|
-
function queuedFacts(locator, path, localId) {
|
|
2046
|
-
for (const batch of replicas.get(locator)?.queue ?? []) {
|
|
2047
|
-
const change = batch.changes[queuedFile(batch, path, localId)];
|
|
2048
|
-
if (change?.kind === 'binary')
|
|
2049
|
-
return change;
|
|
2050
|
-
}
|
|
2051
|
-
const drafted = roomDrafts.get(locator)?.get(path)?.parts.file;
|
|
2052
|
-
return drafted?.localId === localId ? drafted : null;
|
|
2053
|
-
}
|
|
2054
|
-
function batchFile(batch) {
|
|
2055
|
-
return async (localId) => {
|
|
2056
|
-
const change = batch.changes.find((held) => held.kind === 'binary' && held.localId === localId);
|
|
2057
|
-
return (await openLocal()).file(localId, change?.kind === 'binary' ? change.mediaType : '');
|
|
2058
|
-
};
|
|
2059
|
-
}
|
|
2060
|
-
function binaryRoom(request) {
|
|
2061
|
-
if (request.kind === 'path')
|
|
2062
|
-
return request.locator;
|
|
2063
|
-
return options.adapter.referrerScope(request.referrer)?.locator ?? null;
|
|
2064
|
-
}
|
|
2065
|
-
async function transferBinary(request, transfer, answer) {
|
|
2066
|
-
if (closed || refusal !== null)
|
|
2067
|
-
return UNCERTAIN;
|
|
2068
|
-
try {
|
|
2069
|
-
await ensureAuthorization();
|
|
2070
|
-
}
|
|
2071
|
-
catch {
|
|
2072
|
-
return UNCERTAIN;
|
|
2073
|
-
}
|
|
2074
|
-
if (closed || authorization === undefined || refusal !== null)
|
|
2075
|
-
return UNCERTAIN;
|
|
2076
|
-
const since = fencings;
|
|
2077
|
-
journal.record(request.kind === 'path'
|
|
2078
|
-
? `transfer binary ${request.locator} ${request.path}`
|
|
2079
|
-
: `transfer binary ${request.fileRef}`);
|
|
2080
|
-
try {
|
|
2081
|
-
const result = await transfer(authorization);
|
|
2082
|
-
const settled = result;
|
|
2083
|
-
journal.record(`outcome binary ${settled.kind}`);
|
|
2084
|
-
const locator = binaryRoom(request);
|
|
2085
|
-
if (locator !== null && fencedSince(locator, since))
|
|
2086
|
-
return failure({ kind: 'room-not-readable', locator });
|
|
2087
|
-
if (settled.kind === 'scoped-refusal') {
|
|
2088
|
-
const room = replicas.get(settled.locator)?.confirmed.record;
|
|
2089
|
-
if (room !== undefined)
|
|
2090
|
-
await scoped(settled, room, await openLocal());
|
|
2091
|
-
}
|
|
2092
|
-
if (settled.kind === 'revoked-authorization')
|
|
2093
|
-
await refuse('revoked-authorization');
|
|
2094
|
-
return answer(result);
|
|
2095
|
-
}
|
|
2096
|
-
catch {
|
|
2097
|
-
journal.record('outcome binary transport-uncertainty');
|
|
2098
|
-
return UNCERTAIN;
|
|
2099
|
-
}
|
|
2100
|
-
}
|
|
2101
|
-
async function readBinary(request, name) {
|
|
2102
|
-
if (closed)
|
|
2103
|
-
return UNCERTAIN;
|
|
2104
|
-
const held = await keptFiles.find(name);
|
|
2105
|
-
if (held !== null)
|
|
2106
|
-
return held;
|
|
2107
|
-
return transferBinary(request, (authorization) => keptFiles.fetch(name, () => options.adapter.binary(authorization, request)), binaryAnswer);
|
|
2108
|
-
}
|
|
2109
|
-
function binaryPath(locator, path, revision) {
|
|
2110
|
-
if (revision !== undefined)
|
|
2111
|
-
return { kind: 'path', locator, path, revision };
|
|
2112
|
-
const visible = replicas.get(locator)?.visible;
|
|
2113
|
-
const held = visible?.binaries[path];
|
|
2114
|
-
if (visible === undefined || held === undefined)
|
|
2115
|
-
return null;
|
|
2116
|
-
if (held.state === 'pending')
|
|
2117
|
-
return { kind: 'pending', localId: held.localId };
|
|
2118
|
-
const record = binaryRecord(path, held, visible.revisions[path]);
|
|
2119
|
-
if (record.state !== 'accepted')
|
|
2120
|
-
return null;
|
|
2121
|
-
const replica = replicas.get(locator);
|
|
2122
|
-
const queued = (replica?.queue ?? []).flatMap((batch) => batch.changes);
|
|
2123
|
-
const holds = (at) => {
|
|
2124
|
-
const kept = replica?.confirmed.record.binaries[at];
|
|
2125
|
-
return (kept?.state === 'accepted' &&
|
|
2126
|
-
kept.fileRef === record.fileRef &&
|
|
2127
|
-
replica?.confirmed.record.revisions[at] === record.revision);
|
|
2128
|
-
};
|
|
2129
|
-
let confirmed = path;
|
|
2130
|
-
for (let index = queued.length - 1; index >= 0 && !holds(confirmed); index -= 1) {
|
|
2131
|
-
const change = queued[index];
|
|
2132
|
-
if (change.kind === 'move' && change.to === confirmed)
|
|
2133
|
-
confirmed = change.path;
|
|
2134
|
-
}
|
|
2135
|
-
return {
|
|
2136
|
-
kind: 'path',
|
|
2137
|
-
locator,
|
|
2138
|
-
path: confirmed,
|
|
2139
|
-
revision: record.revision,
|
|
2140
|
-
fileRef: record.fileRef,
|
|
2141
|
-
};
|
|
2142
|
-
}
|
|
2143
|
-
async function readBinaryPath(locator, path, revision) {
|
|
2144
|
-
await ready;
|
|
2145
|
-
const drafted = roomDrafts.get(locator)?.get(path)?.parts.file;
|
|
2146
|
-
const asked = drafted !== undefined && drafted.localId === revision
|
|
2147
|
-
? { kind: 'pending', localId: revision }
|
|
2148
|
-
: binaryPath(locator, path, revision);
|
|
2149
|
-
if (asked === null)
|
|
2150
|
-
return absentBinary(path);
|
|
2151
|
-
if (asked.kind === 'pending') {
|
|
2152
|
-
const facts = queuedFacts(locator, path, asked.localId);
|
|
2153
|
-
return facts === null
|
|
2154
|
-
? absentBinary(path)
|
|
2155
|
-
: {
|
|
2156
|
-
kind: 'binary',
|
|
2157
|
-
file: asked.localId,
|
|
2158
|
-
byteLength: facts.byteLength,
|
|
2159
|
-
mediaType: facts.mediaType,
|
|
2160
|
-
};
|
|
2161
|
-
}
|
|
2162
|
-
return readBinary(asked, { locator, path: asked.path, revision: asked.revision });
|
|
2163
|
-
}
|
|
2164
|
-
async function linkBinaryPath(locator, path, revision) {
|
|
2165
|
-
await ready;
|
|
2166
|
-
const asked = binaryPath(locator, path, revision);
|
|
2167
|
-
if (asked === null || asked.kind === 'pending')
|
|
2168
|
-
return absentBinary(path);
|
|
2169
|
-
return transferBinary(asked, (held) => options.adapter.link(held, asked), binaryLinkAnswer);
|
|
2170
|
-
}
|
|
2171
|
-
async function readBinaryReference(reference) {
|
|
2172
|
-
await ready;
|
|
2173
|
-
const scope = options.adapter.referrerScope(reference.referrer);
|
|
2174
|
-
if (scope === null)
|
|
2175
|
-
return absentReference(reference.fileRef);
|
|
2176
|
-
return readBinary({ kind: 'reference', fileRef: reference.fileRef, referrer: reference.referrer }, { locator: scope.locator, path: scope.path ?? '', revision: reference.fileRef });
|
|
2177
|
-
}
|
|
2178
|
-
function readPart(file, part) {
|
|
2179
|
-
return options.database.ask({ kind: 'file.part', key: file, part });
|
|
2180
|
-
}
|
|
2181
|
-
async function cleanUp() {
|
|
2182
|
-
const freed = await options.database.ask({ kind: 'opened.clean' });
|
|
2183
|
-
return freed + ((await options.shell.cleanUp?.()) ?? 0);
|
|
2184
|
-
}
|
|
2185
|
-
function declaredAgents() {
|
|
2186
|
-
for (const capability of capabilities) {
|
|
2187
|
-
if (capability.conversationAgents !== undefined)
|
|
2188
|
-
return capability.conversationAgents;
|
|
2189
|
-
}
|
|
2190
|
-
return undefined;
|
|
2191
|
-
}
|
|
2192
|
-
function declaredAction(name) {
|
|
2193
|
-
for (const capability of capabilities) {
|
|
2194
|
-
for (const action of capability.actions ?? []) {
|
|
2195
|
-
if (action.name === name)
|
|
2196
|
-
return action;
|
|
2197
|
-
}
|
|
2198
|
-
}
|
|
2199
|
-
return undefined;
|
|
2200
|
-
}
|
|
2201
|
-
function calledRooms(name, input) {
|
|
2202
|
-
const member = declaredAction(name)?.room;
|
|
2203
|
-
if (member === undefined || input === null || typeof input !== 'object')
|
|
2204
|
-
return [];
|
|
2205
|
-
const named = input[member];
|
|
2206
|
-
return (Array.isArray(named) ? named : [named]).filter((room) => typeof room === 'string');
|
|
2207
|
-
}
|
|
2208
|
-
async function invokeAction(name, input, dispatching) {
|
|
2209
|
-
await ready;
|
|
2210
|
-
if (closed || refusal !== null)
|
|
2211
|
-
return UNCERTAIN;
|
|
2212
|
-
if (declaredAction(name) === undefined)
|
|
2213
|
-
return undeclared(name);
|
|
2214
|
-
try {
|
|
2215
|
-
await ensureAuthorization();
|
|
2216
|
-
}
|
|
2217
|
-
catch {
|
|
2218
|
-
return UNCERTAIN;
|
|
2219
|
-
}
|
|
2220
|
-
if (closed || authorization === undefined || refusal !== null)
|
|
2221
|
-
return UNCERTAIN;
|
|
2222
|
-
await dispatching?.();
|
|
2223
|
-
journal.record(`transfer action ${name}`);
|
|
2224
|
-
try {
|
|
2225
|
-
const result = await options.adapter.action(authorization, { name, input });
|
|
2226
|
-
if (result.kind === 'scoped-refusal') {
|
|
2227
|
-
const room = replicas.get(result.locator)?.confirmed.record;
|
|
2228
|
-
if (room !== undefined)
|
|
2229
|
-
await scoped(result, room, await openLocal());
|
|
2230
|
-
}
|
|
2231
|
-
if (result.kind === 'revoked-authorization')
|
|
2232
|
-
await refuse('revoked-authorization');
|
|
2233
|
-
journal.record(`outcome action ${result.kind}`);
|
|
2234
|
-
if (result.kind === 'rejected')
|
|
2235
|
-
journal.record(`refusal rejected ${result.code}`);
|
|
2236
|
-
return calledResult(result);
|
|
2237
|
-
}
|
|
2238
|
-
catch {
|
|
2239
|
-
journal.record('outcome action transport-uncertainty');
|
|
2240
|
-
return UNCERTAIN;
|
|
2241
|
-
}
|
|
2242
|
-
}
|
|
2243
|
-
function unsettled(result) {
|
|
2244
|
-
return result.kind !== 'action' && result.retryable;
|
|
2245
|
-
}
|
|
2246
|
-
async function recoveredAction(name, input) {
|
|
2247
|
-
const operation = operationOf(input);
|
|
2248
|
-
if (operation === null)
|
|
2249
|
-
return invokeAction(name, input);
|
|
2250
|
-
const kept = async () => (await openLocal()).keepCall({ operation, name, input });
|
|
2251
|
-
calling.add(operation);
|
|
2252
|
-
try {
|
|
2253
|
-
let result = await invokeAction(name, input, kept);
|
|
2254
|
-
if (unsettled(result)) {
|
|
2255
|
-
await recovery.attempt(`action ${operation}`, async () => {
|
|
2256
|
-
if (closed || refusal !== null)
|
|
2257
|
-
return 'done';
|
|
2258
|
-
if (!socketOpen)
|
|
2259
|
-
return 'again';
|
|
2260
|
-
result = await invokeAction(name, input, kept);
|
|
2261
|
-
return unsettled(result) ? 'again' : 'done';
|
|
2262
|
-
}, { again: true });
|
|
2263
|
-
}
|
|
2264
|
-
if (!unsettled(result))
|
|
2265
|
-
await (await openLocal()).dropCall(operation);
|
|
2266
|
-
return result;
|
|
2267
|
-
}
|
|
2268
|
-
finally {
|
|
2269
|
-
calling.delete(operation);
|
|
2270
|
-
}
|
|
2271
|
-
}
|
|
2272
|
-
async function resendCalls(signal) {
|
|
2273
|
-
if (!socketOpen || closed || stopping)
|
|
2274
|
-
return 'done';
|
|
2275
|
-
const local = await openLocal();
|
|
2276
|
-
for (const held of await local.calls()) {
|
|
2277
|
-
if (calling.has(held.operation))
|
|
2278
|
-
continue;
|
|
2279
|
-
if (closed || signal.aborted)
|
|
2280
|
-
return 'done';
|
|
2281
|
-
if (pastHorizon(held.operation)) {
|
|
2282
|
-
await local.dropCall(held.operation);
|
|
2283
|
-
continue;
|
|
2284
|
-
}
|
|
2285
|
-
calling.add(held.operation);
|
|
2286
|
-
try {
|
|
2287
|
-
if (unsettled(await invokeAction(held.name, held.input)))
|
|
2288
|
-
return 'again';
|
|
2289
|
-
await local.dropCall(held.operation);
|
|
2290
|
-
}
|
|
2291
|
-
finally {
|
|
2292
|
-
calling.delete(held.operation);
|
|
2293
|
-
}
|
|
2294
|
-
}
|
|
2295
|
-
return 'done';
|
|
2296
|
-
}
|
|
2297
|
-
function continuing() {
|
|
2298
|
-
return !closed && !discoveryPaused;
|
|
2299
|
-
}
|
|
2300
|
-
function reachedBy(locator, roomVersion) {
|
|
2301
|
-
const held = replicas.get(locator);
|
|
2302
|
-
return (held !== undefined &&
|
|
2303
|
-
options.adapter.reached(locator, held.confirmed.record.roomVersion, roomVersion));
|
|
2304
|
-
}
|
|
2305
|
-
function writtenAfter(locator, roomVersion, path) {
|
|
2306
|
-
const written = replicas.get(locator)?.confirmed.record.written[path];
|
|
2307
|
-
return (written !== undefined &&
|
|
2308
|
-
options.adapter.reached(locator, written, roomVersion) &&
|
|
2309
|
-
!options.adapter.reached(locator, roomVersion, written));
|
|
2310
|
-
}
|
|
2311
|
-
async function pullRefresh(authorized, confirmed, live) {
|
|
2312
|
-
if (!live())
|
|
2313
|
-
return unconfirmed;
|
|
2314
|
-
const turn = generation;
|
|
2315
|
-
try {
|
|
2316
|
-
const result = await refreshRoom(reads, authorized, confirmed, (models, held) => (live() ? remodel(confirmed.record.locator, models, held) : held), live);
|
|
2317
|
-
const detail = result.kind === 'advanced' ? result.confirmed.record.roomVersion : result.kind;
|
|
2318
|
-
journal.record(`transfer refresh ${confirmed.record.locator} ${detail}`);
|
|
2319
|
-
return result;
|
|
2320
|
-
}
|
|
2321
|
-
catch (error) {
|
|
2322
|
-
journal.record(`transfer refresh ${confirmed.record.locator} transport-uncertainty`);
|
|
2323
|
-
throw error;
|
|
2324
|
-
}
|
|
2325
|
-
finally {
|
|
2326
|
-
reads.finished(confirmed.record.locator, turn);
|
|
2327
|
-
}
|
|
2328
|
-
}
|
|
2329
|
-
function staging(local, live) {
|
|
2330
|
-
return {
|
|
2331
|
-
held: (locator) => transfers.get(locator) ?? null,
|
|
2332
|
-
staged: (record) => local.staged(record),
|
|
2333
|
-
stage: (record, page) => exclusive(async () => {
|
|
2334
|
-
if (!live())
|
|
2335
|
-
return false;
|
|
2336
|
-
const bytes = layerBytes(page);
|
|
2337
|
-
if (!(await admitted(local, record.locator, bytes)))
|
|
2338
|
-
return false;
|
|
29
|
+
const { adapter, shell } = options;
|
|
30
|
+
const roomTypes = adapter.roomTypes ?? NO_ROOM_TYPES;
|
|
31
|
+
const builtIn = builtInModel(roomTypes);
|
|
32
|
+
const typedPaths = adapter.typedPaths ?? [];
|
|
33
|
+
const retries = createRetries(shell);
|
|
34
|
+
const socket = createSocket(adapter, retries, options.authorization);
|
|
35
|
+
const presence = createPresence(notReadyWaitMs);
|
|
36
|
+
const store = createStore({
|
|
37
|
+
retries,
|
|
38
|
+
database: {
|
|
39
|
+
async ask(request) {
|
|
2339
40
|
try {
|
|
2340
|
-
await
|
|
41
|
+
return await options.database.ask(request);
|
|
2341
42
|
}
|
|
2342
43
|
catch (error) {
|
|
2343
|
-
if (
|
|
2344
|
-
|
|
2345
|
-
|
|
2346
|
-
return false;
|
|
2347
|
-
}
|
|
2348
|
-
transfers.set(record.locator, record);
|
|
2349
|
-
readSide.recover();
|
|
2350
|
-
return true;
|
|
2351
|
-
}),
|
|
2352
|
-
abandon: (locator) => exclusive(async () => {
|
|
2353
|
-
if (!live())
|
|
2354
|
-
return;
|
|
2355
|
-
await local.abandon(locator);
|
|
2356
|
-
transfers.delete(locator);
|
|
2357
|
-
readSide.recover();
|
|
2358
|
-
}),
|
|
2359
|
-
};
|
|
2360
|
-
}
|
|
2361
|
-
function reusable(room) {
|
|
2362
|
-
const record = replicas.get(room.locator)?.confirmed.record;
|
|
2363
|
-
if (record === undefined || record.replica.selection !== room.replica.selection)
|
|
2364
|
-
return null;
|
|
2365
|
-
return { documents: record.documents, revisions: record.revisions };
|
|
2366
|
-
}
|
|
2367
|
-
async function pullBootstrap(authorized, room, local, live) {
|
|
2368
|
-
if (!live())
|
|
2369
|
-
return unconfirmed;
|
|
2370
|
-
const turn = generation;
|
|
2371
|
-
if (replicas.has(room.locator)) {
|
|
2372
|
-
catching.add(room.locator);
|
|
2373
|
-
readSide.recover();
|
|
2374
|
-
}
|
|
2375
|
-
try {
|
|
2376
|
-
const result = await bootstrapRoom(reads, authorized, room, {
|
|
2377
|
-
collection: modelOf(room.locator),
|
|
2378
|
-
selection: modelOf(room.locator, 'typed-selection'),
|
|
2379
|
-
}, (models, held) => (live() ? remodel(room.locator, models, held) : held), live, staging(local, live), reusable(room));
|
|
2380
|
-
const detail = result.kind === 'staged' ? result.confirmed.record.roomVersion : result.kind;
|
|
2381
|
-
journal.record(`transfer bootstrap ${room.locator} ${detail}`);
|
|
2382
|
-
if (result.kind !== 'staged')
|
|
2383
|
-
caughtUpTo(room.locator);
|
|
2384
|
-
return result;
|
|
2385
|
-
}
|
|
2386
|
-
catch (error) {
|
|
2387
|
-
journal.record(`transfer bootstrap ${room.locator} transport-uncertainty`);
|
|
2388
|
-
caughtUpTo(room.locator);
|
|
2389
|
-
throw error;
|
|
2390
|
-
}
|
|
2391
|
-
finally {
|
|
2392
|
-
reads.finished(room.locator, turn);
|
|
2393
|
-
}
|
|
2394
|
-
}
|
|
2395
|
-
function caughtUpTo(locator) {
|
|
2396
|
-
if (catching.delete(locator))
|
|
2397
|
-
readSide.recover();
|
|
2398
|
-
}
|
|
2399
|
-
function behind(room) {
|
|
2400
|
-
const held = replicas.get(room.locator)?.confirmed.record.roomVersion;
|
|
2401
|
-
return (held !== undefined &&
|
|
2402
|
-
[announced.get(room.locator), room.roomVersion].some((later) => later !== undefined && !options.adapter.reached(room.locator, held, later)));
|
|
2403
|
-
}
|
|
2404
|
-
async function advance(room, local, authorized, live) {
|
|
2405
|
-
const carried = reads.carried(room.locator);
|
|
2406
|
-
const withheld = await advanceOnce(room, local, authorized, live);
|
|
2407
|
-
if (withheld !== null || reads.carried(room.locator) === carried || !behind(room)) {
|
|
2408
|
-
return withheld;
|
|
2409
|
-
}
|
|
2410
|
-
return advanceOnce(room, local, authorized, live);
|
|
2411
|
-
}
|
|
2412
|
-
async function advanceOnce(room, local, authorized, live) {
|
|
2413
|
-
await referenced(room.locator);
|
|
2414
|
-
if (!live() || paused.has(room.locator))
|
|
2415
|
-
return unconfirmed;
|
|
2416
|
-
const held = replicas.get(room.locator);
|
|
2417
|
-
if (held !== undefined) {
|
|
2418
|
-
const refreshed = await pullRefresh(authorized, held.confirmed, live);
|
|
2419
|
-
if (!live())
|
|
2420
|
-
return unconfirmed;
|
|
2421
|
-
if (refreshed.kind === 'still-current') {
|
|
2422
|
-
stale.delete(room.locator);
|
|
2423
|
-
if (sourceRefusals.has(room.locator))
|
|
2424
|
-
return null;
|
|
2425
|
-
if (unreadable.delete(room.locator)) {
|
|
2426
|
-
scopedRefusals.delete(room.locator);
|
|
2427
|
-
list(room, true);
|
|
2428
|
-
emitRooms();
|
|
2429
|
-
}
|
|
2430
|
-
return null;
|
|
2431
|
-
}
|
|
2432
|
-
if (refreshed.kind === 'advanced') {
|
|
2433
|
-
if (!(await publish(local, room, refreshed.confirmed, { base: held.confirmed }, live))) {
|
|
2434
|
-
const now = replicas.get(room.locator)?.confirmed.record.roomVersion;
|
|
2435
|
-
const reached = now !== undefined &&
|
|
2436
|
-
options.adapter.reached(room.locator, now, refreshed.confirmed.record.roomVersion);
|
|
2437
|
-
return reached ? null : advance(room, local, authorized, live);
|
|
2438
|
-
}
|
|
2439
|
-
await retainModel(local, room, 'collection', modelOf(room.locator));
|
|
2440
|
-
return null;
|
|
2441
|
-
}
|
|
2442
|
-
if (refreshed.kind !== 'beyond-horizon')
|
|
2443
|
-
return refreshed;
|
|
2444
|
-
if (opened !== null) {
|
|
2445
|
-
owed.add(room.locator);
|
|
2446
|
-
readSide.recover();
|
|
2447
|
-
return unconfirmed;
|
|
2448
|
-
}
|
|
2449
|
-
if (reloadsDue.get(room.locator) === generation)
|
|
2450
|
-
return unconfirmed;
|
|
2451
|
-
}
|
|
2452
|
-
const bootstrapped = await pullBootstrap(authorized, room, local, live);
|
|
2453
|
-
if (!live())
|
|
2454
|
-
return unconfirmed;
|
|
2455
|
-
if (bootstrapped.kind !== 'staged')
|
|
2456
|
-
return bootstrapped;
|
|
2457
|
-
await publish(local, room, bootstrapped.confirmed, { stored: bootstrapped.stored }, live);
|
|
2458
|
-
return null;
|
|
2459
|
-
}
|
|
2460
|
-
async function withhold(withheld, room, local, progress) {
|
|
2461
|
-
if (withheld.kind === 'unconfirmed')
|
|
2462
|
-
return;
|
|
2463
|
-
if (withheld.kind === 'refused')
|
|
2464
|
-
stale.delete(room.locator);
|
|
2465
|
-
else
|
|
2466
|
-
stale.add(room.locator);
|
|
2467
|
-
if (withheld.kind === 'transport-uncertainty' || withheld.kind === 'retryable-refusal') {
|
|
2468
|
-
const reset = withheld.kind === 'retryable-refusal' ? withheld.reset : undefined;
|
|
2469
|
-
repairable.set(room.locator, reset);
|
|
2470
|
-
repairLater(room.locator, reset === undefined ? { again: true } : { at: Date.parse(reset) });
|
|
2471
|
-
}
|
|
2472
|
-
else
|
|
2473
|
-
repairable.delete(room.locator);
|
|
2474
|
-
if (withheld.kind === 'scoped-refusal') {
|
|
2475
|
-
await scoped(withheld, room, local);
|
|
2476
|
-
}
|
|
2477
|
-
else if (withheld.kind === 'transport-uncertainty') {
|
|
2478
|
-
progress.reachable = false;
|
|
2479
|
-
}
|
|
2480
|
-
else if (withheld.kind === 'retryable-refusal') {
|
|
2481
|
-
journal.record(`refusal ${withheld.kind} ${withheld.code}`);
|
|
2482
|
-
}
|
|
2483
|
-
else if (withheld.kind === 'room-not-readable') {
|
|
2484
|
-
unreadable.add(room.locator);
|
|
2485
|
-
list(room, false);
|
|
2486
|
-
emitRooms();
|
|
2487
|
-
}
|
|
2488
|
-
else if (withheld.kind === 'refused') {
|
|
2489
|
-
refusedSource(room, withheld);
|
|
2490
|
-
}
|
|
2491
|
-
else if (withheld.kind === 'revoked-authorization') {
|
|
2492
|
-
await refuse('revoked-authorization');
|
|
2493
|
-
}
|
|
2494
|
-
}
|
|
2495
|
-
function refusedSource(room, { refusal }) {
|
|
2496
|
-
sourceRefusals.set(room.locator, {
|
|
2497
|
-
code: refusal.rule,
|
|
2498
|
-
retryable: false,
|
|
2499
|
-
fields: {
|
|
2500
|
-
file: refusal.file,
|
|
2501
|
-
...(refusal.location === undefined ? {} : { location: refusal.location }),
|
|
2502
|
-
...(refusal.referrers === undefined ? {} : { referrers: refusal.referrers }),
|
|
2503
|
-
},
|
|
2504
|
-
});
|
|
2505
|
-
declarationRefusals.delete(room.locator);
|
|
2506
|
-
unreadable.add(room.locator);
|
|
2507
|
-
list(room, false);
|
|
2508
|
-
emitRooms();
|
|
2509
|
-
moveTo({ ...status, ...attention() });
|
|
2510
|
-
journal.record(`source refused ${room.locator} ${refusal.rule} ${refusal.file}`);
|
|
2511
|
-
}
|
|
2512
|
-
function leaving(batch, result) {
|
|
2513
|
-
if (result.kind === 'expired')
|
|
2514
|
-
return { batch, returned: returnedBy('expired') };
|
|
2515
|
-
return {
|
|
2516
|
-
batch,
|
|
2517
|
-
returned: {
|
|
2518
|
-
kind: result.kind,
|
|
2519
|
-
code: result.code,
|
|
2520
|
-
fields: result.fields,
|
|
2521
|
-
retryable: result.retryable,
|
|
2522
|
-
},
|
|
2523
|
-
};
|
|
2524
|
-
}
|
|
2525
|
-
function logAccepted(locator, submitted, accepted) {
|
|
2526
|
-
journal.record(`outcome ${locator} ${submitted.id} accepted ${accepted.roomVersion}` +
|
|
2527
|
-
(accepted.author === undefined ? '' : ` author ${accepted.author}`) +
|
|
2528
|
-
(accepted.time === undefined ? '' : ` time ${accepted.time}`));
|
|
2529
|
-
}
|
|
2530
|
-
async function adoptAccepted(room, local, submitted, accepted) {
|
|
2531
|
-
await referenced(room.locator);
|
|
2532
|
-
if (!continuing())
|
|
2533
|
-
return unconfirmed;
|
|
2534
|
-
const current = replicas.get(room.locator);
|
|
2535
|
-
if (current === undefined || !current.queue.some((batch) => batch.id === submitted.id)) {
|
|
2536
|
-
return null;
|
|
2537
|
-
}
|
|
2538
|
-
const held = current.confirmed.record.roomVersion;
|
|
2539
|
-
logAccepted(room.locator, submitted, accepted);
|
|
2540
|
-
const applied = options.adapter.reached(room.locator, held, accepted.roomVersion)
|
|
2541
|
-
? { kind: 'staged', confirmed: current.confirmed }
|
|
2542
|
-
: await applyReturned(current.confirmed, submitted, accepted, options.adapter.follows(room.locator, held, accepted.roomVersion)
|
|
2543
|
-
? accepted.roomVersion
|
|
2544
|
-
: held, accepted.roomVersion);
|
|
2545
|
-
if (applied.kind !== 'staged') {
|
|
2546
|
-
const key = pendingKey(room.locator, submitted.id);
|
|
2547
|
-
const state = pendings.get(key);
|
|
2548
|
-
await local.accept(room.locator, submitted.id, accepted.roomVersion);
|
|
2549
|
-
if (state !== undefined && !fences.has(room.locator))
|
|
2550
|
-
pendings.set(key, { ...state, accepted: accepted.roomVersion });
|
|
2551
|
-
emitQueue(room.locator);
|
|
2552
|
-
return applied;
|
|
2553
|
-
}
|
|
2554
|
-
const settled = await settle(local, room.locator, current, applied.confirmed, current.queue.filter((batch) => batch.id !== submitted.id), { room: true });
|
|
2555
|
-
pendings.delete(pendingKey(room.locator, submitted.id));
|
|
2556
|
-
unreadable.delete(room.locator);
|
|
2557
|
-
sourceRefusals.delete(room.locator);
|
|
2558
|
-
declarationRefusals.delete(room.locator);
|
|
2559
|
-
const set = settled();
|
|
2560
|
-
list(room, true);
|
|
2561
|
-
publishChangeSet(set);
|
|
2562
|
-
moveTo({ ...status, ...attention() });
|
|
2563
|
-
return null;
|
|
2564
|
-
}
|
|
2565
|
-
async function adopted(room, local, submitted, accepted) {
|
|
2566
|
-
const failed = await exclusive(async () => {
|
|
2567
|
-
const adopting = await adoptAccepted(room, local, submitted, accepted);
|
|
2568
|
-
await unpair(local);
|
|
2569
|
-
return adopting;
|
|
2570
|
-
});
|
|
2571
|
-
if (failed === null)
|
|
2572
|
-
return true;
|
|
2573
|
-
if (failed.kind === 'refused' && continuing())
|
|
2574
|
-
refusedSource(room, failed);
|
|
2575
|
-
return false;
|
|
2576
|
-
}
|
|
2577
|
-
async function adoptedMove(room, partner, local, submitted, accepted) {
|
|
2578
|
-
const other = discovered.get(partner);
|
|
2579
|
-
const failed = await exclusive(async () => {
|
|
2580
|
-
const left = await adoptAccepted(room, local, submitted, accepted);
|
|
2581
|
-
const arriving = replicas.get(partner)?.queue.find((batch) => batch.id === submitted.id);
|
|
2582
|
-
const arrived = other === undefined || arriving === undefined || accepted.destination === undefined
|
|
2583
|
-
? null
|
|
2584
|
-
: await adoptAccepted(other, local, arriving, {
|
|
2585
|
-
kind: 'accepted',
|
|
2586
|
-
...accepted.destination,
|
|
2587
|
-
});
|
|
2588
|
-
if (other !== undefined && arrived?.kind === 'refused' && continuing()) {
|
|
2589
|
-
refusedSource(other, arrived);
|
|
2590
|
-
}
|
|
2591
|
-
await unpair(local);
|
|
2592
|
-
return left;
|
|
2593
|
-
});
|
|
2594
|
-
submitLater(partner);
|
|
2595
|
-
if (failed === null)
|
|
2596
|
-
return true;
|
|
2597
|
-
if (failed.kind === 'refused' && continuing())
|
|
2598
|
-
refusedSource(room, failed);
|
|
2599
|
-
return false;
|
|
2600
|
-
}
|
|
2601
|
-
function queueIn(locator) {
|
|
2602
|
-
return replicas.get(locator)?.queue ?? queuesWithoutReplica.get(locator) ?? [];
|
|
2603
|
-
}
|
|
2604
|
-
function behindIn(locator, batch) {
|
|
2605
|
-
const held = replicas.get(locator)?.queue;
|
|
2606
|
-
if (held === undefined)
|
|
2607
|
-
return queuesWithoutReplica.get(locator) !== undefined;
|
|
2608
|
-
return held.findIndex((one) => one.id === batch.id) > 0;
|
|
2609
|
-
}
|
|
2610
|
-
function unpaired(skipped) {
|
|
2611
|
-
for (const locator of [...replicas.keys(), ...queuesWithoutReplica.keys()]) {
|
|
2612
|
-
for (const batch of queueIn(locator)) {
|
|
2613
|
-
const partner = partnerOf(batch, locator);
|
|
2614
|
-
if (partner === null || skipped.has(pendingKey(locator, batch.id)))
|
|
2615
|
-
continue;
|
|
2616
|
-
if (queueIn(partner).some((held) => held.id === batch.id))
|
|
2617
|
-
continue;
|
|
2618
|
-
if (pendings.get(pendingKey(locator, batch.id))?.accepted !== undefined)
|
|
2619
|
-
continue;
|
|
2620
|
-
if (leavingIn(batch, locator) && !withdrawable(locator)(batch))
|
|
2621
|
-
continue;
|
|
2622
|
-
return { locator, batch };
|
|
2623
|
-
}
|
|
2624
|
-
}
|
|
2625
|
-
return null;
|
|
2626
|
-
}
|
|
2627
|
-
async function unpair(local) {
|
|
2628
|
-
const handled = new Set();
|
|
2629
|
-
for (let held = unpaired(handled); held !== null && continuing(); held = unpaired(handled)) {
|
|
2630
|
-
const { locator, batch } = held;
|
|
2631
|
-
handled.add(pendingKey(locator, batch.id));
|
|
2632
|
-
journal.record(`outcome ${locator} ${batch.id} ${localSaves ? 'dropped' : 'unpaired'}`);
|
|
2633
|
-
const leaving = {
|
|
2634
|
-
batch,
|
|
2635
|
-
returned: !localSaves && leavingIn(batch, locator) ? returnedBy('withdrawn') : null,
|
|
2636
|
-
};
|
|
2637
|
-
const current = replicas.get(locator);
|
|
2638
|
-
if (current !== undefined) {
|
|
2639
|
-
const settled = await settle(local, locator, current, current.confirmed, current.queue.filter((one) => one.id !== batch.id), { leaving });
|
|
2640
|
-
publishChangeSet(settled());
|
|
2641
|
-
continue;
|
|
2642
|
-
}
|
|
2643
|
-
const queue = queueIn(locator).filter((one) => one.id !== batch.id);
|
|
2644
|
-
const written = new Map((leaving.returned === null
|
|
2645
|
-
? []
|
|
2646
|
-
: (pendings.get(pendingKey(locator, batch.id))?.drafts ?? [])).map((saved) => [
|
|
2647
|
-
saved.path,
|
|
2648
|
-
{
|
|
2649
|
-
locator,
|
|
2650
|
-
path: saved.path,
|
|
2651
|
-
revision: roomDraftRevision(),
|
|
2652
|
-
parts: returnedInto(roomDrafts.get(locator)?.get(saved.path)?.parts, saved.parts),
|
|
2653
|
-
returned: leaving.returned,
|
|
2654
|
-
},
|
|
2655
|
-
]));
|
|
2656
|
-
const carried = carriedBack(locator, leaving.returned === null ? [] : [batch], written);
|
|
2657
|
-
await local.keepAuthored({
|
|
2658
|
-
locator,
|
|
2659
|
-
queue,
|
|
2660
|
-
roomDrafts: [...written.values()],
|
|
2661
|
-
consumedRoomDrafts: carried.taken,
|
|
2662
|
-
}, ...carried.writes);
|
|
2663
|
-
pendings.delete(pendingKey(locator, batch.id));
|
|
2664
|
-
if (queue.length > 0)
|
|
2665
|
-
queuesWithoutReplica.set(locator, queue);
|
|
2666
|
-
else
|
|
2667
|
-
queuesWithoutReplica.delete(locator);
|
|
2668
|
-
for (const record of written.values())
|
|
2669
|
-
rememberRoomDraft(record);
|
|
2670
|
-
carried.remember();
|
|
2671
|
-
publishChangeSet(mergeChangeSets([
|
|
2672
|
-
changeSet(locator, null, null, {
|
|
2673
|
-
queue: true,
|
|
2674
|
-
drafts: [...written.keys(), ...carried.taken],
|
|
2675
|
-
}),
|
|
2676
|
-
...carried.changes,
|
|
2677
|
-
]));
|
|
2678
|
-
}
|
|
2679
|
-
if (handled.size === 0)
|
|
2680
|
-
return;
|
|
2681
|
-
moveTo({ ...status, ...attention() });
|
|
2682
|
-
for (const key of handled)
|
|
2683
|
-
submitLater(key.slice(0, key.indexOf('\u0000')));
|
|
2684
|
-
}
|
|
2685
|
-
async function discardHeld(head, room, local, signal) {
|
|
2686
|
-
const partner = partnerOf(head, room.locator);
|
|
2687
|
-
const other = partner === null ? undefined : discovered.get(partner);
|
|
2688
|
-
await discardPending(room, local, signal);
|
|
2689
|
-
if (other !== undefined && !signal.aborted)
|
|
2690
|
-
await discardPending(other, local, signal);
|
|
2691
|
-
}
|
|
2692
|
-
async function submitRoom(room, local, authorized, progress, signal) {
|
|
2693
|
-
while (continuing() && authorization !== undefined && !signal.aborted) {
|
|
2694
|
-
const replica = replicas.get(room.locator);
|
|
2695
|
-
const head = replica?.queue[0];
|
|
2696
|
-
if (replica === undefined || head === undefined)
|
|
2697
|
-
return 'done';
|
|
2698
|
-
const state = pendings.get(pendingKey(room.locator, head.id));
|
|
2699
|
-
if (state?.accepted !== undefined)
|
|
2700
|
-
return 'done';
|
|
2701
|
-
const partner = partnerOf(head, room.locator);
|
|
2702
|
-
if (partner !== null && !leavingIn(head, room.locator)) {
|
|
2703
|
-
submitLater(partner);
|
|
2704
|
-
return 'done';
|
|
2705
|
-
}
|
|
2706
|
-
if (partner !== null && behindIn(partner, head)) {
|
|
2707
|
-
progress.complete = false;
|
|
2708
|
-
return 'done';
|
|
2709
|
-
}
|
|
2710
|
-
const { submission, lost: earlier } = state ?? {
|
|
2711
|
-
submission: { state: 'waiting' },
|
|
2712
|
-
lost: false,
|
|
2713
|
-
};
|
|
2714
|
-
if (submission.state === 'reset' && Date.now() < Date.parse(submission.reset)) {
|
|
2715
|
-
progress.complete = false;
|
|
2716
|
-
return { at: Date.parse(submission.reset) };
|
|
2717
|
-
}
|
|
2718
|
-
if (writesHeld()) {
|
|
2719
|
-
progress.complete = false;
|
|
2720
|
-
journal.record(`submission ${room.locator} ${head.id} held`);
|
|
2721
|
-
return 'done';
|
|
2722
|
-
}
|
|
2723
|
-
const lost = earlier || submission.state === 'submitted';
|
|
2724
|
-
if (lost && pastHorizon(head.id)) {
|
|
2725
|
-
await discardHeld(head, room, local, signal);
|
|
2726
|
-
return 'done';
|
|
2727
|
-
}
|
|
2728
|
-
let result;
|
|
2729
|
-
journal.record(`submission ${room.locator} ${head.id}`);
|
|
2730
|
-
await exclusive(() => mark(local, room.locator, head, { state: 'submitted' }, lost));
|
|
2731
|
-
if (discoveryPaused || fences.has(room.locator))
|
|
2732
|
-
return 'done';
|
|
2733
|
-
if (signal.aborted || writesHeld()) {
|
|
2734
|
-
await exclusive(() => mark(local, room.locator, head, submission, earlier));
|
|
2735
|
-
if (signal.aborted)
|
|
2736
|
-
return 'done';
|
|
2737
|
-
progress.complete = false;
|
|
2738
|
-
journal.record(`submission ${room.locator} ${head.id} held`);
|
|
2739
|
-
return 'done';
|
|
2740
|
-
}
|
|
2741
|
-
const opensBefore = openSignals;
|
|
2742
|
-
const answeredHere = awaitingAnswer(room.locator);
|
|
2743
|
-
const answeredThere = partner === null ? () => { } : awaitingAnswer(partner);
|
|
2744
|
-
const answered = () => {
|
|
2745
|
-
answeredHere();
|
|
2746
|
-
answeredThere();
|
|
2747
|
-
};
|
|
2748
|
-
try {
|
|
2749
|
-
result = await options.adapter.mutate(authorized, {
|
|
2750
|
-
locator: room.locator,
|
|
2751
|
-
changeBatch: head,
|
|
2752
|
-
file: batchFile(head),
|
|
2753
|
-
...(state?.upload === undefined ? {} : { upload: state.upload }),
|
|
2754
|
-
}, (upload) => exclusive(() => keepUpload(local, room.locator, head.id, upload)));
|
|
2755
|
-
}
|
|
2756
|
-
catch {
|
|
2757
|
-
answered();
|
|
2758
|
-
progress.complete = false;
|
|
2759
|
-
if (continuing())
|
|
2760
|
-
progress.reachable = false;
|
|
2761
|
-
return 'again';
|
|
2762
|
-
}
|
|
2763
|
-
if (signal.aborted) {
|
|
2764
|
-
answered();
|
|
2765
|
-
return 'done';
|
|
2766
|
-
}
|
|
2767
|
-
if (result.kind !== 'accepted' || !continuing())
|
|
2768
|
-
answered();
|
|
2769
|
-
if (!continuing())
|
|
2770
|
-
return 'done';
|
|
2771
|
-
if (result.kind === 'transport-uncertainty') {
|
|
2772
|
-
progress.complete = false;
|
|
2773
|
-
progress.reachable = false;
|
|
2774
|
-
return 'again';
|
|
2775
|
-
}
|
|
2776
|
-
if (result.kind === 'room-not-readable') {
|
|
2777
|
-
const unread = discovered.get(result.locator) ?? room;
|
|
2778
|
-
progress.complete = false;
|
|
2779
|
-
unreadable.add(unread.locator);
|
|
2780
|
-
list(unread, false);
|
|
2781
|
-
emitRooms();
|
|
2782
|
-
return 'done';
|
|
2783
|
-
}
|
|
2784
|
-
if (result.kind === 'revoked-authorization') {
|
|
2785
|
-
await refuse('revoked-authorization');
|
|
2786
|
-
return 'done';
|
|
2787
|
-
}
|
|
2788
|
-
if (result.kind === 'scoped-refusal') {
|
|
2789
|
-
await scoped(result, room, local);
|
|
2790
|
-
progress.complete = false;
|
|
2791
|
-
return 'done';
|
|
2792
|
-
}
|
|
2793
|
-
if (result.kind === 'write-halted') {
|
|
2794
|
-
journal.record(`outcome ${room.locator} ${head.id} write-halted`);
|
|
2795
|
-
await exclusive(() => mark(local, room.locator, head, { state: 'waiting' }, lost));
|
|
2796
|
-
if (serviceMode === 'open' && openSignals !== opensBefore)
|
|
2797
|
-
continue;
|
|
2798
|
-
haltedRefusal = true;
|
|
2799
|
-
progress.complete = false;
|
|
2800
|
-
return 'done';
|
|
2801
|
-
}
|
|
2802
|
-
const other = partner === null ? undefined : discovered.get(partner);
|
|
2803
|
-
if (result.kind === 'conflicted' ||
|
|
2804
|
-
result.kind === 'rejected' ||
|
|
2805
|
-
result.kind === 'expired' ||
|
|
2806
|
-
result.kind === 'retryable-refusal') {
|
|
2807
|
-
if (result.kind === 'expired' && lost && result.restored !== true) {
|
|
2808
|
-
journal.record(`outcome ${room.locator} ${head.id} expired`);
|
|
2809
|
-
await discardHeld(head, room, local, signal);
|
|
2810
|
-
return 'done';
|
|
2811
|
-
}
|
|
2812
|
-
if (result.kind === 'expired') {
|
|
2813
|
-
await exclusive(() => mark(local, room.locator, head, { state: 'waiting' }, partner !== null && lost));
|
|
2814
|
-
const there = other === undefined ? null : await advance(other, local, authorized, continuing);
|
|
2815
|
-
if (other !== undefined && there !== null) {
|
|
2816
|
-
await withhold(there, other, local, progress);
|
|
2817
|
-
return 'done';
|
|
2818
|
-
}
|
|
2819
|
-
const withheld = await advance(room, local, authorized, continuing);
|
|
2820
|
-
if (withheld !== null) {
|
|
2821
|
-
await withhold(withheld, room, local, progress);
|
|
2822
|
-
return 'done';
|
|
2823
|
-
}
|
|
2824
|
-
}
|
|
2825
|
-
journal.record(`outcome ${room.locator} ${head.id} ${result.kind}` +
|
|
2826
|
-
(result.kind === 'conflicted' && result.roomVersion !== undefined
|
|
2827
|
-
? ` ${result.roomVersion}`
|
|
2828
|
-
: ''));
|
|
2829
|
-
if (result.kind !== 'expired')
|
|
2830
|
-
journal.record(`refusal ${result.kind} ${result.code}`);
|
|
2831
|
-
}
|
|
2832
|
-
if (result.kind === 'retryable-refusal') {
|
|
2833
|
-
const reset = result.reset;
|
|
2834
|
-
progress.complete = false;
|
|
2835
|
-
await exclusive(() => mark(local, room.locator, head, reset === undefined ? { state: 'waiting' } : { state: 'reset', reset }, lost));
|
|
2836
|
-
return reset === undefined ? 'again' : { at: Date.parse(reset) };
|
|
2837
|
-
}
|
|
2838
|
-
if (result.kind === 'conflicted' || result.kind === 'rejected' || result.kind === 'expired') {
|
|
2839
|
-
const left = leaving(head, result);
|
|
2840
|
-
const refreshed = async () => ({
|
|
2841
|
-
there: other === undefined ? null : await advance(other, local, authorized, continuing),
|
|
2842
|
-
here: await advance(room, local, authorized, continuing),
|
|
2843
|
-
});
|
|
2844
|
-
const judged = result.kind === 'conflicted' && other !== undefined ? await refreshed() : null;
|
|
2845
|
-
if (judged !== null && (judged.there !== null || judged.here !== null)) {
|
|
2846
|
-
await exclusive(() => mark(local, room.locator, head, { state: 'waiting' }, lost));
|
|
2847
|
-
if (other !== undefined && judged.there !== null) {
|
|
2848
|
-
await withhold(judged.there, other, local, progress);
|
|
2849
|
-
}
|
|
2850
|
-
if (judged.here !== null)
|
|
2851
|
-
await withhold(judged.here, room, local, progress);
|
|
2852
|
-
return 'done';
|
|
2853
|
-
}
|
|
2854
|
-
await exclusive(async () => {
|
|
2855
|
-
if (!continuing())
|
|
2856
|
-
return;
|
|
2857
|
-
const current = replicas.get(room.locator);
|
|
2858
|
-
if (current === undefined || !current.queue.some((batch) => batch.id === head.id)) {
|
|
2859
|
-
return;
|
|
2860
|
-
}
|
|
2861
|
-
const settled = await settle(local, room.locator, current, current.confirmed, current.queue.filter((batch) => batch.id !== head.id), {
|
|
2862
|
-
leaving: (result.kind === 'expired' && landedWhole(room.locator, head, current.confirmed)) ||
|
|
2863
|
-
(result.kind === 'conflicted' &&
|
|
2864
|
-
landedWhole(room.locator, head, current.confirmed, result.affected))
|
|
2865
|
-
? { ...left, returned: null }
|
|
2866
|
-
: left,
|
|
2867
|
-
});
|
|
2868
|
-
publishChangeSet(settled());
|
|
2869
|
-
await unpair(local);
|
|
2870
|
-
moveTo({ ...status, ...attention() });
|
|
2871
|
-
});
|
|
2872
|
-
if (result.kind === 'expired')
|
|
2873
|
-
continue;
|
|
2874
|
-
const { there, here } = judged ?? (await refreshed());
|
|
2875
|
-
if (other !== undefined && there !== null)
|
|
2876
|
-
await withhold(there, other, local, progress);
|
|
2877
|
-
if (here !== null) {
|
|
2878
|
-
await withhold(here, room, local, progress);
|
|
2879
|
-
return 'done';
|
|
2880
|
-
}
|
|
2881
|
-
continue;
|
|
2882
|
-
}
|
|
2883
|
-
const kept = await (partner === null
|
|
2884
|
-
? adopted(room, local, head, result)
|
|
2885
|
-
: adoptedMove(room, partner, local, head, result)).finally(answered);
|
|
2886
|
-
if (!kept) {
|
|
2887
|
-
progress.complete = false;
|
|
2888
|
-
return 'done';
|
|
2889
|
-
}
|
|
2890
|
-
}
|
|
2891
|
-
return 'done';
|
|
2892
|
-
}
|
|
2893
|
-
function pastHorizon(identity) {
|
|
2894
|
-
return (outcomeRetention !== null && identityTime(identity) + outcomeRetention * 1000 <= Date.now());
|
|
2895
|
-
}
|
|
2896
|
-
async function discardPending(room, local, signal) {
|
|
2897
|
-
const { locator } = room;
|
|
2898
|
-
const discarded = await exclusive(async () => {
|
|
2899
|
-
if (fences.has(locator))
|
|
2900
|
-
return false;
|
|
2901
|
-
const before = replicas.get(locator);
|
|
2902
|
-
const queue = before?.queue ?? queuesWithoutReplica.get(locator) ?? [];
|
|
2903
|
-
fences.set(locator, { at: discoveries, erased: false });
|
|
2904
|
-
lastFenced.set(locator, ++fencings);
|
|
2905
|
-
try {
|
|
2906
|
-
await local.discard(locator);
|
|
2907
|
-
}
|
|
2908
|
-
finally {
|
|
2909
|
-
fences.delete(locator);
|
|
2910
|
-
}
|
|
2911
|
-
for (const batch of queue)
|
|
2912
|
-
pendings.delete(pendingKey(locator, batch.id));
|
|
2913
|
-
queuesWithoutReplica.delete(locator);
|
|
2914
|
-
const after = before === undefined ? null : await stepped(replicating(before.confirmed, [], before));
|
|
2915
|
-
if (after !== null)
|
|
2916
|
-
replicas.set(locator, after);
|
|
2917
|
-
journal.record(`room discarded ${locator}`);
|
|
2918
|
-
publishChangeSet(changeSet(locator, before ?? null, after, { queue: true }));
|
|
2919
|
-
moveTo({ ...status, ...attention() });
|
|
2920
|
-
return true;
|
|
2921
|
-
});
|
|
2922
|
-
if (!discarded)
|
|
2923
|
-
return;
|
|
2924
|
-
const progress = { complete: true, reachable: true };
|
|
2925
|
-
await roomTask(locator, async (live) => {
|
|
2926
|
-
await Promise.race([
|
|
2927
|
-
reload(room, local, progress, () => live() && !signal.aborted),
|
|
2928
|
-
abandonedOn(signal),
|
|
2929
|
-
]);
|
|
2930
|
-
});
|
|
2931
|
-
if (signal.aborted)
|
|
2932
|
-
return;
|
|
2933
|
-
await rest(progress);
|
|
2934
|
-
}
|
|
2935
|
-
function awaitingAnswer(locator) {
|
|
2936
|
-
let release = () => { };
|
|
2937
|
-
const awaited = new Promise((resolve) => {
|
|
2938
|
-
release = resolve;
|
|
2939
|
-
});
|
|
2940
|
-
answering.set(locator, { generation, answered: awaited });
|
|
2941
|
-
return () => {
|
|
2942
|
-
if (answering.get(locator)?.answered === awaited)
|
|
2943
|
-
answering.delete(locator);
|
|
2944
|
-
release();
|
|
2945
|
-
};
|
|
2946
|
-
}
|
|
2947
|
-
async function retainModel(local, room, attached, next) {
|
|
2948
|
-
const key = modelKey(room.locator, attached);
|
|
2949
|
-
const previous = modelOf(room.locator, attached);
|
|
2950
|
-
const heldBefore = replicas.get(room.locator)?.confirmed.record;
|
|
2951
|
-
if (JSON.stringify(previous) === JSON.stringify(next) &&
|
|
2952
|
-
(heldBefore === undefined ||
|
|
2953
|
-
(JSON.stringify(heldBefore.operations) === JSON.stringify(room.operations) &&
|
|
2954
|
-
JSON.stringify(heldBefore.replica) === JSON.stringify(room.replica) &&
|
|
2955
|
-
JSON.stringify(heldBefore.typedSelection) ===
|
|
2956
|
-
JSON.stringify(room.typedSelection ?? null))))
|
|
2957
|
-
return;
|
|
2958
|
-
if (next.status === 'unavailable') {
|
|
2959
|
-
invalidModels.add(key);
|
|
2960
|
-
liveModels.delete(key);
|
|
2961
|
-
}
|
|
2962
|
-
await exclusive(async () => {
|
|
2963
|
-
if (!continuing())
|
|
2964
|
-
return;
|
|
2965
|
-
const held = replicas.get(room.locator);
|
|
2966
|
-
let changed = null;
|
|
2967
|
-
if (held !== undefined) {
|
|
2968
|
-
const declared = {
|
|
2969
|
-
...held.confirmed.record,
|
|
2970
|
-
operations: room.operations,
|
|
2971
|
-
replica: room.replica,
|
|
2972
|
-
typedSelection: room.typedSelection ?? null,
|
|
2973
|
-
...(attached === 'collection' ? { model: next } : { selectionModel: next }),
|
|
2974
|
-
};
|
|
2975
|
-
const reclassified = sameMembership(declared, held.confirmed.record)
|
|
2976
|
-
? { kind: 'staged', confirmed: await confirmedOf(declared, held.confirmed) }
|
|
2977
|
-
: await readReclassified(declared, held.confirmed);
|
|
2978
|
-
const record = reclassified.kind === 'staged'
|
|
2979
|
-
? declared
|
|
2980
|
-
: {
|
|
2981
|
-
...declared,
|
|
2982
|
-
typedSelection: held.confirmed.record.typedSelection,
|
|
2983
|
-
};
|
|
2984
|
-
const read = reclassified.kind === 'deferred'
|
|
2985
|
-
? { kind: 'staged', confirmed: await confirmedOf(record, held.confirmed) }
|
|
2986
|
-
: reclassified;
|
|
2987
|
-
await local.write({ next: record, previous: held.confirmed.record });
|
|
2988
|
-
const replica = read.kind === 'staged'
|
|
2989
|
-
? await stepped(replicating(read.confirmed, held.queue, held))
|
|
2990
|
-
: { ...held, confirmed: { ...held.confirmed, record } };
|
|
2991
|
-
await stepped(counting(replica));
|
|
2992
|
-
const set = await stepped(changing(room.locator, held, replica, { room: true }));
|
|
2993
|
-
replicas.set(room.locator, replica);
|
|
2994
|
-
changed = heldChange(room.locator, held, replica, set, { room: true });
|
|
2995
|
-
if (read.kind === 'staged') {
|
|
2996
|
-
if (declarationRefusals.delete(room.locator)) {
|
|
2997
|
-
sourceRefusals.delete(room.locator);
|
|
2998
|
-
unreadable.delete(room.locator);
|
|
2999
|
-
}
|
|
3000
|
-
}
|
|
3001
|
-
else {
|
|
3002
|
-
refusedSource(room, read);
|
|
3003
|
-
declarationRefusals.add(room.locator);
|
|
3004
|
-
}
|
|
3005
|
-
}
|
|
3006
|
-
models.set(key, next);
|
|
3007
|
-
if (next.status === 'current') {
|
|
3008
|
-
liveModels.set(key, JSON.stringify(next.snapshot));
|
|
3009
|
-
invalidModels.delete(key);
|
|
3010
|
-
}
|
|
3011
|
-
list(room, room.replica.admission === 'admitted' && !unreadable.has(room.locator));
|
|
3012
|
-
if (changed === null)
|
|
3013
|
-
emitRooms();
|
|
3014
|
-
else
|
|
3015
|
-
publishChangeSet(changed);
|
|
3016
|
-
});
|
|
3017
|
-
}
|
|
3018
|
-
async function scoped(result, room, local) {
|
|
3019
|
-
if (result.scope === 'content' && !result.retryable) {
|
|
3020
|
-
journal.record(`scoped refusal ${room.locator} ${result.scope} ${result.code}`);
|
|
3021
|
-
await loseRooms([room.locator]);
|
|
3022
|
-
return;
|
|
3023
|
-
}
|
|
3024
|
-
scopedRefusals.set(room.locator, {
|
|
3025
|
-
code: result.code,
|
|
3026
|
-
fields: result.fields,
|
|
3027
|
-
retryable: result.retryable,
|
|
3028
|
-
});
|
|
3029
|
-
let scopedAway = room;
|
|
3030
|
-
if (result.scope === 'model')
|
|
3031
|
-
await retainModel(local, room, 'collection', {
|
|
3032
|
-
status: 'unavailable',
|
|
3033
|
-
reason: 'not-readable',
|
|
3034
|
-
});
|
|
3035
|
-
else if (result.scope !== 'operation') {
|
|
3036
|
-
unreadable.add(room.locator);
|
|
3037
|
-
scopedAway = { ...room, replica: { ...room.replica, admission: 'unavailable' } };
|
|
3038
|
-
await retainModel(local, scopedAway, 'collection', modelOf(room.locator));
|
|
3039
|
-
}
|
|
3040
|
-
if (!continuing())
|
|
3041
|
-
return;
|
|
3042
|
-
list(scopedAway, scopedAway.replica.admission === 'admitted' && !unreadable.has(room.locator));
|
|
3043
|
-
emitRooms();
|
|
3044
|
-
journal.record(`scoped refusal ${room.locator} ${result.scope} ${result.code}`);
|
|
3045
|
-
}
|
|
3046
|
-
function heldRooms(listed) {
|
|
3047
|
-
return listed.flatMap((room) => {
|
|
3048
|
-
const record = replicas.get(room.locator)?.confirmed.record;
|
|
3049
|
-
if (record === undefined || record.replica.selection !== room.replica.selection)
|
|
3050
|
-
return [];
|
|
3051
|
-
return [
|
|
3052
|
-
{
|
|
3053
|
-
locator: room.locator,
|
|
3054
|
-
roomVersion: record.roomVersion,
|
|
3055
|
-
documents: record.documents,
|
|
3056
|
-
revisions: record.revisions,
|
|
3057
|
-
},
|
|
3058
|
-
];
|
|
3059
|
-
});
|
|
3060
|
-
}
|
|
3061
|
-
async function synchronize(listed, local, progress, attempt, live) {
|
|
3062
|
-
const prepared = await Promise.allSettled(listed.map((room) => prepareRoom(room, local, progress)));
|
|
3063
|
-
if (!live())
|
|
3064
|
-
return;
|
|
3065
|
-
const ready = listed.filter((_, index) => {
|
|
3066
|
-
const outcome = prepared[index];
|
|
3067
|
-
return outcome?.status === 'fulfilled' && outcome.value;
|
|
3068
|
-
});
|
|
3069
|
-
if (attempt === 'opened') {
|
|
3070
|
-
options.adapter.roomStream?.hold(heldRooms(ready));
|
|
3071
|
-
handed = true;
|
|
3072
|
-
}
|
|
3073
|
-
discovering?.release();
|
|
3074
|
-
const loaded = await Promise.allSettled(ready
|
|
3075
|
-
.filter((room) => attempt === 'unstreamed' || !replicas.has(room.locator))
|
|
3076
|
-
.map((room) => roomTask(room.locator, (held) => loadRoom(room, local, progress, held))));
|
|
3077
|
-
const failed = [...prepared, ...loaded].find((room) => room.status === 'rejected');
|
|
3078
|
-
if (failed !== undefined)
|
|
3079
|
-
throw failed.reason;
|
|
3080
|
-
}
|
|
3081
|
-
async function prepareRoom(room, local, progress) {
|
|
3082
|
-
if (closed || authorization === undefined) {
|
|
3083
|
-
progress.complete = false;
|
|
3084
|
-
return false;
|
|
3085
|
-
}
|
|
3086
|
-
const prior = replicas.get(room.locator)?.confirmed.record;
|
|
3087
|
-
if (prior !== undefined && prior.replica.selection !== room.replica.selection) {
|
|
3088
|
-
list(prior, false);
|
|
3089
|
-
emitRooms();
|
|
3090
|
-
journal.record(`selection changed ${room.locator}`);
|
|
3091
|
-
progress.complete = false;
|
|
3092
|
-
return false;
|
|
3093
|
-
}
|
|
3094
|
-
if (prior !== undefined)
|
|
3095
|
-
await retainModel(local, room, 'collection', modelOf(room.locator));
|
|
3096
|
-
if (discoveryPaused || authorization === undefined)
|
|
3097
|
-
return false;
|
|
3098
|
-
return room.replica.admission === 'admitted';
|
|
3099
|
-
}
|
|
3100
|
-
async function caughtUp(room, local, progress, live) {
|
|
3101
|
-
if (authorization === undefined || !live() || !behind(room))
|
|
3102
|
-
return;
|
|
3103
|
-
const withheld = await advance(room, local, authorization, live);
|
|
3104
|
-
if (withheld !== null)
|
|
3105
|
-
await withhold(withheld, room, local, progress);
|
|
3106
|
-
}
|
|
3107
|
-
function revoked(locator) {
|
|
3108
|
-
return ['collection', 'typed-selection'].some((attached) => {
|
|
3109
|
-
const model = modelOf(locator, attached);
|
|
3110
|
-
return model.status === 'unavailable' && model.reason === 'revoked';
|
|
3111
|
-
});
|
|
3112
|
-
}
|
|
3113
|
-
async function loadRoom(room, local, progress, live) {
|
|
3114
|
-
if (!live() || authorization === undefined)
|
|
3115
|
-
return;
|
|
3116
|
-
if (replicas.has(room.locator) && revoked(room.locator)) {
|
|
3117
|
-
await reload(room, local, progress, live);
|
|
3118
|
-
return;
|
|
3119
|
-
}
|
|
3120
|
-
const withheld = await advance(room, local, authorization, live);
|
|
3121
|
-
if (withheld !== null) {
|
|
3122
|
-
await withhold(withheld, room, local, progress);
|
|
3123
|
-
return;
|
|
3124
|
-
}
|
|
3125
|
-
await caughtUp(room, local, progress, live);
|
|
3126
|
-
}
|
|
3127
|
-
async function reload(room, local, progress, live) {
|
|
3128
|
-
try {
|
|
3129
|
-
if (live())
|
|
3130
|
-
reloadsDue.delete(room.locator);
|
|
3131
|
-
if (!live() || authorization === undefined)
|
|
3132
|
-
return;
|
|
3133
|
-
const bootstrapped = await pullBootstrap(authorization, room, local, live);
|
|
3134
|
-
if (!live())
|
|
3135
|
-
return;
|
|
3136
|
-
if (bootstrapped.kind !== 'staged') {
|
|
3137
|
-
await withhold(bootstrapped, room, local, progress);
|
|
3138
|
-
return;
|
|
3139
|
-
}
|
|
3140
|
-
await publish(local, room, bootstrapped.confirmed, { stored: bootstrapped.stored }, live);
|
|
3141
|
-
await caughtUp(room, local, progress, live);
|
|
3142
|
-
}
|
|
3143
|
-
finally {
|
|
3144
|
-
caughtUpTo(room.locator);
|
|
3145
|
-
}
|
|
3146
|
-
}
|
|
3147
|
-
async function discoverRooms(local, progress, attempt, live, scope) {
|
|
3148
|
-
if (closed || authorization === undefined) {
|
|
3149
|
-
notifyReady();
|
|
3150
|
-
return;
|
|
3151
|
-
}
|
|
3152
|
-
moveTo(transferring(status));
|
|
3153
|
-
discoveries += 1;
|
|
3154
|
-
const started = discoveries;
|
|
3155
|
-
let result;
|
|
3156
|
-
try {
|
|
3157
|
-
result = await options.adapter.discover(authorization, scope);
|
|
3158
|
-
}
|
|
3159
|
-
catch {
|
|
3160
|
-
result = { kind: 'transport-uncertainty' };
|
|
3161
|
-
}
|
|
3162
|
-
if (!live()) {
|
|
3163
|
-
progress.complete = false;
|
|
3164
|
-
notifyReady();
|
|
3165
|
-
return;
|
|
3166
|
-
}
|
|
3167
|
-
journal.record(`connection discover ${result.kind}`);
|
|
3168
|
-
if (result.kind === 'transport-uncertainty') {
|
|
3169
|
-
for (const room of rooms.values()) {
|
|
3170
|
-
await retainModel(local, room, 'collection', cached(modelOf(room.locator)));
|
|
3171
|
-
if (room.typedSelection !== null) {
|
|
3172
|
-
await retainModel(local, room, 'typed-selection', cached(modelOf(room.locator, 'typed-selection')));
|
|
3173
|
-
}
|
|
3174
|
-
}
|
|
3175
|
-
progress.reachable = false;
|
|
3176
|
-
progress.complete = false;
|
|
3177
|
-
notifyReady();
|
|
3178
|
-
return;
|
|
3179
|
-
}
|
|
3180
|
-
if (result.kind === 'contract-unavailable') {
|
|
3181
|
-
journal.record(`connection contract unavailable ${result.code}`);
|
|
3182
|
-
await refuse('missing-required-guarantee', {
|
|
3183
|
-
code: result.code,
|
|
3184
|
-
fields: result.fields,
|
|
3185
|
-
retryable: result.retryable,
|
|
3186
|
-
});
|
|
3187
|
-
notifyReady();
|
|
3188
|
-
return;
|
|
3189
|
-
}
|
|
3190
|
-
if (result.kind === 'revoked-authorization') {
|
|
3191
|
-
await refuse('revoked-authorization');
|
|
3192
|
-
notifyReady();
|
|
3193
|
-
return;
|
|
3194
|
-
}
|
|
3195
|
-
for (const room of result.rooms) {
|
|
3196
|
-
if (room.operations === undefined ||
|
|
3197
|
-
!['write', 'delete'].every((operation) => Array.isArray(room.operations[operation]) &&
|
|
3198
|
-
room.operations[operation].every((scope) => typeof scope === 'string')) ||
|
|
3199
|
-
room.replica === undefined ||
|
|
3200
|
-
typeof room.replica.selection !== 'string' ||
|
|
3201
|
-
room.replica.selection.length === 0 ||
|
|
3202
|
-
!['admitted', 'unavailable'].includes(room.replica.admission) ||
|
|
3203
|
-
!['locked', 'open'].includes(room.replica.offline)) {
|
|
3204
|
-
journal.record(`invalid model or replica declaration ${room.locator}`);
|
|
3205
|
-
await refuse('missing-required-guarantee');
|
|
3206
|
-
notifyReady();
|
|
3207
|
-
return;
|
|
3208
|
-
}
|
|
3209
|
-
if (!declaredSelection(room)) {
|
|
3210
|
-
journal.record(`invalid typed selection declaration ${room.locator}`);
|
|
3211
|
-
await refuse('missing-required-guarantee');
|
|
3212
|
-
notifyReady();
|
|
3213
|
-
return;
|
|
3214
|
-
}
|
|
3215
|
-
}
|
|
3216
|
-
if (refusal !== null) {
|
|
3217
|
-
refusal = null;
|
|
3218
|
-
emitRefusal();
|
|
3219
|
-
}
|
|
3220
|
-
const previousCapabilities = capabilities;
|
|
3221
|
-
capabilities = result.capabilities;
|
|
3222
|
-
outcomeRetention = result.retention.outcome;
|
|
3223
|
-
notifyReady();
|
|
3224
|
-
if (JSON.stringify(result.providerLimits) !== JSON.stringify(limits) ||
|
|
3225
|
-
JSON.stringify(result.capabilities) !== JSON.stringify(previousCapabilities)) {
|
|
3226
|
-
limits = result.providerLimits;
|
|
3227
|
-
await local.declare(limits, capabilities);
|
|
3228
|
-
}
|
|
3229
|
-
const signedIn = result.member ?? null;
|
|
3230
|
-
if (JSON.stringify(signedIn) !== JSON.stringify(member)) {
|
|
3231
|
-
await local.keepMember(signedIn);
|
|
3232
|
-
member = signedIn;
|
|
3233
|
-
emitMember();
|
|
3234
|
-
}
|
|
3235
|
-
await synchronize(await applyDiscovery(result.rooms, started, result.covered), local, progress, attempt, live);
|
|
3236
|
-
}
|
|
3237
|
-
async function ensureAuthorization() {
|
|
3238
|
-
if (authorization !== undefined)
|
|
3239
|
-
return;
|
|
3240
|
-
try {
|
|
3241
|
-
authorization = await options.adapter.authorize();
|
|
3242
|
-
journal.record('connection authorize');
|
|
3243
|
-
}
|
|
3244
|
-
catch (error) {
|
|
3245
|
-
journal.record('connection authorize transport-uncertainty');
|
|
3246
|
-
throw error;
|
|
3247
|
-
}
|
|
3248
|
-
}
|
|
3249
|
-
async function admittedRead(work) {
|
|
3250
|
-
if (roomReads.generation !== generation) {
|
|
3251
|
-
roomReads = { generation, free: ROOM_READS, waiting: [] };
|
|
3252
|
-
}
|
|
3253
|
-
const reads = roomReads;
|
|
3254
|
-
while (reads.free === 0)
|
|
3255
|
-
await new Promise((admit) => reads.waiting.push(admit));
|
|
3256
|
-
reads.free -= 1;
|
|
3257
|
-
try {
|
|
3258
|
-
await work();
|
|
3259
|
-
}
|
|
3260
|
-
finally {
|
|
3261
|
-
reads.free += 1;
|
|
3262
|
-
reads.waiting.shift()?.();
|
|
3263
|
-
}
|
|
3264
|
-
}
|
|
3265
|
-
function roomTask(locator, work) {
|
|
3266
|
-
return task(roomLane(locator), (live) => admittedRead(() => work(live)));
|
|
3267
|
-
}
|
|
3268
|
-
function task(lane, work) {
|
|
3269
|
-
if (stopping)
|
|
3270
|
-
return Promise.resolve();
|
|
3271
|
-
const held = lanes.get(lane);
|
|
3272
|
-
const current = held?.generation === generation ? held : { generation, chain: Promise.resolve() };
|
|
3273
|
-
const turn = current.generation;
|
|
3274
|
-
const live = () => turn === generation && continuing();
|
|
3275
|
-
const run = current.chain.then(() => work(live)).catch(() => undefined);
|
|
3276
|
-
current.chain = run;
|
|
3277
|
-
lanes.set(lane, current);
|
|
3278
|
-
working.add(run);
|
|
3279
|
-
void run.finally(() => working.delete(run));
|
|
3280
|
-
return run;
|
|
3281
|
-
}
|
|
3282
|
-
function sync(attempt) {
|
|
3283
|
-
return task(OPENING_LANE, async (live) => {
|
|
3284
|
-
if (!live()) {
|
|
3285
|
-
notifyReady();
|
|
3286
|
-
return;
|
|
3287
|
-
}
|
|
3288
|
-
const progress = { complete: true, reachable: true };
|
|
3289
|
-
const gate = discover();
|
|
3290
|
-
if (attempt === 'opened')
|
|
3291
|
-
opened = generation;
|
|
3292
|
-
underway = attempt === 'opened' ? { generation, progress } : null;
|
|
3293
|
-
if (attempt === 'opened')
|
|
3294
|
-
streamed = progress;
|
|
3295
|
-
complete = false;
|
|
3296
|
-
recorded = false;
|
|
3297
|
-
moveTo(transferring(status));
|
|
3298
|
-
handed = false;
|
|
3299
|
-
try {
|
|
3300
|
-
const local = await openLocal();
|
|
3301
|
-
if (!live())
|
|
3302
|
-
return;
|
|
3303
|
-
await ensureAuthorization();
|
|
3304
|
-
if (!live())
|
|
3305
|
-
return;
|
|
3306
|
-
await discoverRooms(local, progress, attempt, live);
|
|
3307
|
-
}
|
|
3308
|
-
catch {
|
|
3309
|
-
progress.complete = false;
|
|
3310
|
-
if (attempt === 'opened' && !handed)
|
|
3311
|
-
progress.reachable = false;
|
|
3312
|
-
}
|
|
3313
|
-
finally {
|
|
3314
|
-
gate.release();
|
|
3315
|
-
notifyReady();
|
|
3316
|
-
}
|
|
3317
|
-
if (!live())
|
|
3318
|
-
return;
|
|
3319
|
-
if (attempt !== 'opened') {
|
|
3320
|
-
await finishOpening(progress, live);
|
|
3321
|
-
return;
|
|
3322
|
-
}
|
|
3323
|
-
if (handed || closed || progress.reachable)
|
|
3324
|
-
return;
|
|
3325
|
-
underway = null;
|
|
3326
|
-
opened = null;
|
|
3327
|
-
journal.record('connection reopen');
|
|
3328
|
-
await rest(progress, live);
|
|
3329
|
-
options.adapter.roomStream?.reopen();
|
|
3330
|
-
});
|
|
3331
|
-
}
|
|
3332
|
-
function rediscover(scope) {
|
|
3333
|
-
return task(OPENING_LANE, async (live) => {
|
|
3334
|
-
if (!live() || !socketOpen)
|
|
3335
|
-
return;
|
|
3336
|
-
const progress = { complete: true, reachable: true };
|
|
3337
|
-
const gate = discover();
|
|
3338
|
-
moveTo(transferring(status));
|
|
3339
|
-
try {
|
|
3340
|
-
const local = await openLocal();
|
|
3341
|
-
if (!live())
|
|
3342
|
-
return;
|
|
3343
|
-
await ensureAuthorization();
|
|
3344
|
-
if (!live())
|
|
3345
|
-
return;
|
|
3346
|
-
await discoverRooms(local, progress, 'authorized', live, scope);
|
|
3347
|
-
}
|
|
3348
|
-
catch {
|
|
3349
|
-
progress.complete = false;
|
|
3350
|
-
}
|
|
3351
|
-
finally {
|
|
3352
|
-
gate.release();
|
|
3353
|
-
notifyReady();
|
|
3354
|
-
}
|
|
3355
|
-
if (!live())
|
|
3356
|
-
return;
|
|
3357
|
-
if (!progress.complete)
|
|
3358
|
-
complete = false;
|
|
3359
|
-
await rest(progress, live);
|
|
3360
|
-
});
|
|
3361
|
-
}
|
|
3362
|
-
function closedSocket(revoked, lost) {
|
|
3363
|
-
const opened = socketOpen;
|
|
3364
|
-
socketOpen = false;
|
|
3365
|
-
connectionLost();
|
|
3366
|
-
if (lost) {
|
|
3367
|
-
reads.lost();
|
|
3368
|
-
conversations.lost();
|
|
3369
|
-
}
|
|
3370
|
-
if (revoked) {
|
|
3371
|
-
void refuse('revoked-authorization');
|
|
3372
|
-
return;
|
|
3373
|
-
}
|
|
3374
|
-
complete = false;
|
|
3375
|
-
if (streamed !== null)
|
|
3376
|
-
streamed.complete = false;
|
|
3377
|
-
moveTo({
|
|
3378
|
-
...status,
|
|
3379
|
-
state: status.state === 'synced' ? 'syncing' : status.state,
|
|
3380
|
-
providerUnreachable: status.providerUnreachable || !opened,
|
|
3381
|
-
});
|
|
3382
|
-
}
|
|
3383
|
-
function applyOpening(expired) {
|
|
3384
|
-
const progress = underway?.generation === generation ? underway.progress : null;
|
|
3385
|
-
const cycle = progress ?? { complete: true, reachable: true };
|
|
3386
|
-
if (opened === generation)
|
|
3387
|
-
opened = null;
|
|
3388
|
-
const reloading = progress === null ? [] : owedReloads(expired);
|
|
3389
|
-
const replacing = reloadNow((room) => expired.includes(room.locator) || reloading.includes(room.locator), cycle);
|
|
3390
|
-
return task(OPENING_LANE, async (live) => {
|
|
3391
|
-
underway = null;
|
|
3392
|
-
if (!live())
|
|
3393
|
-
return;
|
|
3394
|
-
if (progress === null) {
|
|
3395
|
-
await replacing;
|
|
3396
|
-
await rest(cycle, live);
|
|
3397
|
-
return;
|
|
3398
|
-
}
|
|
3399
|
-
await roomsCarried([...expired, ...reloading]);
|
|
3400
|
-
if (!live())
|
|
3401
|
-
return;
|
|
3402
|
-
try {
|
|
3403
|
-
const local = await openLocal();
|
|
3404
|
-
const reloaded = await replacing;
|
|
3405
|
-
if (progress.reachable) {
|
|
3406
|
-
for (const room of discovered.values()) {
|
|
3407
|
-
if (replicas.has(room.locator) &&
|
|
3408
|
-
!expired.includes(room.locator) &&
|
|
3409
|
-
!reloading.includes(room.locator)) {
|
|
3410
|
-
await confirmModels(room, local);
|
|
3411
|
-
}
|
|
3412
|
-
}
|
|
44
|
+
if (refusedForSpace(error))
|
|
45
|
+
filled(runtime);
|
|
46
|
+
throw error;
|
|
3413
47
|
}
|
|
3414
|
-
const failed = reloaded.find((outcome) => outcome.status === 'rejected');
|
|
3415
|
-
if (failed !== undefined)
|
|
3416
|
-
throw failed.reason;
|
|
3417
|
-
}
|
|
3418
|
-
catch {
|
|
3419
|
-
progress.complete = false;
|
|
3420
|
-
progress.reachable = false;
|
|
3421
|
-
}
|
|
3422
|
-
if (live())
|
|
3423
|
-
await finishOpening(progress, live);
|
|
3424
|
-
});
|
|
3425
|
-
}
|
|
3426
|
-
function owedReloads(expired) {
|
|
3427
|
-
const reloading = [...discovered.values()]
|
|
3428
|
-
.filter((room) => replicas.has(room.locator) &&
|
|
3429
|
-
!expired.includes(room.locator) &&
|
|
3430
|
-
(owed.has(room.locator) || revoked(room.locator)))
|
|
3431
|
-
.map((room) => room.locator);
|
|
3432
|
-
owed.clear();
|
|
3433
|
-
for (const locator of reloading)
|
|
3434
|
-
catching.add(locator);
|
|
3435
|
-
readSide.recover();
|
|
3436
|
-
return reloading;
|
|
3437
|
-
}
|
|
3438
|
-
async function reloadNow(replaced, progress) {
|
|
3439
|
-
const reloaded = [...discovered.values()].filter((room) => replicas.has(room.locator) && replaced(room));
|
|
3440
|
-
for (const room of reloaded)
|
|
3441
|
-
reloadsDue.set(room.locator, generation);
|
|
3442
|
-
try {
|
|
3443
|
-
const local = await openLocal();
|
|
3444
|
-
return await Promise.allSettled(reloaded.map((room) => roomTask(room.locator, (live) => reload(room, local, progress, live))));
|
|
3445
|
-
}
|
|
3446
|
-
catch {
|
|
3447
|
-
for (const room of reloaded)
|
|
3448
|
-
reloadsDue.delete(room.locator);
|
|
3449
|
-
progress.reachable = false;
|
|
3450
|
-
return [];
|
|
3451
|
-
}
|
|
3452
|
-
}
|
|
3453
|
-
async function confirmModels(room, local) {
|
|
3454
|
-
for (const attached of ['collection', 'typed-selection']) {
|
|
3455
|
-
const model = modelOf(room.locator, attached);
|
|
3456
|
-
if (model.status === 'cached') {
|
|
3457
|
-
await retainModel(local, room, attached, { ...model, status: 'current' });
|
|
3458
|
-
}
|
|
3459
|
-
}
|
|
3460
|
-
}
|
|
3461
|
-
function submitLater(locator) {
|
|
3462
|
-
if (localSaves)
|
|
3463
|
-
return;
|
|
3464
|
-
void recovery.attempt(`submit ${locator}`, (signal) => submitPass(locator, signal));
|
|
3465
|
-
}
|
|
3466
|
-
async function submitPass(locator, signal) {
|
|
3467
|
-
const room = discovered.get(locator);
|
|
3468
|
-
if (closed || stopping || discoveryPaused || room === undefined)
|
|
3469
|
-
return 'done';
|
|
3470
|
-
const progress = { complete: true, reachable: true };
|
|
3471
|
-
let next;
|
|
3472
|
-
try {
|
|
3473
|
-
await ensureAuthorization();
|
|
3474
|
-
if (authorization === undefined)
|
|
3475
|
-
return 'done';
|
|
3476
|
-
next = await submitRoom(room, await openLocal(), authorization, progress, signal);
|
|
3477
|
-
}
|
|
3478
|
-
catch {
|
|
3479
|
-
progress.reachable = false;
|
|
3480
|
-
next = 'again';
|
|
3481
|
-
}
|
|
3482
|
-
if (signal.aborted)
|
|
3483
|
-
return 'done';
|
|
3484
|
-
await rest(progress);
|
|
3485
|
-
return next === 'again' && !socketOpen ? 'done' : next;
|
|
3486
|
-
}
|
|
3487
|
-
function repairLater(locator, when) {
|
|
3488
|
-
if (!socketOpen || repairing.has(locator))
|
|
3489
|
-
return;
|
|
3490
|
-
void recovery.attempt(`repair ${locator}`, (signal) => repairPass(locator, signal), when);
|
|
3491
|
-
}
|
|
3492
|
-
async function repairPass(locator, signal) {
|
|
3493
|
-
const room = discovered.get(locator);
|
|
3494
|
-
if (!socketOpen || closed || stopping || discoveryPaused || !stale.has(locator))
|
|
3495
|
-
return 'done';
|
|
3496
|
-
if (room === undefined || room.replica.admission !== 'admitted')
|
|
3497
|
-
return 'done';
|
|
3498
|
-
const progress = { complete: true, reachable: true };
|
|
3499
|
-
repairing.add(locator);
|
|
3500
|
-
try {
|
|
3501
|
-
const local = await openLocal();
|
|
3502
|
-
await roomTask(locator, async (live) => {
|
|
3503
|
-
const current = () => live() && !signal.aborted;
|
|
3504
|
-
if (!current() || authorization === undefined)
|
|
3505
|
-
return;
|
|
3506
|
-
const withheld = await Promise.race([
|
|
3507
|
-
advance(room, local, authorization, current),
|
|
3508
|
-
abandonedOn(signal),
|
|
3509
|
-
]);
|
|
3510
|
-
if (withheld !== null && current())
|
|
3511
|
-
await withhold(withheld, room, local, progress);
|
|
3512
|
-
});
|
|
3513
|
-
}
|
|
3514
|
-
catch {
|
|
3515
|
-
stale.add(locator);
|
|
3516
|
-
progress.reachable = false;
|
|
3517
|
-
}
|
|
3518
|
-
finally {
|
|
3519
|
-
repairing.delete(locator);
|
|
3520
|
-
}
|
|
3521
|
-
if (signal.aborted)
|
|
3522
|
-
return 'done';
|
|
3523
|
-
await rest(progress);
|
|
3524
|
-
if (!stale.has(locator)) {
|
|
3525
|
-
if ((replicas.get(locator)?.queue.length ?? 0) > 0)
|
|
3526
|
-
submitLater(locator);
|
|
3527
|
-
return 'done';
|
|
3528
|
-
}
|
|
3529
|
-
if (!repairable.has(locator))
|
|
3530
|
-
return 'done';
|
|
3531
|
-
const reset = repairable.get(locator);
|
|
3532
|
-
return reset === undefined ? 'again' : { at: Date.parse(reset) };
|
|
3533
|
-
}
|
|
3534
|
-
function resendLater() {
|
|
3535
|
-
if (!socketOpen)
|
|
3536
|
-
return;
|
|
3537
|
-
void recovery.attempt('resend', resendPass, { again: true });
|
|
3538
|
-
}
|
|
3539
|
-
async function resendPass(signal) {
|
|
3540
|
-
if (!socketOpen || closed || stopping || discoveryPaused)
|
|
3541
|
-
return 'done';
|
|
3542
|
-
const reading = { complete: true, reachable: true };
|
|
3543
|
-
try {
|
|
3544
|
-
await conversations.resend(reading);
|
|
3545
|
-
}
|
|
3546
|
-
catch {
|
|
3547
|
-
reading.reachable = false;
|
|
3548
|
-
}
|
|
3549
|
-
if (signal.aborted)
|
|
3550
|
-
return 'done';
|
|
3551
|
-
return reading.reachable && reading.complete ? 'done' : 'again';
|
|
3552
|
-
}
|
|
3553
|
-
function submitAll() {
|
|
3554
|
-
for (const [locator, replica] of replicas) {
|
|
3555
|
-
if (replica.queue.length > 0)
|
|
3556
|
-
submitLater(locator);
|
|
3557
|
-
}
|
|
3558
|
-
}
|
|
3559
|
-
async function finishOpening(progress, live) {
|
|
3560
|
-
try {
|
|
3561
|
-
if (!live()) {
|
|
3562
|
-
progress.complete = false;
|
|
3563
|
-
return;
|
|
3564
|
-
}
|
|
3565
|
-
reads.applied();
|
|
3566
|
-
submitAll();
|
|
3567
|
-
for (const locator of stale)
|
|
3568
|
-
if (repairable.has(locator))
|
|
3569
|
-
repairLater(locator, {});
|
|
3570
|
-
await conversations.reconcile();
|
|
3571
|
-
if (status.providerUnreachable)
|
|
3572
|
-
conversations.reconnected();
|
|
3573
|
-
const reading = { complete: true, reachable: true };
|
|
3574
|
-
await conversations.catchUp(reading);
|
|
3575
|
-
if (progress.reachable && reading.reachable)
|
|
3576
|
-
await conversations.resend(reading);
|
|
3577
|
-
if (progress.reachable)
|
|
3578
|
-
void recovery.attempt('calls', resendCalls);
|
|
3579
|
-
if (!reading.reachable) {
|
|
3580
|
-
progress.reachable = false;
|
|
3581
|
-
resendLater();
|
|
3582
|
-
}
|
|
3583
|
-
}
|
|
3584
|
-
catch {
|
|
3585
|
-
progress.complete = false;
|
|
3586
|
-
}
|
|
3587
|
-
finally {
|
|
3588
|
-
if (live()) {
|
|
3589
|
-
complete = progress.complete;
|
|
3590
|
-
await rest(progress, live);
|
|
3591
|
-
}
|
|
3592
|
-
}
|
|
3593
|
-
}
|
|
3594
|
-
async function rest(progress, live = () => !closed) {
|
|
3595
|
-
if (!live())
|
|
3596
|
-
return;
|
|
3597
|
-
let lastCompleted = status.lastCompleted;
|
|
3598
|
-
let synced = complete && stale.size === 0 && !pending();
|
|
3599
|
-
if (synced && !recorded) {
|
|
3600
|
-
const completedAt = new Date().toISOString();
|
|
3601
|
-
try {
|
|
3602
|
-
await (await openLocal()).complete(completedAt);
|
|
3603
|
-
if (!live())
|
|
3604
|
-
return;
|
|
3605
|
-
recorded = true;
|
|
3606
|
-
lastCompleted = completedAt;
|
|
3607
|
-
}
|
|
3608
|
-
catch {
|
|
3609
|
-
synced = false;
|
|
3610
|
-
}
|
|
3611
|
-
}
|
|
3612
|
-
moveTo({
|
|
3613
|
-
state: pending() ? 'pending' : synced && complete ? 'synced' : 'syncing',
|
|
3614
|
-
lastCompleted,
|
|
3615
|
-
providerUnreachable: !progress.reachable,
|
|
3616
|
-
...attention(),
|
|
3617
|
-
});
|
|
3618
|
-
}
|
|
3619
|
-
function discover() {
|
|
3620
|
-
let release = () => { };
|
|
3621
|
-
const done = new Promise((resolve) => {
|
|
3622
|
-
release = resolve;
|
|
3623
|
-
});
|
|
3624
|
-
discovering = { generation, done, release };
|
|
3625
|
-
return discovering;
|
|
3626
|
-
}
|
|
3627
|
-
function applyRoom(locator, roomVersion) {
|
|
3628
|
-
announced.set(locator, roomVersion);
|
|
3629
|
-
return task(roomLane(locator), async (live) => {
|
|
3630
|
-
if (discovering?.generation === generation)
|
|
3631
|
-
await discovering.done;
|
|
3632
|
-
const saving = answering.get(locator);
|
|
3633
|
-
if (saving?.generation === generation)
|
|
3634
|
-
await saving.answered;
|
|
3635
|
-
if (!live() || authorization === undefined)
|
|
3636
|
-
return;
|
|
3637
|
-
const room = discovered.get(locator);
|
|
3638
|
-
const held = replicas.get(locator);
|
|
3639
|
-
if (room === undefined || room.replica.admission !== 'admitted')
|
|
3640
|
-
return;
|
|
3641
|
-
if (held !== undefined &&
|
|
3642
|
-
(held.confirmed.record.replica.selection !== room.replica.selection ||
|
|
3643
|
-
options.adapter.reached(locator, held.confirmed.record.roomVersion, roomVersion))) {
|
|
3644
|
-
return;
|
|
3645
|
-
}
|
|
3646
|
-
const during = underway?.generation === generation ? underway.progress : null;
|
|
3647
|
-
const progress = during ?? { complete: true, reachable: true };
|
|
3648
|
-
if (during === null)
|
|
3649
|
-
moveTo(transferring(status));
|
|
3650
|
-
try {
|
|
3651
|
-
const local = await openLocal();
|
|
3652
|
-
await admittedRead(async () => {
|
|
3653
|
-
if (!live() || authorization === undefined)
|
|
3654
|
-
return;
|
|
3655
|
-
const withheld = await advance(room, local, authorization, live);
|
|
3656
|
-
if (withheld !== null)
|
|
3657
|
-
await withhold(withheld, room, local, progress);
|
|
3658
|
-
});
|
|
3659
|
-
}
|
|
3660
|
-
catch {
|
|
3661
|
-
stale.add(locator);
|
|
3662
|
-
}
|
|
3663
|
-
finally {
|
|
3664
|
-
if (during === null)
|
|
3665
|
-
await rest(progress, live);
|
|
3666
|
-
}
|
|
3667
|
-
});
|
|
3668
|
-
}
|
|
3669
|
-
function roomsCarried(replacing) {
|
|
3670
|
-
const replaced = new Set(replacing.map(roomLane));
|
|
3671
|
-
return Promise.all([...lanes]
|
|
3672
|
-
.filter(([lane, held]) => lane !== OPENING_LANE && !replaced.has(lane) && held.generation === generation)
|
|
3673
|
-
.map(([, held]) => held.chain));
|
|
3674
|
-
}
|
|
3675
|
-
const receipts = {
|
|
3676
|
-
heads: async () => (await openLocal()).receivedHeads(),
|
|
3677
|
-
parts: async (key, count) => (await openLocal()).receivedParts(key, count),
|
|
3678
|
-
keep: async (key, head, part) => (await openLocal()).keepReceived(key, head, part),
|
|
3679
|
-
drop: async (keys) => (await openLocal()).dropReceived(keys),
|
|
3680
|
-
};
|
|
3681
|
-
function observeStream() {
|
|
3682
|
-
const stream = options.adapter.roomStream;
|
|
3683
|
-
if (stream === undefined || withdrawStream !== undefined)
|
|
3684
|
-
return;
|
|
3685
|
-
withdrawStream = stream.observe((event) => {
|
|
3686
|
-
if (closed || stopping)
|
|
3687
|
-
return;
|
|
3688
|
-
if (event.kind === 'opened') {
|
|
3689
|
-
socketOpen = true;
|
|
3690
|
-
connectionLive();
|
|
3691
|
-
generation += 1;
|
|
3692
|
-
reads.opened();
|
|
3693
|
-
conversations.reopened();
|
|
3694
|
-
recovery.resume();
|
|
3695
|
-
void sync('opened');
|
|
3696
|
-
}
|
|
3697
|
-
else if (event.kind === 'closed')
|
|
3698
|
-
closedSocket(event.revoked, event.lost);
|
|
3699
|
-
else if (event.kind === 'opening')
|
|
3700
|
-
void applyOpening(event.expired);
|
|
3701
|
-
else if (event.kind === 'authority-changed')
|
|
3702
|
-
void rediscover(event.scope);
|
|
3703
|
-
else
|
|
3704
|
-
void applyRoom(event.locator, event.roomVersion);
|
|
3705
|
-
}, receipts);
|
|
3706
|
-
}
|
|
3707
|
-
function writesHeld() {
|
|
3708
|
-
return serviceMode === 'write-halted' || haltedRefusal;
|
|
3709
|
-
}
|
|
3710
|
-
function signalled(mode) {
|
|
3711
|
-
if (closed)
|
|
3712
|
-
return;
|
|
3713
|
-
if (mode === 'open')
|
|
3714
|
-
openSignals += 1;
|
|
3715
|
-
const releasing = mode === 'open' && (haltedRefusal || serviceMode === 'write-halted');
|
|
3716
|
-
if (mode === 'open')
|
|
3717
|
-
haltedRefusal = false;
|
|
3718
|
-
if (mode !== serviceMode) {
|
|
3719
|
-
serviceMode = mode;
|
|
3720
|
-
queueReadiness();
|
|
3721
|
-
journal.record(`service mode ${mode}`);
|
|
3722
|
-
for (const listener of serviceModeListeners)
|
|
3723
|
-
listener(mode);
|
|
3724
|
-
}
|
|
3725
|
-
if (releasing)
|
|
3726
|
-
submitAll();
|
|
3727
|
-
}
|
|
3728
|
-
function observeConversations() {
|
|
3729
|
-
const stream = options.adapter.conversations;
|
|
3730
|
-
if (stream === undefined || withdrawConversations !== undefined)
|
|
3731
|
-
return;
|
|
3732
|
-
withdrawConversations = stream.observe((event) => {
|
|
3733
|
-
if (event.kind === 'list' || event.kind === 'listed' || event.kind === 'unlisted')
|
|
3734
|
-
queueReadiness();
|
|
3735
|
-
if (conversations.receive(event)) {
|
|
3736
|
-
void ready.then(scheduleCurrency);
|
|
3737
|
-
return;
|
|
3738
|
-
}
|
|
3739
|
-
if (event.kind !== 'gap' || conversations.current())
|
|
3740
|
-
return;
|
|
3741
|
-
show();
|
|
3742
|
-
scheduleCurrency();
|
|
3743
|
-
});
|
|
3744
|
-
}
|
|
3745
|
-
function scheduleCurrency() {
|
|
3746
|
-
if (currencyQueued === generation || closed || stopping)
|
|
3747
|
-
return;
|
|
3748
|
-
currencyQueued = generation;
|
|
3749
|
-
void task(CONVERSATION_LANE, runCurrency);
|
|
3750
|
-
}
|
|
3751
|
-
async function runCurrency(live) {
|
|
3752
|
-
if (currencyQueued === generation)
|
|
3753
|
-
currencyQueued = null;
|
|
3754
|
-
if (!live())
|
|
3755
|
-
return;
|
|
3756
|
-
await conversations.reconcile();
|
|
3757
|
-
if (conversations.current()) {
|
|
3758
|
-
show();
|
|
3759
|
-
return;
|
|
3760
|
-
}
|
|
3761
|
-
const progress = { complete: false, reachable: !status.providerUnreachable };
|
|
3762
|
-
moveTo(transferring(status));
|
|
3763
|
-
try {
|
|
3764
|
-
await conversations.catchUp(progress);
|
|
3765
|
-
}
|
|
3766
|
-
catch {
|
|
3767
|
-
progress.reachable = false;
|
|
3768
|
-
}
|
|
3769
|
-
await rest(progress, live);
|
|
3770
|
-
}
|
|
3771
|
-
function close() {
|
|
3772
|
-
if (closed)
|
|
3773
|
-
return;
|
|
3774
|
-
closed = true;
|
|
3775
|
-
if (rechecking !== null)
|
|
3776
|
-
clearInterval(rechecking);
|
|
3777
|
-
connectionLive();
|
|
3778
|
-
lockListeners.clear();
|
|
3779
|
-
readinessWatches.clear();
|
|
3780
|
-
withdrawStream?.();
|
|
3781
|
-
withdrawStream = undefined;
|
|
3782
|
-
withdrawConversations?.();
|
|
3783
|
-
withdrawConversations = undefined;
|
|
3784
|
-
withdrawServiceMode?.();
|
|
3785
|
-
conversations.close();
|
|
3786
|
-
void recovery.retire();
|
|
3787
|
-
store?.close();
|
|
3788
|
-
void opening?.then((opened) => {
|
|
3789
|
-
opened.close();
|
|
3790
|
-
}, () => { });
|
|
3791
|
-
roomListeners.clear();
|
|
3792
|
-
refusalListeners.clear();
|
|
3793
|
-
storageLossListeners.clear();
|
|
3794
|
-
statusListeners.clear();
|
|
3795
|
-
serviceModeListeners.clear();
|
|
3796
|
-
memberListeners.clear();
|
|
3797
|
-
readSide.close();
|
|
3798
|
-
queueSubscriptions.clear();
|
|
3799
|
-
roomDraftListeners.clear();
|
|
3800
|
-
presentationListeners.clear();
|
|
3801
|
-
}
|
|
3802
|
-
async function stop() {
|
|
3803
|
-
stopping = true;
|
|
3804
|
-
await recovery.retire();
|
|
3805
|
-
await Promise.all(working);
|
|
3806
|
-
await mutations;
|
|
3807
|
-
close();
|
|
3808
|
-
}
|
|
3809
|
-
const withdrawServiceMode = options.adapter.serviceMode?.observe(signalled);
|
|
3810
|
-
observeConversations();
|
|
3811
|
-
options.signal?.addEventListener('abort', close, { once: true });
|
|
3812
|
-
if (options.signal?.aborted)
|
|
3813
|
-
close();
|
|
3814
|
-
observeStream();
|
|
3815
|
-
void openLocal().then(() => {
|
|
3816
|
-
if (capabilities.length > 0)
|
|
3817
|
-
notifyReady();
|
|
3818
|
-
}, () => {
|
|
3819
|
-
notifyReady();
|
|
3820
|
-
});
|
|
3821
|
-
if (options.adapter.roomStream === undefined)
|
|
3822
|
-
void sync('unstreamed');
|
|
3823
|
-
function planned(input, reach) {
|
|
3824
|
-
const plan = planOf(input, roomFacts(reach), planReach(reach));
|
|
3825
|
-
const named = plan.paths !== null &&
|
|
3826
|
-
plan.rooms !== null &&
|
|
3827
|
-
plan.paths.length * plan.rooms.length <= MAXIMUM_WINDOW;
|
|
3828
|
-
return plan.limit === null && named ? plan : { ...plan, limit: capped(plan.limit) };
|
|
3829
|
-
}
|
|
3830
|
-
function watchPlan(plan, deliver) {
|
|
3831
|
-
let seeded = false;
|
|
3832
|
-
let pending = true;
|
|
3833
|
-
const shown = () => {
|
|
3834
|
-
const seed = seeds.get(plan.key);
|
|
3835
|
-
if (seed === undefined || seeded || !pending)
|
|
3836
|
-
return;
|
|
3837
|
-
seeded = true;
|
|
3838
|
-
deliver(seededResult(seed));
|
|
3839
|
-
};
|
|
3840
|
-
const watchers = seedWatchers.get(plan.key) ?? new Set();
|
|
3841
|
-
seedWatchers.set(plan.key, watchers);
|
|
3842
|
-
watchers.add(shown);
|
|
3843
|
-
const stop = readSide.watch(plan, identityOf(plan), () => {
|
|
3844
|
-
const cover = covered(plan);
|
|
3845
|
-
awaitPreparation(cover);
|
|
3846
|
-
return seedBehind(plan, cover);
|
|
3847
|
-
}, (message) => {
|
|
3848
|
-
const answered = message;
|
|
3849
|
-
pending = whole(answered) && 'pending' in answered.result;
|
|
3850
|
-
if (pending && seeds.has(plan.key)) {
|
|
3851
|
-
shown();
|
|
3852
|
-
return;
|
|
3853
|
-
}
|
|
3854
|
-
seeded = false;
|
|
3855
|
-
deliver(message);
|
|
3856
|
-
});
|
|
3857
|
-
return () => {
|
|
3858
|
-
watchers.delete(shown);
|
|
3859
|
-
if (watchers.size === 0)
|
|
3860
|
-
seedWatchers.delete(plan.key);
|
|
3861
|
-
stop();
|
|
3862
|
-
};
|
|
3863
|
-
}
|
|
3864
|
-
async function searched(input, reach, locked) {
|
|
3865
|
-
const asked = searchPlanOf(input);
|
|
3866
|
-
const plan = { ...asked, limit: capped(asked.limit) };
|
|
3867
|
-
const filter = {
|
|
3868
|
-
...filterOf(plan.documents ?? {}, roomFacts(reach), planReach(reach)),
|
|
3869
|
-
locked,
|
|
3870
|
-
};
|
|
3871
|
-
const unlocking = (filter.rooms ?? [])
|
|
3872
|
-
.filter((room) => locked.includes(room))
|
|
3873
|
-
.map((room) => ({ room, awaits: 'unlock' }));
|
|
3874
|
-
for (;;) {
|
|
3875
|
-
const cover = covered(filter);
|
|
3876
|
-
awaitPreparation(cover);
|
|
3877
|
-
const pending = [
|
|
3878
|
-
...unlocking,
|
|
3879
|
-
...('pending' in cover ? cover.pending : []),
|
|
3880
|
-
];
|
|
3881
|
-
const awaited = new Set('pending' in cover ? cover.pending.map(({ room }) => room) : []);
|
|
3882
|
-
const held = covered({
|
|
3883
|
-
...filter,
|
|
3884
|
-
rooms: reachedRooms(filter).filter((room) => !awaited.has(room)),
|
|
3885
|
-
});
|
|
3886
|
-
const covering = 'pending' in held ? [] : held.coverage.rooms;
|
|
3887
|
-
const unindexed = covering
|
|
3888
|
-
.filter(({ room }) => !searchIndex.rooms().has(room))
|
|
3889
|
-
.map(({ room }) => room);
|
|
3890
|
-
for (const room of unindexed)
|
|
3891
|
-
pending.push({ room, awaits: 'index' });
|
|
3892
|
-
const listed = conversations.searchable();
|
|
3893
|
-
const named = reach !== null && !reach.conversations
|
|
3894
|
-
? []
|
|
3895
|
-
: (plan.conversations ?? listed).filter((one) => listed.includes(one) && conversations.acquired(one));
|
|
3896
|
-
const waiting = named.filter((one) => !searchIndex.conversations().has(one));
|
|
3897
|
-
for (const conversation of waiting)
|
|
3898
|
-
pending.push({ conversation, awaits: 'index' });
|
|
3899
|
-
if (unindexed.length > 0 || waiting.length > 0)
|
|
3900
|
-
index(unindexed, waiting);
|
|
3901
|
-
const complete = pending.length === 0 && !('pending' in cover);
|
|
3902
|
-
const answering = complete
|
|
3903
|
-
? filter
|
|
3904
|
-
: {
|
|
3905
|
-
...filter,
|
|
3906
|
-
rooms: covering
|
|
3907
|
-
.filter(({ room }) => searchIndex.rooms().has(room))
|
|
3908
|
-
.map(({ room }) => room),
|
|
3909
|
-
};
|
|
3910
|
-
const answered = covered(answering);
|
|
3911
|
-
if ('pending' in answered)
|
|
3912
|
-
continue;
|
|
3913
|
-
const searchedConversations = named.filter((one) => searchIndex.conversations().has(one));
|
|
3914
|
-
await readSide.settled();
|
|
3915
|
-
const seen = searchIndex.changes();
|
|
3916
|
-
await searchIndex.caughtUp();
|
|
3917
|
-
const selected = roomsAlone(answering) ? null : await rowsQuery(answering);
|
|
3918
|
-
if (selected !== null && 'pending' in selected)
|
|
3919
|
-
continue;
|
|
3920
|
-
if (searchIndex.changes() !== seen ||
|
|
3921
|
-
JSON.stringify(covered(answering)) !== JSON.stringify(answered))
|
|
3922
|
-
continue;
|
|
3923
|
-
const hits = searchIndex.search(plan, selected === null ? null : selected.documents, searchedConversations, answering.rooms !== null
|
|
3924
|
-
? new Set(answering.rooms)
|
|
3925
|
-
: locked.length === 0
|
|
3926
|
-
? null
|
|
3927
|
-
: new Set(reachedRooms(answering)), plan.collection
|
|
3928
|
-
? new Map(answered.coverage.rooms.map(({ room }) => [
|
|
3929
|
-
room,
|
|
3930
|
-
replicas.get(room)?.confirmed.record.typedSelection?.roots ?? [],
|
|
3931
|
-
]))
|
|
3932
|
-
: null);
|
|
3933
|
-
const coverage = {
|
|
3934
|
-
rooms: answered.coverage.rooms,
|
|
3935
|
-
conversations: searchedConversations,
|
|
3936
|
-
index: searchIndex.generation(),
|
|
3937
|
-
overlay: answered.coverage.overlay,
|
|
3938
|
-
};
|
|
3939
|
-
return complete
|
|
3940
|
-
? { ...hits, coverage }
|
|
3941
|
-
: { pending, documents: hits.documents, messages: hits.messages, coverage };
|
|
3942
|
-
}
|
|
3943
|
-
}
|
|
3944
|
-
const watch = (topic, input, deliver) => {
|
|
3945
|
-
if (topic === 'room-drafts') {
|
|
3946
|
-
const listener = { notify: deliver, ready: false };
|
|
3947
|
-
roomDraftListeners.add(listener);
|
|
3948
|
-
void exclusive(async () => {
|
|
3949
|
-
await openLocal();
|
|
3950
|
-
if (closed || !roomDraftListeners.has(listener))
|
|
3951
|
-
return;
|
|
3952
|
-
listener.ready = true;
|
|
3953
|
-
}).then(() => {
|
|
3954
|
-
if (closed || !listener.ready || !roomDraftListeners.has(listener))
|
|
3955
|
-
return;
|
|
3956
|
-
listener.notify(snapshotRoomDrafts());
|
|
3957
|
-
}, () => { });
|
|
3958
|
-
return () => {
|
|
3959
|
-
roomDraftListeners.delete(listener);
|
|
3960
|
-
};
|
|
3961
|
-
}
|
|
3962
|
-
if (topic === 'conversation') {
|
|
3963
|
-
return conversations.watch(input[0], input[1], deliver);
|
|
3964
|
-
}
|
|
3965
|
-
if (topic === 'conversations')
|
|
3966
|
-
return conversations.watchList(deliver);
|
|
3967
|
-
if (topic === 'agents')
|
|
3968
|
-
return conversations.watchAgents(deliver);
|
|
3969
|
-
if (topic === 'presentation') {
|
|
3970
|
-
const listener = {
|
|
3971
|
-
app: input[0],
|
|
3972
|
-
notify: deliver,
|
|
3973
|
-
ready: false,
|
|
3974
|
-
};
|
|
3975
|
-
presentationListeners.add(listener);
|
|
3976
|
-
void exclusive(async () => {
|
|
3977
|
-
await openLocal();
|
|
3978
|
-
}).then(() => {
|
|
3979
|
-
if (closed || !presentationListeners.has(listener))
|
|
3980
|
-
return;
|
|
3981
|
-
listener.ready = true;
|
|
3982
|
-
listener.notify(presentationOf(listener.app));
|
|
3983
|
-
}, () => { });
|
|
3984
|
-
return () => {
|
|
3985
|
-
presentationListeners.delete(listener);
|
|
3986
|
-
};
|
|
3987
|
-
}
|
|
3988
|
-
if (topic === 'readiness') {
|
|
3989
|
-
return watchReadiness({ target: '', code: 'stored', capacity: null, search: 'unused' }, null, deliver);
|
|
3990
|
-
}
|
|
3991
|
-
if (topic === 'rooms') {
|
|
3992
|
-
roomListeners.add(deliver);
|
|
3993
|
-
deliver(listed());
|
|
3994
|
-
return () => {
|
|
3995
|
-
roomListeners.delete(deliver);
|
|
3996
|
-
};
|
|
3997
|
-
}
|
|
3998
|
-
if (topic === 'connection-refusal') {
|
|
3999
|
-
refusalListeners.add(deliver);
|
|
4000
|
-
deliver(refusal);
|
|
4001
|
-
return () => {
|
|
4002
|
-
refusalListeners.delete(deliver);
|
|
4003
|
-
};
|
|
4004
|
-
}
|
|
4005
|
-
if (topic === 'storage-loss') {
|
|
4006
|
-
storageLossListeners.add(deliver);
|
|
4007
|
-
deliver(storageLoss);
|
|
4008
|
-
return () => {
|
|
4009
|
-
storageLossListeners.delete(deliver);
|
|
4010
|
-
};
|
|
4011
|
-
}
|
|
4012
|
-
if (topic === 'sync-status') {
|
|
4013
|
-
statusListeners.add(deliver);
|
|
4014
|
-
deliver(shown);
|
|
4015
|
-
return () => {
|
|
4016
|
-
statusListeners.delete(deliver);
|
|
4017
|
-
};
|
|
4018
|
-
}
|
|
4019
|
-
if (topic === 'service-mode') {
|
|
4020
|
-
serviceModeListeners.add(deliver);
|
|
4021
|
-
deliver(serviceMode);
|
|
4022
|
-
return () => {
|
|
4023
|
-
serviceModeListeners.delete(deliver);
|
|
4024
|
-
};
|
|
4025
|
-
}
|
|
4026
|
-
if (topic === 'member') {
|
|
4027
|
-
memberListeners.add(deliver);
|
|
4028
|
-
deliver(member);
|
|
4029
|
-
return () => {
|
|
4030
|
-
memberListeners.delete(deliver);
|
|
4031
|
-
};
|
|
4032
|
-
}
|
|
4033
|
-
if (topic === 'queue') {
|
|
4034
|
-
const queue = { locator: input[0], notify: deliver };
|
|
4035
|
-
queueSubscriptions.add(queue);
|
|
4036
|
-
queue.notify(entriesOf(queue.locator));
|
|
4037
|
-
return () => {
|
|
4038
|
-
queueSubscriptions.delete(queue);
|
|
4039
|
-
};
|
|
4040
|
-
}
|
|
4041
|
-
return watchPlan(planned(input[0], null), deliver);
|
|
4042
|
-
};
|
|
4043
|
-
const md = {
|
|
4044
|
-
loaded() {
|
|
4045
|
-
return openLocal().then(() => undefined);
|
|
4046
|
-
},
|
|
4047
|
-
rooms() {
|
|
4048
|
-
return listed();
|
|
4049
|
-
},
|
|
4050
|
-
query: ((input) => rowsQuery(planned(input, null))),
|
|
4051
|
-
search: (input) => searched(input, null, []),
|
|
4052
|
-
types(locator) {
|
|
4053
|
-
return {
|
|
4054
|
-
collection: modelTypes(modelOf(locator)),
|
|
4055
|
-
typedSelection: rooms.get(locator)?.typedSelection === undefined ||
|
|
4056
|
-
rooms.get(locator)?.typedSelection === null
|
|
4057
|
-
? null
|
|
4058
|
-
: modelTypes(modelOf(locator, 'typed-selection')),
|
|
4059
|
-
};
|
|
4060
|
-
},
|
|
4061
|
-
roomDraft: {
|
|
4062
|
-
list() {
|
|
4063
|
-
return exclusive(async () => {
|
|
4064
|
-
await openLocal();
|
|
4065
|
-
return snapshotRoomDrafts();
|
|
4066
|
-
}).then((listed) => {
|
|
4067
|
-
publishRoomDrafts(true);
|
|
4068
|
-
return listed;
|
|
4069
|
-
});
|
|
4070
|
-
},
|
|
4071
|
-
read(room, path) {
|
|
4072
|
-
const record = roomDrafts.get(room)?.get(path);
|
|
4073
|
-
return record === undefined ? null : roomDraftOf(record);
|
|
4074
|
-
},
|
|
4075
|
-
write(room, path, revision, input) {
|
|
4076
|
-
return exclusive(async () => {
|
|
4077
|
-
const parts = readParts(input);
|
|
4078
|
-
if (path === '' || normalize(path) !== path)
|
|
4079
|
-
throw runtimeError('room-draft-malformed');
|
|
4080
|
-
const local = await openLocal();
|
|
4081
|
-
const current = roomDrafts.get(room)?.get(path);
|
|
4082
|
-
if ((current?.revision ?? null) !== revision) {
|
|
4083
|
-
return staleWrite(current === undefined ? null : roomDraftOf(current));
|
|
4084
|
-
}
|
|
4085
|
-
const file = parts.file === undefined
|
|
4086
|
-
? undefined
|
|
4087
|
-
: await heldFile(parts.file.blob, binaryBase(replicas.get(room)?.visible, path));
|
|
4088
|
-
const record = {
|
|
4089
|
-
locator: room,
|
|
4090
|
-
path,
|
|
4091
|
-
revision: roomDraftRevision(),
|
|
4092
|
-
parts: held(current?.parts, parts, file),
|
|
4093
|
-
returned: current?.returned ?? null,
|
|
4094
|
-
};
|
|
4095
|
-
await local.keepRoomDraft(record, parts.file === undefined || file === undefined
|
|
4096
|
-
? []
|
|
4097
|
-
: [{ key: file.localId, blob: parts.file.blob }]);
|
|
4098
|
-
rememberRoomDraft(record);
|
|
4099
|
-
publishChangeSet(changeSet(room, null, null, { drafts: [path] }));
|
|
4100
|
-
return { outcome: 'written', roomDraft: roomDraftOf(record) };
|
|
4101
|
-
});
|
|
4102
|
-
},
|
|
4103
|
-
discard(room, path, revision) {
|
|
4104
|
-
return exclusive(async () => {
|
|
4105
|
-
const local = await openLocal();
|
|
4106
|
-
const current = roomDrafts.get(room)?.get(path);
|
|
4107
|
-
if (current === undefined || current.revision !== revision) {
|
|
4108
|
-
return staleWrite(current === undefined ? null : roomDraftOf(current));
|
|
4109
|
-
}
|
|
4110
|
-
await local.discardRoomDraft(room, path);
|
|
4111
|
-
forgetRoomDraft(room, path);
|
|
4112
|
-
publishChangeSet(changeSet(room, null, null, { drafts: [path] }));
|
|
4113
|
-
moveTo({ ...status, ...attention() });
|
|
4114
|
-
return { outcome: 'written', roomDraft: null };
|
|
4115
|
-
});
|
|
4116
48
|
},
|
|
4117
49
|
},
|
|
4118
|
-
|
|
4119
|
-
|
|
4120
|
-
|
|
4121
|
-
|
|
4122
|
-
|
|
4123
|
-
|
|
4124
|
-
|
|
4125
|
-
|
|
4126
|
-
|
|
4127
|
-
|
|
4128
|
-
|
|
50
|
+
roomTypes,
|
|
51
|
+
builtIn,
|
|
52
|
+
typedPaths,
|
|
53
|
+
persistence: shell.persistence,
|
|
54
|
+
lost: presence.lost,
|
|
55
|
+
losing: presence.losing,
|
|
56
|
+
opening: (local) => open(runtime, local),
|
|
57
|
+
unpublished: uncaught,
|
|
58
|
+
changed(set) {
|
|
59
|
+
if (set.unindexed.length > 0)
|
|
60
|
+
prepare(runtime, set.unindexed);
|
|
61
|
+
for (const locator of set.due)
|
|
62
|
+
submitLater(runtime, locator);
|
|
63
|
+
return publishChangeSet(runtime, set);
|
|
64
|
+
},
|
|
65
|
+
deliverReadiness: (owed, rooms) => deliverOwedReadiness(runtime, owed, rooms),
|
|
66
|
+
spaceFreed: () => spaceFreed(runtime),
|
|
67
|
+
});
|
|
68
|
+
const recovery = (options.recovery ?? createRecovery()).scope(ROOM_ATTEMPTS);
|
|
69
|
+
const runtime = {
|
|
70
|
+
store,
|
|
71
|
+
socket,
|
|
72
|
+
presence,
|
|
73
|
+
recovery,
|
|
74
|
+
retries,
|
|
75
|
+
shell,
|
|
76
|
+
savesLocally: (locator) => adapter.localSaves === true && !writable(presence.room(locator)),
|
|
77
|
+
roomTypes,
|
|
78
|
+
builtIn,
|
|
79
|
+
typedPaths,
|
|
80
|
+
renamedActions: adapter.renamedActions ?? new Map(),
|
|
81
|
+
rewrittenInputs: adapter.rewrittenInputs ?? new Map(),
|
|
82
|
+
keptInput: adapter.keptInput ?? ((input) => input),
|
|
83
|
+
writeRule: (declaration) => writeRule(declaration, adapter.pathRule ?? (() => true), adapter.localSaves === true && !writable(declaration)),
|
|
84
|
+
build: options.build ?? '',
|
|
85
|
+
conversations: createLiveConversations({
|
|
86
|
+
call: (name, input, attempt) => invokeAction(runtime, name, input, { attempt }),
|
|
87
|
+
history: (request) => readConversationHistory(runtime, request),
|
|
88
|
+
durably: store.durably,
|
|
89
|
+
local: store.open,
|
|
90
|
+
again: () => {
|
|
91
|
+
void socket.ready.then(() => scheduleCurrency(runtime));
|
|
4129
92
|
},
|
|
4130
|
-
|
|
4131
|
-
|
|
4132
|
-
...Object.entries(plain(held) ? held : {}).filter(([member]) => !Object.hasOwn(members, member)),
|
|
4133
|
-
...Object.entries(structuredClone(members)).filter(([, value]) => value !== null),
|
|
4134
|
-
]));
|
|
93
|
+
settled: () => {
|
|
94
|
+
show(runtime);
|
|
4135
95
|
},
|
|
4136
|
-
|
|
4137
|
-
|
|
4138
|
-
|
|
4139
|
-
|
|
4140
|
-
|
|
4141
|
-
|
|
4142
|
-
|
|
4143
|
-
|
|
4144
|
-
|
|
4145
|
-
},
|
|
4146
|
-
|
|
4147
|
-
|
|
4148
|
-
|
|
4149
|
-
|
|
4150
|
-
|
|
4151
|
-
|
|
4152
|
-
|
|
4153
|
-
|
|
4154
|
-
|
|
4155
|
-
|
|
4156
|
-
|
|
4157
|
-
|
|
4158
|
-
|
|
4159
|
-
|
|
4160
|
-
|
|
4161
|
-
|
|
4162
|
-
|
|
4163
|
-
|
|
4164
|
-
|
|
4165
|
-
|
|
4166
|
-
|
|
4167
|
-
|
|
4168
|
-
cleanUp,
|
|
4169
|
-
persistence() {
|
|
4170
|
-
return persistence === 'granted';
|
|
4171
|
-
},
|
|
4172
|
-
async retry() {
|
|
4173
|
-
journal.record('retry');
|
|
4174
|
-
unindexable.clear();
|
|
4175
|
-
queueReadiness();
|
|
4176
|
-
resume();
|
|
4177
|
-
},
|
|
4178
|
-
observe: observing(watch),
|
|
4179
|
-
async reauthorize() {
|
|
4180
|
-
if (refusal === null || !refusal.reauthorizationOffered)
|
|
4181
|
-
return;
|
|
4182
|
-
journal.record('connection reauthorize');
|
|
4183
|
-
await Promise.all([...lanes.values()]
|
|
4184
|
-
.filter((held) => held.generation === generation)
|
|
4185
|
-
.map((held) => held.chain));
|
|
4186
|
-
await mutations;
|
|
4187
|
-
authorization = undefined;
|
|
4188
|
-
discoveryPaused = false;
|
|
4189
|
-
if (options.adapter.roomStream === undefined)
|
|
4190
|
-
await sync('unstreamed');
|
|
4191
|
-
else
|
|
4192
|
-
await task(OPENING_LANE, ensureAuthorization);
|
|
4193
|
-
},
|
|
4194
|
-
};
|
|
4195
|
-
const reachable = {
|
|
4196
|
-
md,
|
|
4197
|
-
watch,
|
|
4198
|
-
referrerScope: (referrer) => options.adapter.referrerScope(referrer),
|
|
4199
|
-
plan: planned,
|
|
4200
|
-
query: (plan) => rowsQuery(plan),
|
|
4201
|
-
watchPlan,
|
|
4202
|
-
search: searched,
|
|
4203
|
-
watchReadiness,
|
|
4204
|
-
locked,
|
|
4205
|
-
lockedRooms,
|
|
4206
|
-
watchLocks,
|
|
4207
|
-
located,
|
|
4208
|
-
};
|
|
4209
|
-
return {
|
|
4210
|
-
md,
|
|
4211
|
-
seed,
|
|
4212
|
-
stop,
|
|
4213
|
-
lose: loseRooms,
|
|
4214
|
-
watch,
|
|
4215
|
-
persisted(answer) {
|
|
4216
|
-
if (answer === persistence)
|
|
4217
|
-
return;
|
|
4218
|
-
persistence = answer;
|
|
4219
|
-
journal.record(`persistence ${answer}`);
|
|
4220
|
-
queueReadiness();
|
|
4221
|
-
},
|
|
4222
|
-
within: (reach, port) => narrowed(reachable, reach, port),
|
|
96
|
+
stream: socket.conversations,
|
|
97
|
+
publish: store.changed,
|
|
98
|
+
online: socket.reached,
|
|
99
|
+
full: store.space.full,
|
|
100
|
+
closed: socket.closed,
|
|
101
|
+
unanswered: () => resendLater(runtime),
|
|
102
|
+
heard: (operation, lost) => socket.lanes.settle(operation, lost),
|
|
103
|
+
recovery: recovery.scope(),
|
|
104
|
+
retries,
|
|
105
|
+
}),
|
|
106
|
+
liveQueries: createLiveQueries((plan, cover) => answeredPlan(runtime, plan, cover), store.covering),
|
|
107
|
+
figures: createFigures({
|
|
108
|
+
cover: () => figuresCover(runtime),
|
|
109
|
+
rooms: (rooms, since) => roomTallies(runtime, rooms, since),
|
|
110
|
+
conversations: (conversations, since) => store.ask({ kind: 'conversation.tallies', conversations, since }),
|
|
111
|
+
}),
|
|
112
|
+
lastAnswers: readAnswers({
|
|
113
|
+
database: store,
|
|
114
|
+
build: options.build ?? '',
|
|
115
|
+
unkept: adapter.unkeptReads ?? [],
|
|
116
|
+
leading: adapter.leadingReads ?? [],
|
|
117
|
+
recovery: recovery.scope(),
|
|
118
|
+
retries,
|
|
119
|
+
call: (name, input, attempt) => called(runtime, name, input, attempt),
|
|
120
|
+
online: socket.reached,
|
|
121
|
+
streaming: socket.isOpen,
|
|
122
|
+
closed: socket.closed,
|
|
123
|
+
full: store.space.full,
|
|
124
|
+
filled: () => filled(runtime),
|
|
125
|
+
}),
|
|
126
|
+
discover: () => discover(runtime),
|
|
127
|
+
adopt: (unstored) => adopt(runtime, unstored),
|
|
4223
128
|
};
|
|
129
|
+
start(runtime, options.signal, options.storeOnNeed === true);
|
|
130
|
+
return composedRuntime(runtime);
|
|
4224
131
|
}
|