BlueGit

timfa questward

Add midnight deploy with always-pull systemd install, editor console, and dimension settings modal.

On every service start (including crash recovery) hard-reset, pull, and npm install so fixed commits can recover bad builds; stream server logs to the world editor Console tab.

timfa Tim Falken · pushed by timfa

Authored 2026-08-27 · 2 months ago

Hash
cc95fee2ab4276b9c9b7837727df21f0fadfd4c1
Parent
e3c5ae2f
22 files changed +1189 −51
client/editor.html +48 −30
@@ -20,6 +20,7 @@
20 20 <span class="dimension-picker-label">Dimension</span>
21 21 <div id="dimension-combo"></div>
22 22 <p id="dimension-purge-hint" class="hint" hidden></p>
23 <button id="open-dimension-settings" type="button">Dimension settings…</button>
23 24 </div>
24 25 <div class="nav">
25 26 <button id="north" type="button">Up</button>
@@ -29,33 +30,6 @@
29 30 </div>
30 31 <button id="south" type="button">Down</button>
31 32 </div>
32 <div id="dimension-settings" class="dimension-settings">
33 <label>Display name <input id="dim-display-name" type="text" autocomplete="off"></label>
34 <label>Lighting
35 <select id="dim-lighting">
36 <option value="dayNight">Day / night</option>
37 <option value="alwaysLit">Always lit</option>
38 <option value="alwaysDark">Always dark</option>
39 </select>
40 </label>
41 <label>Season
42 <select id="dim-season">
43 <option value="auto">Auto (calendar)</option>
44 <option value="summer">Summer</option>
45 <option value="spring">Spring</option>
46 <option value="autumn">Autumn</option>
47 <option value="winter">Winter</option>
48 </select>
49 </label>
50 <label>Default ground
51 <select id="dim-default-ground"></select>
52 </label>
53 <div class="dimension-settings-actions">
54 <button id="dim-save" type="button">Save dimension</button>
55 <button id="dim-delete" type="button" hidden>Delete dimension</button>
56 <button id="dim-cancel-delete" type="button" hidden>Cancel deletion</button>
57 </div>
58 </div>
59 33 <p>Tool: <strong id="tool"></strong></p>
60 34 <div class="palette">
61 35 <button id="open-palette" type="button">Select block…</button>
@@ -78,9 +52,18 @@
78 52 <button id="open-dialogues" type="button">Dialogues</button>
79 53 <p class="hint">The red border is the chunk you are editing. Paint only inside the border. Hover shows tile config tooltips. Right-click a spawner to edit or remove it. Spawners are editor-only markers (invisible and non-blocking in play). Mouse wheel zooms; Shift+wheel cycles visual states (seasonal outdoor tiles cycle spring/summer/fall/winter and update Season preview).</p>
80 54 </aside>
81 <section id="changelog-wrap">
82 <h2>Changelog</h2>
83 <div id="changelog"></div>
55 <section id="side-panels">
56 <div class="side-panel-tabs" role="tablist">
57 <button type="button" class="side-panel-tab active" data-side-panel="changelog" role="tab" aria-selected="true">Changelog</button>
58 <button type="button" class="side-panel-tab" data-side-panel="console" role="tab" aria-selected="false">Console</button>
59 </div>
60 <div id="changelog-wrap" class="side-panel-body" data-side-panel-body="changelog">
61 <div id="changelog"></div>
62 </div>
63 <div id="console-wrap" class="side-panel-body" data-side-panel-body="console" hidden>
64 <pre id="editor-console" aria-live="polite"></pre>
65 <button id="console-clear" type="button">Clear</button>
66 </div>
84 67 </section>
85 68 <div id="selection-border" aria-hidden="true"></div>
86 69 <div id="tile-tooltip" hidden></div>
@@ -208,6 +191,41 @@
208 191 </div>
209 192 </div>
210 193
194 <div id="dimension-settings-backdrop" hidden></div>
195 <div id="dimension-settings-modal" hidden role="dialog" aria-modal="true" aria-labelledby="dimension-settings-title">
196 <header>
197 <h2 id="dimension-settings-title">Dimension settings</h2>
198 <button id="dimension-settings-close" type="button">Close</button>
199 </header>
200 <div id="dimension-settings" class="dimension-settings">
201 <label>Display name <input id="dim-display-name" type="text" autocomplete="off"></label>
202 <label>Lighting
203 <select id="dim-lighting">
204 <option value="dayNight">Day / night</option>
205 <option value="alwaysLit">Always lit</option>
206 <option value="alwaysDark">Always dark</option>
207 </select>
208 </label>
209 <label>Season
210 <select id="dim-season">
211 <option value="auto">Auto (calendar)</option>
212 <option value="summer">Summer</option>
213 <option value="spring">Spring</option>
214 <option value="autumn">Autumn</option>
215 <option value="winter">Winter</option>
216 </select>
217 </label>
218 <label>Default ground
219 <select id="dim-default-ground"></select>
220 </label>
221 <div class="dimension-settings-actions">
222 <button id="dim-save" type="button">Save dimension</button>
223 <button id="dim-delete" type="button" hidden>Delete dimension</button>
224 <button id="dim-cancel-delete" type="button" hidden>Cancel deletion</button>
225 </div>
226 </div>
227 </div>
228
211 229 <div id="unsaved-chunk-backdrop" hidden></div>
212 230 <div id="unsaved-chunk-modal" hidden role="dialog" aria-modal="true" aria-labelledby="unsaved-chunk-title">
213 231 <header>
@@ -20,6 +20,7 @@
20 <span class="dimension-picker-label">Dimension</span>
20 <span class="dimension-picker-label">Dimension</span>
21 <div id="dimension-combo"></div>
21 <div id="dimension-combo"></div>
22 <p id="dimension-purge-hint" class="hint" hidden></p>
22 <p id="dimension-purge-hint" class="hint" hidden></p>
23 <button id="open-dimension-settings" type="button">Dimension settings…</button>
23 </div>
24 </div>
24 <div class="nav">
25 <div class="nav">
25 <button id="north" type="button">Up</button>
26 <button id="north" type="button">Up</button>
@@ -29,33 +30,6 @@
29 </div>
30 </div>
30 <button id="south" type="button">Down</button>
31 <button id="south" type="button">Down</button>
31 </div>
32 </div>
32 <div id="dimension-settings" class="dimension-settings">
33 <label>Display name <input id="dim-display-name" type="text" autocomplete="off"></label>
34 <label>Lighting
35 <select id="dim-lighting">
36 <option value="dayNight">Day / night</option>
37 <option value="alwaysLit">Always lit</option>
38 <option value="alwaysDark">Always dark</option>
39 </select>
40 </label>
41 <label>Season
42 <select id="dim-season">
43 <option value="auto">Auto (calendar)</option>
44 <option value="summer">Summer</option>
45 <option value="spring">Spring</option>
46 <option value="autumn">Autumn</option>
47 <option value="winter">Winter</option>
48 </select>
49 </label>
50 <label>Default ground
51 <select id="dim-default-ground"></select>
52 </label>
53 <div class="dimension-settings-actions">
54 <button id="dim-save" type="button">Save dimension</button>
55 <button id="dim-delete" type="button" hidden>Delete dimension</button>
56 <button id="dim-cancel-delete" type="button" hidden>Cancel deletion</button>
57 </div>
58 </div>
59 <p>Tool: <strong id="tool"></strong></p>
33 <p>Tool: <strong id="tool"></strong></p>
60 <div class="palette">
34 <div class="palette">
61 <button id="open-palette" type="button">Select block…</button>
35 <button id="open-palette" type="button">Select block…</button>
@@ -78,9 +52,18 @@
78 <button id="open-dialogues" type="button">Dialogues</button>
52 <button id="open-dialogues" type="button">Dialogues</button>
79 <p class="hint">The red border is the chunk you are editing. Paint only inside the border. Hover shows tile config tooltips. Right-click a spawner to edit or remove it. Spawners are editor-only markers (invisible and non-blocking in play). Mouse wheel zooms; Shift+wheel cycles visual states (seasonal outdoor tiles cycle spring/summer/fall/winter and update Season preview).</p>
53 <p class="hint">The red border is the chunk you are editing. Paint only inside the border. Hover shows tile config tooltips. Right-click a spawner to edit or remove it. Spawners are editor-only markers (invisible and non-blocking in play). Mouse wheel zooms; Shift+wheel cycles visual states (seasonal outdoor tiles cycle spring/summer/fall/winter and update Season preview).</p>
80 </aside>
54 </aside>
81 <section id="changelog-wrap">
55 <section id="side-panels">
82 <h2>Changelog</h2>
56 <div class="side-panel-tabs" role="tablist">
83 <div id="changelog"></div>
57 <button type="button" class="side-panel-tab active" data-side-panel="changelog" role="tab" aria-selected="true">Changelog</button>
58 <button type="button" class="side-panel-tab" data-side-panel="console" role="tab" aria-selected="false">Console</button>
59 </div>
60 <div id="changelog-wrap" class="side-panel-body" data-side-panel-body="changelog">
61 <div id="changelog"></div>
62 </div>
63 <div id="console-wrap" class="side-panel-body" data-side-panel-body="console" hidden>
64 <pre id="editor-console" aria-live="polite"></pre>
65 <button id="console-clear" type="button">Clear</button>
66 </div>
84 </section>
67 </section>
85 <div id="selection-border" aria-hidden="true"></div>
68 <div id="selection-border" aria-hidden="true"></div>
86 <div id="tile-tooltip" hidden></div>
69 <div id="tile-tooltip" hidden></div>
@@ -208,6 +191,41 @@
208 </div>
191 </div>
209 </div>
192 </div>
210
193
194 <div id="dimension-settings-backdrop" hidden></div>
195 <div id="dimension-settings-modal" hidden role="dialog" aria-modal="true" aria-labelledby="dimension-settings-title">
196 <header>
197 <h2 id="dimension-settings-title">Dimension settings</h2>
198 <button id="dimension-settings-close" type="button">Close</button>
199 </header>
200 <div id="dimension-settings" class="dimension-settings">
201 <label>Display name <input id="dim-display-name" type="text" autocomplete="off"></label>
202 <label>Lighting
203 <select id="dim-lighting">
204 <option value="dayNight">Day / night</option>
205 <option value="alwaysLit">Always lit</option>
206 <option value="alwaysDark">Always dark</option>
207 </select>
208 </label>
209 <label>Season
210 <select id="dim-season">
211 <option value="auto">Auto (calendar)</option>
212 <option value="summer">Summer</option>
213 <option value="spring">Spring</option>
214 <option value="autumn">Autumn</option>
215 <option value="winter">Winter</option>
216 </select>
217 </label>
218 <label>Default ground
219 <select id="dim-default-ground"></select>
220 </label>
221 <div class="dimension-settings-actions">
222 <button id="dim-save" type="button">Save dimension</button>
223 <button id="dim-delete" type="button" hidden>Delete dimension</button>
224 <button id="dim-cancel-delete" type="button" hidden>Cancel deletion</button>
225 </div>
226 </div>
227 </div>
228
211 <div id="unsaved-chunk-backdrop" hidden></div>
229 <div id="unsaved-chunk-backdrop" hidden></div>
212 <div id="unsaved-chunk-modal" hidden role="dialog" aria-modal="true" aria-labelledby="unsaved-chunk-title">
230 <div id="unsaved-chunk-modal" hidden role="dialog" aria-modal="true" aria-labelledby="unsaved-chunk-title">
213 <header>
231 <header>
client/src/editor/main.js +79 −3
@@ -76,12 +76,82 @@ let applyInFlight = false;
76 76 const EDITOR_ZOOM_MIN = 0.25;
77 77 const EDITOR_ZOOM_MAX = 8;
78 78 const EDITOR_ZOOM_STEP = 1.12;
79 const CONSOLE_MAX_LINES = 2000;
79 80
80 81 function $ (id)
81 82 {
82 83 return document.getElementById(id);
83 84 }
84 85
86 function formatConsoleTime (t)
87 {
88 try
89 { return new Date(t).toLocaleTimeString(); }
90 catch
91 { return ""; }
92 }
93
94 function appendConsoleLine (entry, { scroll = true } = {})
95 {
96 const pre = $("editor-console");
97 if (!pre || !entry)
98 { return; }
99 const line = document.createElement("div");
100 const level = entry.level || "info";
101 line.className = `console-${level}`;
102 line.textContent = `[${formatConsoleTime(entry.t)}] ${entry.text ?? ""}`;
103 pre.append(line);
104 while (pre.childElementCount > CONSOLE_MAX_LINES)
105 { pre.firstChild?.remove(); }
106 if (scroll)
107 { pre.scrollTop = pre.scrollHeight; }
108 }
109
110 function applyConsoleSnapshot (lines)
111 {
112 const pre = $("editor-console");
113 if (!pre)
114 { return; }
115 pre.replaceChildren();
116 for (const entry of lines ?? [])
117 { appendConsoleLine(entry, { scroll: false }); }
118 pre.scrollTop = pre.scrollHeight;
119 }
120
121 function initSidePanelTabs ()
122 {
123 const tabs = document.querySelectorAll(".side-panel-tab");
124 const bodies = document.querySelectorAll("[data-side-panel-body]");
125 function activate (name)
126 {
127 for (const tab of tabs)
128 {
129 const on = tab.dataset.sidePanel === name;
130 tab.classList.toggle("active", on);
131 tab.setAttribute("aria-selected", on ? "true" : "false");
132 }
133 for (const body of bodies)
134 { body.hidden = body.dataset.sidePanelBody !== name; }
135 if (name === "console")
136 {
137 const pre = $("editor-console");
138 if (pre)
139 { pre.scrollTop = pre.scrollHeight; }
140 }
141 }
142 for (const tab of tabs)
143 {
144 tab.addEventListener("click", () => activate(tab.dataset.sidePanel));
145 }
146 $("console-clear")?.addEventListener("click", () =>
147 {
148 const pre = $("editor-console");
149 if (pre)
150 { pre.replaceChildren(); }
151 });
152 activate("changelog");
153 }
154
85 155 function selectedToolLabel ()
86 156 {
87 157 if (tool.kind === "erase")
@@ -628,12 +698,12 @@ function layoutScene ()
628 698 {
629 699 const header = document.querySelector("body > header");
630 700 const aside = document.querySelector("body > aside");
631 const changelog = $("changelog-wrap");
701 const sidePanels = $("side-panels") || $("changelog-wrap");
632 702 const top = header.offsetHeight;
633 703 aside.style.top = `${top}px`;
634 changelog.style.top = `${top}px`;
704 sidePanels.style.top = `${top}px`;
635 705 const left = aside.offsetWidth;
636 const right = changelog.offsetWidth;
706 const right = sidePanels.offsetWidth;
637 707 const width = Math.max(64, window.innerWidth - left - right);
638 708 const height = Math.max(64, window.innerHeight - top);
639 709 scene.position.x = left;
@@ -943,11 +1013,16 @@ async function main ()
943 1013 {
944 1014 $("who").textContent = `${message.authSubject}${message.isAdmin ? " · admin" : ""}`;
945 1015 socket.send({ type: MessageType.editorLoadSettings });
1016 socket.send({ type: MessageType.editorConsoleSubscribe });
946 1017 requestDimensions();
947 1018 loadNeighborhood(0, 0);
948 1019 }
949 1020 else if (message.type === MessageType.editorSettings)
950 1021 { settingsModal.handleMessage(message); }
1022 else if (message.type === MessageType.editorConsoleSnapshot)
1023 { applyConsoleSnapshot(message.lines); }
1024 else if (message.type === MessageType.editorConsoleLine)
1025 { appendConsoleLine(message.line); }
951 1026 else if (message.type === MessageType.editorDimensions)
952 1027 {
953 1028 applyDimensionsList(message);
@@ -1055,6 +1130,7 @@ async function main ()
1055 1130 });
1056 1131 questsModal = initQuestsModal({ socket, MessageType });
1057 1132 dialoguesModal = initDialoguesModal({ socket, MessageType });
1133 initSidePanelTabs();
1058 1134 game.startGame();
1059 1135 await socket.connect();
1060 1136 }
@@ -76,12 +76,82 @@ let applyInFlight = false;
76const EDITOR_ZOOM_MIN = 0.25;
76const EDITOR_ZOOM_MIN = 0.25;
77const EDITOR_ZOOM_MAX = 8;
77const EDITOR_ZOOM_MAX = 8;
78const EDITOR_ZOOM_STEP = 1.12;
78const EDITOR_ZOOM_STEP = 1.12;
79const CONSOLE_MAX_LINES = 2000;
79
80
80function $ (id)
81function $ (id)
81{
82{
82 return document.getElementById(id);
83 return document.getElementById(id);
83}
84}
84
85
86function formatConsoleTime (t)
87{
88 try
89 { return new Date(t).toLocaleTimeString(); }
90 catch
91 { return ""; }
92}
93
94function appendConsoleLine (entry, { scroll = true } = {})
95{
96 const pre = $("editor-console");
97 if (!pre || !entry)
98 { return; }
99 const line = document.createElement("div");
100 const level = entry.level || "info";
101 line.className = `console-${level}`;
102 line.textContent = `[${formatConsoleTime(entry.t)}] ${entry.text ?? ""}`;
103 pre.append(line);
104 while (pre.childElementCount > CONSOLE_MAX_LINES)
105 { pre.firstChild?.remove(); }
106 if (scroll)
107 { pre.scrollTop = pre.scrollHeight; }
108}
109
110function applyConsoleSnapshot (lines)
111{
112 const pre = $("editor-console");
113 if (!pre)
114 { return; }
115 pre.replaceChildren();
116 for (const entry of lines ?? [])
117 { appendConsoleLine(entry, { scroll: false }); }
118 pre.scrollTop = pre.scrollHeight;
119}
120
121function initSidePanelTabs ()
122{
123 const tabs = document.querySelectorAll(".side-panel-tab");
124 const bodies = document.querySelectorAll("[data-side-panel-body]");
125 function activate (name)
126 {
127 for (const tab of tabs)
128 {
129 const on = tab.dataset.sidePanel === name;
130 tab.classList.toggle("active", on);
131 tab.setAttribute("aria-selected", on ? "true" : "false");
132 }
133 for (const body of bodies)
134 { body.hidden = body.dataset.sidePanelBody !== name; }
135 if (name === "console")
136 {
137 const pre = $("editor-console");
138 if (pre)
139 { pre.scrollTop = pre.scrollHeight; }
140 }
141 }
142 for (const tab of tabs)
143 {
144 tab.addEventListener("click", () => activate(tab.dataset.sidePanel));
145 }
146 $("console-clear")?.addEventListener("click", () =>
147 {
148 const pre = $("editor-console");
149 if (pre)
150 { pre.replaceChildren(); }
151 });
152 activate("changelog");
153}
154
85function selectedToolLabel ()
155function selectedToolLabel ()
86{
156{
87 if (tool.kind === "erase")
157 if (tool.kind === "erase")
@@ -628,12 +698,12 @@ function layoutScene ()
628{
698{
629 const header = document.querySelector("body > header");
699 const header = document.querySelector("body > header");
630 const aside = document.querySelector("body > aside");
700 const aside = document.querySelector("body > aside");
631 const changelog = $("changelog-wrap");
701 const sidePanels = $("side-panels") || $("changelog-wrap");
632 const top = header.offsetHeight;
702 const top = header.offsetHeight;
633 aside.style.top = `${top}px`;
703 aside.style.top = `${top}px`;
634 changelog.style.top = `${top}px`;
704 sidePanels.style.top = `${top}px`;
635 const left = aside.offsetWidth;
705 const left = aside.offsetWidth;
636 const right = changelog.offsetWidth;
706 const right = sidePanels.offsetWidth;
637 const width = Math.max(64, window.innerWidth - left - right);
707 const width = Math.max(64, window.innerWidth - left - right);
638 const height = Math.max(64, window.innerHeight - top);
708 const height = Math.max(64, window.innerHeight - top);
639 scene.position.x = left;
709 scene.position.x = left;
@@ -943,11 +1013,16 @@ async function main ()
943 {
1013 {
944 $("who").textContent = `${message.authSubject}${message.isAdmin ? " · admin" : ""}`;
1014 $("who").textContent = `${message.authSubject}${message.isAdmin ? " · admin" : ""}`;
945 socket.send({ type: MessageType.editorLoadSettings });
1015 socket.send({ type: MessageType.editorLoadSettings });
1016 socket.send({ type: MessageType.editorConsoleSubscribe });
946 requestDimensions();
1017 requestDimensions();
947 loadNeighborhood(0, 0);
1018 loadNeighborhood(0, 0);
948 }
1019 }
949 else if (message.type === MessageType.editorSettings)
1020 else if (message.type === MessageType.editorSettings)
950 { settingsModal.handleMessage(message); }
1021 { settingsModal.handleMessage(message); }
1022 else if (message.type === MessageType.editorConsoleSnapshot)
1023 { applyConsoleSnapshot(message.lines); }
1024 else if (message.type === MessageType.editorConsoleLine)
1025 { appendConsoleLine(message.line); }
951 else if (message.type === MessageType.editorDimensions)
1026 else if (message.type === MessageType.editorDimensions)
952 {
1027 {
953 applyDimensionsList(message);
1028 applyDimensionsList(message);
@@ -1055,6 +1130,7 @@ async function main ()
1055 });
1130 });
1056 questsModal = initQuestsModal({ socket, MessageType });
1131 questsModal = initQuestsModal({ socket, MessageType });
1057 dialoguesModal = initDialoguesModal({ socket, MessageType });
1132 dialoguesModal = initDialoguesModal({ socket, MessageType });
1133 initSidePanelTabs();
1058 game.startGame();
1134 game.startGame();
1059 await socket.connect();
1135 await socket.connect();
1060}
1136}
client/src/editor/settingsModal.js +23 −4
@@ -977,7 +977,7 @@ function escapeHtml (text)
977 977 }
978 978
979 979 /**
980 * Aside panel for the selected dimension's lighting / season / ground / soft-delete.
980 * Modal for the selected dimension's lighting / season / ground / soft-delete.
981 981 */
982 982 export function initDimensionSettings ({
983 983 socket,
@@ -997,6 +997,10 @@ export function initDimensionSettings ({
997 997 const deleteBtn = document.getElementById("dim-delete");
998 998 const cancelBtn = document.getElementById("dim-cancel-delete");
999 999 const panel = document.getElementById("dimension-settings");
1000 const modal = document.getElementById("dimension-settings-modal");
1001 const backdrop = document.getElementById("dimension-settings-backdrop");
1002 const closeBtn = document.getElementById("dimension-settings-close");
1003 const openBtn = document.getElementById("open-dimension-settings");
1000 1004
1001 1005 if (ground && !ground.options.length)
1002 1006 {
@@ -1009,14 +1013,22 @@ export function initDimensionSettings ({
1009 1013 }
1010 1014 }
1011 1015
1016 function setOpen (open)
1017 {
1018 if (modal)
1019 { modal.hidden = !open; }
1020 if (backdrop)
1021 { backdrop.hidden = !open; }
1022 if (open)
1023 { refresh(); }
1024 }
1025
1012 1026 function refresh ()
1013 1027 {
1014 1028 const id = getSelectedDimensionId?.() ?? OVERWORLD_ID;
1015 1029 const record = getDimensionRecord?.(id);
1016 1030 const overworld = isOverworld?.(id) ?? id === OVERWORLD_ID;
1017 1031 const softDeleted = record?.deletedAt != null;
1018 if (panel)
1019 { panel.hidden = false; }
1020 1032 if (displayName)
1021 1033 {
1022 1034 displayName.value = record?.displayName ?? id;
@@ -1046,8 +1058,14 @@ export function initDimensionSettings ({
1046 1058 }
1047 1059 if (cancelBtn)
1048 1060 { cancelBtn.hidden = !softDeleted; }
1061 if (panel)
1062 { panel.hidden = false; }
1049 1063 }
1050 1064
1065 openBtn?.addEventListener("click", () => setOpen(true));
1066 closeBtn?.addEventListener("click", () => setOpen(false));
1067 backdrop?.addEventListener("click", () => setOpen(false));
1068
1051 1069 saveBtn?.addEventListener("click", () =>
1052 1070 {
1053 1071 const id = getSelectedDimensionId?.();
@@ -1083,5 +1101,6 @@ export function initDimensionSettings ({
1083 1101 socket.send({ type: MessageType.editorCancelDimensionDeletion, dimensionId: id });
1084 1102 });
1085 1103
1086 return { refresh };
1104 setOpen(false);
1105 return { refresh, open: () => setOpen(true), close: () => setOpen(false) };
1087 1106 }
@@ -977,7 +977,7 @@ function escapeHtml (text)
977}
977}
978
978
979/**
979/**
980 * Aside panel for the selected dimension's lighting / season / ground / soft-delete.
980 * Modal for the selected dimension's lighting / season / ground / soft-delete.
981 */
981 */
982export function initDimensionSettings ({
982export function initDimensionSettings ({
983 socket,
983 socket,
@@ -997,6 +997,10 @@ export function initDimensionSettings ({
997 const deleteBtn = document.getElementById("dim-delete");
997 const deleteBtn = document.getElementById("dim-delete");
998 const cancelBtn = document.getElementById("dim-cancel-delete");
998 const cancelBtn = document.getElementById("dim-cancel-delete");
999 const panel = document.getElementById("dimension-settings");
999 const panel = document.getElementById("dimension-settings");
1000 const modal = document.getElementById("dimension-settings-modal");
1001 const backdrop = document.getElementById("dimension-settings-backdrop");
1002 const closeBtn = document.getElementById("dimension-settings-close");
1003 const openBtn = document.getElementById("open-dimension-settings");
1000
1004
1001 if (ground && !ground.options.length)
1005 if (ground && !ground.options.length)
1002 {
1006 {
@@ -1009,14 +1013,22 @@ export function initDimensionSettings ({
1009 }
1013 }
1010 }
1014 }
1011
1015
1016 function setOpen (open)
1017 {
1018 if (modal)
1019 { modal.hidden = !open; }
1020 if (backdrop)
1021 { backdrop.hidden = !open; }
1022 if (open)
1023 { refresh(); }
1024 }
1025
1012 function refresh ()
1026 function refresh ()
1013 {
1027 {
1014 const id = getSelectedDimensionId?.() ?? OVERWORLD_ID;
1028 const id = getSelectedDimensionId?.() ?? OVERWORLD_ID;
1015 const record = getDimensionRecord?.(id);
1029 const record = getDimensionRecord?.(id);
1016 const overworld = isOverworld?.(id) ?? id === OVERWORLD_ID;
1030 const overworld = isOverworld?.(id) ?? id === OVERWORLD_ID;
1017 const softDeleted = record?.deletedAt != null;
1031 const softDeleted = record?.deletedAt != null;
1018 if (panel)
1019 { panel.hidden = false; }
1020 if (displayName)
1032 if (displayName)
1021 {
1033 {
1022 displayName.value = record?.displayName ?? id;
1034 displayName.value = record?.displayName ?? id;
@@ -1046,8 +1058,14 @@ export function initDimensionSettings ({
1046 }
1058 }
1047 if (cancelBtn)
1059 if (cancelBtn)
1048 { cancelBtn.hidden = !softDeleted; }
1060 { cancelBtn.hidden = !softDeleted; }
1061 if (panel)
1062 { panel.hidden = false; }
1049 }
1063 }
1050
1064
1065 openBtn?.addEventListener("click", () => setOpen(true));
1066 closeBtn?.addEventListener("click", () => setOpen(false));
1067 backdrop?.addEventListener("click", () => setOpen(false));
1068
1051 saveBtn?.addEventListener("click", () =>
1069 saveBtn?.addEventListener("click", () =>
1052 {
1070 {
1053 const id = getSelectedDimensionId?.();
1071 const id = getSelectedDimensionId?.();
@@ -1083,5 +1101,6 @@ export function initDimensionSettings ({
1083 socket.send({ type: MessageType.editorCancelDimensionDeletion, dimensionId: id });
1101 socket.send({ type: MessageType.editorCancelDimensionDeletion, dimensionId: id });
1084 });
1102 });
1085
1103
1086 return { refresh };
1104 setOpen(false);
1105 return { refresh, open: () => setOpen(true), close: () => setOpen(false) };
1087}
1106}
client/src/play/main.js +5 −0
@@ -1162,6 +1162,7 @@ async function main ()
1162 1162 closeCreateModal();
1163 1163 startPlay(message);
1164 1164 inventory?.setLocalCharacterId(message.characterId);
1165 toasts?.applyRestartStatus?.(message.restartStatus);
1165 1166 socket.send({ type: MessageType.requestQuests });
1166 1167 break;
1167 1168 case MessageType.chunkSnapshot:
@@ -1298,6 +1299,10 @@ async function main ()
1298 1299 view.setWorldSeason(message.worldTime?.season);
1299 1300 chat?.syncSettings();
1300 1301 }
1302 toasts?.applyRestartStatus?.(message.restartStatus);
1303 break;
1304 case MessageType.restartStatus:
1305 toasts?.applyRestartStatus?.(message.restartStatus);
1301 1306 break;
1302 1307 case MessageType.chatBubble:
1303 1308 chat?.showBubble(message);
@@ -1162,6 +1162,7 @@ async function main ()
1162 closeCreateModal();
1162 closeCreateModal();
1163 startPlay(message);
1163 startPlay(message);
1164 inventory?.setLocalCharacterId(message.characterId);
1164 inventory?.setLocalCharacterId(message.characterId);
1165 toasts?.applyRestartStatus?.(message.restartStatus);
1165 socket.send({ type: MessageType.requestQuests });
1166 socket.send({ type: MessageType.requestQuests });
1166 break;
1167 break;
1167 case MessageType.chunkSnapshot:
1168 case MessageType.chunkSnapshot:
@@ -1298,6 +1299,10 @@ async function main ()
1298 view.setWorldSeason(message.worldTime?.season);
1299 view.setWorldSeason(message.worldTime?.season);
1299 chat?.syncSettings();
1300 chat?.syncSettings();
1300 }
1301 }
1302 toasts?.applyRestartStatus?.(message.restartStatus);
1303 break;
1304 case MessageType.restartStatus:
1305 toasts?.applyRestartStatus?.(message.restartStatus);
1301 break;
1306 break;
1302 case MessageType.chatBubble:
1307 case MessageType.chatBubble:
1303 chat?.showBubble(message);
1308 chat?.showBubble(message);
client/src/play/toasts.js +100 −1
@@ -1,5 +1,8 @@
1 import { restartCountdownMessage } from "/shared/deploy/schedule.js";
2
1 3 const DEFAULT_DURATION_MS = 3500;
2 4 const LEAVE_MS = 280;
5 const PERSISTENT_RESTART_ID = "server-restart";
3 6
4 7 /**
5 8 * Temporary top-of-screen toast messages (play HUD).
@@ -7,10 +10,19 @@ const LEAVE_MS = 280;
7 10 export function initToasts ()
8 11 {
9 12 const root = document.getElementById("toast-stack");
13 /** @type {Map<string, { el: HTMLElement, timer: number | null }>} */
14 const persistent = new Map();
15 let restartTick = null;
16 let restartScheduledAt = null;
17
10 18 if (!root)
11 19 {
12 20 return {
13 21 show ()
22 {},
23 clearPersistent ()
24 {},
25 applyRestartStatus ()
14 26 {}
15 27 };
16 28 }
@@ -54,5 +66,92 @@ export function initToasts ()
54 66 window.setTimeout(dismiss, durationMs);
55 67 }
56 68
57 return { show };
69 function clearPersistent (id)
70 {
71 const entry = persistent.get(id);
72 if (!entry)
73 { return; }
74 persistent.delete(id);
75 entry.el.classList.remove("toast-visible");
76 entry.el.classList.add("toast-leaving");
77 window.setTimeout(() => entry.el.remove(), LEAVE_MS);
78 }
79
80 function showPersistent (id, text)
81 {
82 const message = String(text ?? "").trim();
83 if (!message)
84 {
85 clearPersistent(id);
86 return;
87 }
88 let entry = persistent.get(id);
89 if (!entry)
90 {
91 const el = document.createElement("div");
92 el.className = "toast toast-persistent";
93 el.setAttribute("role", "status");
94 el.dataset.toastId = id;
95 root.appendChild(el);
96 entry = { el };
97 persistent.set(id, entry);
98 requestAnimationFrame(() =>
99 {
100 el.classList.add("toast-visible");
101 });
102 }
103 entry.el.textContent = message;
104 }
105
106 function stopRestartCountdown ()
107 {
108 if (restartTick != null)
109 {
110 window.clearInterval(restartTick);
111 restartTick = null;
112 }
113 restartScheduledAt = null;
114 clearPersistent(PERSISTENT_RESTART_ID);
115 }
116
117 function refreshRestartToast ()
118 {
119 if (restartScheduledAt == null)
120 { return; }
121 const remaining = restartScheduledAt - Date.now();
122 if (remaining <= 0)
123 {
124 showPersistent(PERSISTENT_RESTART_ID, "Server restart for a game update is starting…");
125 return;
126 }
127 showPersistent(PERSISTENT_RESTART_ID, restartCountdownMessage(remaining));
128 }
129
130 /**
131 * @param {{ scheduled?: boolean, warning?: boolean, scheduledAt?: number | null } | null | undefined} status
132 */
133 function applyRestartStatus (status)
134 {
135 if (!status?.scheduled || !status.scheduledAt)
136 {
137 stopRestartCountdown();
138 return;
139 }
140 if (!status.warning)
141 {
142 stopRestartCountdown();
143 return;
144 }
145 restartScheduledAt = Number(status.scheduledAt);
146 refreshRestartToast();
147 if (restartTick == null)
148 { restartTick = window.setInterval(refreshRestartToast, 1000); }
149 }
150
151 return {
152 show,
153 showPersistent,
154 clearPersistent,
155 applyRestartStatus
156 };
58 157 }
@@ -1,5 +1,8 @@
1import { restartCountdownMessage } from "/shared/deploy/schedule.js";
2
1const DEFAULT_DURATION_MS = 3500;
3const DEFAULT_DURATION_MS = 3500;
2const LEAVE_MS = 280;
4const LEAVE_MS = 280;
5const PERSISTENT_RESTART_ID = "server-restart";
3
6
4/**
7/**
5 * Temporary top-of-screen toast messages (play HUD).
8 * Temporary top-of-screen toast messages (play HUD).
@@ -7,10 +10,19 @@ const LEAVE_MS = 280;
7export function initToasts ()
10export function initToasts ()
8{
11{
9 const root = document.getElementById("toast-stack");
12 const root = document.getElementById("toast-stack");
13 /** @type {Map<string, { el: HTMLElement, timer: number | null }>} */
14 const persistent = new Map();
15 let restartTick = null;
16 let restartScheduledAt = null;
17
10 if (!root)
18 if (!root)
11 {
19 {
12 return {
20 return {
13 show ()
21 show ()
22 {},
23 clearPersistent ()
24 {},
25 applyRestartStatus ()
14 {}
26 {}
15 };
27 };
16 }
28 }
@@ -54,5 +66,92 @@ export function initToasts ()
54 window.setTimeout(dismiss, durationMs);
66 window.setTimeout(dismiss, durationMs);
55 }
67 }
56
68
57 return { show };
69 function clearPersistent (id)
70 {
71 const entry = persistent.get(id);
72 if (!entry)
73 { return; }
74 persistent.delete(id);
75 entry.el.classList.remove("toast-visible");
76 entry.el.classList.add("toast-leaving");
77 window.setTimeout(() => entry.el.remove(), LEAVE_MS);
78 }
79
80 function showPersistent (id, text)
81 {
82 const message = String(text ?? "").trim();
83 if (!message)
84 {
85 clearPersistent(id);
86 return;
87 }
88 let entry = persistent.get(id);
89 if (!entry)
90 {
91 const el = document.createElement("div");
92 el.className = "toast toast-persistent";
93 el.setAttribute("role", "status");
94 el.dataset.toastId = id;
95 root.appendChild(el);
96 entry = { el };
97 persistent.set(id, entry);
98 requestAnimationFrame(() =>
99 {
100 el.classList.add("toast-visible");
101 });
102 }
103 entry.el.textContent = message;
104 }
105
106 function stopRestartCountdown ()
107 {
108 if (restartTick != null)
109 {
110 window.clearInterval(restartTick);
111 restartTick = null;
112 }
113 restartScheduledAt = null;
114 clearPersistent(PERSISTENT_RESTART_ID);
115 }
116
117 function refreshRestartToast ()
118 {
119 if (restartScheduledAt == null)
120 { return; }
121 const remaining = restartScheduledAt - Date.now();
122 if (remaining <= 0)
123 {
124 showPersistent(PERSISTENT_RESTART_ID, "Server restart for a game update is starting…");
125 return;
126 }
127 showPersistent(PERSISTENT_RESTART_ID, restartCountdownMessage(remaining));
128 }
129
130 /**
131 * @param {{ scheduled?: boolean, warning?: boolean, scheduledAt?: number | null } | null | undefined} status
132 */
133 function applyRestartStatus (status)
134 {
135 if (!status?.scheduled || !status.scheduledAt)
136 {
137 stopRestartCountdown();
138 return;
139 }
140 if (!status.warning)
141 {
142 stopRestartCountdown();
143 return;
144 }
145 restartScheduledAt = Number(status.scheduledAt);
146 refreshRestartToast();
147 if (restartTick == null)
148 { restartTick = window.setInterval(refreshRestartToast, 1000); }
149 }
150
151 return {
152 show,
153 showPersistent,
154 clearPersistent,
155 applyRestartStatus
156 };
58}
157}
client/ui/editor.css +88 −4
@@ -28,18 +28,65 @@ body > aside {
28 28 border-right: 1px solid #2c3340;
29 29 }
30 30
31 #changelog-wrap {
31 #side-panels {
32 32 position: absolute;
33 33 right: 0;
34 34 top: 56px;
35 width: 280px;
35 width: 320px;
36 36 bottom: 0;
37 overflow: auto;
38 padding: 0.75rem;
37 display: flex;
38 flex-direction: column;
39 39 box-sizing: border-box;
40 40 background: #1a1e26;
41 41 border-left: 1px solid #2c3340;
42 42 }
43 .side-panel-tabs {
44 display: flex;
45 gap: 0;
46 border-bottom: 1px solid #2c3340;
47 flex: 0 0 auto;
48 }
49 .side-panel-tab {
50 flex: 1 1 0;
51 border: 0;
52 border-radius: 0;
53 background: transparent;
54 color: #9aa3b2;
55 padding: 0.55rem 0.4rem;
56 cursor: pointer;
57 }
58 .side-panel-tab.active {
59 color: #e8e4d9;
60 background: #222833;
61 box-shadow: inset 0 -2px 0 #6a8cbf;
62 }
63 .side-panel-body {
64 flex: 1 1 auto;
65 min-height: 0;
66 overflow: auto;
67 padding: 0.75rem;
68 box-sizing: border-box;
69 }
70 #editor-console {
71 margin: 0;
72 padding: 0.4rem;
73 min-height: 12rem;
74 max-height: calc(100% - 2.5rem);
75 overflow: auto;
76 font: 0.72rem/1.35 ui-monospace, Consolas, monospace;
77 white-space: pre-wrap;
78 word-break: break-word;
79 background: #0e1116;
80 border: 1px solid #2c3340;
81 color: #c8d0dc;
82 }
83 #editor-console .console-warn { color: #e0c070; }
84 #editor-console .console-error { color: #f0a0a0; }
85 #editor-console .console-debug { color: #7a8494; }
86 #console-clear {
87 margin-top: 0.5rem;
88 width: 100%;
89 }
43 90
44 91 .nav, .palette {
45 92 display: flex;
@@ -201,6 +248,43 @@ button:disabled {
201 248 margin: 0;
202 249 font-size: 1.1rem;
203 250 }
251 #dimension-settings-backdrop {
252 position: fixed;
253 inset: 0;
254 background: rgba(0, 0, 0, 0.62);
255 z-index: 29;
256 }
257 #dimension-settings-modal {
258 position: fixed;
259 left: 50%;
260 top: 50%;
261 transform: translate(-50%, -50%);
262 z-index: 30;
263 width: min(420px, 92vw);
264 padding: 1rem 1.1rem;
265 background: #161a22;
266 border: 1px solid #3a4250;
267 box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
268 }
269 #dimension-settings-modal header {
270 display: flex;
271 align-items: center;
272 justify-content: space-between;
273 gap: 0.75rem;
274 margin: 0 0 0.75rem;
275 padding: 0;
276 border: 0;
277 }
278 #dimension-settings-modal h2 {
279 margin: 0;
280 font-size: 1.1rem;
281 }
282 #dimension-settings-modal .dimension-settings {
283 margin: 0;
284 padding: 0;
285 border: 0;
286 background: transparent;
287 }
204 288 .unsaved-chunk-actions {
205 289 display: flex;
206 290 justify-content: flex-end;
@@ -28,18 +28,65 @@ body > aside {
28 border-right: 1px solid #2c3340;
28 border-right: 1px solid #2c3340;
29}
29}
30
30
31#changelog-wrap {
31#side-panels {
32 position: absolute;
32 position: absolute;
33 right: 0;
33 right: 0;
34 top: 56px;
34 top: 56px;
35 width: 280px;
35 width: 320px;
36 bottom: 0;
36 bottom: 0;
37 overflow: auto;
37 display: flex;
38 padding: 0.75rem;
38 flex-direction: column;
39 box-sizing: border-box;
39 box-sizing: border-box;
40 background: #1a1e26;
40 background: #1a1e26;
41 border-left: 1px solid #2c3340;
41 border-left: 1px solid #2c3340;
42}
42}
43.side-panel-tabs {
44 display: flex;
45 gap: 0;
46 border-bottom: 1px solid #2c3340;
47 flex: 0 0 auto;
48}
49.side-panel-tab {
50 flex: 1 1 0;
51 border: 0;
52 border-radius: 0;
53 background: transparent;
54 color: #9aa3b2;
55 padding: 0.55rem 0.4rem;
56 cursor: pointer;
57}
58.side-panel-tab.active {
59 color: #e8e4d9;
60 background: #222833;
61 box-shadow: inset 0 -2px 0 #6a8cbf;
62}
63.side-panel-body {
64 flex: 1 1 auto;
65 min-height: 0;
66 overflow: auto;
67 padding: 0.75rem;
68 box-sizing: border-box;
69}
70#editor-console {
71 margin: 0;
72 padding: 0.4rem;
73 min-height: 12rem;
74 max-height: calc(100% - 2.5rem);
75 overflow: auto;
76 font: 0.72rem/1.35 ui-monospace, Consolas, monospace;
77 white-space: pre-wrap;
78 word-break: break-word;
79 background: #0e1116;
80 border: 1px solid #2c3340;
81 color: #c8d0dc;
82}
83#editor-console .console-warn { color: #e0c070; }
84#editor-console .console-error { color: #f0a0a0; }
85#editor-console .console-debug { color: #7a8494; }
86#console-clear {
87 margin-top: 0.5rem;
88 width: 100%;
89}
43
90
44.nav, .palette {
91.nav, .palette {
45 display: flex;
92 display: flex;
@@ -201,6 +248,43 @@ button:disabled {
201 margin: 0;
248 margin: 0;
202 font-size: 1.1rem;
249 font-size: 1.1rem;
203}
250}
251#dimension-settings-backdrop {
252 position: fixed;
253 inset: 0;
254 background: rgba(0, 0, 0, 0.62);
255 z-index: 29;
256}
257#dimension-settings-modal {
258 position: fixed;
259 left: 50%;
260 top: 50%;
261 transform: translate(-50%, -50%);
262 z-index: 30;
263 width: min(420px, 92vw);
264 padding: 1rem 1.1rem;
265 background: #161a22;
266 border: 1px solid #3a4250;
267 box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
268}
269#dimension-settings-modal header {
270 display: flex;
271 align-items: center;
272 justify-content: space-between;
273 gap: 0.75rem;
274 margin: 0 0 0.75rem;
275 padding: 0;
276 border: 0;
277}
278#dimension-settings-modal h2 {
279 margin: 0;
280 font-size: 1.1rem;
281}
282#dimension-settings-modal .dimension-settings {
283 margin: 0;
284 padding: 0;
285 border: 0;
286 background: transparent;
287}
204.unsaved-chunk-actions {
288.unsaved-chunk-actions {
205 display: flex;
289 display: flex;
206 justify-content: flex-end;
290 justify-content: flex-end;
client/ui/play.css +6 −0
@@ -182,6 +182,12 @@ html, body {
182 182 transform: translateY(-4px);
183 183 }
184 184
185 .toast.toast-persistent {
186 border-color: #c9a227;
187 background: rgba(28, 22, 10, 0.96);
188 color: #ffe9a8;
189 }
190
185 191 .panel {
186 192 width: min(420px, 92vw);
187 193 background: #1a1e26;
@@ -182,6 +182,12 @@ html, body {
182 transform: translateY(-4px);
182 transform: translateY(-4px);
183}
183}
184
184
185.toast.toast-persistent {
186 border-color: #c9a227;
187 background: rgba(28, 22, 10, 0.96);
188 color: #ffe9a8;
189}
190
185.panel {
191.panel {
186 width: min(420px, 92vw);
192 width: min(420px, 92vw);
187 background: #1a1e26;
193 background: #1a1e26;
deploy/README.md added +40 −0
@@ -0,0 +1,40 @@
1 # Production deploy (systemd)
2
3 ## Behaviour
4
5 On **every** service start (clean midnight restart, crash, or power loss recovery):
6
7 1. `git fetch` + `git reset --hard origin/<branch>`
8 2. `git pull --ff-only`
9 3. `npm install --omit=dev`
10 4. start `node --experimental-sqlite server/src/index.js`
11
12 Pull-on-crash is intentional so a fixed commit on origin can recover a bad build.
13
14 Player-facing midnight schedule (3-hour countdown toast) still lives in the Node
15 process: it detects that origin is ahead, warns players, then exits cleanly so
16 systemd runs the update script above.
17
18 ## Install on the host
19
20 ```bash
21 cd /srv/tile-mmo/current # or your clone
22 sudo ./deploy/install-service.sh
23 ```
24
25 Optional env overrides:
26
27 | Variable | Default |
28 |----------|---------|
29 | `TILE_MMO_REPO` | parent of `deploy/` |
30 | `TILE_MMO_USER` | `tilemmo` |
31 | `TILE_MMO_GIT_BRANCH` | `master` |
32
33 ## Manual ops
34
35 ```bash
36 sudo systemctl restart tile-mmo
37 journalctl -u tile-mmo -f
38 ```
39
40 Disable the in-process schedule locally with `TILE_MMO_DEPLOY_SCHEDULER=0`.
@@ -0,0 +1,40 @@
1# Production deploy (systemd)
2
3## Behaviour
4
5On **every** service start (clean midnight restart, crash, or power loss recovery):
6
71. `git fetch` + `git reset --hard origin/<branch>`
82. `git pull --ff-only`
93. `npm install --omit=dev`
104. start `node --experimental-sqlite server/src/index.js`
11
12Pull-on-crash is intentional so a fixed commit on origin can recover a bad build.
13
14Player-facing midnight schedule (3-hour countdown toast) still lives in the Node
15process: it detects that origin is ahead, warns players, then exits cleanly so
16systemd runs the update script above.
17
18## Install on the host
19
20```bash
21cd /srv/tile-mmo/current # or your clone
22sudo ./deploy/install-service.sh
23```
24
25Optional env overrides:
26
27| Variable | Default |
28|----------|---------|
29| `TILE_MMO_REPO` | parent of `deploy/` |
30| `TILE_MMO_USER` | `tilemmo` |
31| `TILE_MMO_GIT_BRANCH` | `master` |
32
33## Manual ops
34
35```bash
36sudo systemctl restart tile-mmo
37journalctl -u tile-mmo -f
38```
39
40Disable the in-process schedule locally with `TILE_MMO_DEPLOY_SCHEDULER=0`.
deploy/install-service.sh added +41 −0
@@ -0,0 +1,41 @@
1 #!/usr/bin/env bash
2 # Install and start the Tile MMO systemd unit (run as root on the game host).
3 set -euo pipefail
4
5 SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
6 REPO="${TILE_MMO_REPO:-$(cd "$SCRIPT_DIR/.." && pwd)}"
7 UNIT_SRC="$SCRIPT_DIR/tile-mmo.service"
8 UNIT_DST="/etc/systemd/system/tile-mmo.service"
9 SERVICE_USER="${TILE_MMO_USER:-tilemmo}"
10
11 if [[ "$(id -u)" -ne 0 ]]; then
12 echo "Run as root: sudo $0" >&2
13 exit 1
14 fi
15
16 if [[ ! -f "$UNIT_SRC" ]]; then
17 echo "Missing unit file: $UNIT_SRC" >&2
18 exit 1
19 fi
20
21 chmod +x "$SCRIPT_DIR/start-server.sh" "$SCRIPT_DIR/update-if-requested.mjs" 2>/dev/null || true
22
23 # Rewrite WorkingDirectory / paths for this checkout.
24 tmp="$(mktemp)"
25 sed \
26 -e "s|/srv/tile-mmo/current|$REPO|g" \
27 -e "s|^User=.*|User=$SERVICE_USER|" \
28 -e "s|^Group=.*|Group=$SERVICE_USER|" \
29 "$UNIT_SRC" > "$tmp"
30 install -m 0644 "$tmp" "$UNIT_DST"
31 rm -f "$tmp"
32
33 systemctl daemon-reload
34 systemctl enable tile-mmo.service
35 systemctl restart tile-mmo.service
36 systemctl --no-pager --full status tile-mmo.service || true
37
38 echo
39 echo "Installed $UNIT_DST"
40 echo "Repo: $REPO"
41 echo "Logs: journalctl -u tile-mmo -f"
@@ -0,0 +1,41 @@
1#!/usr/bin/env bash
2# Install and start the Tile MMO systemd unit (run as root on the game host).
3set -euo pipefail
4
5SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
6REPO="${TILE_MMO_REPO:-$(cd "$SCRIPT_DIR/.." && pwd)}"
7UNIT_SRC="$SCRIPT_DIR/tile-mmo.service"
8UNIT_DST="/etc/systemd/system/tile-mmo.service"
9SERVICE_USER="${TILE_MMO_USER:-tilemmo}"
10
11if [[ "$(id -u)" -ne 0 ]]; then
12 echo "Run as root: sudo $0" >&2
13 exit 1
14fi
15
16if [[ ! -f "$UNIT_SRC" ]]; then
17 echo "Missing unit file: $UNIT_SRC" >&2
18 exit 1
19fi
20
21chmod +x "$SCRIPT_DIR/start-server.sh" "$SCRIPT_DIR/update-if-requested.mjs" 2>/dev/null || true
22
23# Rewrite WorkingDirectory / paths for this checkout.
24tmp="$(mktemp)"
25sed \
26 -e "s|/srv/tile-mmo/current|$REPO|g" \
27 -e "s|^User=.*|User=$SERVICE_USER|" \
28 -e "s|^Group=.*|Group=$SERVICE_USER|" \
29 "$UNIT_SRC" > "$tmp"
30install -m 0644 "$tmp" "$UNIT_DST"
31rm -f "$tmp"
32
33systemctl daemon-reload
34systemctl enable tile-mmo.service
35systemctl restart tile-mmo.service
36systemctl --no-pager --full status tile-mmo.service || true
37
38echo
39echo "Installed $UNIT_DST"
40echo "Repo: $REPO"
41echo "Logs: journalctl -u tile-mmo -f"
deploy/start-server.sh added +21 −0
@@ -0,0 +1,21 @@
1 #!/usr/bin/env bash
2 # Production process entrypoint for systemd.
3 # Always updates the tree before starting Node so crash/power-loss recovery
4 # can pick up a fix from origin (intentional — do not skip pull on crash).
5 set -euo pipefail
6
7 REPO="${TILE_MMO_REPO:-$(cd "$(dirname "$0")/.." && pwd)}"
8 BRANCH="${TILE_MMO_GIT_BRANCH:-master}"
9 cd "$REPO"
10
11 echo "[deploy] Working tree: $REPO (branch $BRANCH)"
12 git fetch origin "$BRANCH"
13 git reset --hard "origin/$BRANCH"
14 git clean -fd
15 git pull --ff-only origin "$BRANCH" || true
16
17 echo "[deploy] npm install…"
18 npm install --omit=dev
19
20 echo "[deploy] Starting server…"
21 exec node --experimental-sqlite server/src/index.js
@@ -0,0 +1,21 @@
1#!/usr/bin/env bash
2# Production process entrypoint for systemd.
3# Always updates the tree before starting Node so crash/power-loss recovery
4# can pick up a fix from origin (intentional — do not skip pull on crash).
5set -euo pipefail
6
7REPO="${TILE_MMO_REPO:-$(cd "$(dirname "$0")/.." && pwd)}"
8BRANCH="${TILE_MMO_GIT_BRANCH:-master}"
9cd "$REPO"
10
11echo "[deploy] Working tree: $REPO (branch $BRANCH)"
12git fetch origin "$BRANCH"
13git reset --hard "origin/$BRANCH"
14git clean -fd
15git pull --ff-only origin "$BRANCH" || true
16
17echo "[deploy] npm install…"
18npm install --omit=dev
19
20echo "[deploy] Starting server…"
21exec node --experimental-sqlite server/src/index.js
deploy/tile-mmo.service added +24 −0
@@ -0,0 +1,24 @@
1 [Unit]
2 Description=Tile MMO Server
3 After=network-online.target
4 Wants=network-online.target
5
6 [Service]
7 Type=simple
8 User=tilemmo
9 Group=tilemmo
10 WorkingDirectory=/srv/tile-mmo/current
11 Environment=NODE_ENV=production
12 Environment=TILE_MMO_GIT_BRANCH=master
13 Environment=TILE_MMO_REPO=/srv/tile-mmo/current
14 Environment=TILE_MMO_DATA=/srv/tile-mmo/current/server/data
15 # Every start (including crash recovery) hard-resets, pulls, npm installs, then runs Node.
16 ExecStart=/srv/tile-mmo/current/deploy/start-server.sh
17 Restart=always
18 RestartSec=5s
19 TimeoutStartSec=600s
20 TimeoutStopSec=120s
21 KillSignal=SIGTERM
22
23 [Install]
24 WantedBy=multi-user.target
@@ -0,0 +1,24 @@
1[Unit]
2Description=Tile MMO Server
3After=network-online.target
4Wants=network-online.target
5
6[Service]
7Type=simple
8User=tilemmo
9Group=tilemmo
10WorkingDirectory=/srv/tile-mmo/current
11Environment=NODE_ENV=production
12Environment=TILE_MMO_GIT_BRANCH=master
13Environment=TILE_MMO_REPO=/srv/tile-mmo/current
14Environment=TILE_MMO_DATA=/srv/tile-mmo/current/server/data
15# Every start (including crash recovery) hard-resets, pulls, npm installs, then runs Node.
16ExecStart=/srv/tile-mmo/current/deploy/start-server.sh
17Restart=always
18RestartSec=5s
19TimeoutStartSec=600s
20TimeoutStopSec=120s
21KillSignal=SIGTERM
22
23[Install]
24WantedBy=multi-user.target
deploy/update-if-requested.mjs added +58 −0
@@ -0,0 +1,58 @@
1 #!/usr/bin/env node
2 /**
3 * systemd ExecStartPre helper: pull/ff-only only when a restart manifest
4 * requested a code deployment. Crashes without a manifest never pull.
5 *
6 * Env:
7 * TILE_MMO_REPO — git working tree (default: cwd)
8 * TILE_MMO_DATA — directory containing restart-request.json (default: <repo>/server/data)
9 * TILE_MMO_GIT_BRANCH — remote branch (default: master)
10 */
11 import { spawnSync } from "node:child_process";
12 import { join } from "node:path";
13 import { consumeRestartManifest, restartManifestPath } from "../server/src/deploy/manifest.js";
14
15 const repo = process.env.TILE_MMO_REPO || process.cwd();
16 const dataDir = process.env.TILE_MMO_DATA || join(repo, "server", "data");
17 const branch = process.env.TILE_MMO_GIT_BRANCH || "master";
18 const manifestPath = restartManifestPath(dataDir);
19
20 const manifest = consumeRestartManifest(manifestPath);
21 if (!manifest)
22 {
23 console.log("[deploy] No restart manifest; starting checked-out version.");
24 process.exit(0);
25 }
26
27 console.log("[deploy] Consumed restart manifest:", JSON.stringify(manifest));
28
29 if (!manifest.deployCode)
30 {
31 console.log("[deploy] World-only / non-code restart; skipping git pull.");
32 process.exit(0);
33 }
34
35 function git (args)
36 {
37 const result = spawnSync("git", args, {
38 cwd: repo,
39 stdio: "inherit",
40 windowsHide: true
41 });
42 if (result.status !== 0)
43 {
44 console.error(`[deploy] git ${args.join(" ")} failed with status ${result.status}`);
45 process.exit(result.status ?? 1);
46 }
47 }
48
49 git(["fetch", "origin", branch]);
50 if (manifest.targetCommit)
51 {
52 git(["merge", "--ff-only", manifest.targetCommit]);
53 }
54 else
55 { git(["merge", "--ff-only", `origin/${branch}`]); }
56
57 console.log("[deploy] Fast-forward complete.");
58 process.exit(0);
@@ -0,0 +1,58 @@
1#!/usr/bin/env node
2/**
3 * systemd ExecStartPre helper: pull/ff-only only when a restart manifest
4 * requested a code deployment. Crashes without a manifest never pull.
5 *
6 * Env:
7 * TILE_MMO_REPO — git working tree (default: cwd)
8 * TILE_MMO_DATA — directory containing restart-request.json (default: <repo>/server/data)
9 * TILE_MMO_GIT_BRANCH — remote branch (default: master)
10 */
11import { spawnSync } from "node:child_process";
12import { join } from "node:path";
13import { consumeRestartManifest, restartManifestPath } from "../server/src/deploy/manifest.js";
14
15const repo = process.env.TILE_MMO_REPO || process.cwd();
16const dataDir = process.env.TILE_MMO_DATA || join(repo, "server", "data");
17const branch = process.env.TILE_MMO_GIT_BRANCH || "master";
18const manifestPath = restartManifestPath(dataDir);
19
20const manifest = consumeRestartManifest(manifestPath);
21if (!manifest)
22{
23 console.log("[deploy] No restart manifest; starting checked-out version.");
24 process.exit(0);
25}
26
27console.log("[deploy] Consumed restart manifest:", JSON.stringify(manifest));
28
29if (!manifest.deployCode)
30{
31 console.log("[deploy] World-only / non-code restart; skipping git pull.");
32 process.exit(0);
33}
34
35function git (args)
36{
37 const result = spawnSync("git", args, {
38 cwd: repo,
39 stdio: "inherit",
40 windowsHide: true
41 });
42 if (result.status !== 0)
43 {
44 console.error(`[deploy] git ${args.join(" ")} failed with status ${result.status}`);
45 process.exit(result.status ?? 1);
46 }
47}
48
49git(["fetch", "origin", branch]);
50if (manifest.targetCommit)
51{
52 git(["merge", "--ff-only", manifest.targetCommit]);
53}
54else
55{ git(["merge", "--ff-only", `origin/${branch}`]); }
56
57console.log("[deploy] Fast-forward complete.");
58process.exit(0);
docs/FEATURES.md +5 −5
@@ -52,7 +52,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
52 52 ## World revisions and pending editor saves
53 53
54 54 **Status:** partial
55 **Spec:** Editor chunk saves write a pending world revision. The running process stays pinned to the map revision loaded at startup until an admin **Apply now** (in-process reload). Live world settings do not use this path. Midnight restart/Git deploy is not implemented yet.
55 **Spec:** Editor chunk saves write a pending world revision. The running process stays pinned to the map revision loaded at startup until an admin **Apply now** (in-process reload). Live world settings do not use this path. Code updates use the midnight deploy path (see **Midnight restart and Git deploy**).
56 56 **Code:** `server/src/persistence/worldDb.js` (`ensurePendingRevision`, `promotePendingRevision`)
57 57
58 58 ## World settings
@@ -76,7 +76,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
76 76 ## World editor (client)
77 77
78 78 **Status:** full
79 **Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, hover preview of the selected tool, mouse-wheel zoom (centred on the selected chunk) and Shift+wheel to cycle visual states (for outdoor seasonal tiles: spring/summer/fall/winter, which also updates Season preview), open/closed, per-chunk changelog, night preview slider, **season preview** dropdown, world-settings modal, **Quests** and **Dialogues** buttons under Settings (see docs/QUESTS.md), save chunk and Apply now. **Save chunk** is disabled when clean and **pulses** when the draft is dirty; navigating N/S/E/W with unsaved edits opens a confirm modal (Cancel / Discard / Save). Bottom status bar shows hovered **tile** and **chunk** coordinates. **Select block…** opens a modal with auto-loaded tabs (Ground tiles / Blocks / Spawners — one entry per mob type with mob icon). **Flower** is a single palette entry; each paint rolls a random colour (same as harvest respawn). Hover shows a tooltip of tile/spawner config and highlights a spawner’s spawn range (cyan) and wander range (amber); right-click a spawner opens its config modal. Spawners render as mob icons in the editor only.
79 **Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, hover preview of the selected tool, mouse-wheel zoom (centred on the selected chunk) and Shift+wheel to cycle visual states (for outdoor seasonal tiles: spring/summer/fall/winter, which also updates Season preview), open/closed, right-side **Changelog / Console** tabs (console streams live server output to admins), night preview slider, **season preview** dropdown, world-settings modal, **Dimension settings…** opens a modal (lighting / season / default ground / soft-delete), **Quests** and **Dialogues** buttons under Settings (see docs/QUESTS.md), save chunk and Apply now. **Save chunk** is disabled when clean and **pulses** when the draft is dirty; navigating N/S/E/W with unsaved edits opens a confirm modal (Cancel / Discard / Save). Bottom status bar shows hovered **tile** and **chunk** coordinates. **Select block…** opens a modal with auto-loaded tabs (Ground tiles / Blocks / Spawners — one entry per mob type with mob icon). **Flower** is a single palette entry; each paint rolls a random colour (same as harvest respawn). Hover shows a tooltip of tile/spawner config and highlights a spawner’s spawn range (cyan) and wander range (amber); right-click a spawner opens its config modal. Spawners render as mob icons in the editor only.
80 80 **Code:** `client/editor.html`, `client/src/editor/main.js`, `client/src/editor/paletteModal.js`, `client/src/editor/tileConfigModal.js`, `client/ui/editor.css`
81 81
82 82 ## Per-chunk changelog
@@ -183,9 +183,9 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
183 183
184 184 ## Midnight restart and Git deploy
185 185
186 **Status:** full
187 **Spec:** systemd + manifest-driven Git deploy. Pending world/code changes apply at server-local midnight, with an admin immediate-restart path. Crashes must not pull.
188 **Code:** —
186 **Status:** full
187 **Spec:** The live process periodically `git fetch`es and compares `HEAD` to `origin/<branch>` (default `master`). When the remote is **ahead**, a graceful restart is scheduled for the next **server-local midnight**. From **3 hours before** midnight, every connected player gets a **permanent toast** with a live countdown. At midnight the server writes `server/data/restart-request.json`, force-logs out sessions, unloads/persists the world, and exits. **systemd** (`Restart=always`) relaunches via `deploy/start-server.sh`, which **always** hard-resets to `origin/<branch>`, pulls, runs `npm install`, then starts Node — including after crashes or power loss (intentional, so a fixed commit can recover a bad build). Install with `sudo ./deploy/install-service.sh`. World editor **Console** tab streams live server stdout to admins.
188 **Code:** `shared/deploy/schedule.js`, `server/src/deploy/`, `server/src/index.js`, `server/src/logging/consoleCapture.js`, `deploy/start-server.sh`, `deploy/install-service.sh`, `deploy/tile-mmo.service`, `client/src/play/toasts.js`, `client/src/editor/main.js`, tests in `server/tests/deploy.test.js`
189 189
190 190 ## Spawners
191 191
@@ -52,7 +52,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
52## World revisions and pending editor saves
52## World revisions and pending editor saves
53
53
54**Status:** partial
54**Status:** partial
55**Spec:** Editor chunk saves write a pending world revision. The running process stays pinned to the map revision loaded at startup until an admin **Apply now** (in-process reload). Live world settings do not use this path. Midnight restart/Git deploy is not implemented yet.
55**Spec:** Editor chunk saves write a pending world revision. The running process stays pinned to the map revision loaded at startup until an admin **Apply now** (in-process reload). Live world settings do not use this path. Code updates use the midnight deploy path (see **Midnight restart and Git deploy**).
56**Code:** `server/src/persistence/worldDb.js` (`ensurePendingRevision`, `promotePendingRevision`)
56**Code:** `server/src/persistence/worldDb.js` (`ensurePendingRevision`, `promotePendingRevision`)
57
57
58## World settings
58## World settings
@@ -76,7 +76,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
76## World editor (client)
76## World editor (client)
77
77
78**Status:** full
78**Status:** full
79**Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, hover preview of the selected tool, mouse-wheel zoom (centred on the selected chunk) and Shift+wheel to cycle visual states (for outdoor seasonal tiles: spring/summer/fall/winter, which also updates Season preview), open/closed, per-chunk changelog, night preview slider, **season preview** dropdown, world-settings modal, **Quests** and **Dialogues** buttons under Settings (see docs/QUESTS.md), save chunk and Apply now. **Save chunk** is disabled when clean and **pulses** when the draft is dirty; navigating N/S/E/W with unsaved edits opens a confirm modal (Cancel / Discard / Save). Bottom status bar shows hovered **tile** and **chunk** coordinates. **Select block…** opens a modal with auto-loaded tabs (Ground tiles / Blocks / Spawners — one entry per mob type with mob icon). **Flower** is a single palette entry; each paint rolls a random colour (same as harvest respawn). Hover shows a tooltip of tile/spawner config and highlights a spawner’s spawn range (cyan) and wander range (amber); right-click a spawner opens its config modal. Spawners render as mob icons in the editor only.
79**Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, hover preview of the selected tool, mouse-wheel zoom (centred on the selected chunk) and Shift+wheel to cycle visual states (for outdoor seasonal tiles: spring/summer/fall/winter, which also updates Season preview), open/closed, right-side **Changelog / Console** tabs (console streams live server output to admins), night preview slider, **season preview** dropdown, world-settings modal, **Dimension settings…** opens a modal (lighting / season / default ground / soft-delete), **Quests** and **Dialogues** buttons under Settings (see docs/QUESTS.md), save chunk and Apply now. **Save chunk** is disabled when clean and **pulses** when the draft is dirty; navigating N/S/E/W with unsaved edits opens a confirm modal (Cancel / Discard / Save). Bottom status bar shows hovered **tile** and **chunk** coordinates. **Select block…** opens a modal with auto-loaded tabs (Ground tiles / Blocks / Spawners — one entry per mob type with mob icon). **Flower** is a single palette entry; each paint rolls a random colour (same as harvest respawn). Hover shows a tooltip of tile/spawner config and highlights a spawner’s spawn range (cyan) and wander range (amber); right-click a spawner opens its config modal. Spawners render as mob icons in the editor only.
80**Code:** `client/editor.html`, `client/src/editor/main.js`, `client/src/editor/paletteModal.js`, `client/src/editor/tileConfigModal.js`, `client/ui/editor.css`
80**Code:** `client/editor.html`, `client/src/editor/main.js`, `client/src/editor/paletteModal.js`, `client/src/editor/tileConfigModal.js`, `client/ui/editor.css`
81
81
82## Per-chunk changelog
82## Per-chunk changelog
@@ -183,9 +183,9 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
183
183
184## Midnight restart and Git deploy
184## Midnight restart and Git deploy
185
185
186**Status:** full
186**Status:** full
187**Spec:** systemd + manifest-driven Git deploy. Pending world/code changes apply at server-local midnight, with an admin immediate-restart path. Crashes must not pull.
187**Spec:** The live process periodically `git fetch`es and compares `HEAD` to `origin/<branch>` (default `master`). When the remote is **ahead**, a graceful restart is scheduled for the next **server-local midnight**. From **3 hours before** midnight, every connected player gets a **permanent toast** with a live countdown. At midnight the server writes `server/data/restart-request.json`, force-logs out sessions, unloads/persists the world, and exits. **systemd** (`Restart=always`) relaunches via `deploy/start-server.sh`, which **always** hard-resets to `origin/<branch>`, pulls, runs `npm install`, then starts Node — including after crashes or power loss (intentional, so a fixed commit can recover a bad build). Install with `sudo ./deploy/install-service.sh`. World editor **Console** tab streams live server stdout to admins.
188**Code:** —
188**Code:** `shared/deploy/schedule.js`, `server/src/deploy/`, `server/src/index.js`, `server/src/logging/consoleCapture.js`, `deploy/start-server.sh`, `deploy/install-service.sh`, `deploy/tile-mmo.service`, `client/src/play/toasts.js`, `client/src/editor/main.js`, tests in `server/tests/deploy.test.js`
189
189
190## Spawners
190## Spawners
191
191
server/src/deploy/gitRemote.js added +42 −0
@@ -0,0 +1,42 @@
1 import { execFile } from "node:child_process";
2 import { promisify } from "node:util";
3
4 const execFileAsync = promisify(execFile);
5
6 async function git (repoRoot, args)
7 {
8 const { stdout } = await execFileAsync("git", args, {
9 cwd: repoRoot,
10 windowsHide: true,
11 maxBuffer: 1024 * 1024
12 });
13 return String(stdout ?? "").trim();
14 }
15
16 /**
17 * Non-destructive check: fetch origin and see if remote branch is ahead of HEAD.
18 * @returns {Promise<{ ok: true, ahead: boolean, local: string, remote: string }
19 * | { ok: false, error: string }>}
20 */
21 export async function checkGitRemoteAhead (repoRoot, branch = "master")
22 {
23 try
24 {
25 const local = await git(repoRoot, ["rev-parse", "HEAD"]);
26 await git(repoRoot, ["fetch", "--quiet", "origin", branch]);
27 const remote = await git(repoRoot, ["rev-parse", `origin/${branch}`]);
28 if (!local || !remote)
29 { return { ok: false, error: "Missing git commit hashes." }; }
30 if (local === remote)
31 { return { ok: true, ahead: false, local, remote }; }
32 const counts = await git(repoRoot, ["rev-list", "--left-right", "--count", `HEAD...origin/${branch}`]);
33 // "A\tB" = commits reachable from HEAD not remote, commits from remote not HEAD
34 const parts = counts.split(/\s+/);
35 const behind = Number(parts[1]) || 0;
36 return { ok: true, ahead: behind > 0, local, remote };
37 }
38 catch (error)
39 {
40 return { ok: false, error: error?.message ?? String(error) };
41 }
42 }
@@ -0,0 +1,42 @@
1import { execFile } from "node:child_process";
2import { promisify } from "node:util";
3
4const execFileAsync = promisify(execFile);
5
6async function git (repoRoot, args)
7{
8 const { stdout } = await execFileAsync("git", args, {
9 cwd: repoRoot,
10 windowsHide: true,
11 maxBuffer: 1024 * 1024
12 });
13 return String(stdout ?? "").trim();
14}
15
16/**
17 * Non-destructive check: fetch origin and see if remote branch is ahead of HEAD.
18 * @returns {Promise<{ ok: true, ahead: boolean, local: string, remote: string }
19 * | { ok: false, error: string }>}
20 */
21export async function checkGitRemoteAhead (repoRoot, branch = "master")
22{
23 try
24 {
25 const local = await git(repoRoot, ["rev-parse", "HEAD"]);
26 await git(repoRoot, ["fetch", "--quiet", "origin", branch]);
27 const remote = await git(repoRoot, ["rev-parse", `origin/${branch}`]);
28 if (!local || !remote)
29 { return { ok: false, error: "Missing git commit hashes." }; }
30 if (local === remote)
31 { return { ok: true, ahead: false, local, remote }; }
32 const counts = await git(repoRoot, ["rev-list", "--left-right", "--count", `HEAD...origin/${branch}`]);
33 // "A\tB" = commits reachable from HEAD not remote, commits from remote not HEAD
34 const parts = counts.split(/\s+/);
35 const behind = Number(parts[1]) || 0;
36 return { ok: true, ahead: behind > 0, local, remote };
37 }
38 catch (error)
39 {
40 return { ok: false, error: error?.message ?? String(error) };
41 }
42}
server/src/deploy/manifest.js added +71 −0
@@ -0,0 +1,71 @@
1 import { mkdirSync, renameSync, writeFileSync, unlinkSync, existsSync, readFileSync } from "node:fs";
2 import { dirname, join } from "node:path";
3
4 export const RESTART_MANIFEST_NAME = "restart-request.json";
5
6 export function restartManifestPath (dataDir)
7 {
8 return join(dataDir, RESTART_MANIFEST_NAME);
9 }
10
11 /**
12 * Atomically write a restart request for systemd ExecStartPre.
13 * @param {string} filePath
14 * @param {{
15 * reasons?: string[],
16 * deployCode?: boolean,
17 * targetCommit?: string | null,
18 * pendingWorldRevision?: number | null,
19 * writtenAt?: number
20 * }} payload
21 */
22 export function writeRestartManifest (filePath, payload)
23 {
24 const body = {
25 reasons: Array.isArray(payload.reasons) ? payload.reasons : [],
26 deployCode: !!payload.deployCode,
27 targetCommit: payload.targetCommit ?? null,
28 pendingWorldRevision: payload.pendingWorldRevision ?? null,
29 writtenAt: payload.writtenAt ?? Date.now()
30 };
31 mkdirSync(dirname(filePath), { recursive: true });
32 const tmp = `${filePath}.${process.pid}.tmp`;
33 writeFileSync(tmp, `${JSON.stringify(body, null, 2)}\n`, "utf8");
34 renameSync(tmp, filePath);
35 return body;
36 }
37
38 export function readRestartManifest (filePath)
39 {
40 if (!existsSync(filePath))
41 { return null; }
42 try
43 {
44 const raw = JSON.parse(readFileSync(filePath, "utf8"));
45 if (!raw || typeof raw !== "object")
46 { return null; }
47 return {
48 reasons: Array.isArray(raw.reasons) ? raw.reasons.map(String) : [],
49 deployCode: !!raw.deployCode,
50 targetCommit: raw.targetCommit ? String(raw.targetCommit) : null,
51 pendingWorldRevision: raw.pendingWorldRevision != null
52 ? Number(raw.pendingWorldRevision)
53 : null,
54 writtenAt: Number(raw.writtenAt) || 0
55 };
56 }
57 catch
58 {
59 return null;
60 }
61 }
62
63 export function consumeRestartManifest (filePath)
64 {
65 const manifest = readRestartManifest(filePath);
66 try
67 { unlinkSync(filePath); }
68 catch
69 { /* missing is fine */ }
70 return manifest;
71 }
@@ -0,0 +1,71 @@
1import { mkdirSync, renameSync, writeFileSync, unlinkSync, existsSync, readFileSync } from "node:fs";
2import { dirname, join } from "node:path";
3
4export const RESTART_MANIFEST_NAME = "restart-request.json";
5
6export function restartManifestPath (dataDir)
7{
8 return join(dataDir, RESTART_MANIFEST_NAME);
9}
10
11/**
12 * Atomically write a restart request for systemd ExecStartPre.
13 * @param {string} filePath
14 * @param {{
15 * reasons?: string[],
16 * deployCode?: boolean,
17 * targetCommit?: string | null,
18 * pendingWorldRevision?: number | null,
19 * writtenAt?: number
20 * }} payload
21 */
22export function writeRestartManifest (filePath, payload)
23{
24 const body = {
25 reasons: Array.isArray(payload.reasons) ? payload.reasons : [],
26 deployCode: !!payload.deployCode,
27 targetCommit: payload.targetCommit ?? null,
28 pendingWorldRevision: payload.pendingWorldRevision ?? null,
29 writtenAt: payload.writtenAt ?? Date.now()
30 };
31 mkdirSync(dirname(filePath), { recursive: true });
32 const tmp = `${filePath}.${process.pid}.tmp`;
33 writeFileSync(tmp, `${JSON.stringify(body, null, 2)}\n`, "utf8");
34 renameSync(tmp, filePath);
35 return body;
36}
37
38export function readRestartManifest (filePath)
39{
40 if (!existsSync(filePath))
41 { return null; }
42 try
43 {
44 const raw = JSON.parse(readFileSync(filePath, "utf8"));
45 if (!raw || typeof raw !== "object")
46 { return null; }
47 return {
48 reasons: Array.isArray(raw.reasons) ? raw.reasons.map(String) : [],
49 deployCode: !!raw.deployCode,
50 targetCommit: raw.targetCommit ? String(raw.targetCommit) : null,
51 pendingWorldRevision: raw.pendingWorldRevision != null
52 ? Number(raw.pendingWorldRevision)
53 : null,
54 writtenAt: Number(raw.writtenAt) || 0
55 };
56 }
57 catch
58 {
59 return null;
60 }
61}
62
63export function consumeRestartManifest (filePath)
64{
65 const manifest = readRestartManifest(filePath);
66 try
67 { unlinkSync(filePath); }
68 catch
69 { /* missing is fine */ }
70 return manifest;
71}
server/src/deploy/scheduler.js added +168 −0
@@ -0,0 +1,168 @@
1 import {
2 RESTART_WARN_BEFORE_MS,
3 DEFAULT_DEPLOY_CHECK_MS,
4 nextLocalMidnightMs,
5 isInRestartWarningWindow
6 } from "../../../shared/deploy/schedule.js";
7 import { checkGitRemoteAhead } from "./gitRemote.js";
8
9 /**
10 * Schedules a graceful midnight restart only when origin/<branch> is ahead of HEAD.
11 * Three hours before midnight, clients enter the permanent countdown toast window.
12 */
13 export class DeployScheduler
14 {
15 /**
16 * @param {{
17 * repoRoot: string,
18 * branch?: string,
19 * checkIntervalMs?: number,
20 * warnBeforeMs?: number,
21 * enabled?: boolean,
22 * now?: () => number,
23 * checkRemote?: (repoRoot: string, branch: string) => Promise<object>,
24 * onStatusChange?: (status: object) => void,
25 * onRestartDue?: (status: object) => void
26 * }} options
27 */
28 constructor (options)
29 {
30 this.repoRoot = options.repoRoot;
31 this.branch = options.branch ?? process.env.TILE_MMO_GIT_BRANCH ?? "master";
32 this.checkIntervalMs = Math.max(
33 30_000,
34 Number(options.checkIntervalMs ?? process.env.TILE_MMO_DEPLOY_CHECK_MS) || DEFAULT_DEPLOY_CHECK_MS
35 );
36 this.warnBeforeMs = options.warnBeforeMs ?? RESTART_WARN_BEFORE_MS;
37 this.enabled = options.enabled ?? process.env.TILE_MMO_DEPLOY_SCHEDULER !== "0";
38 this.now = options.now ?? (() => Date.now());
39 this.checkRemote = options.checkRemote ?? checkGitRemoteAhead;
40 this.onStatusChange = options.onStatusChange ?? (() => {});
41 this.onRestartDue = options.onRestartDue ?? (() => {});
42
43 this.scheduledAt = null;
44 this.reasons = [];
45 this.localCommit = null;
46 this.remoteCommit = null;
47 this.warningActive = false;
48 this.restartFired = false;
49 this.#checkTimer = null;
50 this.#tickTimer = null;
51 this.#checking = false;
52 }
53
54 #checkTimer;
55 #tickTimer;
56 #checking;
57
58 start ()
59 {
60 if (!this.enabled)
61 { return; }
62 void this.poll();
63 this.#checkTimer = setInterval(() => { void this.poll(); }, Math.max(30_000, this.checkIntervalMs));
64 this.#tickTimer = setInterval(() => this.tick(), 1000);
65 }
66
67 stop ()
68 {
69 if (this.#checkTimer)
70 { clearInterval(this.#checkTimer); }
71 if (this.#tickTimer)
72 { clearInterval(this.#tickTimer); }
73 this.#checkTimer = null;
74 this.#tickTimer = null;
75 }
76
77 status ()
78 {
79 const now = this.now();
80 const scheduled = this.scheduledAt != null;
81 const warning = scheduled && (
82 this.warningActive || isInRestartWarningWindow(now, this.scheduledAt, this.warnBeforeMs)
83 );
84 return {
85 scheduled,
86 scheduledAt: this.scheduledAt,
87 warning: !!warning,
88 reasons: [...this.reasons],
89 localCommit: this.localCommit,
90 remoteCommit: this.remoteCommit,
91 branch: this.branch,
92 remainingMs: scheduled ? Math.max(0, this.scheduledAt - now) : null
93 };
94 }
95
96 async poll ()
97 {
98 if (!this.enabled || this.#checking || this.restartFired)
99 { return; }
100 this.#checking = true;
101 try
102 {
103 const result = await this.checkRemote(this.repoRoot, this.branch);
104 if (!result?.ok)
105 { return; }
106 this.localCommit = result.local ?? this.localCommit;
107 this.remoteCommit = result.remote ?? this.remoteCommit;
108 if (result.ahead)
109 { this.#scheduleCodeUpdate(); }
110 else if (this.scheduledAt != null && this.reasons.includes("code-update"))
111 { this.#clearSchedule(); }
112 }
113 finally
114 {
115 this.#checking = false;
116 }
117 }
118
119 tick ()
120 {
121 if (!this.enabled || this.restartFired || this.scheduledAt == null)
122 { return; }
123 const now = this.now();
124 const warning = isInRestartWarningWindow(now, this.scheduledAt, this.warnBeforeMs)
125 || now >= this.scheduledAt;
126 if (warning !== this.warningActive)
127 {
128 this.warningActive = warning;
129 this.onStatusChange(this.status());
130 }
131 if (now >= this.scheduledAt)
132 {
133 this.restartFired = true;
134 this.onRestartDue(this.status());
135 }
136 }
137
138 /** Test helper: force a pending midnight restart. */
139 forceScheduleForTests (scheduledAt, reasons = ["code-update"])
140 {
141 this.scheduledAt = scheduledAt;
142 this.reasons = [...reasons];
143 this.warningActive = isInRestartWarningWindow(this.now(), scheduledAt, this.warnBeforeMs);
144 this.onStatusChange(this.status());
145 }
146
147 #scheduleCodeUpdate ()
148 {
149 if (this.scheduledAt != null)
150 { return; }
151 this.scheduledAt = nextLocalMidnightMs(this.now());
152 this.reasons = ["code-update"];
153 this.warningActive = isInRestartWarningWindow(this.now(), this.scheduledAt, this.warnBeforeMs);
154 console.log(
155 `[deploy] origin/${this.branch} is ahead; restart scheduled for ${new Date(this.scheduledAt).toString()}`
156 );
157 this.onStatusChange(this.status());
158 }
159
160 #clearSchedule ()
161 {
162 this.scheduledAt = null;
163 this.reasons = [];
164 this.warningActive = false;
165 console.log("[deploy] Remote no longer ahead; cancelled scheduled restart.");
166 this.onStatusChange(this.status());
167 }
168 }
@@ -0,0 +1,168 @@
1import {
2 RESTART_WARN_BEFORE_MS,
3 DEFAULT_DEPLOY_CHECK_MS,
4 nextLocalMidnightMs,
5 isInRestartWarningWindow
6} from "../../../shared/deploy/schedule.js";
7import { checkGitRemoteAhead } from "./gitRemote.js";
8
9/**
10 * Schedules a graceful midnight restart only when origin/<branch> is ahead of HEAD.
11 * Three hours before midnight, clients enter the permanent countdown toast window.
12 */
13export class DeployScheduler
14{
15 /**
16 * @param {{
17 * repoRoot: string,
18 * branch?: string,
19 * checkIntervalMs?: number,
20 * warnBeforeMs?: number,
21 * enabled?: boolean,
22 * now?: () => number,
23 * checkRemote?: (repoRoot: string, branch: string) => Promise<object>,
24 * onStatusChange?: (status: object) => void,
25 * onRestartDue?: (status: object) => void
26 * }} options
27 */
28 constructor (options)
29 {
30 this.repoRoot = options.repoRoot;
31 this.branch = options.branch ?? process.env.TILE_MMO_GIT_BRANCH ?? "master";
32 this.checkIntervalMs = Math.max(
33 30_000,
34 Number(options.checkIntervalMs ?? process.env.TILE_MMO_DEPLOY_CHECK_MS) || DEFAULT_DEPLOY_CHECK_MS
35 );
36 this.warnBeforeMs = options.warnBeforeMs ?? RESTART_WARN_BEFORE_MS;
37 this.enabled = options.enabled ?? process.env.TILE_MMO_DEPLOY_SCHEDULER !== "0";
38 this.now = options.now ?? (() => Date.now());
39 this.checkRemote = options.checkRemote ?? checkGitRemoteAhead;
40 this.onStatusChange = options.onStatusChange ?? (() => {});
41 this.onRestartDue = options.onRestartDue ?? (() => {});
42
43 this.scheduledAt = null;
44 this.reasons = [];
45 this.localCommit = null;
46 this.remoteCommit = null;
47 this.warningActive = false;
48 this.restartFired = false;
49 this.#checkTimer = null;
50 this.#tickTimer = null;
51 this.#checking = false;
52 }
53
54 #checkTimer;
55 #tickTimer;
56 #checking;
57
58 start ()
59 {
60 if (!this.enabled)
61 { return; }
62 void this.poll();
63 this.#checkTimer = setInterval(() => { void this.poll(); }, Math.max(30_000, this.checkIntervalMs));
64 this.#tickTimer = setInterval(() => this.tick(), 1000);
65 }
66
67 stop ()
68 {
69 if (this.#checkTimer)
70 { clearInterval(this.#checkTimer); }
71 if (this.#tickTimer)
72 { clearInterval(this.#tickTimer); }
73 this.#checkTimer = null;
74 this.#tickTimer = null;
75 }
76
77 status ()
78 {
79 const now = this.now();
80 const scheduled = this.scheduledAt != null;
81 const warning = scheduled && (
82 this.warningActive || isInRestartWarningWindow(now, this.scheduledAt, this.warnBeforeMs)
83 );
84 return {
85 scheduled,
86 scheduledAt: this.scheduledAt,
87 warning: !!warning,
88 reasons: [...this.reasons],
89 localCommit: this.localCommit,
90 remoteCommit: this.remoteCommit,
91 branch: this.branch,
92 remainingMs: scheduled ? Math.max(0, this.scheduledAt - now) : null
93 };
94 }
95
96 async poll ()
97 {
98 if (!this.enabled || this.#checking || this.restartFired)
99 { return; }
100 this.#checking = true;
101 try
102 {
103 const result = await this.checkRemote(this.repoRoot, this.branch);
104 if (!result?.ok)
105 { return; }
106 this.localCommit = result.local ?? this.localCommit;
107 this.remoteCommit = result.remote ?? this.remoteCommit;
108 if (result.ahead)
109 { this.#scheduleCodeUpdate(); }
110 else if (this.scheduledAt != null && this.reasons.includes("code-update"))
111 { this.#clearSchedule(); }
112 }
113 finally
114 {
115 this.#checking = false;
116 }
117 }
118
119 tick ()
120 {
121 if (!this.enabled || this.restartFired || this.scheduledAt == null)
122 { return; }
123 const now = this.now();
124 const warning = isInRestartWarningWindow(now, this.scheduledAt, this.warnBeforeMs)
125 || now >= this.scheduledAt;
126 if (warning !== this.warningActive)
127 {
128 this.warningActive = warning;
129 this.onStatusChange(this.status());
130 }
131 if (now >= this.scheduledAt)
132 {
133 this.restartFired = true;
134 this.onRestartDue(this.status());
135 }
136 }
137
138 /** Test helper: force a pending midnight restart. */
139 forceScheduleForTests (scheduledAt, reasons = ["code-update"])
140 {
141 this.scheduledAt = scheduledAt;
142 this.reasons = [...reasons];
143 this.warningActive = isInRestartWarningWindow(this.now(), scheduledAt, this.warnBeforeMs);
144 this.onStatusChange(this.status());
145 }
146
147 #scheduleCodeUpdate ()
148 {
149 if (this.scheduledAt != null)
150 { return; }
151 this.scheduledAt = nextLocalMidnightMs(this.now());
152 this.reasons = ["code-update"];
153 this.warningActive = isInRestartWarningWindow(this.now(), this.scheduledAt, this.warnBeforeMs);
154 console.log(
155 `[deploy] origin/${this.branch} is ahead; restart scheduled for ${new Date(this.scheduledAt).toString()}`
156 );
157 this.onStatusChange(this.status());
158 }
159
160 #clearSchedule ()
161 {
162 this.scheduledAt = null;
163 this.reasons = [];
164 this.warningActive = false;
165 console.log("[deploy] Remote no longer ahead; cancelled scheduled restart.");
166 this.onStatusChange(this.status());
167 }
168}
server/src/gateway/websocket.js +53 −3
@@ -8,13 +8,29 @@ import { CraftingStationId, craftingStationDefinition } from "../../../shared/de
8 8 import { publicSkillsView } from "../../../shared/skills/state.js";
9 9 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
10 10 import { canCharacterSeeGroundItem } from "../../../shared/items/letters.js";
11 import { getConsoleSnapshot, subscribeConsole } from "../logging/consoleCapture.js";
11 12
12 13 let nextSessionId = 1;
13 14
14 export function attachGateway ({ httpServer, auth, stateDb, characters, friends, editor, simulation })
15 export function attachGateway ({ httpServer, auth, stateDb, characters, friends, editor, simulation, deploy = null })
15 16 {
16 17 const wss = new WebSocketServer({ server: httpServer, path: "/ws" });
17 18 const sessions = new Map();
19 let draining = false;
20
21 subscribeConsole((entry) =>
22 {
23 for (const session of sessions.values())
24 {
25 if (session.consoleSubscribed && session.account?.is_admin)
26 {
27 send(session, {
28 type: MessageType.editorConsoleLine,
29 line: entry
30 });
31 }
32 }
33 });
18 34
19 35 wss.on("connection", (socket) =>
20 36 {
@@ -29,6 +45,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
29 45 entityId: null,
30 46 /** Client graphics: long = STATIC_CHUNK_RADIUS map ring; short = VISIBLE_CHUNK_RADIUS. */
31 47 viewDistance: ViewDistance.long,
48 consoleSubscribed: false,
32 49 /** Chunks where entity / ground-item replication is active (3×3). */
33 50 entitySubscribed: new Set(),
34 51 /** Chunks with map + baked lighting only (5×5 when long). */
@@ -810,6 +827,14 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
810 827 itemLastSales: simulation.itemLastSalesSnapshot?.() ?? {}
811 828 });
812 829 break;
830 case MessageType.editorConsoleSubscribe:
831 requireAdmin(session);
832 session.consoleSubscribed = true;
833 send(session, {
834 type: MessageType.editorConsoleSnapshot,
835 lines: getConsoleSnapshot(800)
836 });
837 break;
813 838 case MessageType.editorSaveSettings:
814 839 requireAdmin(session);
815 840 {
@@ -925,6 +950,12 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
925 950
926 951 function enterWorld (session, characterId)
927 952 {
953 if (draining || deploy?.isDraining?.())
954 {
955 const error = new Error("The server is restarting for an update. Please try again in a moment.");
956 error.userFacing = true;
957 throw error;
958 }
928 959 leaveWorld(session);
929 960 const character = characters.getOwned(session.account.account_id, characterId);
930 961 if (character.deletion_scheduled_at)
@@ -964,7 +995,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
964 995 health: spawned.health,
965 996 maxHealth: spawned.maxHealth,
966 997 settings: simulation.settings,
967 worldTime: simulation.worldTime()
998 worldTime: simulation.worldTime(),
999 restartStatus: deploy?.getStatus?.() ?? { scheduled: false }
968 1000 });
969 1001 syncSubscriptions(session, true);
970 1002 send(session, { type: MessageType.friends, ...friends.snapshot(session.characterId) });
@@ -1086,6 +1118,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1086 1118 function broadcastStatus ()
1087 1119 {
1088 1120 const worldTime = simulation.worldTime();
1121 const restartStatus = deploy?.getStatus?.() ?? { scheduled: false };
1089 1122 for (const session of sessions.values())
1090 1123 {
1091 1124 if (session.entityId)
@@ -1094,12 +1127,23 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1094 1127 type: MessageType.worldStatus,
1095 1128 worldTime,
1096 1129 settings: simulation.settings,
1097 activeRevisionId: simulation.activeRevisionId
1130 activeRevisionId: simulation.activeRevisionId,
1131 restartStatus
1098 1132 });
1099 1133 }
1100 1134 }
1101 1135 }
1102 1136
1137 function broadcastRestartStatus ()
1138 {
1139 const restartStatus = deploy?.getStatus?.() ?? { scheduled: false };
1140 for (const session of sessions.values())
1141 {
1142 if (session.entityId)
1143 { send(session, { type: MessageType.restartStatus, restartStatus }); }
1144 }
1145 }
1146
1103 1147 function pushFriends (...characterIds)
1104 1148 {
1105 1149 const seen = new Set();
@@ -1931,8 +1975,14 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1931 1975 sessions,
1932 1976 onTickResult,
1933 1977 wss,
1978 broadcastRestartStatus,
1979 setDraining (value)
1980 {
1981 draining = !!value;
1982 },
1934 1983 async shutdown ()
1935 1984 {
1985 draining = true;
1936 1986 await Promise.all([...sessions.values()].map(async (session) =>
1937 1987 {
1938 1988 await sendAsync(session, {
@@ -8,13 +8,29 @@ import { CraftingStationId, craftingStationDefinition } from "../../../shared/de
8import { publicSkillsView } from "../../../shared/skills/state.js";
8import { publicSkillsView } from "../../../shared/skills/state.js";
9import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
9import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
10import { canCharacterSeeGroundItem } from "../../../shared/items/letters.js";
10import { canCharacterSeeGroundItem } from "../../../shared/items/letters.js";
11import { getConsoleSnapshot, subscribeConsole } from "../logging/consoleCapture.js";
11
12
12let nextSessionId = 1;
13let nextSessionId = 1;
13
14
14export function attachGateway ({ httpServer, auth, stateDb, characters, friends, editor, simulation })
15export function attachGateway ({ httpServer, auth, stateDb, characters, friends, editor, simulation, deploy = null })
15{
16{
16 const wss = new WebSocketServer({ server: httpServer, path: "/ws" });
17 const wss = new WebSocketServer({ server: httpServer, path: "/ws" });
17 const sessions = new Map();
18 const sessions = new Map();
19 let draining = false;
20
21 subscribeConsole((entry) =>
22 {
23 for (const session of sessions.values())
24 {
25 if (session.consoleSubscribed && session.account?.is_admin)
26 {
27 send(session, {
28 type: MessageType.editorConsoleLine,
29 line: entry
30 });
31 }
32 }
33 });
18
34
19 wss.on("connection", (socket) =>
35 wss.on("connection", (socket) =>
20 {
36 {
@@ -29,6 +45,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
29 entityId: null,
45 entityId: null,
30 /** Client graphics: long = STATIC_CHUNK_RADIUS map ring; short = VISIBLE_CHUNK_RADIUS. */
46 /** Client graphics: long = STATIC_CHUNK_RADIUS map ring; short = VISIBLE_CHUNK_RADIUS. */
31 viewDistance: ViewDistance.long,
47 viewDistance: ViewDistance.long,
48 consoleSubscribed: false,
32 /** Chunks where entity / ground-item replication is active (3×3). */
49 /** Chunks where entity / ground-item replication is active (3×3). */
33 entitySubscribed: new Set(),
50 entitySubscribed: new Set(),
34 /** Chunks with map + baked lighting only (5×5 when long). */
51 /** Chunks with map + baked lighting only (5×5 when long). */
@@ -810,6 +827,14 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
810 itemLastSales: simulation.itemLastSalesSnapshot?.() ?? {}
827 itemLastSales: simulation.itemLastSalesSnapshot?.() ?? {}
811 });
828 });
812 break;
829 break;
830 case MessageType.editorConsoleSubscribe:
831 requireAdmin(session);
832 session.consoleSubscribed = true;
833 send(session, {
834 type: MessageType.editorConsoleSnapshot,
835 lines: getConsoleSnapshot(800)
836 });
837 break;
813 case MessageType.editorSaveSettings:
838 case MessageType.editorSaveSettings:
814 requireAdmin(session);
839 requireAdmin(session);
815 {
840 {
@@ -925,6 +950,12 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
925
950
926 function enterWorld (session, characterId)
951 function enterWorld (session, characterId)
927 {
952 {
953 if (draining || deploy?.isDraining?.())
954 {
955 const error = new Error("The server is restarting for an update. Please try again in a moment.");
956 error.userFacing = true;
957 throw error;
958 }
928 leaveWorld(session);
959 leaveWorld(session);
929 const character = characters.getOwned(session.account.account_id, characterId);
960 const character = characters.getOwned(session.account.account_id, characterId);
930 if (character.deletion_scheduled_at)
961 if (character.deletion_scheduled_at)
@@ -964,7 +995,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
964 health: spawned.health,
995 health: spawned.health,
965 maxHealth: spawned.maxHealth,
996 maxHealth: spawned.maxHealth,
966 settings: simulation.settings,
997 settings: simulation.settings,
967 worldTime: simulation.worldTime()
998 worldTime: simulation.worldTime(),
999 restartStatus: deploy?.getStatus?.() ?? { scheduled: false }
968 });
1000 });
969 syncSubscriptions(session, true);
1001 syncSubscriptions(session, true);
970 send(session, { type: MessageType.friends, ...friends.snapshot(session.characterId) });
1002 send(session, { type: MessageType.friends, ...friends.snapshot(session.characterId) });
@@ -1086,6 +1118,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1086 function broadcastStatus ()
1118 function broadcastStatus ()
1087 {
1119 {
1088 const worldTime = simulation.worldTime();
1120 const worldTime = simulation.worldTime();
1121 const restartStatus = deploy?.getStatus?.() ?? { scheduled: false };
1089 for (const session of sessions.values())
1122 for (const session of sessions.values())
1090 {
1123 {
1091 if (session.entityId)
1124 if (session.entityId)
@@ -1094,12 +1127,23 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1094 type: MessageType.worldStatus,
1127 type: MessageType.worldStatus,
1095 worldTime,
1128 worldTime,
1096 settings: simulation.settings,
1129 settings: simulation.settings,
1097 activeRevisionId: simulation.activeRevisionId
1130 activeRevisionId: simulation.activeRevisionId,
1131 restartStatus
1098 });
1132 });
1099 }
1133 }
1100 }
1134 }
1101 }
1135 }
1102
1136
1137 function broadcastRestartStatus ()
1138 {
1139 const restartStatus = deploy?.getStatus?.() ?? { scheduled: false };
1140 for (const session of sessions.values())
1141 {
1142 if (session.entityId)
1143 { send(session, { type: MessageType.restartStatus, restartStatus }); }
1144 }
1145 }
1146
1103 function pushFriends (...characterIds)
1147 function pushFriends (...characterIds)
1104 {
1148 {
1105 const seen = new Set();
1149 const seen = new Set();
@@ -1931,8 +1975,14 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1931 sessions,
1975 sessions,
1932 onTickResult,
1976 onTickResult,
1933 wss,
1977 wss,
1978 broadcastRestartStatus,
1979 setDraining (value)
1980 {
1981 draining = !!value;
1982 },
1934 async shutdown ()
1983 async shutdown ()
1935 {
1984 {
1985 draining = true;
1936 await Promise.all([...sessions.values()].map(async (session) =>
1986 await Promise.all([...sessions.values()].map(async (session) =>
1937 {
1987 {
1938 await sendAsync(session, {
1988 await sendAsync(session, {
server/src/index.js +65 −1
@@ -8,6 +8,11 @@ import { StubAuth } from "./auth/stub.js";
8 8 import { Simulation } from "./simulation/simulation.js";
9 9 import { createHttpServer, repoRootFrom } from "./gateway/http.js";
10 10 import { attachGateway } from "./gateway/websocket.js";
11 import { DeployScheduler } from "./deploy/scheduler.js";
12 import { writeRestartManifest, restartManifestPath } from "./deploy/manifest.js";
13 import { hookConsoleCapture } from "./logging/consoleCapture.js";
14
15 hookConsoleCapture();
11 16
12 17 const rootDir = repoRootFrom(import.meta.url);
13 18 const dataDir = join(rootDir, "server", "data");
@@ -21,10 +26,32 @@ const friends = new FriendService(stateDb);
21 26 const simulation = new Simulation(worldDb, stateDb);
22 27 const auth = new StubAuth();
23 28 const httpServer = createHttpServer(rootDir);
24 const gateway = attachGateway({ httpServer, auth, stateDb, characters, friends, editor, simulation });
29
30 const deployBridge = {
31 getStatus ()
32 {
33 return deployScheduler?.status() ?? { scheduled: false };
34 },
35 isDraining ()
36 {
37 return shuttingDown;
38 }
39 };
40
41 const gateway = attachGateway({
42 httpServer,
43 auth,
44 stateDb,
45 characters,
46 friends,
47 editor,
48 simulation,
49 deploy: deployBridge
50 });
25 51
26 52 let tickTimer = null;
27 53 let shuttingDown = false;
54 let deployScheduler = null;
28 55
29 56 function scheduleTick ()
30 57 {
@@ -41,12 +68,47 @@ function scheduleTick ()
41 68 }
42 69 scheduleTick();
43 70
71 deployScheduler = new DeployScheduler({
72 repoRoot: rootDir,
73 onStatusChange ()
74 {
75 gateway.broadcastRestartStatus?.();
76 },
77 onRestartDue (status)
78 {
79 void plannedRestart(status);
80 }
81 });
82 deployScheduler.start();
83
44 84 httpServer.listen(port, () =>
45 85 {
46 86 console.log(`Tile MMO listening on http://localhost:${port}`);
47 87 console.log(`World editor: http://localhost:${port}/editor`);
48 88 });
49 89
90 async function plannedRestart (status)
91 {
92 if (shuttingDown)
93 { return; }
94 console.log("[deploy] Planned restart due:", status?.reasons?.join(", ") ?? "unknown");
95 try
96 {
97 writeRestartManifest(restartManifestPath(dataDir), {
98 reasons: status?.reasons ?? ["code-update"],
99 deployCode: true,
100 targetCommit: status?.remoteCommit ?? null,
101 pendingWorldRevision: worldDb.getPendingRevisionId?.() ?? null,
102 writtenAt: Date.now()
103 });
104 }
105 catch (error)
106 {
107 console.error("[deploy] Failed to write restart manifest:", error);
108 }
109 await shutdown("planned-restart");
110 }
111
50 112 async function shutdown (signal)
51 113 {
52 114 if (shuttingDown)
@@ -54,6 +116,8 @@ async function shutdown (signal)
54 116 shuttingDown = true;
55 117 console.log(`Shutting down (${signal})…`);
56 118 clearTimeout(tickTimer);
119 deployScheduler?.stop();
120 gateway.setDraining?.(true);
57 121 try
58 122 { await gateway.shutdown(); }
59 123 catch (error)
@@ -8,6 +8,11 @@ import { StubAuth } from "./auth/stub.js";
8import { Simulation } from "./simulation/simulation.js";
8import { Simulation } from "./simulation/simulation.js";
9import { createHttpServer, repoRootFrom } from "./gateway/http.js";
9import { createHttpServer, repoRootFrom } from "./gateway/http.js";
10import { attachGateway } from "./gateway/websocket.js";
10import { attachGateway } from "./gateway/websocket.js";
11import { DeployScheduler } from "./deploy/scheduler.js";
12import { writeRestartManifest, restartManifestPath } from "./deploy/manifest.js";
13import { hookConsoleCapture } from "./logging/consoleCapture.js";
14
15hookConsoleCapture();
11
16
12const rootDir = repoRootFrom(import.meta.url);
17const rootDir = repoRootFrom(import.meta.url);
13const dataDir = join(rootDir, "server", "data");
18const dataDir = join(rootDir, "server", "data");
@@ -21,10 +26,32 @@ const friends = new FriendService(stateDb);
21const simulation = new Simulation(worldDb, stateDb);
26const simulation = new Simulation(worldDb, stateDb);
22const auth = new StubAuth();
27const auth = new StubAuth();
23const httpServer = createHttpServer(rootDir);
28const httpServer = createHttpServer(rootDir);
24const gateway = attachGateway({ httpServer, auth, stateDb, characters, friends, editor, simulation });
29
30const deployBridge = {
31 getStatus ()
32 {
33 return deployScheduler?.status() ?? { scheduled: false };
34 },
35 isDraining ()
36 {
37 return shuttingDown;
38 }
39};
40
41const gateway = attachGateway({
42 httpServer,
43 auth,
44 stateDb,
45 characters,
46 friends,
47 editor,
48 simulation,
49 deploy: deployBridge
50});
25
51
26let tickTimer = null;
52let tickTimer = null;
27let shuttingDown = false;
53let shuttingDown = false;
54let deployScheduler = null;
28
55
29function scheduleTick ()
56function scheduleTick ()
30{
57{
@@ -41,12 +68,47 @@ function scheduleTick ()
41}
68}
42scheduleTick();
69scheduleTick();
43
70
71deployScheduler = new DeployScheduler({
72 repoRoot: rootDir,
73 onStatusChange ()
74 {
75 gateway.broadcastRestartStatus?.();
76 },
77 onRestartDue (status)
78 {
79 void plannedRestart(status);
80 }
81});
82deployScheduler.start();
83
44httpServer.listen(port, () =>
84httpServer.listen(port, () =>
45{
85{
46 console.log(`Tile MMO listening on http://localhost:${port}`);
86 console.log(`Tile MMO listening on http://localhost:${port}`);
47 console.log(`World editor: http://localhost:${port}/editor`);
87 console.log(`World editor: http://localhost:${port}/editor`);
48});
88});
49
89
90async function plannedRestart (status)
91{
92 if (shuttingDown)
93 { return; }
94 console.log("[deploy] Planned restart due:", status?.reasons?.join(", ") ?? "unknown");
95 try
96 {
97 writeRestartManifest(restartManifestPath(dataDir), {
98 reasons: status?.reasons ?? ["code-update"],
99 deployCode: true,
100 targetCommit: status?.remoteCommit ?? null,
101 pendingWorldRevision: worldDb.getPendingRevisionId?.() ?? null,
102 writtenAt: Date.now()
103 });
104 }
105 catch (error)
106 {
107 console.error("[deploy] Failed to write restart manifest:", error);
108 }
109 await shutdown("planned-restart");
110}
111
50async function shutdown (signal)
112async function shutdown (signal)
51{
113{
52 if (shuttingDown)
114 if (shuttingDown)
@@ -54,6 +116,8 @@ async function shutdown (signal)
54 shuttingDown = true;
116 shuttingDown = true;
55 console.log(`Shutting down (${signal})…`);
117 console.log(`Shutting down (${signal})…`);
56 clearTimeout(tickTimer);
118 clearTimeout(tickTimer);
119 deployScheduler?.stop();
120 gateway.setDraining?.(true);
57 try
121 try
58 { await gateway.shutdown(); }
122 { await gateway.shutdown(); }
59 catch (error)
123 catch (error)
server/src/logging/consoleCapture.js added +73 −0
@@ -0,0 +1,73 @@
1 /**
2 * Capture console output into a ring buffer and fan out to subscribers (editor).
3 */
4
5 const MAX_LINES = 2500;
6
7 /** @type {Array<{ t: number, level: string, text: string }>} */
8 const lines = [];
9 /** @type {Set<(entry: { t: number, level: string, text: string }) => void>} */
10 const listeners = new Set();
11 let hooked = false;
12
13 function formatArgs (args)
14 {
15 return args.map((arg) =>
16 {
17 if (typeof arg === "string")
18 { return arg; }
19 try
20 { return JSON.stringify(arg); }
21 catch
22 { return String(arg); }
23 }).join(" ");
24 }
25
26 function push (level, args)
27 {
28 const entry = {
29 t: Date.now(),
30 level,
31 text: formatArgs(args)
32 };
33 lines.push(entry);
34 if (lines.length > MAX_LINES)
35 { lines.splice(0, lines.length - MAX_LINES); }
36 for (const listener of listeners)
37 {
38 try
39 { listener(entry); }
40 catch
41 { /* ignore subscriber errors */ }
42 }
43 }
44
45 export function hookConsoleCapture ()
46 {
47 if (hooked)
48 { return; }
49 hooked = true;
50 for (const level of ["log", "info", "warn", "error", "debug"])
51 {
52 const original = console[level]?.bind(console);
53 if (!original)
54 { continue; }
55 console[level] = (...args) =>
56 {
57 push(level === "log" ? "info" : level, args);
58 original(...args);
59 };
60 }
61 }
62
63 export function getConsoleSnapshot (limit = 500)
64 {
65 const n = Math.max(1, Math.min(MAX_LINES, limit | 0 || 500));
66 return lines.slice(-n);
67 }
68
69 export function subscribeConsole (listener)
70 {
71 listeners.add(listener);
72 return () => listeners.delete(listener);
73 }
@@ -0,0 +1,73 @@
1/**
2 * Capture console output into a ring buffer and fan out to subscribers (editor).
3 */
4
5const MAX_LINES = 2500;
6
7/** @type {Array<{ t: number, level: string, text: string }>} */
8const lines = [];
9/** @type {Set<(entry: { t: number, level: string, text: string }) => void>} */
10const listeners = new Set();
11let hooked = false;
12
13function formatArgs (args)
14{
15 return args.map((arg) =>
16 {
17 if (typeof arg === "string")
18 { return arg; }
19 try
20 { return JSON.stringify(arg); }
21 catch
22 { return String(arg); }
23 }).join(" ");
24}
25
26function push (level, args)
27{
28 const entry = {
29 t: Date.now(),
30 level,
31 text: formatArgs(args)
32 };
33 lines.push(entry);
34 if (lines.length > MAX_LINES)
35 { lines.splice(0, lines.length - MAX_LINES); }
36 for (const listener of listeners)
37 {
38 try
39 { listener(entry); }
40 catch
41 { /* ignore subscriber errors */ }
42 }
43}
44
45export function hookConsoleCapture ()
46{
47 if (hooked)
48 { return; }
49 hooked = true;
50 for (const level of ["log", "info", "warn", "error", "debug"])
51 {
52 const original = console[level]?.bind(console);
53 if (!original)
54 { continue; }
55 console[level] = (...args) =>
56 {
57 push(level === "log" ? "info" : level, args);
58 original(...args);
59 };
60 }
61}
62
63export function getConsoleSnapshot (limit = 500)
64{
65 const n = Math.max(1, Math.min(MAX_LINES, limit | 0 || 500));
66 return lines.slice(-n);
67}
68
69export function subscribeConsole (listener)
70{
71 listeners.add(listener);
72 return () => listeners.delete(listener);
73}
server/tests/deploy.test.js added +123 −0
@@ -0,0 +1,123 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { mkdtempSync, existsSync } from "node:fs";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import {
7 nextLocalMidnightMs,
8 isInRestartWarningWindow,
9 restartWarningStartsAt,
10 formatRestartCountdown,
11 restartCountdownMessage,
12 RESTART_WARN_BEFORE_MS
13 } from "../../shared/deploy/schedule.js";
14 import { DeployScheduler } from "../src/deploy/scheduler.js";
15 import {
16 writeRestartManifest,
17 readRestartManifest,
18 consumeRestartManifest,
19 restartManifestPath
20 } from "../src/deploy/manifest.js";
21
22 test("nextLocalMidnightMs is the following calendar midnight", () =>
23 {
24 const noon = new Date(2026, 7, 27, 12, 0, 0, 0).getTime();
25 const midnight = nextLocalMidnightMs(noon);
26 const d = new Date(midnight);
27 assert.equal(d.getFullYear(), 2026);
28 assert.equal(d.getMonth(), 7);
29 assert.equal(d.getDate(), 28);
30 assert.equal(d.getHours(), 0);
31 assert.equal(d.getMinutes(), 0);
32 });
33
34 test("warning window opens three hours before midnight", () =>
35 {
36 const scheduledAt = new Date(2026, 7, 28, 0, 0, 0, 0).getTime();
37 assert.equal(restartWarningStartsAt(scheduledAt), scheduledAt - RESTART_WARN_BEFORE_MS);
38 assert.equal(isInRestartWarningWindow(scheduledAt - RESTART_WARN_BEFORE_MS, scheduledAt), true);
39 assert.equal(isInRestartWarningWindow(scheduledAt - RESTART_WARN_BEFORE_MS - 1, scheduledAt), false);
40 assert.equal(isInRestartWarningWindow(scheduledAt, scheduledAt), false);
41 });
42
43 test("countdown formatting", () =>
44 {
45 assert.equal(formatRestartCountdown(45_000), "45s");
46 assert.equal(formatRestartCountdown(125_000), "2m 05s");
47 assert.match(restartCountdownMessage(3_600_000), /1h 00m 00s/);
48 });
49
50 test("restart manifest write read consume is atomic-ish", () =>
51 {
52 const dir = mkdtempSync(join(tmpdir(), "mmo-restart-"));
53 const path = restartManifestPath(dir);
54 writeRestartManifest(path, {
55 reasons: ["code-update"],
56 deployCode: true,
57 targetCommit: "abc",
58 writtenAt: 123
59 });
60 assert.equal(existsSync(path), true);
61 const read = readRestartManifest(path);
62 assert.equal(read.deployCode, true);
63 assert.equal(read.targetCommit, "abc");
64 const consumed = consumeRestartManifest(path);
65 assert.equal(consumed.deployCode, true);
66 assert.equal(existsSync(path), false);
67 assert.equal(consumeRestartManifest(path), null);
68 });
69
70 test("DeployScheduler schedules only when remote is ahead", async () =>
71 {
72 let now = new Date(2026, 7, 27, 12, 0, 0, 0).getTime();
73 const statuses = [];
74 let ahead = true;
75 const scheduler = new DeployScheduler({
76 repoRoot: ".",
77 enabled: true,
78 now: () => now,
79 checkIntervalMs: 60_000,
80 checkRemote: async () => ({
81 ok: true,
82 ahead,
83 local: "aaa",
84 remote: ahead ? "bbb" : "aaa"
85 }),
86 onStatusChange (status)
87 { statuses.push(status); }
88 });
89 await scheduler.poll();
90 assert.equal(scheduler.status().scheduled, true);
91 assert.equal(scheduler.status().scheduledAt, nextLocalMidnightMs(now));
92 assert.equal(scheduler.status().warning, false);
93
94 now = scheduler.status().scheduledAt - RESTART_WARN_BEFORE_MS;
95 scheduler.tick();
96 assert.equal(scheduler.status().warning, true);
97
98 ahead = false;
99 await scheduler.poll();
100 assert.equal(scheduler.status().scheduled, false);
101 scheduler.stop();
102 });
103
104 test("DeployScheduler fires onRestartDue once at midnight", async () =>
105 {
106 let now = new Date(2026, 7, 27, 23, 0, 0, 0).getTime();
107 let restarts = 0;
108 const scheduler = new DeployScheduler({
109 repoRoot: ".",
110 enabled: true,
111 now: () => now,
112 checkRemote: async () => ({ ok: true, ahead: true, local: "a", remote: "b" }),
113 onRestartDue ()
114 { restarts += 1; }
115 });
116 await scheduler.poll();
117 const at = scheduler.status().scheduledAt;
118 now = at;
119 scheduler.tick();
120 scheduler.tick();
121 assert.equal(restarts, 1);
122 scheduler.stop();
123 });
@@ -0,0 +1,123 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { mkdtempSync, existsSync } from "node:fs";
4import { tmpdir } from "node:os";
5import { join } from "node:path";
6import {
7 nextLocalMidnightMs,
8 isInRestartWarningWindow,
9 restartWarningStartsAt,
10 formatRestartCountdown,
11 restartCountdownMessage,
12 RESTART_WARN_BEFORE_MS
13} from "../../shared/deploy/schedule.js";
14import { DeployScheduler } from "../src/deploy/scheduler.js";
15import {
16 writeRestartManifest,
17 readRestartManifest,
18 consumeRestartManifest,
19 restartManifestPath
20} from "../src/deploy/manifest.js";
21
22test("nextLocalMidnightMs is the following calendar midnight", () =>
23{
24 const noon = new Date(2026, 7, 27, 12, 0, 0, 0).getTime();
25 const midnight = nextLocalMidnightMs(noon);
26 const d = new Date(midnight);
27 assert.equal(d.getFullYear(), 2026);
28 assert.equal(d.getMonth(), 7);
29 assert.equal(d.getDate(), 28);
30 assert.equal(d.getHours(), 0);
31 assert.equal(d.getMinutes(), 0);
32});
33
34test("warning window opens three hours before midnight", () =>
35{
36 const scheduledAt = new Date(2026, 7, 28, 0, 0, 0, 0).getTime();
37 assert.equal(restartWarningStartsAt(scheduledAt), scheduledAt - RESTART_WARN_BEFORE_MS);
38 assert.equal(isInRestartWarningWindow(scheduledAt - RESTART_WARN_BEFORE_MS, scheduledAt), true);
39 assert.equal(isInRestartWarningWindow(scheduledAt - RESTART_WARN_BEFORE_MS - 1, scheduledAt), false);
40 assert.equal(isInRestartWarningWindow(scheduledAt, scheduledAt), false);
41});
42
43test("countdown formatting", () =>
44{
45 assert.equal(formatRestartCountdown(45_000), "45s");
46 assert.equal(formatRestartCountdown(125_000), "2m 05s");
47 assert.match(restartCountdownMessage(3_600_000), /1h 00m 00s/);
48});
49
50test("restart manifest write read consume is atomic-ish", () =>
51{
52 const dir = mkdtempSync(join(tmpdir(), "mmo-restart-"));
53 const path = restartManifestPath(dir);
54 writeRestartManifest(path, {
55 reasons: ["code-update"],
56 deployCode: true,
57 targetCommit: "abc",
58 writtenAt: 123
59 });
60 assert.equal(existsSync(path), true);
61 const read = readRestartManifest(path);
62 assert.equal(read.deployCode, true);
63 assert.equal(read.targetCommit, "abc");
64 const consumed = consumeRestartManifest(path);
65 assert.equal(consumed.deployCode, true);
66 assert.equal(existsSync(path), false);
67 assert.equal(consumeRestartManifest(path), null);
68});
69
70test("DeployScheduler schedules only when remote is ahead", async () =>
71{
72 let now = new Date(2026, 7, 27, 12, 0, 0, 0).getTime();
73 const statuses = [];
74 let ahead = true;
75 const scheduler = new DeployScheduler({
76 repoRoot: ".",
77 enabled: true,
78 now: () => now,
79 checkIntervalMs: 60_000,
80 checkRemote: async () => ({
81 ok: true,
82 ahead,
83 local: "aaa",
84 remote: ahead ? "bbb" : "aaa"
85 }),
86 onStatusChange (status)
87 { statuses.push(status); }
88 });
89 await scheduler.poll();
90 assert.equal(scheduler.status().scheduled, true);
91 assert.equal(scheduler.status().scheduledAt, nextLocalMidnightMs(now));
92 assert.equal(scheduler.status().warning, false);
93
94 now = scheduler.status().scheduledAt - RESTART_WARN_BEFORE_MS;
95 scheduler.tick();
96 assert.equal(scheduler.status().warning, true);
97
98 ahead = false;
99 await scheduler.poll();
100 assert.equal(scheduler.status().scheduled, false);
101 scheduler.stop();
102});
103
104test("DeployScheduler fires onRestartDue once at midnight", async () =>
105{
106 let now = new Date(2026, 7, 27, 23, 0, 0, 0).getTime();
107 let restarts = 0;
108 const scheduler = new DeployScheduler({
109 repoRoot: ".",
110 enabled: true,
111 now: () => now,
112 checkRemote: async () => ({ ok: true, ahead: true, local: "a", remote: "b" }),
113 onRestartDue ()
114 { restarts += 1; }
115 });
116 await scheduler.poll();
117 const at = scheduler.status().scheduledAt;
118 now = at;
119 scheduler.tick();
120 scheduler.tick();
121 assert.equal(restarts, 1);
122 scheduler.stop();
123});
shared/deploy/schedule.js added +52 −0
@@ -0,0 +1,52 @@
1 /** Shared helpers for midnight deploy / restart scheduling (server-local calendar). */
2
3 export const RESTART_WARN_BEFORE_MS = 3 * 60 * 60 * 1000;
4 export const DEFAULT_DEPLOY_CHECK_MS = 5 * 60 * 1000;
5
6 /** Next local calendar midnight strictly after `now`. */
7 export function nextLocalMidnightMs (now = Date.now())
8 {
9 const d = new Date(now);
10 const next = new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1, 0, 0, 0, 0);
11 return next.getTime();
12 }
13
14 export function restartWarningStartsAt (scheduledAt, warnBeforeMs = RESTART_WARN_BEFORE_MS)
15 {
16 const at = Number(scheduledAt);
17 const warn = Number(warnBeforeMs);
18 if (!Number.isFinite(at))
19 { return 0; }
20 return Math.max(0, at - (Number.isFinite(warn) ? warn : RESTART_WARN_BEFORE_MS));
21 }
22
23 export function isInRestartWarningWindow (now, scheduledAt, warnBeforeMs = RESTART_WARN_BEFORE_MS)
24 {
25 if (scheduledAt == null)
26 { return false; }
27 const at = Number(scheduledAt);
28 if (!Number.isFinite(at))
29 { return false; }
30 const t = Number(now);
31 return t >= restartWarningStartsAt(at, warnBeforeMs) && t < at;
32 }
33
34 /** Human countdown like `2h 05m 03s` or `45s`. */
35 export function formatRestartCountdown (remainingMs)
36 {
37 const ms = Math.max(0, Math.ceil(Number(remainingMs) || 0));
38 const totalSec = Math.floor(ms / 1000);
39 const h = Math.floor(totalSec / 3600);
40 const m = Math.floor((totalSec % 3600) / 60);
41 const s = totalSec % 60;
42 if (h > 0)
43 { return `${h}h ${String(m).padStart(2, "0")}m ${String(s).padStart(2, "0")}s`; }
44 if (m > 0)
45 { return `${m}m ${String(s).padStart(2, "0")}s`; }
46 return `${s}s`;
47 }
48
49 export function restartCountdownMessage (remainingMs)
50 {
51 return `Server restart for a game update in ${formatRestartCountdown(remainingMs)}.`;
52 }
@@ -0,0 +1,52 @@
1/** Shared helpers for midnight deploy / restart scheduling (server-local calendar). */
2
3export const RESTART_WARN_BEFORE_MS = 3 * 60 * 60 * 1000;
4export const DEFAULT_DEPLOY_CHECK_MS = 5 * 60 * 1000;
5
6/** Next local calendar midnight strictly after `now`. */
7export function nextLocalMidnightMs (now = Date.now())
8{
9 const d = new Date(now);
10 const next = new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1, 0, 0, 0, 0);
11 return next.getTime();
12}
13
14export function restartWarningStartsAt (scheduledAt, warnBeforeMs = RESTART_WARN_BEFORE_MS)
15{
16 const at = Number(scheduledAt);
17 const warn = Number(warnBeforeMs);
18 if (!Number.isFinite(at))
19 { return 0; }
20 return Math.max(0, at - (Number.isFinite(warn) ? warn : RESTART_WARN_BEFORE_MS));
21}
22
23export function isInRestartWarningWindow (now, scheduledAt, warnBeforeMs = RESTART_WARN_BEFORE_MS)
24{
25 if (scheduledAt == null)
26 { return false; }
27 const at = Number(scheduledAt);
28 if (!Number.isFinite(at))
29 { return false; }
30 const t = Number(now);
31 return t >= restartWarningStartsAt(at, warnBeforeMs) && t < at;
32}
33
34/** Human countdown like `2h 05m 03s` or `45s`. */
35export function formatRestartCountdown (remainingMs)
36{
37 const ms = Math.max(0, Math.ceil(Number(remainingMs) || 0));
38 const totalSec = Math.floor(ms / 1000);
39 const h = Math.floor(totalSec / 3600);
40 const m = Math.floor((totalSec % 3600) / 60);
41 const s = totalSec % 60;
42 if (h > 0)
43 { return `${h}h ${String(m).padStart(2, "0")}m ${String(s).padStart(2, "0")}s`; }
44 if (m > 0)
45 { return `${m}m ${String(s).padStart(2, "0")}s`; }
46 return `${s}s`;
47}
48
49export function restartCountdownMessage (remainingMs)
50{
51 return `Server restart for a game update in ${formatRestartCountdown(remainingMs)}.`;
52}
shared/protocol/constants.js +4 −0
@@ -230,6 +230,10 @@ export const MessageType = Object.freeze({
230 230 spellLightUpdate: "SPELL_LIGHT_UPDATE",
231 231 spellLightRemove: "SPELL_LIGHT_REMOVE",
232 232 toast: "TOAST",
233 restartStatus: "RESTART_STATUS",
234 editorConsoleSubscribe: "EDITOR_CONSOLE_SUBSCRIBE",
235 editorConsoleSnapshot: "EDITOR_CONSOLE_SNAPSHOT",
236 editorConsoleLine: "EDITOR_CONSOLE_LINE",
233 237 editorLoadQuests: "EDITOR_LOAD_QUESTS",
234 238 editorQuests: "EDITOR_QUESTS",
235 239 editorSaveQuest: "EDITOR_SAVE_QUEST",
@@ -230,6 +230,10 @@ export const MessageType = Object.freeze({
230 spellLightUpdate: "SPELL_LIGHT_UPDATE",
230 spellLightUpdate: "SPELL_LIGHT_UPDATE",
231 spellLightRemove: "SPELL_LIGHT_REMOVE",
231 spellLightRemove: "SPELL_LIGHT_REMOVE",
232 toast: "TOAST",
232 toast: "TOAST",
233 restartStatus: "RESTART_STATUS",
234 editorConsoleSubscribe: "EDITOR_CONSOLE_SUBSCRIBE",
235 editorConsoleSnapshot: "EDITOR_CONSOLE_SNAPSHOT",
236 editorConsoleLine: "EDITOR_CONSOLE_LINE",
233 editorLoadQuests: "EDITOR_LOAD_QUESTS",
237 editorLoadQuests: "EDITOR_LOAD_QUESTS",
234 editorQuests: "EDITOR_QUESTS",
238 editorQuests: "EDITOR_QUESTS",
235 editorSaveQuest: "EDITOR_SAVE_QUEST",
239 editorSaveQuest: "EDITOR_SAVE_QUEST",