@crowdedkingdoms/crowdyjs 18.29.0-dev.1 → 18.30.0-test.1

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.
@@ -25,8 +25,92 @@ const HYDRATE_CONCURRENCY = 8;
25
25
  const BUSY_ATTEMPTS = 4;
26
26
  /** A chunk whose hydration failed this many times in a row is not asked for again. */
27
27
  const HYDRATE_GIVE_UP = 3;
28
- /** How long a local voxel edit waits for its echo before it is forgotten (a lost or refused send). */
29
- const PENDING_EDIT_TTL_MS = 10000;
28
+ /** How long a sent voxel edit waits for its echo before it is undone and reported. */
29
+ const EDIT_TIMEOUT_MS = 10000;
30
+ /**
31
+ * Edits sent and not yet echoed, refused or timed out. The sequence number that matches an echo
32
+ * or a refusal to its edit is one byte, so at most half its values are in use at once.
33
+ */
34
+ const MAX_EDITS_IN_FLIGHT = 128;
35
+ /** Voxel edits sent per second by default: half of the 500 messages a second the server takes from one session. */
36
+ const EDITS_PER_SECOND = 250;
37
+ /** Chunks one region read asks for per page. */
38
+ const PAGE_SIZE = 1000;
39
+ /** The largest box a region read covers (17³, the cube `maxDistance` 8 reads). */
40
+ const MAX_BOX_CHUNKS = 17 ** 3;
41
+ /** A load needing more boxes than this reads their bounding box instead. */
42
+ const MAX_BOXES = 8;
43
+ /** How far before the connection dropped a catch-up read starts, for the client's and server's clocks. */
44
+ const CATCH_UP_MARGIN_MS = 30000;
45
+ function boxAround(coords) {
46
+ const lo = { ...coords[0] };
47
+ const hi = { ...coords[0] };
48
+ for (const c of coords) {
49
+ lo.x = Math.min(lo.x, c.x);
50
+ lo.y = Math.min(lo.y, c.y);
51
+ lo.z = Math.min(lo.z, c.z);
52
+ hi.x = Math.max(hi.x, c.x);
53
+ hi.y = Math.max(hi.y, c.y);
54
+ hi.z = Math.max(hi.z, c.z);
55
+ }
56
+ return { lo, hi };
57
+ }
58
+ /** A stored row's `updatedAt` (an ISO time, or epoch ms) as epoch ms; null when absent or unreadable. */
59
+ function storedAtMs(updatedAt) {
60
+ if (updatedAt == null || updatedAt === '')
61
+ return null;
62
+ const ms = typeof updatedAt === 'number' ? updatedAt : Date.parse(String(updatedAt));
63
+ return Number.isFinite(ms) ? ms : null;
64
+ }
65
+ function boxVolume(box) {
66
+ return (box.hi.x - box.lo.x + 1) * (box.hi.y - box.lo.y + 1) * (box.hi.z - box.lo.z + 1);
67
+ }
68
+ function inBox(box, c) {
69
+ return (c.x >= box.lo.x && c.x <= box.hi.x &&
70
+ c.y >= box.lo.y && c.y <= box.hi.y &&
71
+ c.z >= box.lo.z && c.z <= box.hi.z);
72
+ }
73
+ /**
74
+ * Boxes covering `coords`, each at most twice as large as the chunks it holds, found by cutting
75
+ * where the two halves' boxes are smallest. The chunks a step uncovers are one slab per axis
76
+ * moved, so a step is one box per slab. A scattered set needing more than {@link MAX_BOXES} is
77
+ * read as its bounding box.
78
+ */
79
+ function coverWithBoxes(coords) {
80
+ const boxes = [];
81
+ const split = (set) => {
82
+ if (set.length === 0)
83
+ return true;
84
+ const box = boxAround(set);
85
+ const volume = boxVolume(box);
86
+ if (volume <= MAX_BOX_CHUNKS && volume <= set.length * 2) {
87
+ boxes.push(box);
88
+ return boxes.length <= MAX_BOXES;
89
+ }
90
+ let best = null;
91
+ for (const axis of ['x', 'y', 'z']) {
92
+ for (let cut = box.lo[axis]; cut < box.hi[axis]; cut++) {
93
+ const low = set.filter((c) => c[axis] <= cut);
94
+ const high = set.filter((c) => c[axis] > cut);
95
+ if (low.length === 0 || high.length === 0)
96
+ continue;
97
+ const cost = boxVolume(boxAround(low)) + boxVolume(boxAround(high));
98
+ if (!best || cost < best.cost)
99
+ best = { axis, cut, cost };
100
+ }
101
+ }
102
+ if (!best) {
103
+ boxes.push(box);
104
+ return boxes.length <= MAX_BOXES;
105
+ }
106
+ const { axis, cut } = best;
107
+ return (split(set.filter((c) => c[axis] <= cut)) && split(set.filter((c) => c[axis] > cut)));
108
+ };
109
+ if (split(coords))
110
+ return boxes;
111
+ // Too scattered for a few boxes: one read of the bounding box (an area is at most 17³).
112
+ return [boxAround(coords)];
113
+ }
30
114
  /** The platform refused the call before running it: asking again can succeed. */
