castle-web-cli 0.4.245 → 0.4.247

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.
@@ -1,17 +1,46 @@
1
1
  // One account writer per place instance. The empty user target owns no game
2
2
  // rows: ordinary deck saves stay compatible with their existing key families.
3
+ //
4
+ // THE INVARIANT. A per-player write lands only while the claim it was queued
5
+ // under is still the account's writer on the platform. Ordinary writes carry
6
+ // that claim's writer check (v1.226), so the platform refuses a stale one in
7
+ // the same statement once any instance -- this one included -- has claimed the
8
+ // account again. Everything else here follows from it:
9
+ // - Every lone arrival claims anew, and the place reloads under that claim.
10
+ // While the old claim may still hold, writes the previous visit queues
11
+ // before the new claim is sent go first; anything later through a previous
12
+ // view is refused, locally or by the platform.
13
+ // - A refused write (`WRITER_LOST`) loses its claim for good. Nothing retries
14
+ // it; the place drops the account, and the next lone arrival claims anew.
15
+ // - A claim is only sent (or retried) while a connected visit of the account
16
+ // is here, so a visit that has moved on never takes the account back. A
17
+ // resume picks a waiting claim up again.
18
+ // Where the platform cannot check a write, the lease fences it with a separate
19
+ // check first, leaving one round trip of window: `castle-web serve` and
20
+ // persistent-world sessions (a checked write answers UNAVAILABLE, nothing
21
+ // sent), `transaction`/`conditionalWrite` on a deck or user view (a bucket
22
+ // transaction can only name targets in its own scope), and root atomic calls.
3
23
  export const NOTICE = "You're playing somewhere else, so progress here isn't saved.";
4
24
  export const KEEP_MS = 60000;
5
25
  // How long a claim may keep failing before the account stops saving here.
6
26
  export const CLAIM_WAIT_MS = 20000;
27
+ // How long a lone arrival waits for the previous visit's queued writes before
28
+ // it claims anyway (one stuck on the wire is then refused by the platform).
29
+ export const DRAIN_MS = 5000;
7
30
  const operationId = () => `writer-${Date.now()}-${Math.random().toString(36).slice(2)}`;
8
31
  const lostError = () => Object.assign(new Error(NOTICE), { code: 'CAULDRON_STORAGE_WRITER_LOST', retryable: false, committed: false });
32
+ // A host's storage error carries its details at the top or, as GraphQL and
33
+ // `castle-web serve` do, under `extensions`.
34
+ const detail = (error, key) => error?.[key] ?? error?.extensions?.[key];
9
35
  const invalid = (error) => /(?:WRITER_LOST|STALE_ACCESS|STALE_RESET_GENERATION)$/.test(error?.code ?? '');
10
- const transient = (error) => error?.retryable === true || error?.committed === 'unknown' ||
11
- (!error?.code && error?.retryable !== false) || /(?:NETWORK|TIMEOUT|RATE_LIMITED)$/.test(error?.code ?? '');
12
- // The platform has no save API here at all (an older host, unsupported storage):
13
- // nobody can hold a lease, so saves go on as they did before it.
14
- const missing = (error) => /(?:UNKNOWN_COMMAND|UNAVAILABLE)$/.test(error?.code ?? '') && error?.committed === false && error?.retryable !== true;
36
+ const transient = (error) => detail(error, 'retryable') === true || detail(error, 'committed') === 'unknown' ||
37
+ (!error?.code && detail(error, 'retryable') !== false) || /(?:NETWORK|TIMEOUT|RATE_LIMITED)$/.test(error?.code ?? '');
38
+ // Nothing was sent because this platform cannot do it here: an older host or
39
+ // unsupported storage for a claim, no writer check for an ordinary write.
40
+ const missing = (error) => /(?:UNKNOWN_COMMAND|UNAVAILABLE)$/.test(error?.code ?? '') &&
41
+ detail(error, 'committed') === false && detail(error, 'retryable') !== true;
42
+ // Ordinary writes that take a writer check, and where its options argument sits.
43
+ const CHECKED = { set: 1, remove: 1, increment: 2 };
15
44
 
