castle-web-cli 0.4.244 → 0.4.246
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api.d.ts +1 -0
- package/dist/api.js +13 -0
- package/dist/contentOriginTiming.d.ts +13 -0
- package/dist/contentOriginTiming.js +15 -0
- package/dist/imports.js +28 -6
- package/dist/index.js +60 -4
- package/dist/init.js +1 -1
- package/dist/projectState.d.ts +33 -0
- package/dist/projectState.js +97 -0
- package/dist/save-deck.d.ts +4 -0
- package/dist/save-deck.js +42 -0
- package/dist/saveDropGuard.d.ts +116 -0
- package/dist/saveDropGuard.js +582 -0
- package/dist/serve.d.ts +18 -0
- package/dist/serve.js +103 -2
- package/dist/serveSecurity.d.ts +105 -3
- package/dist/serveSecurity.js +500 -39
- package/dist/shell/assets/{index-DulbYIJm.js → index-Bec6LpAv.js} +87 -87
- package/dist/shell/index.html +1 -1
- package/kits/base/castle.json +1 -1
- package/kits/base/sdk/runtime.js +57 -0
- package/kits/hub-game/code/client/chrome.js +6 -1
- package/kits/hub-game/code/server/friendBests.js +8 -2
- package/kits/hub-game/code/server/hub.js +12 -2
- package/kits/hub-game/code/server/resumePose.js +30 -9
- package/kits/hub-game/code/server/writerLease.js +161 -17
- package/kits/hub-game/docs/contract.md +32 -11
- package/kits/hub-game/scripts/test-menu-client.mjs +7 -6
- package/kits/hub-game/scripts/test-menu-footer-dom.mjs +94 -0
- package/kits/hub-game/scripts/test-resume-pose.mjs +85 -0
- package/kits/hub-game/scripts/test-writer-lease-server.mjs +108 -4
- package/kits/hub-game/scripts/test-writer-lease.mjs +385 -1
- package/package.json +2 -2
package/dist/shell/index.html
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
<link rel="icon" type="image/png" sizes="32x32" href="/__castle/ide/favicon-32x32.png" />
|
|
11
11
|
<link rel="icon" type="image/png" sizes="16x16" href="/__castle/ide/favicon-16x16.png" />
|
|
12
12
|
<link rel="icon" href="/__castle/ide/favicon.ico" sizes="any" />
|
|
13
|
-
<script type="module" crossorigin src="/__castle/ide/assets/index-
|
|
13
|
+
<script type="module" crossorigin src="/__castle/ide/assets/index-Bec6LpAv.js"></script>
|
|
14
14
|
<link rel="stylesheet" crossorigin href="/__castle/ide/assets/index-MVLfNYd9.css">
|
|
15
15
|
</head>
|
|
16
16
|
<body>
|
package/kits/base/castle.json
CHANGED
package/kits/base/sdk/runtime.js
CHANGED
|
@@ -741,6 +741,10 @@ function connectBridge() {
|
|
|
741
741
|
return;
|
|
742
742
|
}
|
|
743
743
|
const port = event.ports[0];
|
|
744
|
+
// A shell that answers reload requests: tell it this SDK will ask before
|
|
745
|
+
// reloading, so it lets restarts through to us (we flush saves first).
|
|
746
|
+
const reloadRequests = data.reloadRequests === true;
|
|
747
|
+
bridgeReloadPort = reloadRequests ? port : null;
|
|
744
748
|
const socket = {
|
|
745
749
|
readyState: WebSocket.OPEN,
|
|
746
750
|
send: (value) => {
|
|
@@ -756,9 +760,15 @@ function connectBridge() {
|
|
|
756
760
|
const value = messageEvent.data;
|
|
757
761
|
if (!value || typeof value !== "object")
|
|
758
762
|
return;
|
|
763
|
+
if (value.type === "castle-reload-response") {
|
|
764
|
+
settleReloadRequest(value);
|
|
765
|
+
return;
|
|
766
|
+
}
|
|
759
767
|
handleLocalMessage(value);
|
|
760
768
|
};
|
|
761
769
|
port.start();
|
|
770
|
+
if (reloadRequests)
|
|
771
|
+
port.postMessage({ type: "castle-sdk-hello", reloadRequests: true });
|
|
762
772
|
localServeSeen = true;
|
|
763
773
|
ws = socket;
|
|
764
774
|
for (const msg of logBuffer)
|
|
@@ -1108,6 +1118,48 @@ function stashReloadState() {
|
|
|
1108
1118
|
export function requestReload() {
|
|
1109
1119
|
scheduleReload(REQUEST_RELOAD_DEBOUNCE_MS, "requestReload");
|
|
1110
1120
|
}
|
|
1121
|
+
// Set when the shell's bridge answers reload requests (castle-bridge-init's
|
|
1122
|
+
// `reloadRequests`). Before reloading, this frame asks the shell: a frame whose
|
|
1123
|
+
// content-origin grant has expired would only fail to reload in place, so the
|
|
1124
|
+
// shell moves it to fresh origins instead and this page does nothing more.
|
|
1125
|
+
let bridgeReloadPort = null;
|
|
1126
|
+
const RELOAD_REQUEST_TIMEOUT_MS = 4000;
|
|
1127
|
+
const pendingReloadRequests = new Map();
|
|
1128
|
+
let nextReloadRequest = 1;
|
|
1129
|
+
function settleReloadRequest(value) {
|
|
1130
|
+
if (typeof value.requestId !== "string")
|
|
1131
|
+
return;
|
|
1132
|
+
const settle = pendingReloadRequests.get(value.requestId);
|
|
1133
|
+
if (!settle)
|
|
1134
|
+
return;
|
|
1135
|
+
pendingReloadRequests.delete(value.requestId);
|
|
1136
|
+
settle(value.relocated === true);
|
|
1137
|
+
}
|
|
1138
|
+
/** Whether the shell moved this frame (so it must not reload itself). */
|
|
1139
|
+
function askShellToRelocate() {
|
|
1140
|
+
const port = bridgeReloadPort;
|
|
1141
|
+
if (!port)
|
|
1142
|
+
return Promise.resolve(false);
|
|
1143
|
+
const requestId = `reload-${nextReloadRequest++}`;
|
|
1144
|
+
return new Promise((resolve) => {
|
|
1145
|
+
const timer = setTimeout(() => {
|
|
1146
|
+
pendingReloadRequests.delete(requestId);
|
|
1147
|
+
resolve(false);
|
|
1148
|
+
}, RELOAD_REQUEST_TIMEOUT_MS);
|
|
1149
|
+
pendingReloadRequests.set(requestId, (relocated) => {
|
|
1150
|
+
clearTimeout(timer);
|
|
1151
|
+
resolve(relocated);
|
|
1152
|
+
});
|
|
1153
|
+
try {
|
|
1154
|
+
port.postMessage({ type: "castle-reload-request", requestId, href: location.href });
|
|
1155
|
+
}
|
|
1156
|
+
catch {
|
|
1157
|
+
clearTimeout(timer);
|
|
1158
|
+
pendingReloadRequests.delete(requestId);
|
|
1159
|
+
resolve(false);
|
|
1160
|
+
}
|
|
1161
|
+
});
|
|
1162
|
+
}
|
|
1111
1163
|
function scheduleReload(delayMs, reason = "unknown") {
|
|
1112
1164
|
console.log(`[reload] ${panelTag()} scheduling reload (${reason})`);
|
|
1113
1165
|
if (restartTimer !== null)
|
|
@@ -1121,6 +1173,11 @@ function scheduleReload(delayMs, reason = "unknown") {
|
|
|
1121
1173
|
// a failed flush shouldn't block the reload
|
|
1122
1174
|
}
|
|
1123
1175
|
stashReloadState();
|
|
1176
|
+
// Saves are flushed above either way. A frame the shell moves (its
|
|
1177
|
+
// grant expired) loads afresh elsewhere; otherwise reload in place,
|
|
1178
|
+
// keeping this origin and the save queue stored on it.
|
|
1179
|
+
if (await askShellToRelocate())
|
|
1180
|
+
return;
|
|
1124
1181
|
location.reload();
|
|
1125
1182
|
})();
|
|
1126
1183
|
}, delayMs);
|
|
@@ -1637,6 +1637,12 @@ export function makeChrome({ onBack, onAvatar, onColor = () => {}, avatarCount,
|
|
|
1637
1637
|
// The same column, padding, corners and shadow as the Doors/chat panels.
|
|
1638
1638
|
// Token fallbacks use their existing palette when no tokens are installed.
|
|
1639
1639
|
const sheet = el('div', { position: 'absolute', left: '50%', bottom: '0', transform: 'translateX(-50%)', width: 'min(100%, 720px)', maxHeight: cap('vh'), boxSizing: 'border-box', overflow: 'hidden', pointerEvents: 'auto', display: 'flex', flexDirection: 'column', gap: '6px', padding: '12px', paddingBottom: 'max(12px, env(safe-area-inset-bottom))', borderRadius: '12px 12px 0 0', background: 'var(--castle-surface-3, rgba(20,16,12,0.88))', color: 'var(--castle-text-primary, #fff)', boxShadow: '0 4px 14px rgba(0,0,0,0.45)', zIndex: '9' }, root);
|
|
1640
|
+
// The dvh cap replaces the vh one where dvh exists (an unknown value is
|
|
1641
|
+
// dropped). It stays an inline declaration, never an !important rule, so
|
|
1642
|
+
// the safe-inset pass's own cap (`safeStyle.js`) outranks it: that pass
|
|
1643
|
+
// moves the sheet by the height it capped, and a cap that lost left the
|
|
1644
|
+
// footer (a shop's Buy) under the frame on a short view.
|
|
1645
|
+
sheet.style.maxHeight = cap('dvh');
|
|
1640
1646
|
sheet.className = 'hub-menu-sheet';
|
|
1641
1647
|
sheet.dataset.hub = 'menu';
|
|
1642
1648
|
sheet.setAttribute('role', 'dialog');
|
|
@@ -1650,7 +1656,6 @@ export function makeChrome({ onBack, onAvatar, onColor = () => {}, avatarCount,
|
|
|
1650
1656
|
@media (prefers-reduced-motion: reduce) { .hub-menu-tile:not(:disabled):active, .hub-menu-tile.is-pressed { transform: none; } }
|
|
1651
1657
|
@media (max-width: 600px) { .hub-menu-grid { grid-template-columns: repeat(4, minmax(64px, 1fr)) !important; } }
|
|
1652
1658
|
@media (max-width: 340px) { .hub-menu-grid { grid-template-columns: repeat(3, minmax(64px, 1fr)) !important; } }
|
|
1653
|
-
@supports (height: 1dvh) { .hub-menu-sheet { max-height: ${cap('dvh')} !important; } }
|
|
1654
1659
|
` + (placeMenu.covers ? ` ${MENU_COVERED_RULE}\n ` : '');
|
|
1655
1660
|
for (const type of ['pointerdown', 'pointermove', 'pointerup', 'mousedown', 'wheel', 'contextmenu', 'keydown', 'keyup']) {
|
|
1656
1661
|
sheet.addEventListener(type, (event) => event.stopPropagation(), { signal });
|
|
@@ -88,7 +88,7 @@ export function friendBests(h, key, options, userIdOf) {
|
|
|
88
88
|
return index ?? read();
|
|
89
89
|
}
|
|
90
90
|
const api = {
|
|
91
|
-
async report(playerId, best) {
|
|
91
|
+
async report(playerId, best, saves) {
|
|
92
92
|
try {
|
|
93
93
|
// The kit retains its filtered identity through the leave hook, so
|
|
94
94
|
// the last record may be reported even after the roster lost the player.
|
|
@@ -97,6 +97,12 @@ export function friendBests(h, key, options, userIdOf) {
|
|
|
97
97
|
return Promise.resolve();
|
|
98
98
|
}
|
|
99
99
|
const username = String(h.ctx.username(playerId)).slice(0, 20);
|
|
100
|
+
// Under a writer lease a best is the player's progress: it is written
|
|
101
|
+
// through the claim it was made under (the caller's `hub.saves` view,
|
|
102
|
+
// else the account's view now), so a best another instance has since
|
|
103
|
+
// superseded never reaches the index. Without a lease, the raw store.
|
|
104
|
+
const lease = h.writerLease?.api;
|
|
105
|
+
const store = lease?.enabled ? (saves && typeof saves.set === 'function' ? saves : lease.deck(userId)) : null;
|
|
100
106
|
writer = writer
|
|
101
107
|
.then(async () => {
|
|
102
108
|
const rows = await read();
|
|
@@ -108,7 +114,7 @@ export function friendBests(h, key, options, userIdOf) {
|
|
|
108
114
|
...rows.filter((row) => row.userId !== userId),
|
|
109
115
|
{ userId, username, best, at: Date.now() },
|
|
110
116
|
]);
|
|
111
|
-
await h.session.storage.deck.set({ [storageKey]: next });
|
|
117
|
+
await (store ?? h.session.storage.deck).set({ [storageKey]: next });
|
|
112
118
|
generation++;
|
|
113
119
|
index = next;
|
|
114
120
|
indexAt = Date.now();
|
|
@@ -281,7 +281,9 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
|
|
|
281
281
|
h.resumeDeparting ??= new Set();
|
|
282
282
|
}
|
|
283
283
|
if (h.place.resumePose === true && session.storage?.deck) {
|
|
284
|
-
h.poseStore = ResumePose.store(session, id, session.hub?.owner ?? null
|
|
284
|
+
h.poseStore = ResumePose.store(session, id, session.hub?.owner ?? null,
|
|
285
|
+
h.writerLease?.api.enabled ? (userId) => h.writerLease.api.deck(userId) : null,
|
|
286
|
+
h.writerLease?.api.enabled ? (userId) => h.writerLease.api.ready(userId) : null);
|
|
285
287
|
} else { delete h.poseStore; }
|
|
286
288
|
if (h.place.decor) {
|
|
287
289
|
h.ctx.decor = Decor.api(h);
|
|
@@ -2034,7 +2036,15 @@ function outcomeOrNone(outcome) {
|
|
|
2034
2036
|
// other connection here shares it. Finalize their authored state before join.
|
|
2035
2037
|
function syncWriterVisits(h) {
|
|
2036
2038
|
if (!h.writerLease?.api.enabled) { return; }
|
|
2037
|
-
h.writerLease.sync((h.session?.players ?? []).map(p => [p.playerId, userIdOf(h, p.playerId)]).filter(([, userId]) => userId !== null), h.players.keys(), playerId =>
|
|
2039
|
+
h.writerLease.sync((h.session?.players ?? []).map(p => [p.playerId, userIdOf(h, p.playerId)]).filter(([, userId]) => userId !== null), h.players.keys(), playerId => {
|
|
2040
|
+
// A held visit replaced before any tick saw it go still ends its pose,
|
|
2041
|
+
// under its own claim, ahead of the arrival's take.
|
|
2042
|
+
const kept = h.resumeKept?.get(playerId);
|
|
2043
|
+
if (h.poseStore && kept && kept.awayAt === undefined && !h.resumeDeparting?.has(playerId) && !h.players.get(playerId)?.ended) {
|
|
2044
|
+
void h.poseStore.end(h.players.get(playerId)?.userId, kept, Date.now(), playerId);
|
|
2045
|
+
}
|
|
2046
|
+
forget(h, playerId);
|
|
2047
|
+
});
|
|
2038
2048
|
}
|
|
2039
2049
|
|
|
2040
2050
|
// Forget players the session no longer has, telling the deck first: its
|
|
@@ -4,8 +4,13 @@ export const TTL_MS = 10 * 60000;
|
|
|
4
4
|
export const READ_MS = 5000;
|
|
5
5
|
const PREFIX = 'hub:resumePose:';
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
// `deckOf(userId)`: the account's writer-lease view (hub.saves.deck), so a
|
|
8
|
+
// fenced instance cannot move the pose revision under the current writer.
|
|
9
|
+
// `readyOf(userId)`: settles once the account's claim does (hub.saves.ready);
|
|
10
|
+
// a take's read budget starts then, not while the claim is still settling.
|
|
11
|
+
export function store(session, placeId, owner = null, deckOf = null, readyOf = null) {
|
|
8
12
|
const storage = session?.storage?.deck;
|
|
13
|
+
const writer = (userId) => deckOf?.(userId) ?? storage;
|
|
9
14
|
const pending = new Map();
|
|
10
15
|
const leases = new Map();
|
|
11
16
|
let cleanup = null;
|
|
@@ -25,8 +30,8 @@ export function store(session, placeId, owner = null) {
|
|
|
25
30
|
});
|
|
26
31
|
return next;
|
|
27
32
|
};
|
|
28
|
-
const change = async (p, snapshot, revision, rows) => {
|
|
29
|
-
const receipt = await
|
|
33
|
+
const change = async (db, p, snapshot, revision, rows) => {
|
|
34
|
+
const receipt = await db.transaction({
|
|
30
35
|
operationId: operationId(),
|
|
31
36
|
expectedAccess: snapshot.access,
|
|
32
37
|
changes: [{ prefix: p, expectedRevision: revision, replace: rows }],
|
|
@@ -47,6 +52,7 @@ export function store(session, placeId, owner = null) {
|
|
|
47
52
|
if (!userId || !supported()) {
|
|
48
53
|
return Promise.resolve();
|
|
49
54
|
}
|
|
55
|
+
const db = writer(userId);
|
|
50
56
|
return enqueue(userId, async () => {
|
|
51
57
|
const lease = leases.get(visitId);
|
|
52
58
|
leases.delete(visitId);
|
|
@@ -54,7 +60,7 @@ export function store(session, placeId, owner = null) {
|
|
|
54
60
|
return;
|
|
55
61
|
}
|
|
56
62
|
const p = prefix(userId);
|
|
57
|
-
await change(p, lease, lease.revision, {
|
|
63
|
+
await change(db, p, lease, lease.revision, {
|
|
58
64
|
[p + 'pose']: { at: { ...pose.at }, facing: pose.facing, endedAt },
|
|
59
65
|
});
|
|
60
66
|
});
|
|
@@ -63,11 +69,12 @@ export function store(session, placeId, owner = null) {
|
|
|
63
69
|
if (!userId || !supported()) {
|
|
64
70
|
return Promise.resolve();
|
|
65
71
|
}
|
|
72
|
+
const db = writer(userId);
|
|
66
73
|
return enqueue(userId, async () => {
|
|
67
74
|
const lease = leases.get(visitId);
|
|
68
75
|
leases.delete(visitId);
|
|
69
76
|
if (lease) {
|
|
70
|
-
await change(prefix(userId), lease, lease.revision, {});
|
|
77
|
+
await change(db, prefix(userId), lease, lease.revision, {});
|
|
71
78
|
}
|
|
72
79
|
});
|
|
73
80
|
},
|
|
@@ -75,13 +82,24 @@ export function store(session, placeId, owner = null) {
|
|
|
75
82
|
if (!userId || !supported()) {
|
|
76
83
|
return null;
|
|
77
84
|
}
|
|
78
|
-
|
|
85
|
+
// The take holds its queue place and view at once (an end asked
|
|
86
|
+
// meanwhile runs after it); under the lease its budget starts only
|
|
87
|
+
// once the claim has settled.
|
|
88
|
+
const ready = readyOf ? Promise.resolve(readyOf(userId)).catch(() => {}) : null;
|
|
89
|
+
let deadline = Date.now() + READ_MS;
|
|
90
|
+
const db = writer(userId);
|
|
79
91
|
const work = enqueue(userId, async () => {
|
|
92
|
+
if (ready) {
|
|
93
|
+
await ready;
|
|
94
|
+
deadline = Date.now() + READ_MS;
|
|
95
|
+
}
|
|
80
96
|
if (Date.now() >= deadline) {
|
|
81
97
|
return null;
|
|
82
98
|
}
|
|
83
99
|
const p = prefix(userId);
|
|
84
|
-
|
|
100
|
+
// Through the lease view, which reads only once the claim settles: a
|
|
101
|
+
// snapshot before it can miss the previous writer's last pose save.
|
|
102
|
+
const snapshot = await db.snapshot({ prefix: p });
|
|
85
103
|
if (Date.now() >= deadline) {
|
|
86
104
|
return null;
|
|
87
105
|
}
|
|
@@ -89,13 +107,16 @@ export function store(session, placeId, owner = null) {
|
|
|
89
107
|
const row = target.rows[p + 'pose'];
|
|
90
108
|
// A concurrent claim or a door clear changes this revision. A failed
|
|
91
109
|
// transaction restores nothing, and an old socket cannot write later.
|
|
92
|
-
const revision = await change(p, snapshot, target.revision, {});
|
|
110
|
+
const revision = await change(db, p, snapshot, target.revision, {});
|
|
93
111
|
if (Date.now() >= deadline) {
|
|
94
112
|
return null;
|
|
95
113
|
}
|
|
96
114
|
leases.set(visitId, { access: snapshot.access, revision });
|
|
97
115
|
return valid(row) ? { at: { ...row.at }, facing: row.facing } : null;
|
|
98
116
|
});
|
|
117
|
+
if (ready) {
|
|
118
|
+
await ready;
|
|
119
|
+
}
|
|
99
120
|
let timer;
|
|
100
121
|
try {
|
|
101
122
|
return await Promise.race([
|
|
@@ -132,7 +153,7 @@ export function store(session, placeId, owner = null) {
|
|
|
132
153
|
const p = key.slice(0, -4);
|
|
133
154
|
const snapshot = await storage.snapshot({ prefix: p });
|
|
134
155
|
if (snapshot.targets[0].rows[key] !== undefined && !valid(snapshot.targets[0].rows[key])) {
|
|
135
|
-
await change(p, snapshot, snapshot.targets[0].revision, {});
|
|
156
|
+
await change(storage, p, snapshot, snapshot.targets[0].revision, {});
|
|
136
157
|
}
|
|
137
158
|
}
|
|
138
159
|
} catch (error) {
|
|
@@ -20,12 +20,19 @@ export function create(session, optedIn) {
|
|
|
20
20
|
const visits = new Map();
|
|
21
21
|
const listeners = new Set();
|
|
22
22
|
const views = new Map();
|
|
23
|
+
const bindings = new WeakMap();
|
|
23
24
|
let closed = false;
|
|
24
25
|
let syncing = false;
|
|
25
26
|
const active = (entry) => !closed && accounts.get(entry.userId) === entry;
|
|
27
|
+
// Visits whose connection has gone but whose state the place still holds.
|
|
28
|
+
const away = new Set();
|
|
29
|
+
const visiting = (userId) => [...visits.values()].includes(userId);
|
|
30
|
+
const connected = (userId) => [...visits].some(([id, user]) => user === userId && !away.has(id));
|
|
26
31
|
const markLost = (entry) => {
|
|
27
32
|
if (!active(entry) || entry.lost) { return; }
|
|
28
33
|
entry.lost = true;
|
|
34
|
+
// A revalidating claim that turns out taken is replaced, not reported.
|
|
35
|
+
if (entry.revalidating) { return; }
|
|
29
36
|
for (const fn of listeners) {
|
|
30
37
|
try { fn(entry.userId); } catch (error) { console.warn(`[hub] saves onLost failed: ${error?.message ?? error}`); }
|
|
31
38
|
}
|
|
@@ -71,16 +78,121 @@ export function create(session, optedIn) {
|
|
|
71
78
|
entry.timer = setTimeout(resolve, delay);
|
|
72
79
|
});
|
|
73
80
|
entry.wake = null;
|
|
81
|
+
// Every visit of the account here has gone: a retry now could take
|
|
82
|
+
// the account from the instance the player has moved to.
|
|
83
|
+
if (active(entry) && !visiting(userId)) { entry.lost = true; return; }
|
|
74
84
|
}
|
|
75
85
|
}
|
|
76
86
|
})();
|
|
77
87
|
return entry;
|
|
78
88
|
};
|
|
89
|
+
// A fresh visit back to an account nobody here is connected to may find
|
|
90
|
+
// another instance took it meanwhile. This arrival is the newest, so it
|
|
91
|
+
// claims afresh; the old claim (and every view bound to it) ends silently,
|
|
92
|
+
// so the previous visit's late writes fail rather than land under the new one.
|
|
93
|
+
// Views made while it runs (the arrival's) follow the outcome; views made
|
|
94
|
+
// before it (the previous visit's) keep the old claim.
|
|
95
|
+
// A return while a round is still pending starts its own round after it:
|
|
96
|
+
// the pending round's check may predate a takeover, so this arrival checks
|
|
97
|
+
// again, on whichever claim that round settled on.
|
|
98
|
+
const revalidate = (entry) => {
|
|
99
|
+
if (entry.unleased) { return; }
|
|
100
|
+
const pending = entry.revalidating || null;
|
|
101
|
+
const prior = entry.ready;
|
|
102
|
+
// The round a view made now follows: its outcome only, never a later one.
|
|
103
|
+
const round = {};
|
|
104
|
+
entry.revalidating = round;
|
|
105
|
+
entry.ready = round.ready = (async () => {
|
|
106
|
+
let target = entry;
|
|
107
|
+
try {
|
|
108
|
+
await prior;
|
|
109
|
+
target = pending?.successor ?? entry;
|
|
110
|
+
if (target !== entry) {
|
|
111
|
+
if (!active(target) || target.unleased) { round.successor = target; return; }
|
|
112
|
+
// A later arrival is already checking the replacement claim: its
|
|
113
|
+
// check started after this one's arrival, so this round waits for
|
|
114
|
+
// it and stays with this claim. It never inherits a claim that
|
|
115
|
+
// round opens: that write authority is the later arrival's alone.
|
|
116
|
+
const newer = target.revalidating;
|
|
117
|
+
if (newer) {
|
|
118
|
+
await newer.ready;
|
|
119
|
+
round.successor = target;
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
target.revalidating = round;
|
|
123
|
+
target.ready = round.ready;
|
|
124
|
+
}
|
|
125
|
+
const started = Date.now();
|
|
126
|
+
let unanswered = false;
|
|
127
|
+
for (let tries = 0; active(target) && !target.unleased && !target.lost;) {
|
|
128
|
+
try {
|
|
129
|
+
await storage.transaction({ operationId: operationId(), expectedAccess: target.access,
|
|
130
|
+
checks: [{ target: target.target, writer: target.writer }], changes: [] });
|
|
131
|
+
if (target !== entry) { round.successor = target; }
|
|
132
|
+
return;
|
|
133
|
+
} catch (error) {
|
|
134
|
+
if (invalid(error)) { break; }
|
|
135
|
+
// Only a check that answers keeps the claim for an arrival. One
|
|
136
|
+
// refused, or still failing after the claim's own wait, cannot
|
|
137
|
+
// show that no other instance took the account.
|
|
138
|
+
if (!transient(error) || Date.now() - started >= CLAIM_WAIT_MS) { unanswered = true; break; }
|
|
139
|
+
const delay = Math.max(error?.retryAfterMs ?? 0, Math.min(8000, 250 * 2 ** Math.min(tries++, 5)));
|
|
140
|
+
await new Promise((resolve) => {
|
|
141
|
+
target.wake = resolve;
|
|
142
|
+
target.timer = setTimeout(resolve, delay);
|
|
143
|
+
});
|
|
144
|
+
target.wake = null;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if (!active(target) || target.unleased) { return; }
|
|
148
|
+
// A visit held after its connection went counts as gone: the
|
|
149
|
+
// player may already be on another instance.
|
|
150
|
+
const present = () => connected(target.userId);
|
|
151
|
+
if (unanswered && !target.lost) {
|
|
152
|
+
// The arrival has gone again: nobody here needs a fresh claim, and
|
|
153
|
+
// one would take the account from wherever the player is now.
|
|
154
|
+
if (!present()) { if (target !== entry) { round.successor = target; } return; }
|
|
155
|
+
// Writes the previous visit queued under this claim go first, each
|
|
156
|
+
// under its own fence: they land if the claim is still this
|
|
157
|
+
// instance's. Then the arrival (the newest) claims afresh rather
|
|
158
|
+
// than load under a claim it may have lost.
|
|
159
|
+
target.draining = true;
|
|
160
|
+
for (const wake of target.waiters ?? []) { wake(); }
|
|
161
|
+
try {
|
|
162
|
+
// Including end saves queued while earlier ones were in flight.
|
|
163
|
+
for (let tail; tail !== target.tail;) { tail = target.tail; await tail; }
|
|
164
|
+
} finally { target.draining = false; }
|
|
165
|
+
if (!active(target) || target.unleased) { return; }
|
|
166
|
+
}
|
|
167
|
+
// Taken (or left unconfirmed) with no visit here: end it silently.
|
|
168
|
+
if (!present()) {
|
|
169
|
+
target.lost = true;
|
|
170
|
+
if (target !== entry) { round.successor = target; }
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
target.lost = true;
|
|
174
|
+
cancel(target);
|
|
175
|
+
round.successor = open(target.userId);
|
|
176
|
+
} finally {
|
|
177
|
+
for (const each of new Set([entry, target])) {
|
|
178
|
+
if (each.revalidating === round) { each.revalidating = false; }
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
await round.successor?.ready;
|
|
182
|
+
})();
|
|
183
|
+
};
|
|
79
184
|
const fenceEntry = (entry) => {
|
|
80
185
|
if (!entry || !active(entry) || entry.lost) { return Promise.reject(lostError()); }
|
|
81
186
|
if (entry.fencing) { return entry.fencing; }
|
|
82
187
|
entry.fencing = (async () => {
|
|
83
|
-
|
|
188
|
+
// A return whose check went unanswered lets writes already queued
|
|
189
|
+
// under this claim through (`draining`) before it claims afresh.
|
|
190
|
+
await new Promise((resolve) => {
|
|
191
|
+
if (entry.draining) { resolve(); return; }
|
|
192
|
+
const waiters = (entry.waiters ??= new Set());
|
|
193
|
+
waiters.add(resolve);
|
|
194
|
+
entry.ready.then(() => { waiters.delete(resolve); resolve(); });
|
|
195
|
+
});
|
|
84
196
|
if (!active(entry) || entry.lost) { throw lostError(); }
|
|
85
197
|
if (entry.unleased) { return; }
|
|
86
198
|
try {
|
|
@@ -94,54 +206,83 @@ export function create(session, optedIn) {
|
|
|
94
206
|
})().finally(() => { entry.fencing = null; });
|
|
95
207
|
return entry.fencing;
|
|
96
208
|
};
|
|
97
|
-
|
|
209
|
+
// A view is bound to the claim that existed when it was made: a write a
|
|
210
|
+
// visit queued keeps that claim, never a later visit's.
|
|
211
|
+
const view = (raw, userId, bound = accounts.get(userId), follow = bound?.revalidating || null) => {
|
|
98
212
|
if (!enabled || !raw) { return raw; }
|
|
99
|
-
|
|
213
|
+
const send = (entry, run) => {
|
|
214
|
+
const work = entry.tail.then(async () => { await fenceEntry(entry); return run(); });
|
|
215
|
+
entry.tail = work.catch(() => {});
|
|
216
|
+
return work;
|
|
217
|
+
};
|
|
218
|
+
const proxy = new Proxy(raw, {
|
|
100
219
|
get(target, name) {
|
|
101
|
-
if (['get', 'list'].includes(name) && typeof target[name] === 'function') {
|
|
220
|
+
if (['get', 'list', 'snapshot'].includes(name) && typeof target[name] === 'function') {
|
|
102
221
|
return async (...args) => { await api.ready(userId); return target[name](...args); };
|
|
103
222
|
}
|
|
104
223
|
if (['set', 'remove', 'increment', 'transaction', 'conditionalWrite'].includes(name) && typeof target[name] === 'function') {
|
|
105
224
|
return (...args) => {
|
|
106
|
-
const entry = accounts.get(userId);
|
|
225
|
+
const entry = bound ?? accounts.get(userId);
|
|
107
226
|
if (!entry) { return Promise.reject(lostError()); }
|
|
108
|
-
const
|
|
109
|
-
|
|
110
|
-
|
|
227
|
+
const run = () => target[name](...args);
|
|
228
|
+
// A round's successor may itself be revalidated later: this view
|
|
229
|
+
// stays with the claim its round settled on.
|
|
230
|
+
if (follow) { return follow.ready.then(() => send(follow.successor ?? entry, run)); }
|
|
231
|
+
return send(entry, run);
|
|
111
232
|
};
|
|
112
233
|
}
|
|
113
234
|
return typeof target[name] === 'function' ? target[name].bind(target) : target[name];
|
|
114
235
|
},
|
|
115
236
|
});
|
|
237
|
+
bindings.set(proxy, { userId, bound, follow });
|
|
238
|
+
return proxy;
|
|
116
239
|
};
|
|
117
240
|
const api = {
|
|
118
241
|
enabled,
|
|
119
242
|
deck(userId) {
|
|
120
243
|
if (!enabled) { return storage?.deck; }
|
|
121
|
-
|
|
122
|
-
return
|
|
244
|
+
const entry = accounts.get(userId);
|
|
245
|
+
if (!entry) { return view(storage?.deck, userId); }
|
|
246
|
+
const follow = entry.revalidating || null, cached = views.get(userId);
|
|
247
|
+
if (cached?.entry !== entry || cached.follow !== follow) { views.set(userId, { entry, follow, view: view(storage?.deck, userId, entry, follow) }); }
|
|
248
|
+
return views.get(userId).view;
|
|
123
249
|
},
|
|
124
250
|
user(userId) {
|
|
125
251
|
return view(storage?.user?.(userId), userId);
|
|
126
252
|
},
|
|
253
|
+
async holds(view) {
|
|
254
|
+
const binding = bindings.get(view);
|
|
255
|
+
if (!binding) { return true; }
|
|
256
|
+
const { userId, bound, follow } = binding;
|
|
257
|
+
const entry = bound ?? accounts.get(userId);
|
|
258
|
+
await follow?.ready;
|
|
259
|
+
const target = follow?.successor ?? entry;
|
|
260
|
+
// Even an older view must wait for an in-progress return to decide
|
|
261
|
+
// whether its claim is still active.
|
|
262
|
+
await target?.ready;
|
|
263
|
+
return Boolean(target && active(target) && !target.lost);
|
|
264
|
+
},
|
|
127
265
|
ready(userId) { return enabled ? accounts.get(userId)?.ready ?? Promise.resolve() : Promise.resolve(); },
|
|
128
266
|
fence(userId) { return enabled ? fenceEntry(accounts.get(userId)) : Promise.resolve(); },
|
|
129
|
-
lost(userId) {
|
|
267
|
+
lost(userId) { const entry = accounts.get(userId); return enabled && entry?.lost === true && !entry.revalidating; },
|
|
130
268
|
onLost(fn) { listeners.add(fn); return () => listeners.delete(fn); },
|
|
131
269
|
};
|
|
132
270
|
return {
|
|
133
271
|
api,
|
|
134
272
|
join(playerId, userId) {
|
|
273
|
+
away.delete(playerId);
|
|
135
274
|
if (!enabled || closed || typeof userId !== 'string' || visits.get(playerId) === userId) { return; }
|
|
136
275
|
this.leave(playerId);
|
|
137
276
|
// Retained stale visits must be finalized by sync before a fresh join.
|
|
138
|
-
|
|
277
|
+
const entry = accounts.get(userId);
|
|
278
|
+
if (!entry) { open(userId); } else if (![...visits.values()].includes(userId)) { revalidate(entry); }
|
|
139
279
|
clearTimeout(accounts.get(userId).expiry);
|
|
140
280
|
visits.set(playerId, userId);
|
|
141
281
|
},
|
|
142
282
|
leave(playerId) {
|
|
143
283
|
const userId = visits.get(playerId);
|
|
144
284
|
visits.delete(playerId);
|
|
285
|
+
away.delete(playerId);
|
|
145
286
|
const entry = accounts.get(userId);
|
|
146
287
|
if (!entry || [...visits.values()].includes(userId)) { return; }
|
|
147
288
|
const drop = () => {
|
|
@@ -154,19 +295,20 @@ export function create(session, optedIn) {
|
|
|
154
295
|
clearTimeout(entry.expiry);
|
|
155
296
|
if (entry.lost) { drop(); } else { entry.expiry = setTimeout(drop, KEEP_MS); }
|
|
156
297
|
},
|
|
157
|
-
// `held`: player ids whose authored state remains. A fresh
|
|
158
|
-
// finalizes
|
|
298
|
+
// `held`: player ids whose authored state remains. A fresh connection with
|
|
299
|
+
// no connected peer finalizes held visits through forgetHeld, then claims
|
|
300
|
+
// (a lost account) or revalidates its claim; otherwise keep them.
|
|
159
301
|
sync(players, held = [], forgetHeld) {
|
|
160
302
|
if (!enabled || closed || syncing) { return; }
|
|
161
303
|
const next = new Map(players), kept = new Set(held);
|
|
162
304
|
syncing = true;
|
|
163
305
|
try {
|
|
164
306
|
for (const [id, userId] of next) {
|
|
165
|
-
if (!forgetHeld || visits.has(id) ||
|
|
307
|
+
if (!forgetHeld || visits.has(id) ||
|
|
166
308
|
[...next].some(([otherId, otherUser]) => otherId !== id && otherUser === userId)) { continue; }
|
|
167
309
|
// Only a new connection with no connected account peer can replace
|
|
168
310
|
// stale held state. The kit's ordinary forget runs its leave hook
|
|
169
|
-
//
|
|
311
|
+
// (under the old claim) before the new visit claims or revalidates.
|
|
170
312
|
for (const [oldId, oldUser] of [...visits]) {
|
|
171
313
|
if (oldUser !== userId) { continue; }
|
|
172
314
|
if (kept.has(oldId)) { forgetHeld(oldId); }
|
|
@@ -178,6 +320,8 @@ export function create(session, optedIn) {
|
|
|
178
320
|
for (const [id, userId] of [...visits]) {
|
|
179
321
|
if (next.has(id) ? next.get(id) !== userId : !kept.has(id)) { this.leave(id); }
|
|
180
322
|
}
|
|
323
|
+
away.clear();
|
|
324
|
+
for (const id of visits.keys()) { if (!next.has(id)) { away.add(id); } }
|
|
181
325
|
} finally {
|
|
182
326
|
syncing = false;
|
|
183
327
|
}
|
|
@@ -185,7 +329,7 @@ export function create(session, optedIn) {
|
|
|
185
329
|
shutdown() {
|
|
186
330
|
closed = true;
|
|
187
331
|
for (const entry of accounts.values()) { cancel(entry); }
|
|
188
|
-
accounts.clear(); visits.clear(); views.clear(); listeners.clear();
|
|
332
|
+
accounts.clear(); visits.clear(); views.clear(); listeners.clear(); away.clear();
|
|
189
333
|
},
|
|
190
334
|
};
|
|
191
335
|
}
|