31
115
  function refusedBeforeRunning(error) {
32
116
  const e = error;
@@ -91,23 +175,30 @@ function fitsDenseGrid(x, y, z, voxelType) {
91
175
  * The SDK-managed **chunk/voxel cache** — the client-side source of truth
92
176
  * for terrain:
93
177
  *
94
- * - `ensureAround(center, radius)` bulk-loads via `chunks.byDistance`
95
- * (in-flight deduped), hydrates sparse voxel states, marks chunks the
96
- * server never stored as `missing`, and hands them to your `onMissing`
178
+ * - `ensureAround(center, radius)` reads only the chunks it does not hold yet,
179
+ * as boxes (`chunks.byDistance` with `lowChunk`/`highChunk`, paged): a step
180
+ * reads the slab it uncovers. It hydrates sparse voxel states, marks chunks
181
+ * the server never stored as `missing`, and hands them to your `onMissing`
97
182
  * worldgen hook.
98
183
  * - Realtime `voxelUpdate` notifications merge into the cache automatically
99
184
  * (dense grid write + typed state decode + revision bump + change event; an
100
185
  * edit with a type outside 0-255 or a position outside 0-15 goes to the
101
- * chunk's `overlay` instead).
102
- * - `setVoxel` applies locally (optimistic) and replicates via the UDP path. The
103
- * server delivers every accepted edit back to its sender: that echo is matched
104
- * (sender uuid + sequence number + voxel) and not applied again, so a local edit
105
- * fires one change event, and an older echo never rolls back a newer local edit.
106
- * It is applied only when another client's edit of that voxel arrived in
107
- * between (the server ordered yours last) or the edit was sent with
108
- * `optimistic: false`.
186
+ * chunk's `overlay` instead). A `chunkChanged` (a hub's or mod's
187
+ * `world.set_chunk`) reads the chunk again.
188
+ * - `setVoxel` applies locally (optimistic) and replicates via the UDP path,
189
+ * paced: at most 128 edits unanswered and 250 a second by default. The
190
+ * server delivers every accepted edit back to its sender: that echo is
191
+ * matched (sender uuid + sequence number + voxel) and not applied again, so a
192
+ * local edit fires one change event, and an older echo never rolls back a
193
+ * newer local edit. It is applied only when another client's edit of that
194
+ * voxel arrived in between (the server ordered yours last) or the edit was
195
+ * sent with `optimistic: false`. An edit the server refuses, or whose echo
196
+ * does not come back in time, is undone and reported ({@link onEditRefused}).
197
+ * - After the realtime connection drops and comes back, it reads what changed
198
+ * in the area meanwhile ({@link catchUp}).
109
199
  * - `seed`/`flush` implement deterministic-worldgen write-back through
110
- * `chunks.update`, one throttled chunk at a time.
200
+ * `chunks.update`, one throttled chunk at a time. Only seeded chunks are
201
+ * written back: realtime edits are recorded by the server.
111
202
  *
112
203
  * All reads are synchronous; writes land on WebSocket events, so render
113
204
  * loops and background tabs behave (see the module docs).
@@ -128,11 +219,25 @@ export class ChunkStore {
128
219
  this.writeBackDueAt = new Map();
129
220
  this.changeListeners = new Set();
130
221
  this.writeBackFailureListeners = new Set();
222
+ this.editRefusedListeners = new Set();
131
223
  this.fallbackUuid = generateCrowdyUuid();
132
224
  this.revisionValue = 0;
133
225
  this.sequence = 0;
134
226
  /** This client's edits not yet echoed back, oldest first, per `chunkKey|voxelKey`. */
135
227
  this.pendingEdits = new Map();
228
+ /** Edits waiting to be sent, in order. */
229
+ this.sendQueue = [];
230
+ /** Sent edits not yet answered, by sequence number. */
231
+ this.inFlightEdits = new Map();
232
+ /** Chunks being read again; a key mapped to true is read once more when that read ends. */
233
+ this.reloading = new Map();
234
+ /** The area the last {@link ensureAround} covered, for a catch-up. */
235
+ this.lastArea = null;
236
+ /** When the realtime connection was last lost (while the store had loaded an area). */
237
+ this.disconnectedAt = null;
238
+ this.wasConnected = false;
239
+ this.disposed = false;
240
+ this.duplicatePageCount = 0;
136
241
  this.voxelStateCodec =
137
242
  config.voxelStateCodec ?? rawCodec;
138
243
  this.chunkStateCodec =
@@ -140,6 +245,12 @@ export class ChunkStore {
140
245
  this.hydrateStates = config.hydrateVoxelStates ?? config.voxelStateCodec !== undefined;
141
246
  this.now = config.now ?? Date.now;
142
247
  this.voxelIndex = config.voxelIndex ?? voxelIndex;
248
+ this.maxInFlight = Math.max(1, Math.min(MAX_EDITS_IN_FLIGHT, Math.floor(config.maxEditsInFlight ?? MAX_EDITS_IN_FLIGHT)));
249
+ this.editsPerSecond = Math.max(1, config.maxEditsPerSecond ?? EDITS_PER_SECOND);
250
+ this.sendBurst = Math.max(1, Math.ceil(this.editsPerSecond / 4));
251
+ this.sendTokens = this.sendBurst;
252
+ this.tokensAt = this.now();
253
+ this.editTimeoutMs = Math.max(1, config.editTimeoutMs ?? EDIT_TIMEOUT_MS);
143
254
  // Realtime merge: live edits land in the cache as they replicate.
144
255
  ctx.onDispose(ctx.on('voxelUpdate', (notification) => {
145
256
  const coord = {
@@ -154,12 +265,64 @@ export class ChunkStore {
154
265
  return;
155
266
  this.applyVoxel(chunk, notification.voxelX, notification.voxelY, notification.voxelZ, notification.voxelType, notification.voxelState || undefined);
156
267
  }));
268
+ // A refusal names the sequence number of the send it answers.
269
+ ctx.onDispose(ctx.on('genericError', (notification) => {
270
+ const entry = this.inFlightEdits.get(notification.sequenceNumber);
271
+ if (entry)
272
+ this.undoEdit(entry.key, entry.edit, String(notification.errorCode));
273
+ }));
274
+ if (config.reloadReplacedChunks ?? true) {
275
+ ctx.onDispose(ctx.on('chunkChanged', (notification) => {
276
+ const coord = {
277
+ x: Number(notification.chunkX),
278
+ y: Number(notification.chunkY),
279
+ z: Number(notification.chunkZ),
280
+ };
281
+ const chunk = this.chunks.get(chunkKey(coord));
282
+ if (!chunk)
283
+ return;
284
+ const updatedAt = Number(notification.updatedAtMs);
285
+ if (chunk.storedAt !== null && updatedAt > 0 && chunk.storedAt >= updatedAt)
286
+ return;
287
+ // The server's copy is newer than a seed waiting to be written back over it.
288
+ if (chunk.dirty)
289
+ this.dropWriteBack(chunk);
290
+ void this.reload(coord);
291
+ }));
292
+ }
293
+ if ((config.catchUpOnReconnect ?? true) && ctx.client.realtime) {
294
+ ctx.onDispose(ctx.client.realtime.onStatus((status) => {
295
+ if (status === 'connected') {
296
+ const since = this.disconnectedAt;
297
+ this.disconnectedAt = null;
298
+ if (this.wasConnected && since !== null) {
299
+ void this.catchUp(new Date(since - CATCH_UP_MARGIN_MS)).catch(() => {
300
+ // Best effort: the next reconnect, or a reload, catches up instead.
301
+ });
302
+ }
303
+ this.wasConnected = true;
304
+ }
305
+ else if (this.wasConnected && this.disconnectedAt === null) {
306
+ this.disconnectedAt = this.now();
307
+ }
308
+ }));
309
+ }
310
+ // Sends wait for their turn; answers that never come time out.
311
+ ctx.onDispose(ctx.ticker.every(50, () => {
312
+ this.expireEdits();
313
+ this.pump();
314
+ }));
157
315
  const writeBackInterval = config.writeBackIntervalMs ?? 700;
158
316
  if (writeBackInterval !== false && writeBackInterval > 0) {
159
317
  ctx.onDispose(ctx.ticker.every(writeBackInterval, () => {
160
318
  void this.persistNext();
161
319
  }));
162
320
  }
321
+ ctx.onDispose(() => {
322
+ this.disposed = true;
323
+ for (const send of this.sendQueue.splice(0))
324
+ send.resolve(false);
325
+ });
163
326
  }
164
327
  /** Bumped on every cache change — poll it cheaply from a render loop. */
165
328
  get revision() {
@@ -216,15 +379,39 @@ export class ChunkStore {
216
379
  return () => this.writeBackFailureListeners.delete(listener);
217
380
  }
218
381
  /**
219
- * Ensure every chunk within `radius` (Chebyshev, 1-8) of `center` is
220
- * tracked: bulk-loads untracked ones, hydrates sparse voxel states when
382
+ * Subscribe to the voxel edits the store undid: the server refused one (a voxel the player may
383
+ * not edit is `UNAUTHORIZED`), the transport did not take it, or its echo did not come back
384
+ * within {@link ChunkStoreConfig.editTimeoutMs}. The voxel already shows what it held before
385
+ * (see {@link VoxelEditRefusal.restored}) when the listener runs. A refusal is matched to its
386
+ * edit by the one-byte sequence number, which other stores' sends share, so it is best effort: an
387
+ * edit undone for another send's refusal comes back with its echo. @returns off.
388
+ */
389
+ onEditRefused(listener) {
390
+ this.editRefusedListeners.add(listener);
391
+ return () => this.editRefusedListeners.delete(listener);
392
+ }
393
+ /** Edits sent and not yet echoed, refused or timed out. */
394
+ get editsInFlight() {
395
+ return this.inFlightEdits.size;
396
+ }
397
+ /** Edits waiting for their turn to be sent (see {@link ChunkStoreConfig.maxEditsPerSecond}). */
398
+ get queuedEdits() {
399
+ return this.sendQueue.length;
400
+ }
401
+ /**
402
+ * Ensure every chunk within `radius` (Chebyshev, 0-8) of `center` is
403
+ * tracked: reads the untracked ones, hydrates sparse voxel states when
221
404
  * configured, marks server-unknown chunks `missing`, and seeds them via
222
405
  * `onMissing`. In-flight requests are deduped; safe to call every time the
223
406
  * player crosses a chunk boundary.
224
407
  *
225
- * A chunk already loaded keeps what the store holds for it when a later
226
- * bulk load returns it again: its stored `voxels` carry none of the edits
227
- * hydration and realtime merges applied. Prune it to load it afresh.
408
+ * Only chunks the store does not hold are read, as boxes of chunks
409
+ * (`chunks.byDistance` with `lowChunk` and `highChunk`, ck-api v2.67.0): a
410
+ * step along one axis at range 8 reads the 289 chunks it uncovers, not 4,913.
411
+ * Each box is read in pages, following the page size the server says it
412
+ * applied; a chunk a later page repeats is counted in
413
+ * {@link duplicatePageChunks} and not applied twice. A chunk the store
414
+ * already holds keeps what it has: prune it to load it afresh.
228
415
  *
229
416
  * Requests the platform refuses as busy are asked again with backoff, and
230
417
  * at most 8 hydrations run at once. Hydration is best effort: a chunk whose
@@ -234,7 +421,9 @@ export class ChunkStore {
234
421
  * promise rejects only when the bulk load itself fails.
235
422
  */
236
423
  async ensureAround(center, radius) {
237
- const around = chunksAround(center, radius);
424
+ const range = Math.max(0, Math.min(8, Math.floor(radius)));
425
+ this.lastArea = { center: { ...center }, radius: range };
426
+ const around = chunksAround(center, range);
238
427
  const wanted = around.filter((coord) => {
239
428
  const key = chunkKey(coord);
240
429
  if (this.inFlight.has(key))
@@ -244,36 +433,39 @@ export class ChunkStore {
244
433
  });
245
434
  const returned = new Set();
246
435
  if (wanted.length > 0) {
247
- for (const coord of wanted)
248
- this.inFlight.add(chunkKey(coord));
436
+ const wantedKeys = new Set(wanted.map(chunkKey));
437
+ for (const key of wantedKeys)
438
+ this.inFlight.add(key);
439
+ const pending = new Set(wantedKeys);
249
440
  try {
250
- const response = await whenNotBusy(() => this.ctx.client.chunks.byDistance({
251
- appId: this.ctx.appId,
252
- centerCoordinate: toChunkInput(center),
253
- maxDistance: Math.max(1, Math.min(8, radius)),
254
- limit: (2 * radius + 1) ** 3,
255
- }));
256
- for (const chunk of response.chunks) {
257
- const coord = fromChunkInput(chunk.coordinates);
258
- const key = chunkKey(coord);
259
- // The cube around a new center includes chunks loaded from an earlier one.
260
- if (this.chunks.get(key)?.loadState === 'loaded')
261
- continue;
262
- returned.add(key);
263
- this.applyServerChunk(coord, chunk.voxels ?? null, chunk.chunkState ?? null);
264
- }
265
- // Requested-but-absent chunks have never been stored server-side.
266
- for (const coord of wanted) {
267
- if (returned.has(chunkKey(coord)))
268
- continue;
269
- this.markMissing(coord);
441
+ for (const box of coverWithBoxes(wanted)) {
442
+ await this.readBox(box, (coord, chunk) => {
443
+ const key = chunkKey(coord);
444
+ if (!wantedKeys.has(key))
445
+ return;
446
+ // A chunk tracked meanwhile (an edit, a seed) keeps what it has.
447
+ if (this.chunks.get(key)?.loadState === 'loaded' || this.chunks.get(key)?.dirty)
448
+ return;
449
+ returned.add(key);
450
+ this.applyServerChunk(coord, chunk.voxels ?? null, chunk.chunkState ?? null, chunk.updatedAt);
451
+ });
452
+ // Requested-but-absent chunks have never been stored server-side.
453
+ for (const coord of wanted) {
454
+ const key = chunkKey(coord);
455
+ if (!pending.has(key) || !inBox(box, coord))
456
+ continue;
457
+ pending.delete(key);
458
+ if (!returned.has(key))
459
+ this.markMissing(coord);
460
+ }
270
461
  }
271
462
  }
272
463
  catch (error) {
273
464
  for (const coord of wanted) {
274
- const key = chunkKey(coord);
275
- const chunk = this.chunks.get(key);
276
- if (!chunk || chunk.loadState === 'failed') {
465
+ if (!pending.has(chunkKey(coord)))
466
+ continue;
467
+ const chunk = this.chunks.get(chunkKey(coord));
468
+ if (!chunk || chunk.loadState === 'failed' || chunk.loadState === 'loading') {
277
469
  const entry = this.ensureEntry(coord);
278
470
  entry.loadState = 'failed';
279
471
  this.touch(entry);
@@ -282,8 +474,8 @@ export class ChunkStore {
282
474
  throw error;
283
475
  }
284
476
  finally {
285
- for (const coord of wanted)
286
- this.inFlight.delete(chunkKey(coord));
477
+ for (const key of wantedKeys)
478
+ this.inFlight.delete(key);
287
479
  }
288
480
  }
289
481
  if (this.hydrateStates) {
@@ -322,9 +514,46 @@ export class ChunkStore {
322
514
  };
323
515
  await Promise.all(Array.from({ length: Math.min(HYDRATE_CONCURRENCY, coords.length) }, worker));
324
516
  }
517
+ /** Chunks a region read returned twice (on two of its pages); each was applied once. */
518
+ get duplicatePageChunks() {
519
+ return this.duplicatePageCount;
520
+ }
521
+ /**
522
+ * Read every stored chunk of a box, page by page, handing each to `take` once. A page shorter
523
+ * than the size the server applied is the last.
524
+ */
525
+ async readBox(box, take, since) {
526
+ const seen = new Set();
527
+ let skip = 0;
528
+ for (;;) {
529
+ const response = await whenNotBusy(() => this.ctx.client.chunks.byDistance({
530
+ appId: this.ctx.appId,
531
+ lowChunk: toChunkInput(box.lo),
532
+ highChunk: toChunkInput(box.hi),
533
+ limit: PAGE_SIZE,
534
+ skip,
535
+ ...(since ? { since: since.toISOString() } : {}),
536
+ }));
537
+ for (const chunk of response.chunks) {
538
+ const coord = fromChunkInput(chunk.coordinates);
539
+ const key = chunkKey(coord);
540
+ if (seen.has(key)) {
541
+ this.duplicatePageCount += 1;
542
+ continue;
543
+ }
544
+ seen.add(key);
545
+ take(coord, chunk);
546
+ }
547
+ const applied = response.limit ?? PAGE_SIZE;
548
+ if (response.chunks.length < applied || applied <= 0)
549
+ return;
550
+ skip = (response.skip ?? skip) + applied;
551
+ }
552
+ }
325
553
  /**
326
554
  * Hydrate one chunk's sparse voxel states (and chunk state) via a
327
- * single-chunk fetch — bulk loads omit them.
555
+ * single-chunk fetch — bulk loads omit them. This client's edits the server has not echoed yet
556
+ * stay over the stored copy, which may predate them.
328
557
  */
329
558
  async hydrate(coord) {
330
559
  const full = await this.ctx.client.chunks.get({
@@ -339,11 +568,19 @@ export class ChunkStore {
339
568
  if (full.voxels != null)
340
569
  chunk.voxels = decodeBase64(full.voxels);
341
570
  chunk.chunkState = this.decodeChunkState(full.chunkState ?? null);
571
+ chunk.voxelStatesTruncated = full.voxelStatesTruncated === true;
572
+ chunk.storedAt = storedAtMs(full.updatedAt);
573
+ // The stored copy replaces what the store held for the chunk (a `world.set_chunk` drops the
574
+ // chunk's older edits); a state blob this codec cannot read keeps the one cached before.
575
+ const cachedStates = new Map(chunk.voxelStates);
576
+ const cachedOverlay = new Map(chunk.overlay);
577
+ chunk.voxelStates.clear();
578
+ chunk.overlay.clear();
342
579
  for (const entry of full.voxelStates ?? []) {
343
580
  const { x, y, z } = entry.voxelCoord;
344
581
  if (!fitsDenseGrid(x, y, z, entry.voxelType)) {
345
582
  const key = voxelKey(x, y, z);
346
- let state = entry.state ? chunk.overlay.get(key)?.state : undefined;
583
+ let state = entry.state ? cachedOverlay.get(key)?.state : undefined;
347
584
  if (entry.state) {
348
585
  try {
349
586
  state = this.voxelStateCodec.decode(entry.state);
@@ -356,7 +593,6 @@ export class ChunkStore {
356
593
  continue;
357
594
  }
358
595
  const index = this.voxelIndex(x, y, z);
359
- chunk.overlay.delete(voxelKey(x, y, z));
360
596
  // A chunk stored with `voxels: null` still carries its recorded edits.
361
597
  if (!chunk.voxels)
362
598
  chunk.voxels = new Uint8Array(CHUNK_VOLUME);
@@ -366,64 +602,117 @@ export class ChunkStore {
366
602
  chunk.voxelStates.set(index, this.voxelStateCodec.decode(entry.state));
367
603
  }
368
604
  catch {
369
- // Foreign/legacy blobs skip silently; the dense type still applied.
605
+ // Foreign/legacy blobs keep the state cached before; the dense type still applied.
606
+ const cached = cachedStates.get(index);
607
+ if (cached !== undefined)
608
+ chunk.voxelStates.set(index, cached);
370
609
  }
371
610
  }
372
- else {
373
- chunk.voxelStates.delete(index);
374
- }
375
611
  }
612
+ this.reapplyPendingEdits(chunk);
376
613
  chunk.loadState = 'loaded';
377
614
  chunk.hydrated = true;
378
615
  this.touch(chunk);
379
616
  }
617
+ /**
618
+ * Read the chunks in the last area {@link ensureAround} loaded that changed since `since`: the
619
+ * recorded edits (`voxels.listByDistance`, when the client has `voxels`) are applied to the
620
+ * chunks the store holds, and a chunk whose stored row was written since then
621
+ * (`chunks.byDistance` with `since`: `updateChunk`, `world.set_chunk`) is read again. The store
622
+ * calls it when the realtime connection comes back ({@link ChunkStoreConfig.catchUpOnReconnect}),
623
+ * from 30 s before the connection dropped. Needs ck-api v2.67.0.
624
+ */
625
+ async catchUp(since) {
626
+ const area = this.lastArea;
627
+ if (!area)
628
+ return;
629
+ const box = {
630
+ lo: { x: area.center.x - area.radius, y: area.center.y - area.radius, z: area.center.z - area.radius },
631
+ hi: { x: area.center.x + area.radius, y: area.center.y + area.radius, z: area.center.z + area.radius },
632
+ };
633
+ const replaced = [];
634
+ await this.readBox(box, (coord, stored) => {
635
+ const chunk = this.chunks.get(chunkKey(coord));
636
+ if (!chunk || chunk.dirty || chunk.loadState !== 'loaded')
637
+ return;
638
+ const at = storedAtMs(stored.updatedAt);
639
+ if (at !== null && chunk.storedAt !== null && chunk.storedAt >= at)
640
+ return;
641
+ replaced.push(coord);
642
+ }, since);
643
+ const voxels = this.ctx.client.voxels;
644
+ if (voxels) {
645
+ for (let skip = 0;;) {
646
+ const page = await whenNotBusy(() => voxels.listByDistance({
647
+ appId: this.ctx.appId,
648
+ lowChunk: toChunkInput(box.lo),
649
+ highChunk: toChunkInput(box.hi),
650
+ since: since.toISOString(),
651
+ limit: PAGE_SIZE,
652
+ skip,
653
+ }));
654
+ for (const group of page.chunks) {
655
+ const chunk = this.chunks.get(chunkKey(fromChunkInput(group.coordinates)));
656
+ if (!chunk || chunk.loadState !== 'loaded')
657
+ continue;
658
+ for (const edit of group.voxels) {
659
+ const { x, y, z } = edit.location;
660
+ // This client's own unanswered edit of the voxel settles with its echo.
661
+ if (this.livePendingEdits(`${chunk.key}|${voxelKey(x, y, z)}`).length > 0)
662
+ continue;
663
+ this.applyVoxel(chunk, x, y, z, edit.voxelType, edit.state ?? undefined);
664
+ }
665
+ }
666
+ const applied = page.limit ?? PAGE_SIZE;
667
+ if (page.chunks.length < applied || applied <= 0)
668
+ break;
669
+ skip = (page.skip ?? skip) + applied;
670
+ }
671
+ }
672
+ await Promise.all(replaced.map((coord) => this.reload(coord)));
673
+ }
380
674
  /**
381
675
  * Edit one voxel: applies to the cache immediately (optimistic) and
382
- * replicates via the realtime voxel path. Resolves with the send
383
- * acceptance.
676
+ * replicates via the realtime voxel path. Sends are paced
677
+ * ({@link ChunkStoreConfig.maxEditsInFlight},
678
+ * {@link ChunkStoreConfig.maxEditsPerSecond}); the promise resolves with
679
+ * the transport's acceptance once this edit's turn came. An edit the server
680
+ * refuses, or whose echo does not come back in time, is undone and reported
681
+ * through {@link onEditRefused}.
384
682
  */
385
683
  async setVoxel(input) {
386
684
  const encodedState = input.state !== undefined ? this.voxelStateCodec.encode(input.state) : undefined;
387
685
  const voxel = { x: input.x, y: input.y, z: input.z };
388
686
  assertVoxelEdit({ voxel, voxelType: input.voxelType, voxelState: encodedState });
687
+ if (this.disposed)
688
+ return false;
389
689
  const chunk = this.ensureEntry(input.chunk);
390
690
  const optimistic = input.optimistic ?? true;
691
+ const previous = {
692
+ voxelType: this.voxelTypeAt(input.chunk, input.x, input.y, input.z),
693
+ };
694
+ const previousState = this.voxelStateAt(input.chunk, input.x, input.y, input.z);
695
+ if (previousState !== undefined)
696
+ previous.state = previousState;
391
697
  if (optimistic) {
392
698
  this.applyVoxel(chunk, input.x, input.y, input.z, input.voxelType, undefined, input.state);
393
699
  }
394
- const sequenceNumber = this.nextSequence();
395
- const uuid = this.senderUuid();
396
- this.rememberEdit(chunk, voxel, {
397
- uuid,
398
- sequenceNumber,
399
- voxelType: input.voxelType,
400
- encodedState,
401
- sentAt: this.now(),
402
- stale: !optimistic,
403
- });
404
- this.ctx.trackSend({
405
- kind: 'voxelUpdate',
406
- sequenceNumber,
407
- sentAt: this.now(),
408
- uuid,
409
- detail: { chunk: input.chunk, x: input.x, y: input.y, z: input.z },
410
- });
411
- // Omit voxelState when the caller did not supply state. Sending '' is
412
- // refused by game-api while VoxelUpdateRequestInput.voxelState is String!;
413
- // the sibling schema change makes the field nullable, and omitting it is
414
- // the SDK contract either way.
415
- return this.ctx.client.udp.sendVoxelUpdate({
416
- appId: this.ctx.appId,
417
- chunk: toChunkInput(input.chunk),
418
- uuid,
700
+ const edit = {
701
+ coord: { ...input.chunk },
419
702
  voxel,
703
+ uuid: '',
704
+ sequenceNumber: -1,
420
705
  voxelType: input.voxelType,
421
- ...(encodedState !== undefined ? { voxelState: encodedState } : {}),
422
- sequenceNumber,
423
- ...(this.config.distance !== undefined ? { distance: this.config.distance } : {}),
424
- ...(this.config.decayRate !== undefined
425
- ? { decayRate: this.config.decayRate }
426
- : {}),
706
+ ...(encodedState !== undefined ? { encodedState } : {}),
707
+ ...(input.state !== undefined ? { state: input.state } : {}),
708
+ stale: !optimistic,
709
+ optimistic,
710
+ previous,
711
+ };
712
+ const key = this.rememberEdit(chunk, voxel, edit);
713
+ return new Promise((resolve, reject) => {
714
+ this.sendQueue.push({ key, edit, resolve, reject });
715
+ this.pump();
427
716
  });
428
717
  }
429
718
  /**
@@ -548,14 +837,212 @@ export class ChunkStore {
548
837
  this.writeBackAttempts.delete(key);
549
838
  this.writeBackDueAt.delete(key);
550
839
  }
551
- applyServerChunk(coord, voxels, chunkState) {
840
+ /** Stop writing a chunk back: the server's copy replaced it. */
841
+ dropWriteBack(chunk) {
842
+ const queued = this.writeBackQueue.indexOf(chunk.key);
843
+ if (queued >= 0)
844
+ this.writeBackQueue.splice(queued, 1);
845
+ this.forgetWriteBack(chunk.key);
846
+ chunk.dirty = false;
847
+ }
848
+ /**
849
+ * Read a chunk again (a `chunkChanged`, a catch-up, an edit whose echo never came). A request for
850
+ * a chunk already being read makes that read run once more when it ends, so the last answer is
851
+ * the newest. Failures leave what the store holds, marked for the next hydration.
852
+ */
853
+ async reload(coord) {
854
+ const key = chunkKey(coord);
855
+ if (this.reloading.has(key)) {
856
+ this.reloading.set(key, true);
857
+ return;
858
+ }
859
+ this.reloading.set(key, false);
860
+ try {
861
+ do {
862
+ this.reloading.set(key, false);
863
+ if (!this.chunks.has(key) || this.disposed)
864
+ break;
865
+ try {
866
+ await whenNotBusy(() => this.hydrate(coord));
867
+ this.hydrateFailures.delete(key);
868
+ }
869
+ catch {
870
+ const chunk = this.chunks.get(key);
871
+ if (chunk)
872
+ chunk.hydrated = false;
873
+ this.hydrateFailures.set(key, (this.hydrateFailures.get(key) ?? 0) + 1);
874
+ break;
875
+ }
876
+ } while (this.reloading.get(key) === true);
877
+ }
878
+ finally {
879
+ this.reloading.delete(key);
880
+ }
881
+ }
882
+ applyServerChunk(coord, voxels, chunkState, updatedAt) {
552
883
  const chunk = this.ensureEntry(coord);
553
884
  if (voxels != null)
554
885
  chunk.voxels = decodeBase64(voxels);
555
886
  chunk.chunkState = this.decodeChunkState(chunkState);
887
+ chunk.storedAt = storedAtMs(updatedAt);
888
+ this.reapplyPendingEdits(chunk);
556
889
  chunk.loadState = 'loaded';
557
890
  this.touch(chunk);
558
891
  }
892
+ /**
893
+ * Put this client's unanswered optimistic edits of a chunk back over a stored copy just applied,
894
+ * which may predate them. What the copy holds for each such voxel becomes what an undo restores.
895
+ */
896
+ reapplyPendingEdits(chunk) {
897
+ const prefix = `${chunk.key}|`;
898
+ for (const [key, edits] of this.pendingEdits) {
899
+ if (!key.startsWith(prefix))
900
+ continue;
901
+ const live = edits.filter((edit) => !edit.stale);
902
+ if (live.length === 0)
903
+ continue;
904
+ const { x, y, z } = live[0].voxel;
905
+ const stored = {
906
+ voxelType: this.voxelTypeAt(chunk.coord, x, y, z),
907
+ };
908
+ const storedState = this.voxelStateAt(chunk.coord, x, y, z);
909
+ if (storedState !== undefined)
910
+ stored.state = storedState;
911
+ live[0].previous = stored;
912
+ const newest = live[live.length - 1];
913
+ if (!newest.optimistic)
914
+ continue;
915
+ this.writeVoxel(chunk, x, y, z, newest.voxelType, newest.state);
916
+ }
917
+ }
918
+ /** Send queued edits while the pace and the in-flight limit allow. */
919
+ pump() {
920
+ if (this.disposed)
921
+ return;
922
+ const at = this.now();
923
+ this.sendTokens = Math.min(this.sendBurst, this.sendTokens + ((at - this.tokensAt) * this.editsPerSecond) / 1000);
924
+ this.tokensAt = at;
925
+ while (this.sendQueue.length > 0 &&
926
+ this.inFlightEdits.size < this.maxInFlight &&
927
+ this.sendTokens >= 1) {
928
+ const send = this.sendQueue.shift();
929
+ // An edit undone while it waited (a pruned chunk's) is not sent.
930
+ if (!this.pendingEdits.get(send.key)?.includes(send.edit)) {
931
+ send.resolve(false);
932
+ continue;
933
+ }
934
+ this.sendTokens -= 1;
935
+ this.transmit(send);
936
+ }
937
+ }
938
+ transmit(send) {
939
+ const { edit, key } = send;
940
+ let sequenceNumber = this.nextSequence();
941
+ while (this.inFlightEdits.has(sequenceNumber))
942
+ sequenceNumber = this.nextSequence();
943
+ const uuid = this.senderUuid();
944
+ edit.uuid = uuid;
945
+ edit.sequenceNumber = sequenceNumber;
946
+ edit.sentAt = this.now();
947
+ this.inFlightEdits.set(sequenceNumber, { key, edit });
948
+ this.ctx.trackSend({
949
+ kind: 'voxelUpdate',
950
+ sequenceNumber,
951
+ sentAt: edit.sentAt,
952
+ uuid,
953
+ detail: { chunk: edit.coord, x: edit.voxel.x, y: edit.voxel.y, z: edit.voxel.z },
954
+ });
955
+ // Omit voxelState when the caller did not supply state. Sending '' is
956
+ // refused by game-api while VoxelUpdateRequestInput.voxelState is String!;
957
+ // the sibling schema change makes the field nullable, and omitting it is
958
+ // the SDK contract either way.
959
+ let sent;
960
+ try {
961
+ sent = this.ctx.client.udp.sendVoxelUpdate({
962
+ appId: this.ctx.appId,
963
+ chunk: toChunkInput(edit.coord),
964
+ uuid,
965
+ voxel: edit.voxel,
966
+ voxelType: edit.voxelType,
967
+ ...(edit.encodedState !== undefined ? { voxelState: edit.encodedState } : {}),
968
+ sequenceNumber,
969
+ ...(this.config.distance !== undefined ? { distance: this.config.distance } : {}),
970
+ ...(this.config.decayRate !== undefined
971
+ ? { decayRate: this.config.decayRate }
972
+ : {}),
973
+ });
974
+ }
975
+ catch (error) {
976
+ sent = Promise.reject(error);
977
+ }
978
+ sent.then((accepted) => {
979
+ if (!accepted)
980
+ this.undoEdit(key, edit, 'NOT_SENT');
981
+ send.resolve(accepted);
982
+ }, (error) => {
983
+ this.undoEdit(key, edit, 'SEND_FAILED');
984
+ send.reject(error);
985
+ });
986
+ }
987
+ /** Undo and report the sent edits whose echo did not come back in time. */
988
+ expireEdits() {
989
+ const cutoff = this.now() - this.editTimeoutMs;
990
+ for (const { key, edit } of [...this.inFlightEdits.values()]) {
991
+ if (edit.sentAt !== undefined && edit.sentAt < cutoff)
992
+ this.undoEdit(key, edit, 'TIMEOUT');
993
+ }
994
+ }
995
+ /**
996
+ * Forget an edit the server will not apply and put its voxel back as it was before it, unless a
997
+ * newer edit is what the voxel shows. Reports it, then lets the next queued edit go.
998
+ */
999
+ undoEdit(key, edit, reason) {
1000
+ const edits = this.pendingEdits.get(key);
1001
+ const index = edits?.indexOf(edit) ?? -1;
1002
+ if (!edits || index < 0)
1003
+ return;
1004
+ edits.splice(index, 1);
1005
+ if (edits.length === 0)
1006
+ this.pendingEdits.delete(key);
1007
+ if (this.inFlightEdits.get(edit.sequenceNumber)?.edit === edit) {
1008
+ this.inFlightEdits.delete(edit.sequenceNumber);
1009
+ }
1010
+ let restored = false;
1011
+ const chunk = this.chunks.get(chunkKey(edit.coord));
1012
+ if (chunk && edit.optimistic && !edit.stale) {
1013
+ const next = edits[index];
1014
+ if (next) {
1015
+ // A newer edit of this voxel shows; it now undoes to what this one replaced.
1016
+ if (!next.stale)
1017
+ next.previous = edit.previous;
1018
+ }
1019
+ else {
1020
+ const { x, y, z } = edit.voxel;
1021
+ this.applyVoxel(chunk, x, y, z, edit.previous.voxelType, undefined, edit.previous.state);
1022
+ restored = true;
1023
+ }
1024
+ }
1025
+ const refusal = {
1026
+ coord: edit.coord,
1027
+ voxel: edit.voxel,
1028
+ voxelType: edit.voxelType,
1029
+ ...(edit.state !== undefined ? { state: edit.state } : {}),
1030
+ reason,
1031
+ restored,
1032
+ };
1033
+ for (const listener of [...this.editRefusedListeners]) {
1034
+ try {
1035
+ listener(refusal);
1036
+ }
1037
+ catch {
1038
+ // One listener's throw must not starve the others.
1039
+ }
1040
+ }
1041
+ // An edit may have been applied with its echo lost: the server's copy settles it.
1042
+ if (reason === 'TIMEOUT' && chunk && this.hydrateStates)
1043
+ void this.reload(edit.coord);
1044
+ this.pump();
1045
+ }
559
1046
  markMissing(coord) {
560
1047
  const chunk = this.ensureEntry(coord);
561
1048
  if (chunk.loadState === 'loaded' || chunk.loadState === 'seeded')
@@ -575,16 +1062,12 @@ export class ChunkStore {
575
1062
  const edits = this.livePendingEdits(key);
576
1063
  edits.push(edit);
577
1064
  this.pendingEdits.set(key, edits);
1065
+ return key;
578
1066
  }
579
- /** The unexpired pending edits for one voxel, dropping the expired ones. */
1067
+ /** The pending edits for one voxel, oldest first, after undoing the ones that timed out. */
580
1068
  livePendingEdits(key) {
581
- const cutoff = this.now() - PENDING_EDIT_TTL_MS;
582
- const edits = (this.pendingEdits.get(key) ?? []).filter((edit) => edit.sentAt >= cutoff);
583
- if (edits.length === 0)
584
- this.pendingEdits.delete(key);
585
- else
586
- this.pendingEdits.set(key, edits);
587
- return edits;
1069
+ this.expireEdits();
1070
+ return this.pendingEdits.get(key) ?? [];
588
1071
  }
589
1072
  /**
590
1073
  * Match a realtime voxel edit against this client's pending edits. Returns whether to apply it.
@@ -598,7 +1081,9 @@ export class ChunkStore {
598
1081
  const edits = this.livePendingEdits(key);
599
1082
  if (edits.length === 0)
600
1083
  return true;
601
- const index = edits.findIndex((edit) => edit.uuid === notification.uuid && edit.sequenceNumber === notification.sequenceNumber);
1084
+ const index = edits.findIndex((edit) => edit.sentAt !== undefined &&
1085
+ edit.uuid === notification.uuid &&
1086
+ edit.sequenceNumber === notification.sequenceNumber);
602
1087
  if (index < 0) {
603
1088
  for (const edit of edits)
604
1089
  edit.stale = true;
@@ -607,6 +1092,10 @@ export class ChunkStore {
607
1092
  const [echoed] = edits.splice(index, 1);
608
1093
  if (edits.length === 0)
609
1094
  this.pendingEdits.delete(key);
1095
+ if (this.inFlightEdits.get(echoed.sequenceNumber)?.edit === echoed) {
1096
+ this.inFlightEdits.delete(echoed.sequenceNumber);
1097
+ this.pump();
1098
+ }
610
1099
  const newerLocalEdit = edits.length > index;
611
1100
  return echoed.stale && !newerLocalEdit;
612
1101
  }
@@ -620,9 +1109,13 @@ export class ChunkStore {
620
1109
  state = undefined;
621
1110
  }
622
1111
  }
1112
+ this.writeVoxel(chunk, x, y, z, voxelType, state);
1113
+ this.touch(chunk);
1114
+ }
1115
+ /** Set one voxel's type and state, in the dense grid or the overlay, without a change event. */
1116
+ writeVoxel(chunk, x, y, z, voxelType, state) {
623
1117
  if (!fitsDenseGrid(x, y, z, voxelType)) {
624
1118
  this.putOverlay(chunk, x, y, z, voxelType, state);
625
- this.touch(chunk);
626
1119
  return;
627
1120
  }
628
1121
  chunk.overlay.delete(voxelKey(x, y, z));
@@ -636,7 +1129,6 @@ export class ChunkStore {
636
1129
  else {
637
1130
  chunk.voxelStates.delete(index);
638
1131
  }
639
- this.touch(chunk);
640
1132
  }
641
1133
  /**
642
1134
  * Keep a voxel the dense grid cannot hold in the overlay. An in-grid position with a wide type
@@ -673,6 +1165,8 @@ export class ChunkStore {
673
1165
  revision: 0,
674
1166
  updatedAt: this.now(),
675
1167
  hydrated: false,
1168
+ voxelStatesTruncated: false,
1169
+ storedAt: null,
676
1170
  dirty: false,
677
1171
  };
678
1172
  this.chunks.set(key, chunk);