16
45
  export function create(session, optedIn) {
17
46
  const storage = session?.storage;
@@ -23,26 +52,37 @@ export function create(session, optedIn) {
23
52
  const bindings = new WeakMap();
24
53
  let closed = false;
25
54
  let syncing = false;
55
+ // Set once a checked write answered that this session cannot check writes.
56
+ let checkless = false;
26
57
  const active = (entry) => !closed && accounts.get(entry.userId) === entry;
27
58
  // Visits whose connection has gone but whose state the place still holds.
28
59
  const away = new Set();
29
60
  const visiting = (userId) => [...visits.values()].includes(userId);
30
61
  const connected = (userId) => [...visits].some(([id, user]) => user === userId && !away.has(id));
31
62
  const markLost = (entry) => {
32
- if (!active(entry) || entry.lost) { return; }
33
63
  entry.lost = true;
34
- // A revalidating claim that turns out taken is replaced, not reported.
35
- if (entry.revalidating) { return; }
64
+ if (!active(entry) || entry.told) { return; }
65
+ entry.told = true;
36
66
  for (const fn of listeners) {
37
67
  try { fn(entry.userId); } catch (error) { console.warn(`[hub] saves onLost failed: ${error?.message ?? error}`); }
38
68
  }
39
69
  };
40
- const cancel = (entry) => {
70
+ // Waits `delay` ms, or (none) until a resume wakes the entry or it closes.
71
+ const pause = (entry, delay) => new Promise((resolve) => {
72
+ entry.wake = resolve;
73
+ if (delay !== undefined) { entry.timer = setTimeout(resolve, delay); }
74
+ }).then(() => { entry.wake = null; clearTimeout(entry.timer); });
75
+ // A closed claim is replaced or dropped; once sealed it takes no new write
76
+ // (ones already queued still run).
77
+ const close = (entry, seal = true) => {
78
+ entry.closed = true;
79
+ if (seal) { entry.sealed = true; }
41
80
  clearTimeout(entry.expiry);
42
81
  clearTimeout(entry.timer);
43
82
  entry.wake?.();
44
83
  };
45
- const open = (userId) => {
84
+ const open = (userId, previous) => {
85
+ if (previous) { close(previous, false); }
46
86
  const entry = { userId, target: { scope: 'user', subject: userId, prefix: 'hub:writer:' }, tail: Promise.resolve(), lost: false };
47
87
  accounts.set(userId, entry);
48
88
  // Replaying this exact claim settles a lost reply; a new ID could steal
@@ -50,10 +90,36 @@ export function create(session, optedIn) {
50
90
  const input = { operationId: operationId(), target: entry.target, load: [] };
51
91
  // Reads wait for the claim: a load before it could be overwritten by the
52
92
  // instance that still holds the account. One that cannot claim stops saving.
93
+ let drained;
94
+ entry.drained = new Promise((resolve) => { drained = () => { entry.drainDone = true; resolve(); }; });
53
95
  entry.ready = (async () => {
54
- const started = Date.now();
55
- let tries = 0;
56
- while (active(entry)) {
96
+ // A replaced claim that never got as far as claiming hands on the drain
97
+ // it was still waiting for.
98
+ if (previous && !previous.drainDone) { await previous.drained; }
99
+ // While the previous claim may still hold, its queued writes land (or
100
+ // are refused) first. A lost or never-made claim can only refuse them.
101
+ // The departing visit's leave hooks (resumePose's end among them) may
102
+ // still be on their way to its queue: let them reach it first.
103
+ if (previous && previous.writer !== undefined && !previous.lost) {
104
+ let timer;
105
+ const cap = new Promise((resolve) => { timer = setTimeout(resolve, DRAIN_MS); });
106
+ const quiet = (async () => {
107
+ for (let tail; tail !== previous.tail;) {
108
+ tail = previous.tail;
109
+ await tail;
110
+ await new Promise((resolve) => { (globalThis.setImmediate ?? setTimeout)(resolve); });
111
+ }
112
+ })();
113
+ await Promise.race([quiet, cap]);
114
+ clearTimeout(timer);
115
+ }
116
+ if (previous) { previous.sealed = true; }
117
+ drained();
118
+ let started = Date.now();
119
+ for (let tries = 0; active(entry);) {
120
+ // With no visit left there is nothing to claim for.
121
+ if (!visiting(userId)) { entry.lost = true; return; }
122
+ if (!connected(userId)) { await pause(entry); started = Date.now(); continue; }
57
123
  try {
58
124
  const opened = await storage.claim(input);
59
125
  if (!active(entry)) { return; }
@@ -72,149 +138,66 @@ export function create(session, optedIn) {
72
138
  markLost(entry);
73
139
  return;
74
140
  }
75
- const delay = Math.max(error?.retryAfterMs ?? 0, Math.min(8000, 250 * 2 ** Math.min(tries++, 5)));
76
- await new Promise((resolve) => {
77
- entry.wake = resolve;
78
- entry.timer = setTimeout(resolve, delay);
79
- });
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; }
141
+ await pause(entry, Math.max(detail(error, 'retryAfterMs') ?? 0, Math.min(8000, 250 * 2 ** Math.min(tries++, 5))));
84
142
  }
85
143
  }
86
144
  })();
87
145
  return entry;
88
146
  };
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
- })();
147
+ // Settles once the claim has; throws if it cannot write.
148
+ const claimed = async (entry) => {
149
+ await entry.ready;
150
+ if (closed || entry.lost || (!entry.unleased && entry.writer === undefined)) { throw lostError(); }
183
151
  };
152
+ const refused = (entry, error) => {
153
+ if (invalid(error)) { markLost(entry); throw lostError(); }
154
+ throw error;
155
+ };
156
+ // A separate check before a write that cannot carry one.
184
157
  const fenceEntry = (entry) => {
185
- if (!entry || !active(entry) || entry.lost) { return Promise.reject(lostError()); }
158
+ if (!entry || entry.lost || closed) { return Promise.reject(lostError()); }
186
159
  if (entry.fencing) { return entry.fencing; }
187
160
  entry.fencing = (async () => {
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
- });
196
- if (!active(entry) || entry.lost) { throw lostError(); }
161
+ await claimed(entry);
197
162
  if (entry.unleased) { return; }
198
163
  try {
199
164
  await storage.transaction({ operationId: operationId(), expectedAccess: entry.access,
200
165
  checks: [{ target: entry.target, writer: entry.writer }], changes: [] });
201
- } catch (error) {
202
- if (invalid(error)) { markLost(entry); throw lostError(); }
203
- throw error;
204
- }
205
- if (!active(entry) || entry.lost) { throw lostError(); }
166
+ } catch (error) { refused(entry, error); }
167
+ if (entry.lost || closed) { throw lostError(); }
206
168
  })().finally(() => { entry.fencing = null; });
207
169
  return entry.fencing;
208
170
  };
