Keep editor drafts across WebSocket idle drops.
Add gateway protocol ping/pong keepalive, editor auto-reconnect with backoff, and sessionStorage draft backup so mid-edit 1006 closes no longer wipe unsaved paint.
@@ -22,6 +22,8 @@ npm start
22
22
23
23
Open [http://localhost:8080](http://localhost:8080) to play and [http://localhost:8080/editor](http://localhost:8080/editor) for the world editor.
24
24
25
The world editor keeps an in-memory (and `sessionStorage`) draft across brief WebSocket drops: the gateway sends protocol pings ~every 25s, and the editor client auto-reconnects with backoff without wiping unsaved paint.
26
25
27
Sign in via [auth.timfalken.com](https://auth.timfalken.com) (OAuth). Without `QUESTWARD_AUTH_CLIENT_SECRET`, local dev uses stub admins (`admin-1`, …). A fresh world is infinite closed grass: open chunk `0,0` in the [world editor](http://localhost:8080/editor), save, then **Apply now** before a character can walk.
26
28
27
29
### Auth env (production)
@@ -22,6 +22,8 @@ npm start22
22
23
Open [http://localhost:8080](http://localhost:8080) to play and [http://localhost:8080/editor](http://localhost:8080/editor) for the world editor.
23
Open [http://localhost:8080](http://localhost:8080) to play and [http://localhost:8080/editor](http://localhost:8080/editor) for the world editor.
24
24
25
The world editor keeps an in-memory (and `sessionStorage`) draft across brief WebSocket drops: the gateway sends protocol pings ~every 25s, and the editor client auto-reconnects with backoff without wiping unsaved paint.
26
25
Sign in via [auth.timfalken.com](https://auth.timfalken.com) (OAuth). Without `QUESTWARD_AUTH_CLIENT_SECRET`, local dev uses stub admins (`admin-1`, …). A fresh world is infinite closed grass: open chunk `0,0` in the [world editor](http://localhost:8080/editor), save, then **Apply now** before a character can walk.
27
Sign in via [auth.timfalken.com](https://auth.timfalken.com) (OAuth). Without `QUESTWARD_AUTH_CLIENT_SECRET`, local dev uses stub admins (`admin-1`, …). A fresh world is infinite closed grass: open chunk `0,0` in the [world editor](http://localhost:8080/editor), save, then **Apply now** before a character can walk.
26
28
27
### Auth env (production)
29
### Auth env (production)
@@ -95,6 +95,11 @@ let pendingRevisionId = null;
95
95
let applyInFlight = false;
96
96
/** @type {string|null} */
97
97
let sessionAuthSubject = null;
98
/** True after the first successful SESSION message for this page load. */
99
let sessionReady = false;
100
/** Display label for #who while reconnecting. */
101
let accountWhoLabel = "Editor";
102
const EDITOR_DRAFT_STORAGE_PREFIX = "questward-editor-draft:";
98
103
const EDITOR_ZOOM_MIN = 0.25;
99
104
const EDITOR_ZOOM_MAX = 8;
100
105
const EDITOR_ZOOM_STEP = 1.12;
@@ -299,6 +304,137 @@ function draftPersistable ()
299
304
};
300
305
}
301
306
307
function isSelectedChunkDirty ()
308
{
309
if (!draft || draftBaseline == null)
310
{ return false; }
311
return JSON.stringify(draftPersistable()) !== draftBaseline;
312
}
313
314
function draftStorageKey (cx = chunkX, cy = chunkY, dimensionId = selectedDimensionId, subject = sessionAuthSubject)
315
{
316
const who = subject ?? "anon";
317
return `${EDITOR_DRAFT_STORAGE_PREFIX}${who}:${normalizeDimensionId(dimensionId)}:${cx},${cy}`;
318
}
319
320
function persistDirtyDraftBackup ()
321
{
322
if (!draft || !isSelectedChunkDirty())
323
{ return; }
324
try
325
{
326
const payload = {
327
savedAt: Date.now(),
328
dimensionId: selectedDimensionId,
329
chunkX,
330
chunkY,
331
authSubject: sessionAuthSubject,
332
open: !!draft.open,
333
grounds: draft.grounds,
334
blocks: draft.blocks,
335
spawners: draft.spawners ?? [],
336
light: draft.light,
337
enclosed: draft.enclosed,
338
baseline: draftBaseline
339
};
340
sessionStorage.setItem(draftStorageKey(), JSON.stringify(payload));
341
}
342
catch
343
{ /* quota / private mode */ }
344
}
345
346
function clearDraftBackup (cx = chunkX, cy = chunkY, dimensionId = selectedDimensionId)
347
{
348
try
349
{ sessionStorage.removeItem(draftStorageKey(cx, cy, dimensionId)); }
350
catch
351
{ /* ignore */ }
352
}
353
354
function readDraftBackup (cx = chunkX, cy = chunkY, dimensionId = selectedDimensionId)
355
{
356
try
357
{
358
const raw = sessionStorage.getItem(draftStorageKey(cx, cy, dimensionId));
359
if (!raw)
360
{ return null; }
361
const parsed = JSON.parse(raw);
362
if (!parsed || !Array.isArray(parsed.grounds) || !Array.isArray(parsed.blocks))
363
{ return null; }
364
return parsed;
365
}
366
catch
367
{ return null; }
368
}
369
370
function applyRestoredDraftBackup (backup)
371
{
372
if (!backup || !draft)
373
{ return false; }
374
draft.open = !!backup.open;
375
draft.grounds = backup.grounds.map((ground) => normalizeGround(ground));
376
draft.blocks = backup.blocks.map((block) => (block
377
? { ...block, config: block.config ?? null }
378
: null));
379
const tileCount = CHUNK_SIZE * CHUNK_SIZE;
380
draft.light = Array.isArray(backup.light) && backup.light.length === tileCount
381
? backup.light.slice()
382
: (draft.light ?? new Array(tileCount).fill(0));
383
draft.enclosed = Array.isArray(backup.enclosed) && backup.enclosed.length === tileCount
384
? backup.enclosed.slice().map((v) => (v ? 1 : 0))
385
: (draft.enclosed ?? new Array(tileCount).fill(0));
386
draft.spawners = (backup.spawners ?? []).map((entry) => ({
387
localX: entry.localX | 0,
388
localY: entry.localY | 0,
389
config: { ...(entry.config ?? {}) }
390
}));
391
if (typeof backup.baseline === "string")
392
{ draftBaseline = backup.baseline; }
393
$("open").checked = draft.open;
394
const existing = view?.chunks.get(chunkKey(chunkX, chunkY));
395
view.applySnapshot({
396
chunkX,
397
chunkY,
398
open: draft.open,
399
closedEdges: existing?.closedEdges,
400
grounds: draft.grounds,
401
blocks: draft.blocks,
402
light: draft.light,
403
enclosed: draft.enclosed,
404
entities: []
405
});
406
syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
407
syncSaveButton();
408
return true;
409
}
410
411
function tryRestoreDraftBackupAfterServerLoad (payload)
412
{
413
const backup = readDraftBackup(payload.chunkX, payload.chunkY, selectedDimensionId);
414
if (!backup)
415
{ return false; }
416
const serverPersistable = {
417
open: !!payload.data.open,
418
grounds: payload.data.grounds,
419
blocks: payload.data.blocks,
420
spawners: payload.data.spawners ?? []
421
};
422
const backupPersistable = {
423
open: !!backup.open,
424
grounds: backup.grounds,
425
blocks: backup.blocks,
426
spawners: backup.spawners ?? []
427
};
428
if (JSON.stringify(serverPersistable) === JSON.stringify(backupPersistable))
429
{
430
clearDraftBackup(payload.chunkX, payload.chunkY, selectedDimensionId);
431
return false;
432
}
433
// Treat server payload as the clean baseline so the restored paint stays dirty.
434
draftBaseline = JSON.stringify(serverPersistable);
435
return applyRestoredDraftBackup(backup);
436
}
437
302
438
function cloneDraftContents (source)
303
439
{
304
440
if (!source)
@@ -442,6 +578,7 @@ function captureDraftBaseline ()
442
578
{
443
579
const payload = draftPersistable();
444
580
draftBaseline = payload ? JSON.stringify(payload) : null;
581
clearDraftBackup();
445
582
syncSaveButton();
446
583
}
447
584
@@ -454,9 +591,7 @@ function isDraftDirty ()
454
591
{
455
592
if (dirtyNeighborChunks.size > 0)
456
593
{ return true; }
457
if (!draft || draftBaseline == null)
458
{ return false; }
459
return JSON.stringify(draftPersistable()) !== draftBaseline;
594
return isSelectedChunkDirty();
460
595
}
461
596
462
597
function syncSaveButton ()
@@ -479,6 +614,10 @@ function syncSaveButton ()
479
614
function afterDraftMutation ()
480
615
{
481
616
syncSaveButton();
617
if (isSelectedChunkDirty())
618
{ persistDirtyDraftBackup(); }
619
else
620
{ clearDraftBackup(); }
482
621
}
483
622
484
623
function clearNeighborEditState ()
@@ -970,7 +1109,22 @@ function setRevisionState ({ activeRevisionId: active, pendingRevisionId: pendin
970
1109
971
1110
function showSelectedChunk (payload)
972
1111
{
973
clearNeighborEditState();
1112
const keepDirtyDraft = !!draft
1113
&& payload.chunkX === chunkX
1114
&& payload.chunkY === chunkY
1115
&& isSelectedChunkDirty();
1116
if (!keepDirtyDraft)
1117
{ clearNeighborEditState(); }
1118
if (keepDirtyDraft)
1119
{
1120
setRevisionState({
1121
activeRevisionId: payload.activeRevisionId,
1122
pendingRevisionId: payload.pendingRevisionId
1123
});
1124
$("authored").textContent = payload.authored ? "authored" : "unauthored (dimension default ground)";
1125
syncSaveButton();
1126
return;
1127
}
974
1128
draft = {
975
1129
open: payload.data.open,
976
1130
grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),
@@ -1010,8 +1164,11 @@ function showSelectedChunk (payload)
1010
1164
}
1011
1165
view.applySnapshot(snapshotFromPayload(payload));
1012
1166
syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners);
1013
captureDraftBaseline();
1014
syncSaveButton();
1167
const restored = tryRestoreDraftBackupAfterServerLoad(payload);
1168
if (!restored)
1169
{ captureDraftBaseline(); }
1170
else
1171
{ syncSaveButton(); }
1015
1172
if (navigateAfterSave && pendingNavigate)
1016
1173
{
1017
1174
const next = pendingNavigate;
@@ -1521,15 +1678,46 @@ async function main ()
1521
1678
scene.addObject(ticker);
1522
1679
window.addEventListener("resize", layoutScene);
1523
1680
1681
accountWhoLabel = accountLabel;
1524
1682
$("who").textContent = `${accountLabel} · connecting…`;
1525
1683
1684
function setWhoConnected (label, isAdmin)
1685
{
1686
accountWhoLabel = label;
1687
$("who").textContent = `${label}${isAdmin ? " · admin" : " · not admin"}`;
1688
}
1689
1690
function resubscribeEditorSession ({ reloadMap })
1691
{
1692
socket.send({ type: MessageType.editorLoadSettings });
1693
socket.send({ type: MessageType.editorLoadGameAdmins });
1694
socket.send({ type: MessageType.editorConsoleSubscribe });
1695
requestDimensions();
1696
if (reloadMap)
1697
{
1698
loadNeighborhood(chunkX, chunkY);
1699
return;
1700
}
1701
const coords = neighborhoodCoords(chunkX, chunkY).filter((coord) =>
1702
{
1703
if (coord.chunkX === chunkX && coord.chunkY === chunkY)
1704
{ return !draft || !isSelectedChunkDirty(); }
1705
return !dirtyNeighborChunks.has(chunkKey(coord.chunkX, coord.chunkY));
1706
});
1707
requestChunks(coords);
1708
syncSaveButton();
1709
}
1710
1526
1711
socket = new GameSocket(defaultSocketUrl(), (message) =>
1527
1712
{
1528
1713
if (message.type === MessageType.session)
1529
1714
{
1715
const wasReady = sessionReady;
1530
1716
sessionAuthSubject = message.authSubject ?? null;
1717
sessionReady = true;
1718
socket.notifySessionEstablished();
1531
1719
const label = message.username ?? message.authSubject ?? "Unknown";
1532
$("who").textContent = `${label}${message.isAdmin ? " · admin" : " · not admin"}`;
1720
setWhoConnected(label, !!message.isAdmin);
1533
1721
if (!message.isAdmin)
1534
1722
{
1535
1723
$("error").textContent = "Admin access required.";
@@ -1542,11 +1730,7 @@ async function main ()
1542
1730
restartBtn.hidden = false;
1543
1731
restartBtn.disabled = false;
1544
1732
}
1545
socket.send({ type: MessageType.editorLoadSettings });
1546
socket.send({ type: MessageType.editorLoadGameAdmins });
1547
socket.send({ type: MessageType.editorConsoleSubscribe });
1548
requestDimensions();
1549
loadNeighborhood(0, 0);
1733
resubscribeEditorSession({ reloadMap: !wasReady });
1550
1734
}
1551
1735
else if (message.type === MessageType.editorSettings
1552
1736
|| message.type === MessageType.editorGameAdmins)
@@ -1635,22 +1819,59 @@ async function main ()
1635
1819
}
1636
1820
}
1637
1821
}, {
1822
autoReconnect: true,
1823
onOpen ()
1824
{
1825
if (sessionReady)
1826
{ $("who").textContent = `${accountWhoLabel} · reconnected, waiting for session…`; }
1827
},
1828
onReconnecting ({ attempt, delayMs })
1829
{
1830
$("who").textContent = `${accountWhoLabel} · reconnecting…`;
1831
if (sessionReady)
1832
{
1833
$("error").textContent = "Connection lost while editing. Reconnecting… Your unsaved draft is kept."
1834
+ ` (attempt ${attempt}, retry in ${Math.round(delayMs / 100) / 10}s)`;
1835
}
1836
},
1638
1837
onClose (event)
1639
1838
{
1640
1839
if (event.code === 1000)
1641
1840
{ return; }
1642
const reasons = {
1841
const authOrRestart = {
1643
1842
4401: "Sign in expired or missing. Use Sign out, then sign in again.",
1644
1843
1011: "Server could not verify your account with auth.timfalken.com.",
1645
1006: "Connection dropped before the editor session started.",
1646
1844
1001: "Server is restarting. Reload this page in a moment."
1647
1845
};
1846
if (authOrRestart[event.code])
1847
{
1848
sessionReady = false;
1849
$("who").textContent = "Connection failed";
1850
$("error").textContent = authOrRestart[event.code];
1851
return;
1852
}
1853
if (sessionReady)
1854
{
1855
$("who").textContent = `${accountWhoLabel} · reconnecting…`;
1856
$("error").textContent = "Connection lost while editing. Reconnecting… Your unsaved draft is kept.";
1857
persistDirtyDraftBackup();
1858
return;
1859
}
1860
const reasons = {
1861
1006: "Connection dropped before the editor session started."
1862
};
1648
1863
const detail = reasons[event.code] ?? `Connection closed (code ${event.code}).`;
1649
1864
$("who").textContent = "Connection failed";
1650
1865
$("error").textContent = detail;
1651
1866
},
1652
1867
onError ()
1653
1868
{
1869
if (sessionReady)
1870
{
1871
$("who").textContent = `${accountWhoLabel} · reconnecting…`;
1872
$("error").textContent = "Connection lost while editing. Reconnecting… Your unsaved draft is kept.";
1873
return;
1874
}
1654
1875
$("who").textContent = "Connection failed";
1655
1876
$("error").textContent = "Could not open a live connection to the server.";
1656
1877
}
@@ -1729,7 +1950,17 @@ async function main ()
1729
1950
initSidePanelTabs();
1730
1951
game.startGame();
1731
1952
useNearestNeighbour(scene, game.images);
1732
await socket.connect();
1953
try
1954
{ await socket.connect(); }
1955
catch (error)
1956
{
1957
// autoReconnect keeps retrying; surface the first failure without aborting the editor UI
1958
if (!sessionReady)
1959
{
1960
$("who").textContent = "Connection failed";
1961
$("error").textContent = error?.message || "Could not open a live connection to the server.";
1962
}
1963
}
1733
1964
}
1734
1965
1735
1966
$("tool").textContent = selectedToolLabel();
@@ -95,6 +95,11 @@ let pendingRevisionId = null;95
let applyInFlight = false;95
let applyInFlight = false;96
/** @type {string|null} */96
/** @type {string|null} */97
let sessionAuthSubject = null;97
let sessionAuthSubject = null;98
/** True after the first successful SESSION message for this page load. */99
let sessionReady = false;100
/** Display label for #who while reconnecting. */101
let accountWhoLabel = "Editor";102
const EDITOR_DRAFT_STORAGE_PREFIX = "questward-editor-draft:";98
const EDITOR_ZOOM_MIN = 0.25;103
const EDITOR_ZOOM_MIN = 0.25;99
const EDITOR_ZOOM_MAX = 8;104
const EDITOR_ZOOM_MAX = 8;100
const EDITOR_ZOOM_STEP = 1.12;105
const EDITOR_ZOOM_STEP = 1.12;@@ -299,6 +304,137 @@ function draftPersistable ()299
};304
};300
}305
}301
306
307
function isSelectedChunkDirty ()308
{309
if (!draft || draftBaseline == null)310
{ return false; }311
return JSON.stringify(draftPersistable()) !== draftBaseline;312
}313
314
function draftStorageKey (cx = chunkX, cy = chunkY, dimensionId = selectedDimensionId, subject = sessionAuthSubject)315
{316
const who = subject ?? "anon";317
return `${EDITOR_DRAFT_STORAGE_PREFIX}${who}:${normalizeDimensionId(dimensionId)}:${cx},${cy}`;318
}319
320
function persistDirtyDraftBackup ()321
{322
if (!draft || !isSelectedChunkDirty())323
{ return; }324
try325
{326
const payload = {327
savedAt: Date.now(),328
dimensionId: selectedDimensionId,329
chunkX,330
chunkY,331
authSubject: sessionAuthSubject,332
open: !!draft.open,333
grounds: draft.grounds,334
blocks: draft.blocks,335
spawners: draft.spawners ?? [],336
light: draft.light,337
enclosed: draft.enclosed,338
baseline: draftBaseline339
};340
sessionStorage.setItem(draftStorageKey(), JSON.stringify(payload));341
}342
catch343
{ /* quota / private mode */ }344
}345
346
function clearDraftBackup (cx = chunkX, cy = chunkY, dimensionId = selectedDimensionId)347
{348
try349
{ sessionStorage.removeItem(draftStorageKey(cx, cy, dimensionId)); }350
catch351
{ /* ignore */ }352
}353
354
function readDraftBackup (cx = chunkX, cy = chunkY, dimensionId = selectedDimensionId)355
{356
try357
{358
const raw = sessionStorage.getItem(draftStorageKey(cx, cy, dimensionId));359
if (!raw)360
{ return null; }361
const parsed = JSON.parse(raw);362
if (!parsed || !Array.isArray(parsed.grounds) || !Array.isArray(parsed.blocks))363
{ return null; }364
return parsed;365
}366
catch367
{ return null; }368
}369
370
function applyRestoredDraftBackup (backup)371
{372
if (!backup || !draft)373
{ return false; }374
draft.open = !!backup.open;375
draft.grounds = backup.grounds.map((ground) => normalizeGround(ground));376
draft.blocks = backup.blocks.map((block) => (block377
? { ...block, config: block.config ?? null }378
: null));379
const tileCount = CHUNK_SIZE * CHUNK_SIZE;380
draft.light = Array.isArray(backup.light) && backup.light.length === tileCount381
? backup.light.slice()382
: (draft.light ?? new Array(tileCount).fill(0));383
draft.enclosed = Array.isArray(backup.enclosed) && backup.enclosed.length === tileCount384
? backup.enclosed.slice().map((v) => (v ? 1 : 0))385
: (draft.enclosed ?? new Array(tileCount).fill(0));386
draft.spawners = (backup.spawners ?? []).map((entry) => ({387
localX: entry.localX | 0,388
localY: entry.localY | 0,389
config: { ...(entry.config ?? {}) }390
}));391
if (typeof backup.baseline === "string")392
{ draftBaseline = backup.baseline; }393
$("open").checked = draft.open;394
const existing = view?.chunks.get(chunkKey(chunkX, chunkY));395
view.applySnapshot({396
chunkX,397
chunkY,398
open: draft.open,399
closedEdges: existing?.closedEdges,400
grounds: draft.grounds,401
blocks: draft.blocks,402
light: draft.light,403
enclosed: draft.enclosed,404
entities: []405
});406
syncSpawnersOverlay(chunkX, chunkY, draft.spawners);407
syncSaveButton();408
return true;409
}410
411
function tryRestoreDraftBackupAfterServerLoad (payload)412
{413
const backup = readDraftBackup(payload.chunkX, payload.chunkY, selectedDimensionId);414
if (!backup)415
{ return false; }416
const serverPersistable = {417
open: !!payload.data.open,418
grounds: payload.data.grounds,419
blocks: payload.data.blocks,420
spawners: payload.data.spawners ?? []421
};422
const backupPersistable = {423
open: !!backup.open,424
grounds: backup.grounds,425
blocks: backup.blocks,426
spawners: backup.spawners ?? []427
};428
if (JSON.stringify(serverPersistable) === JSON.stringify(backupPersistable))429
{430
clearDraftBackup(payload.chunkX, payload.chunkY, selectedDimensionId);431
return false;432
}433
// Treat server payload as the clean baseline so the restored paint stays dirty.434
draftBaseline = JSON.stringify(serverPersistable);435
return applyRestoredDraftBackup(backup);436
}437
302
function cloneDraftContents (source)438
function cloneDraftContents (source)303
{439
{304
if (!source)440
if (!source)@@ -442,6 +578,7 @@ function captureDraftBaseline ()442
{578
{443
const payload = draftPersistable();579
const payload = draftPersistable();444
draftBaseline = payload ? JSON.stringify(payload) : null;580
draftBaseline = payload ? JSON.stringify(payload) : null;581
clearDraftBackup();445
syncSaveButton();582
syncSaveButton();446
}583
}447
584
@@ -454,9 +591,7 @@ function isDraftDirty ()454
{591
{455
if (dirtyNeighborChunks.size > 0)592
if (dirtyNeighborChunks.size > 0)456
{ return true; }593
{ return true; }457
if (!draft || draftBaseline == null)594
return isSelectedChunkDirty();458
{ return false; }459
return JSON.stringify(draftPersistable()) !== draftBaseline;460
}595
}461
596
462
function syncSaveButton ()597
function syncSaveButton ()@@ -479,6 +614,10 @@ function syncSaveButton ()479
function afterDraftMutation ()614
function afterDraftMutation ()480
{615
{481
syncSaveButton();616
syncSaveButton();617
if (isSelectedChunkDirty())618
{ persistDirtyDraftBackup(); }619
else620
{ clearDraftBackup(); }482
}621
}483
622
484
function clearNeighborEditState ()623
function clearNeighborEditState ()@@ -970,7 +1109,22 @@ function setRevisionState ({ activeRevisionId: active, pendingRevisionId: pendin970
1109
971
function showSelectedChunk (payload)1110
function showSelectedChunk (payload)972
{1111
{973
clearNeighborEditState();1112
const keepDirtyDraft = !!draft1113
&& payload.chunkX === chunkX1114
&& payload.chunkY === chunkY1115
&& isSelectedChunkDirty();1116
if (!keepDirtyDraft)1117
{ clearNeighborEditState(); }1118
if (keepDirtyDraft)1119
{1120
setRevisionState({1121
activeRevisionId: payload.activeRevisionId,1122
pendingRevisionId: payload.pendingRevisionId1123
});1124
$("authored").textContent = payload.authored ? "authored" : "unauthored (dimension default ground)";1125
syncSaveButton();1126
return;1127
}974
draft = {1128
draft = {975
open: payload.data.open,1129
open: payload.data.open,976
grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),1130
grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),@@ -1010,8 +1164,11 @@ function showSelectedChunk (payload)1010
}1164
}1011
view.applySnapshot(snapshotFromPayload(payload));1165
view.applySnapshot(snapshotFromPayload(payload));1012
syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners);1166
syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners);1013
captureDraftBaseline();1167
const restored = tryRestoreDraftBackupAfterServerLoad(payload);1014
syncSaveButton();1168
if (!restored)1169
{ captureDraftBaseline(); }1170
else1171
{ syncSaveButton(); }1015
if (navigateAfterSave && pendingNavigate)1172
if (navigateAfterSave && pendingNavigate)1016
{1173
{1017
const next = pendingNavigate;1174
const next = pendingNavigate;@@ -1521,15 +1678,46 @@ async function main ()1521
scene.addObject(ticker);1678
scene.addObject(ticker);1522
window.addEventListener("resize", layoutScene);1679
window.addEventListener("resize", layoutScene);1523
1680
1681
accountWhoLabel = accountLabel;1524
$("who").textContent = `${accountLabel} · connecting…`;1682
$("who").textContent = `${accountLabel} · connecting…`;1525
1683
1684
function setWhoConnected (label, isAdmin)1685
{1686
accountWhoLabel = label;1687
$("who").textContent = `${label}${isAdmin ? " · admin" : " · not admin"}`;1688
}1689
1690
function resubscribeEditorSession ({ reloadMap })1691
{1692
socket.send({ type: MessageType.editorLoadSettings });1693
socket.send({ type: MessageType.editorLoadGameAdmins });1694
socket.send({ type: MessageType.editorConsoleSubscribe });1695
requestDimensions();1696
if (reloadMap)1697
{1698
loadNeighborhood(chunkX, chunkY);1699
return;1700
}1701
const coords = neighborhoodCoords(chunkX, chunkY).filter((coord) =>1702
{1703
if (coord.chunkX === chunkX && coord.chunkY === chunkY)1704
{ return !draft || !isSelectedChunkDirty(); }1705
return !dirtyNeighborChunks.has(chunkKey(coord.chunkX, coord.chunkY));1706
});1707
requestChunks(coords);1708
syncSaveButton();1709
}1710
1526
socket = new GameSocket(defaultSocketUrl(), (message) =>1711
socket = new GameSocket(defaultSocketUrl(), (message) =>1527
{1712
{1528
if (message.type === MessageType.session)1713
if (message.type === MessageType.session)1529
{1714
{1715
const wasReady = sessionReady;1530
sessionAuthSubject = message.authSubject ?? null;1716
sessionAuthSubject = message.authSubject ?? null;1717
sessionReady = true;1718
socket.notifySessionEstablished();1531
const label = message.username ?? message.authSubject ?? "Unknown";1719
const label = message.username ?? message.authSubject ?? "Unknown";1532
$("who").textContent = `${label}${message.isAdmin ? " · admin" : " · not admin"}`;1720
setWhoConnected(label, !!message.isAdmin);1533
if (!message.isAdmin)1721
if (!message.isAdmin)1534
{1722
{1535
$("error").textContent = "Admin access required.";1723
$("error").textContent = "Admin access required.";@@ -1542,11 +1730,7 @@ async function main ()1542
restartBtn.hidden = false;1730
restartBtn.hidden = false;1543
restartBtn.disabled = false;1731
restartBtn.disabled = false;1544
}1732
}1545
socket.send({ type: MessageType.editorLoadSettings });1733
resubscribeEditorSession({ reloadMap: !wasReady });1546
socket.send({ type: MessageType.editorLoadGameAdmins });1547
socket.send({ type: MessageType.editorConsoleSubscribe });1548
requestDimensions();1549
loadNeighborhood(0, 0);1550
}1734
}1551
else if (message.type === MessageType.editorSettings1735
else if (message.type === MessageType.editorSettings1552
|| message.type === MessageType.editorGameAdmins)1736
|| message.type === MessageType.editorGameAdmins)@@ -1635,22 +1819,59 @@ async function main ()1635
}1819
}1636
}1820
}1637
}, {1821
}, {1822
autoReconnect: true,1823
onOpen ()1824
{1825
if (sessionReady)1826
{ $("who").textContent = `${accountWhoLabel} · reconnected, waiting for session…`; }1827
},1828
onReconnecting ({ attempt, delayMs })1829
{1830
$("who").textContent = `${accountWhoLabel} · reconnecting…`;1831
if (sessionReady)1832
{1833
$("error").textContent = "Connection lost while editing. Reconnecting… Your unsaved draft is kept."1834
+ ` (attempt ${attempt}, retry in ${Math.round(delayMs / 100) / 10}s)`;1835
}1836
},1638
onClose (event)1837
onClose (event)1639
{1838
{1640
if (event.code === 1000)1839
if (event.code === 1000)1641
{ return; }1840
{ return; }1642
const reasons = {1841
const authOrRestart = {1643
4401: "Sign in expired or missing. Use Sign out, then sign in again.",1842
4401: "Sign in expired or missing. Use Sign out, then sign in again.",1644
1011: "Server could not verify your account with auth.timfalken.com.",1843
1011: "Server could not verify your account with auth.timfalken.com.",1645
1006: "Connection dropped before the editor session started.",1646
1001: "Server is restarting. Reload this page in a moment."1844
1001: "Server is restarting. Reload this page in a moment."1647
};1845
};1846
if (authOrRestart[event.code])1847
{1848
sessionReady = false;1849
$("who").textContent = "Connection failed";1850
$("error").textContent = authOrRestart[event.code];1851
return;1852
}1853
if (sessionReady)1854
{1855
$("who").textContent = `${accountWhoLabel} · reconnecting…`;1856
$("error").textContent = "Connection lost while editing. Reconnecting… Your unsaved draft is kept.";1857
persistDirtyDraftBackup();1858
return;1859
}1860
const reasons = {1861
1006: "Connection dropped before the editor session started."1862
};1648
const detail = reasons[event.code] ?? `Connection closed (code ${event.code}).`;1863
const detail = reasons[event.code] ?? `Connection closed (code ${event.code}).`;1649
$("who").textContent = "Connection failed";1864
$("who").textContent = "Connection failed";1650
$("error").textContent = detail;1865
$("error").textContent = detail;1651
},1866
},1652
onError ()1867
onError ()1653
{1868
{1869
if (sessionReady)1870
{1871
$("who").textContent = `${accountWhoLabel} · reconnecting…`;1872
$("error").textContent = "Connection lost while editing. Reconnecting… Your unsaved draft is kept.";1873
return;1874
}1654
$("who").textContent = "Connection failed";1875
$("who").textContent = "Connection failed";1655
$("error").textContent = "Could not open a live connection to the server.";1876
$("error").textContent = "Could not open a live connection to the server.";1656
}1877
}@@ -1729,7 +1950,17 @@ async function main ()1729
initSidePanelTabs();1950
initSidePanelTabs();1730
game.startGame();1951
game.startGame();1731
useNearestNeighbour(scene, game.images);1952
useNearestNeighbour(scene, game.images);1732
await socket.connect();1953
try1954
{ await socket.connect(); }1955
catch (error)1956
{1957
// autoReconnect keeps retrying; surface the first failure without aborting the editor UI1958
if (!sessionReady)1959
{1960
$("who").textContent = "Connection failed";1961
$("error").textContent = error?.message || "Could not open a live connection to the server.";1962
}1963
}1733
}1964
}1734
1965
1735
$("tool").textContent = selectedToolLabel();1966
$("tool").textContent = selectedToolLabel();@@ -1,34 +1,119 @@
1
/** Close codes that should not trigger auto-reconnect (auth / intentional server kicks). */
2
export const NO_AUTO_RECONNECT_CODES = new Set([
3
1000, // normal closure (also used by intentional close())
4
1001, // going away / server restart
5
4000, // logged in elsewhere
6
4401, // authentication required
7
1011 // authentication / session setup failed
8
]);
9
10
/**
11
* Exponential backoff delay for reconnect attempts.
12
* @param {number} attempt zero-based attempt index
13
* @param {{ baseMs?: number, maxMs?: number }} [options]
14
*/
15
export function nextReconnectDelayMs (attempt, { baseMs = 750, maxMs = 20_000 } = {})
16
{
17
const n = Math.max(0, attempt | 0);
18
return Math.min(maxMs, baseMs * (2 ** n));
19
}
20
21
/**
22
* @param {number} code WebSocket close code
23
* @param {{ intentional?: boolean, autoReconnect?: boolean }} [options]
24
*/
25
export function shouldAutoReconnect (code, { intentional = false, autoReconnect = false } = {})
26
{
27
if (!autoReconnect || intentional)
28
{ return false; }
29
return !NO_AUTO_RECONNECT_CODES.has(code | 0);
30
}
31
1
32
export class GameSocket
2
33
{
3
constructor(url, onMessage, { onClose, onError } = {})
34
/**
35
* @param {string} url
36
* @param {(message: object) => void} onMessage
37
* @param {{
38
* onClose?: (event: CloseEvent) => void,
39
* onError?: (event: Event) => void,
40
* onOpen?: (event: Event) => void,
41
* onReconnecting?: (info: { attempt: number, delayMs: number, code: number }) => void,
42
* autoReconnect?: boolean,
43
* reconnectBaseMs?: number,
44
* reconnectMaxMs?: number
45
* }} [options]
46
*/
47
constructor (url, onMessage, {
48
onClose,
49
onError,
50
onOpen,
51
onReconnecting,
52
autoReconnect = false,
53
reconnectBaseMs = 750,
54
reconnectMaxMs = 20_000
55
} = {})
4
56
{
5
57
this.url = url;
6
58
this.onMessage = onMessage;
7
59
this.onClose = onClose;
8
60
this.onError = onError;
61
this.onOpen = onOpen;
62
this.onReconnecting = onReconnecting;
63
this.autoReconnect = !!autoReconnect;
64
this.reconnectBaseMs = reconnectBaseMs;
65
this.reconnectMaxMs = reconnectMaxMs;
9
66
this.socket = null;
10
}
11
12
connect ()
13
{
14
this.socket = new WebSocket(this.url);
15
this.socket.addEventListener("message", (event) =>
67
this._intentionalClose = false;
68
this._reconnectAttempt = 0;
69
this._reconnectTimer = null;
70
this._boundMessage = (event) =>
16
71
{
17
72
this.onMessage(JSON.parse(event.data));
18
});
19
this.socket.addEventListener("close", (event) =>
73
};
74
this._boundClose = (event) =>
20
75
{
21
this.onClose?.(event);
22
});
23
this.socket.addEventListener("error", (event) =>
76
this._handleClose(event);
77
};
78
this._boundError = (event) =>
24
79
{
25
80
this.onError?.(event);
26
});
27
return new Promise((resolve, reject) =>
81
};
82
this._boundOpen = (event) =>
28
83
{
29
this.socket.addEventListener("open", resolve, { once: true });
30
this.socket.addEventListener("error", () => reject(new Error("WebSocket failed")), { once: true });
31
});
84
this.onOpen?.(event);
85
};
86
}
87
88
connect ()
89
{
90
this._intentionalClose = false;
91
return this._openSocket();
92
}
93
94
/** Graceful client-initiated close — does not auto-reconnect. */
95
close (code = 1000, reason = "Client closed")
96
{
97
this._intentionalClose = true;
98
this._clearReconnectTimer();
99
this._reconnectAttempt = 0;
100
const socket = this.socket;
101
this._detach(socket);
102
if (socket && (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING))
103
{
104
try
105
{ socket.close(code, reason); }
106
catch
107
{ /* ignore */ }
108
}
109
this.socket = null;
110
}
111
112
/** Call when an application SESSION (or equivalent) is established so backoff resets. */
113
notifySessionEstablished ()
114
{
115
this._reconnectAttempt = 0;
116
this._clearReconnectTimer();
32
117
}
33
118
34
119
send (payload)
@@ -37,6 +122,106 @@ export class GameSocket
37
122
{ throw new Error("WebSocket is not connected."); }
38
123
this.socket.send(JSON.stringify(payload));
39
124
}
125
126
get reconnecting ()
127
{
128
return this._reconnectTimer != null;
129
}
130
131
_openSocket ()
132
{
133
this._clearReconnectTimer();
134
this._detach(this.socket);
135
const socket = new WebSocket(this.url);
136
this.socket = socket;
137
socket.addEventListener("message", this._boundMessage);
138
socket.addEventListener("close", this._boundClose);
139
socket.addEventListener("error", this._boundError);
140
socket.addEventListener("open", this._boundOpen);
141
142
return new Promise((resolve, reject) =>
143
{
144
const onOpen = () =>
145
{
146
cleanup();
147
resolve();
148
};
149
const onError = () =>
150
{
151
cleanup();
152
reject(new Error("WebSocket failed"));
153
};
154
const cleanup = () =>
155
{
156
socket.removeEventListener("open", onOpen);
157
socket.removeEventListener("error", onError);
158
};
159
socket.addEventListener("open", onOpen, { once: true });
160
socket.addEventListener("error", onError, { once: true });
161
});
162
}
163
164
_detach (socket)
165
{
166
if (!socket)
167
{ return; }
168
socket.removeEventListener("message", this._boundMessage);
169
socket.removeEventListener("close", this._boundClose);
170
socket.removeEventListener("error", this._boundError);
171
socket.removeEventListener("open", this._boundOpen);
172
}
173
174
_clearReconnectTimer ()
175
{
176
if (this._reconnectTimer != null)
177
{
178
clearTimeout(this._reconnectTimer);
179
this._reconnectTimer = null;
180
}
181
}
182
183
_scheduleReconnect (code)
184
{
185
const attempt = this._reconnectAttempt;
186
const delayMs = nextReconnectDelayMs(attempt, {
187
baseMs: this.reconnectBaseMs,
188
maxMs: this.reconnectMaxMs
189
});
190
this._reconnectAttempt = attempt + 1;
191
this.onReconnecting?.({ attempt: this._reconnectAttempt, delayMs, code: code | 0 });
192
this._reconnectTimer = setTimeout(() =>
193
{
194
this._reconnectTimer = null;
195
void this._openSocket().catch(() =>
196
{
197
// open/error path usually also emits close; if not, retry from here
198
if (this._intentionalClose || !this.autoReconnect || this.socket)
199
{ return; }
200
this._scheduleReconnect(code);
201
});
202
}, delayMs);
203
}
204
205
_handleClose (event)
206
{
207
this._detach(event?.target ?? this.socket);
208
if (this.socket === event?.target)
209
{ this.socket = null; }
210
211
this.onClose?.(event);
212
213
const code = event?.code | 0;
214
if (!shouldAutoReconnect(code, {
215
intentional: this._intentionalClose,
216
autoReconnect: this.autoReconnect
217
}))
218
{
219
this._intentionalClose = false;
220
return;
221
}
222
223
this._scheduleReconnect(code);
224
}
40
225
}
41
226
42
227
export function defaultSocketUrl ()
@@ -1,34 +1,119 @@1
/** Close codes that should not trigger auto-reconnect (auth / intentional server kicks). */2
export const NO_AUTO_RECONNECT_CODES = new Set([3
1000, // normal closure (also used by intentional close())4
1001, // going away / server restart5
4000, // logged in elsewhere6
4401, // authentication required7
1011 // authentication / session setup failed8
]);9
10
/**11
* Exponential backoff delay for reconnect attempts.12
* @param {number} attempt zero-based attempt index13
* @param {{ baseMs?: number, maxMs?: number }} [options]14
*/15
export function nextReconnectDelayMs (attempt, { baseMs = 750, maxMs = 20_000 } = {})16
{17
const n = Math.max(0, attempt | 0);18
return Math.min(maxMs, baseMs * (2 ** n));19
}20
21
/**22
* @param {number} code WebSocket close code23
* @param {{ intentional?: boolean, autoReconnect?: boolean }} [options]24
*/25
export function shouldAutoReconnect (code, { intentional = false, autoReconnect = false } = {})26
{27
if (!autoReconnect || intentional)28
{ return false; }29
return !NO_AUTO_RECONNECT_CODES.has(code | 0);30
}31
1
export class GameSocket32
export class GameSocket2
{33
{3
constructor(url, onMessage, { onClose, onError } = {})34
/**35
* @param {string} url36
* @param {(message: object) => void} onMessage37
* @param {{38
* onClose?: (event: CloseEvent) => void,39
* onError?: (event: Event) => void,40
* onOpen?: (event: Event) => void,41
* onReconnecting?: (info: { attempt: number, delayMs: number, code: number }) => void,42
* autoReconnect?: boolean,43
* reconnectBaseMs?: number,44
* reconnectMaxMs?: number45
* }} [options]46
*/47
constructor (url, onMessage, {48
onClose,49
onError,50
onOpen,51
onReconnecting,52
autoReconnect = false,53
reconnectBaseMs = 750,54
reconnectMaxMs = 20_00055
} = {})4
{56
{5
this.url = url;57
this.url = url;6
this.onMessage = onMessage;58
this.onMessage = onMessage;7
this.onClose = onClose;59
this.onClose = onClose;8
this.onError = onError;60
this.onError = onError;61
this.onOpen = onOpen;62
this.onReconnecting = onReconnecting;63
this.autoReconnect = !!autoReconnect;64
this.reconnectBaseMs = reconnectBaseMs;65
this.reconnectMaxMs = reconnectMaxMs;9
this.socket = null;66
this.socket = null;10
}67
this._intentionalClose = false;11
68
this._reconnectAttempt = 0;12
connect ()69
this._reconnectTimer = null;13
{70
this._boundMessage = (event) =>14
this.socket = new WebSocket(this.url);15
this.socket.addEventListener("message", (event) =>16
{71
{17
this.onMessage(JSON.parse(event.data));72
this.onMessage(JSON.parse(event.data));18
});73
};19
this.socket.addEventListener("close", (event) =>74
this._boundClose = (event) =>20
{75
{21
this.onClose?.(event);76
this._handleClose(event);22
});77
};23
this.socket.addEventListener("error", (event) =>78
this._boundError = (event) =>24
{79
{25
this.onError?.(event);80
this.onError?.(event);26
});81
};27
return new Promise((resolve, reject) =>82
this._boundOpen = (event) =>28
{83
{29
this.socket.addEventListener("open", resolve, { once: true });84
this.onOpen?.(event);30
this.socket.addEventListener("error", () => reject(new Error("WebSocket failed")), { once: true });85
};31
});86
}87
88
connect ()89
{90
this._intentionalClose = false;91
return this._openSocket();92
}93
94
/** Graceful client-initiated close — does not auto-reconnect. */95
close (code = 1000, reason = "Client closed")96
{97
this._intentionalClose = true;98
this._clearReconnectTimer();99
this._reconnectAttempt = 0;100
const socket = this.socket;101
this._detach(socket);102
if (socket && (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING))103
{104
try105
{ socket.close(code, reason); }106
catch107
{ /* ignore */ }108
}109
this.socket = null;110
}111
112
/** Call when an application SESSION (or equivalent) is established so backoff resets. */113
notifySessionEstablished ()114
{115
this._reconnectAttempt = 0;116
this._clearReconnectTimer();32
}117
}33
118
34
send (payload)119
send (payload)@@ -37,6 +122,106 @@ export class GameSocket37
{ throw new Error("WebSocket is not connected."); }122
{ throw new Error("WebSocket is not connected."); }38
this.socket.send(JSON.stringify(payload));123
this.socket.send(JSON.stringify(payload));39
}124
}125
126
get reconnecting ()127
{128
return this._reconnectTimer != null;129
}130
131
_openSocket ()132
{133
this._clearReconnectTimer();134
this._detach(this.socket);135
const socket = new WebSocket(this.url);136
this.socket = socket;137
socket.addEventListener("message", this._boundMessage);138
socket.addEventListener("close", this._boundClose);139
socket.addEventListener("error", this._boundError);140
socket.addEventListener("open", this._boundOpen);141
142
return new Promise((resolve, reject) =>143
{144
const onOpen = () =>145
{146
cleanup();147
resolve();148
};149
const onError = () =>150
{151
cleanup();152
reject(new Error("WebSocket failed"));153
};154
const cleanup = () =>155
{156
socket.removeEventListener("open", onOpen);157
socket.removeEventListener("error", onError);158
};159
socket.addEventListener("open", onOpen, { once: true });160
socket.addEventListener("error", onError, { once: true });161
});162
}163
164
_detach (socket)165
{166
if (!socket)167
{ return; }168
socket.removeEventListener("message", this._boundMessage);169
socket.removeEventListener("close", this._boundClose);170
socket.removeEventListener("error", this._boundError);171
socket.removeEventListener("open", this._boundOpen);172
}173
174
_clearReconnectTimer ()175
{176
if (this._reconnectTimer != null)177
{178
clearTimeout(this._reconnectTimer);179
this._reconnectTimer = null;180
}181
}182
183
_scheduleReconnect (code)184
{185
const attempt = this._reconnectAttempt;186
const delayMs = nextReconnectDelayMs(attempt, {187
baseMs: this.reconnectBaseMs,188
maxMs: this.reconnectMaxMs189
});190
this._reconnectAttempt = attempt + 1;191
this.onReconnecting?.({ attempt: this._reconnectAttempt, delayMs, code: code | 0 });192
this._reconnectTimer = setTimeout(() =>193
{194
this._reconnectTimer = null;195
void this._openSocket().catch(() =>196
{197
// open/error path usually also emits close; if not, retry from here198
if (this._intentionalClose || !this.autoReconnect || this.socket)199
{ return; }200
this._scheduleReconnect(code);201
});202
}, delayMs);203
}204
205
_handleClose (event)206
{207
this._detach(event?.target ?? this.socket);208
if (this.socket === event?.target)209
{ this.socket = null; }210
211
this.onClose?.(event);212
213
const code = event?.code | 0;214
if (!shouldAutoReconnect(code, {215
intentional: this._intentionalClose,216
autoReconnect: this.autoReconnect217
}))218
{219
this._intentionalClose = false;220
return;221
}222
223
this._scheduleReconnect(code);224
}40
}225
}41
226
42
export function defaultSocketUrl ()227
export function defaultSocketUrl ()@@ -0,0 +1,25 @@
1
import test from "node:test";
2
import assert from "node:assert/strict";
3
import {
4
nextReconnectDelayMs,
5
shouldAutoReconnect,
6
NO_AUTO_RECONNECT_CODES
7
} from "../src/net/socket.js";
8
9
test("nextReconnectDelayMs grows exponentially and caps", () =>
10
{
11
assert.equal(nextReconnectDelayMs(0, { baseMs: 750, maxMs: 20_000 }), 750);
12
assert.equal(nextReconnectDelayMs(1, { baseMs: 750, maxMs: 20_000 }), 1500);
13
assert.equal(nextReconnectDelayMs(2, { baseMs: 750, maxMs: 20_000 }), 3000);
14
assert.equal(nextReconnectDelayMs(10, { baseMs: 750, maxMs: 20_000 }), 20_000);
15
assert.equal(nextReconnectDelayMs(-1, { baseMs: 500, maxMs: 1000 }), 500);
16
});
17
18
test("shouldAutoReconnect skips intentional, auth, and restart closes", () =>
19
{
20
assert.equal(shouldAutoReconnect(1006, { autoReconnect: true }), true);
21
assert.equal(shouldAutoReconnect(1006, { autoReconnect: false }), false);
22
assert.equal(shouldAutoReconnect(1006, { autoReconnect: true, intentional: true }), false);
23
for (const code of NO_AUTO_RECONNECT_CODES)
24
{ assert.equal(shouldAutoReconnect(code, { autoReconnect: true }), false); }
25
});
@@ -0,0 +1,25 @@1
import test from "node:test";2
import assert from "node:assert/strict";3
import {4
nextReconnectDelayMs,5
shouldAutoReconnect,6
NO_AUTO_RECONNECT_CODES7
} from "../src/net/socket.js";8
9
test("nextReconnectDelayMs grows exponentially and caps", () =>10
{11
assert.equal(nextReconnectDelayMs(0, { baseMs: 750, maxMs: 20_000 }), 750);12
assert.equal(nextReconnectDelayMs(1, { baseMs: 750, maxMs: 20_000 }), 1500);13
assert.equal(nextReconnectDelayMs(2, { baseMs: 750, maxMs: 20_000 }), 3000);14
assert.equal(nextReconnectDelayMs(10, { baseMs: 750, maxMs: 20_000 }), 20_000);15
assert.equal(nextReconnectDelayMs(-1, { baseMs: 500, maxMs: 1000 }), 500);16
});17
18
test("shouldAutoReconnect skips intentional, auth, and restart closes", () =>19
{20
assert.equal(shouldAutoReconnect(1006, { autoReconnect: true }), true);21
assert.equal(shouldAutoReconnect(1006, { autoReconnect: false }), false);22
assert.equal(shouldAutoReconnect(1006, { autoReconnect: true, intentional: true }), false);23
for (const code of NO_AUTO_RECONNECT_CODES)24
{ assert.equal(shouldAutoReconnect(code, { autoReconnect: true }), false); }25
});@@ -1,4 +1,5 @@
1
1
import { WebSocketServer } from "ws";
2
import { startWebSocketKeepalive } from "./wsKeepalive.js";
2
3
import { MessageType, GAIT } from "../../../shared/protocol/constants.js";
3
4
import { chunkKey, parseChunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
4
5
import { VISIBLE_CHUNK_RADIUS, STATIC_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
@@ -19,6 +20,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
19
20
const wss = new WebSocketServer({ server: httpServer, path: "/ws" });
20
21
const sessions = new Map();
21
22
let draining = false;
23
const keepalive = startWebSocketKeepalive(wss);
22
24
23
25
subscribeConsole((entry) =>
24
26
{
@@ -2545,6 +2547,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
2545
2547
async shutdown ()
2546
2548
{
2547
2549
draining = true;
2550
keepalive.stop();
2548
2551
await Promise.all([...sessions.values()].map(async (session) =>
2549
2552
{
2550
2553
await sendAsync(session, {
@@ -1,4 +1,5 @@1
import { WebSocketServer } from "ws";1
import { WebSocketServer } from "ws";2
import { startWebSocketKeepalive } from "./wsKeepalive.js";2
import { MessageType, GAIT } from "../../../shared/protocol/constants.js";3
import { MessageType, GAIT } from "../../../shared/protocol/constants.js";3
import { chunkKey, parseChunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";4
import { chunkKey, parseChunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";4
import { VISIBLE_CHUNK_RADIUS, STATIC_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";5
import { VISIBLE_CHUNK_RADIUS, STATIC_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";@@ -19,6 +20,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,19
const wss = new WebSocketServer({ server: httpServer, path: "/ws" });20
const wss = new WebSocketServer({ server: httpServer, path: "/ws" });20
const sessions = new Map();21
const sessions = new Map();21
let draining = false;22
let draining = false;23
const keepalive = startWebSocketKeepalive(wss);22
24
23
subscribeConsole((entry) =>25
subscribeConsole((entry) =>24
{26
{@@ -2545,6 +2547,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,2545
async shutdown ()2547
async shutdown ()2546
{2548
{2547
draining = true;2549
draining = true;2550
keepalive.stop();2548
await Promise.all([...sessions.values()].map(async (session) =>2551
await Promise.all([...sessions.values()].map(async (session) =>2549
{2552
{2550
await sendAsync(session, {2553
await sendAsync(session, {@@ -0,0 +1,77 @@
1
/**
2
* Protocol-level WebSocket ping/pong keepalive so idle editor (and play)
3
* sessions are not killed by proxies that drop quiet connections.
4
*
5
* Browsers auto-reply to WebSocket ping frames; the `ws` library surfaces pong.
6
*/
7
8
export const DEFAULT_WS_PING_INTERVAL_MS = 25_000;
9
10
/**
11
* @param {import("ws").WebSocketServer} wss
12
* @param {{ intervalMs?: number, setIntervalFn?: typeof setInterval, clearIntervalFn?: typeof clearInterval }} [options]
13
* @returns {{ stop: () => void, intervalMs: number }}
14
*/
15
export function startWebSocketKeepalive (wss, options = {})
16
{
17
const intervalMs = options.intervalMs ?? DEFAULT_WS_PING_INTERVAL_MS;
18
const setIntervalFn = options.setIntervalFn ?? setInterval;
19
const clearIntervalFn = options.clearIntervalFn ?? clearInterval;
20
21
const onConnection = (socket) =>
22
{
23
socket.isAlive = true;
24
socket.on("pong", () =>
25
{
26
socket.isAlive = true;
27
});
28
};
29
30
wss.on("connection", onConnection);
31
for (const socket of wss.clients)
32
{ onConnection(socket); }
33
34
const interval = setIntervalFn(() =>
35
{
36
for (const socket of wss.clients)
37
{
38
if (socket.isAlive === false)
39
{
40
socket.terminate();
41
continue;
42
}
43
socket.isAlive = false;
44
try
45
{ socket.ping(); }
46
catch
47
{
48
try
49
{ socket.terminate(); }
50
catch
51
{ /* ignore */ }
52
}
53
}
54
}, intervalMs);
55
56
if (typeof interval?.unref === "function")
57
{ interval.unref(); }
58
59
const onClose = () =>
60
{
61
stop();
62
};
63
wss.on("close", onClose);
64
65
let stopped = false;
66
function stop ()
67
{
68
if (stopped)
69
{ return; }
70
stopped = true;
71
clearIntervalFn(interval);
72
wss.off("connection", onConnection);
73
wss.off("close", onClose);
74
}
75
76
return { stop, intervalMs };
77
}
@@ -0,0 +1,77 @@1
/**2
* Protocol-level WebSocket ping/pong keepalive so idle editor (and play)3
* sessions are not killed by proxies that drop quiet connections.4
*5
* Browsers auto-reply to WebSocket ping frames; the `ws` library surfaces pong.6
*/7
8
export const DEFAULT_WS_PING_INTERVAL_MS = 25_000;9
10
/**11
* @param {import("ws").WebSocketServer} wss12
* @param {{ intervalMs?: number, setIntervalFn?: typeof setInterval, clearIntervalFn?: typeof clearInterval }} [options]13
* @returns {{ stop: () => void, intervalMs: number }}14
*/15
export function startWebSocketKeepalive (wss, options = {})16
{17
const intervalMs = options.intervalMs ?? DEFAULT_WS_PING_INTERVAL_MS;18
const setIntervalFn = options.setIntervalFn ?? setInterval;19
const clearIntervalFn = options.clearIntervalFn ?? clearInterval;20
21
const onConnection = (socket) =>22
{23
socket.isAlive = true;24
socket.on("pong", () =>25
{26
socket.isAlive = true;27
});28
};29
30
wss.on("connection", onConnection);31
for (const socket of wss.clients)32
{ onConnection(socket); }33
34
const interval = setIntervalFn(() =>35
{36
for (const socket of wss.clients)37
{38
if (socket.isAlive === false)39
{40
socket.terminate();41
continue;42
}43
socket.isAlive = false;44
try45
{ socket.ping(); }46
catch47
{48
try49
{ socket.terminate(); }50
catch51
{ /* ignore */ }52
}53
}54
}, intervalMs);55
56
if (typeof interval?.unref === "function")57
{ interval.unref(); }58
59
const onClose = () =>60
{61
stop();62
};63
wss.on("close", onClose);64
65
let stopped = false;66
function stop ()67
{68
if (stopped)69
{ return; }70
stopped = true;71
clearIntervalFn(interval);72
wss.off("connection", onConnection);73
wss.off("close", onClose);74
}75
76
return { stop, intervalMs };77
}@@ -0,0 +1,87 @@
1
import test from "node:test";
2
import assert from "node:assert/strict";
3
import { EventEmitter } from "node:events";
4
import {
5
startWebSocketKeepalive,
6
DEFAULT_WS_PING_INTERVAL_MS
7
} from "../src/gateway/wsKeepalive.js";
8
9
class FakeSocket extends EventEmitter
10
{
11
constructor ()
12
{
13
super();
14
this.isAlive = undefined;
15
this.pingCount = 0;
16
this.terminated = false;
17
}
18
19
ping ()
20
{
21
this.pingCount += 1;
22
}
23
24
terminate ()
25
{
26
this.terminated = true;
27
}
28
}
29
30
class FakeWss extends EventEmitter
31
{
32
constructor ()
33
{
34
super();
35
this.clients = new Set();
36
}
37
}
38
39
test("startWebSocketKeepalive pings open sockets and terminates stale ones", () =>
40
{
41
const wss = new FakeWss();
42
const timers = [];
43
const keepalive = startWebSocketKeepalive(wss, {
44
intervalMs: 1000,
45
setIntervalFn (fn, ms)
46
{
47
timers.push({ fn, ms });
48
return 1;
49
},
50
clearIntervalFn () {}
51
});
52
assert.equal(keepalive.intervalMs, 1000);
53
assert.equal(DEFAULT_WS_PING_INTERVAL_MS, 25_000);
54
assert.equal(timers.length, 1);
55
56
const live = new FakeSocket();
57
const stale = new FakeSocket();
58
wss.clients.add(live);
59
wss.clients.add(stale);
60
wss.emit("connection", live);
61
wss.emit("connection", stale);
62
assert.equal(live.isAlive, true);
63
assert.equal(stale.isAlive, true);
64
65
live.emit("pong");
66
assert.equal(live.isAlive, true);
67
68
// First tick: mark not alive and ping
69
timers[0].fn();
70
assert.equal(live.isAlive, false);
71
assert.equal(stale.isAlive, false);
72
assert.equal(live.pingCount, 1);
73
assert.equal(stale.pingCount, 1);
74
assert.equal(stale.terminated, false);
75
76
live.emit("pong");
77
assert.equal(live.isAlive, true);
78
79
// Second tick: live gets pinged again; stale (no pong) is terminated
80
timers[0].fn();
81
assert.equal(live.terminated, false);
82
assert.equal(stale.terminated, true);
83
assert.equal(live.pingCount, 2);
84
85
keepalive.stop();
86
keepalive.stop(); // idempotent
87
});
@@ -0,0 +1,87 @@1
import test from "node:test";2
import assert from "node:assert/strict";3
import { EventEmitter } from "node:events";4
import {5
startWebSocketKeepalive,6
DEFAULT_WS_PING_INTERVAL_MS7
} from "../src/gateway/wsKeepalive.js";8
9
class FakeSocket extends EventEmitter10
{11
constructor ()12
{13
super();14
this.isAlive = undefined;15
this.pingCount = 0;16
this.terminated = false;17
}18
19
ping ()20
{21
this.pingCount += 1;22
}23
24
terminate ()25
{26
this.terminated = true;27
}28
}29
30
class FakeWss extends EventEmitter31
{32
constructor ()33
{34
super();35
this.clients = new Set();36
}37
}38
39
test("startWebSocketKeepalive pings open sockets and terminates stale ones", () =>40
{41
const wss = new FakeWss();42
const timers = [];43
const keepalive = startWebSocketKeepalive(wss, {44
intervalMs: 1000,45
setIntervalFn (fn, ms)46
{47
timers.push({ fn, ms });48
return 1;49
},50
clearIntervalFn () {}51
});52
assert.equal(keepalive.intervalMs, 1000);53
assert.equal(DEFAULT_WS_PING_INTERVAL_MS, 25_000);54
assert.equal(timers.length, 1);55
56
const live = new FakeSocket();57
const stale = new FakeSocket();58
wss.clients.add(live);59
wss.clients.add(stale);60
wss.emit("connection", live);61
wss.emit("connection", stale);62
assert.equal(live.isAlive, true);63
assert.equal(stale.isAlive, true);64
65
live.emit("pong");66
assert.equal(live.isAlive, true);67
68
// First tick: mark not alive and ping69
timers[0].fn();70
assert.equal(live.isAlive, false);71
assert.equal(stale.isAlive, false);72
assert.equal(live.pingCount, 1);73
assert.equal(stale.pingCount, 1);74
assert.equal(stale.terminated, false);75
76
live.emit("pong");77
assert.equal(live.isAlive, true);78
79
// Second tick: live gets pinged again; stale (no pong) is terminated80
timers[0].fn();81
assert.equal(live.terminated, false);82
assert.equal(stale.terminated, true);83
assert.equal(live.pingCount, 2);84
85
keepalive.stop();86
keepalive.stop(); // idempotent87
});