171
+ const write = async (entry, target, name, args) => {
172
+ await claimed(entry);
173
+ if (entry.unleased) { return target[name](...args); }
174
+ const at = CHECKED[name];
175
+ try {
176
+ if (at === undefined || checkless) {
177
+ await fenceEntry(entry);
178
+ // A fence that answered after this instance claimed anew authorizes nothing.
179
+ if (entry.sealed) { throw lostError(); }
180
+ return await target[name](...args);
181
+ }
182
+ const call = args.slice(0, at);
183
+ while (call.length < at) { call.push(undefined); }
184
+ try {
185
+ return await target[name](...call, { ...(args[at] ?? {}), check: { target: entry.target, writer: entry.writer } });
186
+ } catch (error) {
187
+ if (!missing(error)) { throw error; }
188
+ // This session cannot check writes: fence, then write as before.
189
+ await fenceEntry(entry);
190
+ if (entry.sealed) { throw lostError(); }
191
+ const result = await target[name](...args);
192
+ checkless = true;
193
+ return result;
194
+ }
195
+ } catch (error) { return refused(entry, error); }
196
+ };
209
197
  // A view is bound to the claim that existed when it was made: a write a
210
198
  // visit queued keeps that claim, never a later visit's.
211
- const view = (raw, userId, bound = accounts.get(userId), follow = bound?.revalidating || null) => {
199
+ const view = (raw, userId, bound = accounts.get(userId)) => {
212
200
  if (!enabled || !raw) { return raw; }
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
201
  const proxy = new Proxy(raw, {
219
202
  get(target, name) {
220
203
  if (['get', 'list', 'snapshot'].includes(name) && typeof target[name] === 'function') {
@@ -223,18 +206,16 @@ export function create(session, optedIn) {
223
206
  if (['set', 'remove', 'increment', 'transaction', 'conditionalWrite'].includes(name) && typeof target[name] === 'function') {
224
207
  return (...args) => {
225
208
  const entry = bound ?? accounts.get(userId);
226
- if (!entry) { return Promise.reject(lostError()); }
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);
209
+ if (!entry || entry.sealed || entry.lost || closed) { return Promise.reject(lostError()); }
210
+ const work = entry.tail.then(() => write(entry, target, name, args));
211
+ entry.tail = work.catch(() => {});
212
+ return work;
232
213
  };
233
214
  }
234
215
  return typeof target[name] === 'function' ? target[name].bind(target) : target[name];
235
216
  },
236
217
  });
237
- bindings.set(proxy, { userId, bound, follow });
218
+ bindings.set(proxy, { userId, bound });
238
219
  return proxy;
239
220
  };
240
221
  const api = {
@@ -243,61 +224,71 @@ export function create(session, optedIn) {
243
224
  if (!enabled) { return storage?.deck; }
244
225
  const entry = accounts.get(userId);
245
226
  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) }); }
227
+ if (views.get(userId)?.entry !== entry) { views.set(userId, { entry, view: view(storage?.deck, userId, entry) }); }
248
228
  return views.get(userId).view;
249
229
  },
250
230
  user(userId) {
251
231
  return view(storage?.user?.(userId), userId);
252
232
  },
233
+ // Whether the claim a view writes through still writes here, once it and
234
+ // the account's current claim (an arrival's, which may replace it) settle.
253
235
  async holds(view) {
254
236
  const binding = bindings.get(view);
255
237
  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);
238
+ const entry = binding.bound ?? accounts.get(binding.userId);
239
+ await entry?.ready;
240
+ for (let current; current !== accounts.get(binding.userId);) {
241
+ current = accounts.get(binding.userId);
242
+ await current?.ready;
243
+ }
244
+ return Boolean(entry && active(entry) && !entry.closed && !entry.lost && (entry.unleased || entry.writer !== undefined));
264
245
  },
265
246
  ready(userId) { return enabled ? accounts.get(userId)?.ready ?? Promise.resolve() : Promise.resolve(); },
266
247
  fence(userId) { return enabled ? fenceEntry(accounts.get(userId)) : Promise.resolve(); },
267
- lost(userId) { const entry = accounts.get(userId); return enabled && entry?.lost === true && !entry.revalidating; },
248
+ lost(userId) { return enabled && accounts.get(userId)?.lost === true; },
268
249
  onLost(fn) { listeners.add(fn); return () => listeners.delete(fn); },
269
250
  };
270
251
  return {
271
252
  api,
272
253
  join(playerId, userId) {
254
+ if (!enabled || closed || typeof userId !== 'string') { return; }
255
+ if (visits.get(playerId) === userId) {
256
+ // A resume: a claim waiting for a connected visit goes on.
257
+ if (away.delete(playerId)) { accounts.get(userId)?.wake?.(); }
258
+ return;
259
+ }
273
260
  away.delete(playerId);
274
- if (!enabled || closed || typeof userId !== 'string' || visits.get(playerId) === userId) { return; }
275
261
  this.leave(playerId);
276
- // Retained stale visits must be finalized by sync before a fresh join.
262
+ // A lone arrival claims anew; one beside another visit of the account
263
+ // shares its claim (a lost one stays lost). Retained visits are
264
+ // finalized by sync before a fresh connection joins.
277
265
  const entry = accounts.get(userId);
278
- if (!entry) { open(userId); } else if (![...visits.values()].includes(userId)) { revalidate(entry); }
279
- clearTimeout(accounts.get(userId).expiry);
266
+ const lone = !visiting(userId);
280
267
  visits.set(playerId, userId);
268
+ // An unleased account (no save API here) has no claim to renew and keeps
269
+ // one write queue.
270
+ if (lone && !entry?.unleased) { open(userId, entry); } else { entry.wake?.(); }
271
+ clearTimeout(accounts.get(userId).expiry);
281
272
  },
282
273
  leave(playerId) {
283
274
  const userId = visits.get(playerId);
284
275
  visits.delete(playerId);
285
276
  away.delete(playerId);
286
277
  const entry = accounts.get(userId);
287
- if (!entry || [...visits.values()].includes(userId)) { return; }
278
+ if (!entry || visiting(userId)) { return; }
288
279
  const drop = () => {
289
280
  if (accounts.get(userId) !== entry) { return; }
290
281
  accounts.delete(userId);
291
282
  views.delete(userId);
292
- cancel(entry);
283
+ close(entry);
293
284
  };
294
- // A lost account has no end save to keep, so a visit back claims afresh.
285
+ // A lost account has no end save to keep.
295
286
  clearTimeout(entry.expiry);
296
287
  if (entry.lost) { drop(); } else { entry.expiry = setTimeout(drop, KEEP_MS); }
297
288
  },
298
289
  // `held`: player ids whose authored state remains. A fresh connection with
299
290
  // no connected peer finalizes held visits through forgetHeld, then claims
300
- // (a lost account) or revalidates its claim; otherwise keep them.
291
+ // anew; otherwise keep them.
301
292
  sync(players, held = [], forgetHeld) {
302
293
  if (!enabled || closed || syncing) { return; }
303
294
  const next = new Map(players), kept = new Set(held);
@@ -308,19 +299,17 @@ export function create(session, optedIn) {
308
299
  [...next].some(([otherId, otherUser]) => otherId !== id && otherUser === userId)) { continue; }
309
300
  // Only a new connection with no connected account peer can replace
310
301
  // stale held state. The kit's ordinary forget runs its leave hook
311
- // (under the old claim) before the new visit claims or revalidates.
302
+ // (under the old claim) before the new visit claims.
312
303
  for (const [oldId, oldUser] of [...visits]) {
313
304
  if (oldUser !== userId) { continue; }
314
305
  if (kept.has(oldId)) { forgetHeld(oldId); }
315
306
  this.leave(oldId);
316
307
  }
317
308
  }
318
- // Otherwise joins first: a resume or a connected peer stays lost.
319
309
  for (const [id, userId] of next) { this.join(id, userId); }
320
310
  for (const [id, userId] of [...visits]) {
321
311
  if (next.has(id) ? next.get(id) !== userId : !kept.has(id)) { this.leave(id); }
322
312
  }
323
- away.clear();
324
313
  for (const id of visits.keys()) { if (!next.has(id)) { away.add(id); } }
325
314
  } finally {
326
315
  syncing = false;
@@ -328,7 +317,7 @@ export function create(session, optedIn) {
328
317
  },
329
318
  shutdown() {
330
319
  closed = true;
331
- for (const entry of accounts.values()) { cancel(entry); }
320
+ for (const entry of accounts.values()) { close(entry); }
332
321
  accounts.clear(); visits.clear(); views.clear(); listeners.clear(); away.clear();
333
322
  },
334
323
  };
@@ -4139,23 +4139,22 @@ account stays lost on a same-playerId resume, or while another connected visit
4139
4139
  of that account remains here. If a fresh connection has a new playerId and all
4140
4140
  other visits of its account are only retained, the kit first forgets those
4141
4141
  visits through ordinary leave cleanup (including the deck's `leave` hook), then
4142
- joins the new visit. A lost account claims anew before its arrival hooks run; a
4143
- held one is revalidated (a transient failure retried for up to 20 seconds), and
4144
- if another instance took it meanwhile the visit claims anew without the notice.
4145
- Only a check that answers keeps the claim: one refused, or still failing after
4146
- 20 seconds, also claims anew, so the arrival never loads under a claim it may
4147
- have lost; writes the previous visit already queued go first, each under its own
4148
- fence, including ones queued while earlier ones were in flight. A check that
4149
- settles after every connected visit of the account here has gone (a visit held
4150
- only for `resumePose` counts as gone) never claims anew, so it cannot take the
4151
- account from another instance; a claim still retrying stops once no visit of the
4152
- account remains here.
4142
+ joins the new visit. Every lone arrival (no other visit of the account here)
4143
+ claims anew before its arrival hooks run, without the notice, and the place
4144
+ reloads under that claim (v1.226; earlier versions kept a held claim). While
4145
+ the previous claim may still hold, writes the previous visit queues before the
4146
+ new claim is sent (its leave hooks included) go first, for up to 5 seconds;
4147
+ later writes through a previous view are refused. A claim is sent or retried
4148
+ only while a connected visit of the account is here (a visit held only for
4149
+ `resumePose` counts as gone), so a visit that has moved on never takes the
4150
+ account from another instance; a same-playerId resume picks a waiting claim up
4151
+ again, and a claim stops once no visit of the account remains.
4153
4152
  A `resumePose` place ends a replaced held visit's pose under its own claim first.
4154
- Views made while the claim revalidates follow its outcome. A place must reload the account's saves through
4153
+ A place must reload the account's saves through
4155
4154
  `hub.saves` on that fresh arrival; `get`/`list` wait for the claim. Once the kit
4156
4155
  has forgotten every visit, a visit back also claims anew.
4157
4156
  The last departure of a held account keeps the lease for 60 seconds for end
4158
- saves; a visit back inside that window revalidates it the same way. A host with no save API (`UNKNOWN_COMMAND`, or a non-retryable
4157
+ saves; a visit back inside that window claims anew the same way. A host with no save API (`UNKNOWN_COMMAND`, or a non-retryable
4159
4158
  `CAULDRON_STORAGE_UNAVAILABLE`) saves as before, without a lease.
4160
4159
 
4161
4160
  `hub.saves` exposes `enabled`, `deck(userId)`, `fence(userId)`, `ready(userId)`,
@@ -4163,7 +4162,7 @@ saves; a visit back inside that window revalidates it the same way. A host with
4163
4162
  `deck` returns the raw deck store by identity when disabled or when the host
4164
4163
  lacks root `claim`/`transaction`. Otherwise its `get`/`list`/`snapshot` wait for the claim
4165
4164
  to commit or give up; `set`/`remove`/`increment`/`transaction`/`conditionalWrite`
4166
- fence and run in account order. A view is bound to the claim current when it was
4165
+ carry the claim's writer check (or fence, below) and run in account order. A view is bound to the claim current when it was
4167
4166
  made: once the account is claimed anew here, writes through an older view reject
4168
4167
  with `CAULDRON_STORAGE_WRITER_LOST`, so a write a visit queued never lands under a
4169
4168
  later visit's claim. Take the view when the write is queued.
@@ -4174,14 +4173,25 @@ are not wrapped and need an explicit `fence`.
4174
4173
  `hub.wallet` fences its own writes: a lost writer locks that account's wallet
4175
4174
  with nothing sent.
4176
4175
 
4177
- A lost writer rejects with `CAULDRON_STORAGE_WRITER_LOST`, invokes `onLost`,
4178
- and shows a persistent personal HUD line: “You're playing somewhere else, so
4179
- progress here isn't saved.” Repeated fences fail locally. The fence and the
4180
- ordinary write are separate requests: a write already past its fence when
4181
- another instance claims and loads can still land. This one-round-trip window
4182
- remains; the lease does not make ordinary saves atomic. The platform cannot close it yet: ordinary
4183
- `set`/`remove`/`increment` take no writer check, and `transaction`/`conditionalWrite`
4184
- write only managed targets.
4176
+ Every `set`/`remove`/`increment` through a view carries its claim's writer
4177
+ check (`{ check: { target, writer } }`, v1.226), and a `transaction` adds the
4178
+ check: the platform refuses the write in the same statement once any instance,
4179
+ this one included, has claimed the account again. A write a visit sent before
4180
+ another instance claimed can therefore never land after it. Where a write
4181
+ cannot carry the check, the lease runs a separate fence first, which leaves one
4182
+ round trip of window: `castle-web serve` and persistent-world sessions (a
4183
+ checked write answers `CAULDRON_STORAGE_UNAVAILABLE`, nothing sent),
4184
+ `transaction`/`conditionalWrite` on a view (a bucket transaction names only
4185
+ targets in its own scope; `resumePose` uses one), and root atomic calls
4186
+ (`fence(userId)`, `hub.wallet`).
4187
+
4188
+ A refused write rejects with `CAULDRON_STORAGE_WRITER_LOST` and loses the claim
4189
+ for good: nothing retries it, later writes fail locally, `onLost` is invoked and
4190
+ the personal HUD line shows: “You're playing somewhere else, so progress here
4191
+ isn't saved.” A refusal of a claim this instance has already replaced is not
4192
+ reported. `await hub.saves.holds(view)` settles once that view's claim and the
4193
+ account's current claim have, and is true only while the view's claim still
4194
+ writes here.
4185
4195
 
4186
4196
  ### Town pose retention (v1.98)
4187
4197
 
@@ -5445,6 +5455,7 @@ a deck written before them remains valid.
5445
5455
  | 2026-11-18 (v1.222) | Writer leases (server-only, no wire or manifest change): a fresh connection whose account has no connected visit here forgets that account's retained visits whether or not it is lost, and a visit back to a held claim (retained visits, or the 60 s end-save window) revalidates it; a claim another instance took meanwhile is replaced silently instead of losing the fresh visit. `hub.saves.deck`/`user` views are bound to the claim current when made, so a superseded visit's queued writes reject with `CAULDRON_STORAGE_WRITER_LOST`. `resumePose` takes, ends and clears its durable pose through the lease view, so a fenced instance no longer moves the pose revision. No deck opts in yet. |
5446
5456
  | 2026-11-18 (v1.223) | Writer leases (server-only, no wire or manifest change): a lone visit back that arrives while an earlier visit's revalidation is still out checks the claim again once that round settles (on whichever claim it settled), so a check from before another instance's takeover never lets the return proceed only to lose its first save. `resumePose` takes its snapshot through the lease view too, so it reads only once the claim settles and keeps a pose the previous writer saved just before; its 5 s read budget starts once the claim has settled. An older pending round that resumes on a replacement claim a newer arrival is already checking waits for that round and keeps the claim it found; it never inherits a claim that round reopens. A take holds its queue place at once, so an end asked while it waits for the claim runs after it. Without `writerLease` nothing changes. No deck opts in yet. |
5447
5457
  | 2026-11-18 (v1.224) | Writer leases (server-only): `await hub.saves.holds(view)` tells whether the claim a save view writes through is still active and has not been lost, after pending claim checks settle. Unrecognized views and lease-off stores answer true. No manifest or wire change. |
5458
+ | 2026-11-18 (v1.226) | Writer leases (server-only, no manifest or wire change): every `set`/`remove`/`increment` through a `hub.saves` view carries the platform writer check of the claim it is bound to, so a stale write is refused atomically instead of after a separate fence (the write-after-fence window is closed for ordinary writes where the platform checks). A refusal loses the claim and is never retried. Where a checked write answers `CAULDRON_STORAGE_UNAVAILABLE` (`castle-web serve`, persistent-world sessions; the details may sit under `extensions`) the session fences and writes unchecked as before; view `transaction`/`conditionalWrite` and root atomic calls keep their fence. Every lone arrival now claims anew and the place reloads (no revalidation of a held claim): queued writes of the previous visit go first for up to 5 s; claims are sent or retried only while a connected visit is here, and a resume picks a waiting claim up again. `holds(view)` also waits for the account's current claim. Without `writerLease` nothing changes. No deck opts in yet. |
5448
5459
  | 2026-11-18 (v1.225) | Writer leases (server-only): a lone visit back whose claim check is refused, or still failing after 20 s, claims anew like a taken claim instead of keeping a claim its first save may find lost; writes already queued under the old claim go first under their own fences, a check that settles after the account's connected visits here have all gone (held visits count as gone) never claims anew (taken or not), and a claim still retrying stops once no visit of the account remains. `friendBests` `report(playerId, best, saves?)` under a lease writes the `fb:<key>` index through the given `hub.saves` view (else the account's view at the call), so a best whose claim was replaced never reaches the index. The write-after-fence window stays open: the platform has no writer check on ordinary writes. Without `writerLease` nothing changes. No manifest or wire change. |
5449
5460
  | 2026-10-25 (v1.193) | Town purse paid ledger: the Town deck's scope gains `paid:<userId>:<paymentId>`, an integer tokens count for one once-only payment, set once (a repeatable `set`) and never lowered or removed. Payment ids are the fixed list `bell:1`..`bell:7`, `bell:encore:1`..`bell:encore:7` and `errand:cat` (hub-town `tokens.js` `PAID`, T9). A balance is `tokens:<userId>` plus every ledger row, less hat prices and `spent:<userId>`; the Town's wardrobe read and the House's `chirpPurchases` funds read the rows by key. Each payment marks its old claim (`<earn key>:ledger`), raises it, then sets its row, so a layer on older code reads it as claimed. Ghost adds `paid` to `HUB_TOWN_PLAYER_NAMESPACES` (door-deck reads) and to the hub user reset. Compatibility: absent rows, the balance is exactly the old one; an older Town or House reader, or a Ghost without the namespace, shows a lower balance, never a higher one; this House against a Ghost without the namespace has its funds read refused, so Ghost lands first. Gifts, the day's bonuses and game results keep the old claim-then-credit path. No manifest key, wire field or SDK change. |
5450
5461
  | 2026-10-25 (v1.187) | §9 Action chips: every place draws its `hub.actions` offers on the action overflow rail. A landscape place without `hub.safeInsets` or the `hubActionOverflow` scene key leaves the bottom-right column, which trimmed offers from the top with no sign, for the rail portrait and safe-inset places already used: one row, two rows, the first offer and More, then Actions, with a sheet listing all. At 844 × 390 three short offers stand in one row; in a crowded 509 × 218 frame an offer the column dropped is now behind More. The rail now also yields to open panels, sounds the chip cue on a press and leaves no focus behind after a pointer press, as the column did, in every place. The scene key is a no-op. No wire field. |
@@ -161,14 +161,16 @@ async function replacementProgress(name, hub, entryPath) {
161
161
  // a same-playerId resume's take go through the writer lease.
162
162
  async function poseFenced() {
163
163
  const rows = new Map(), revisions = new Map(), sent = [];
164
- const deck = (name) => {
164
+ const deck = (name, binding) => {
165
165
  const raw = fixture.root(`${name}-pose-deck`).storage.deck;
166
166
  return { ...raw,
167
167
  async snapshot({ prefix }) {
168
168
  return { access: 'x', targets: [{ revision: revisions.get(prefix) ?? null,
169
169
  rows: Object.fromEntries([...rows].filter(([k]) => k.startsWith(prefix))) }] };
170
170
  },
171
- async transaction({ changes }) {
171
+ async transaction({ checks, changes }) {
172
+ // The platform runs the lease's writer check with the change.
173
+ fixture.checkAs(binding, checks);
172
174
  const { prefix, expectedRevision, replace } = changes[0];
173
175
  sent.push([name, prefix]);
174
176
  if ((revisions.get(prefix) ?? null) !== expectedRevision) throw Object.assign(Error('conflict'), { code: 'SAVE_CONFLICT' });
@@ -179,10 +181,10 @@ async function poseFenced() {
179
181
  return { revisions: [{ revision }] };
180
182
  } };
181
183
  };
182
- const a = boot('pose-old', true, '101', false, { hub: { resumePose: true }, storage: { deck: deck('a') } });
184
+ const a = boot('pose-old', true, '101', false, { hub: { resumePose: true }, storage: { deck: deck('a', 'pose-old') } });
183
185
  await flush(); a.tick(2000); a.tick(300); await flush();
184
186
  assert.ok(sent.some(([n]) => n === 'a'), 'arrival takes the pose lease');
185
- const other = boot('pose-other', true, '101', false, { hub: { resumePose: true }, storage: { deck: deck('b') } });
187
+ const other = boot('pose-other', true, '101', false, { hub: { resumePose: true }, storage: { deck: deck('b', 'pose-other') } });
186
188
  await flush(); other.tick(2000); other.tick(300); await flush();
187
189
  await assert.rejects(a.ctx.saves.fence('101'), { code: 'CAULDRON_STORAGE_WRITER_LOST' });
188
190
  const before = sent.filter(([n]) => n === 'a').length;
@@ -200,15 +202,16 @@ async function poseFenced() {
200
202
  // take, made while the claim revalidates, follows it (or its replacement).
201
203
  async function poseQuickReturn(taken) {
202
204
  const rows = new Map(), revisions = new Map(), results = [];
203
- const deck = (name) => {
205
+ const deck = (name, binding) => {
204
206
  const raw = fixture.root(`${name}-quick-deck`).storage.deck;
205
207
  return { ...raw,
206
208
  async snapshot({ prefix }) {
207
209
  return { access: 'x', targets: [{ revision: revisions.get(prefix) ?? null,
208
210
  rows: Object.fromEntries([...rows].filter(([k]) => k.startsWith(prefix))) }] };
209
211
  },
210
- async transaction({ changes }) {
212
+ async transaction({ checks, changes }) {
211
213
  const { prefix, expectedRevision, replace } = changes[0];
214
+ try { fixture.checkAs(binding, checks); } catch (error) { results.push([name, Object.keys(replace).length ? 'end' : 'take', false]); throw error; }
212
215
  const ok = (revisions.get(prefix) ?? null) === expectedRevision;
213
216
  results.push([name, Object.keys(replace).length ? 'end' : 'take', ok]);
214
217
  if (!ok) throw Object.assign(Error('conflict'), { code: 'SAVE_CONFLICT' });
@@ -219,7 +222,7 @@ async function poseQuickReturn(taken) {
219
222
  return { revisions: [{ revision }] };
220
223
  } };
221
224
  };
222
- const a = boot(`quick-${taken}`, true, '101', false, { hub: { resumePose: true }, storage: { deck: deck('a') } });
225
+ const a = boot(`quick-${taken}`, true, '101', false, { hub: { resumePose: true }, storage: { deck: deck('a', `quick-${taken}`) } });
223
226
  for (let i = 0; i < 3; i++) { await flush(); await new Promise(r => setImmediate(r)); a.tick(2000); a.tick(300); }
224
227
  if (taken) {
225
228
  const other = boot(`quick-${taken}-other`);
@@ -234,7 +237,7 @@ async function poseQuickReturn(taken) {
234
237
  for (let i = 0; i < 4; i++) { await flush(); await new Promise(r => setImmediate(r)); }
235
238
  const ends = results.filter(([, kind]) => kind === 'end');
236
239
  if (taken) {
237
- assert.equal(ends.length, 0, 'the held visits\' pose ends were refused by their taken claim');
240
+ assert.ok(ends.every(([, , ok]) => !ok), 'the held visits\' pose ends were refused by their taken claim');
238
241
  } else {
239
242
  // Two visits of one account: only the later take's revision can end it.
240
243
  assert.ok(ends.some(([, , ok]) => ok), 'the held pose was ended before it was forgotten');