Public: anyone can read this; the crew can change it.

A proxy held back for a jar comes up once the jar is there, with no new commit #17798

opened this

Merged 11h 16m ago, live in production

sold/jar-there-later → main 0 commits

  • Merged. sold/jar-there-later was merged into main as 776f58f.

Review

Sign in to review this change.
6 files changed +312 −40
docs/features/games.md +10 −3
@@ -128,10 +128,17 @@ To add one, on the proxy's page, under Forge plugins:
128128
129129 If the page says the proxy is left as it is:
130130
131 1. Upload the jar, if the page says nobody did. Take out a jar the page says is refused.
132 2. Commit a change to the compose file; a comment is enough. The box does not try the same commit twice.
131 - Upload the jar, if the page says nobody did. The box takes it at its next full sync, with no new commit, and the proxy restarts when nobody is on.
132 - Take out a jar the page says is refused. That is a commit.
133 - If the box could not fetch the jar (no answer, or an error), wait: it tries again after 5 minutes, then 15, then every hour. Nothing needs a commit. Once the jar is there, the proxy restarts when nobody is on.
134 - If the page says the jar is here, the proxy waits for the last player to leave. The box goes by the proxy's own count (`glist all`), and a count it cannot read is someone on. **Recreate** on the proxy's page does not wait. The first try, right after a commit, does not wait either.
135 - To stop the waiting, revert the commit that names the jar. The box then runs an ordinary `up` of the old file, which leaves a proxy that already runs it alone.
136 - A player who joins between the look and the `up` is disconnected: the two are seconds apart.
137 - A branch moved back to the exact commit the box ran before, instead of a revert, does not end the waiting: the forge then sends no file. **Recreate** on the proxy's page ends it.
138 - If the jar it fetched had the wrong bytes, commit a change to the compose file; a comment is enough. The box does not try the same commit and the same jars twice.
139 - If a jar it already had has the wrong bytes and cannot be fetched, the box keeps the file while the proxy runs and removes it once the proxy is stopped. The proxy then does not start until the jar is back. The box's run log says which of the two happened.
133140
134 The other servers come up as usual meanwhile. This also happens when the box waited more than 6 hours to fetch the jar, because its address had run out. The next full sync brings a new one.
141 The other servers come up as usual meanwhile. An address for a jar runs out after 6 hours; each full sync brings a new one, and the next try uses it.
135142
136143 If the page says that no change reaches the box until its agent updates, wait: nothing is lost. The agent updates itself when it syncs, and the box then takes the newest commit.
137144
src/games/agent.sh +106 −23
@@ -179,7 +179,7 @@ HELD_READ="docs/features/game-box.md (Held) says how to choose, and both are kep
179179 vol_hold() {
180180 printf '%s %s\n' "$1" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" >"$VOLUME_HOLD"
181181 # No compose file counts as up, or as failed: whichever way the hold ends, the next sync brings the games up.
182 rm -f "$DIR/.compose-sha" "$DIR/.up.failed"
182 rm -f "$DIR/.compose-sha" "$DIR/.up.failed" "$DIR/.jars.rest"
183183 vol_step "refused: $2: nothing is started; $HELD_READ"
184184 }
185185 # Mount the volume at the data directory. At a fresh boot the directory is empty; one that holds
@@ -852,28 +852,67 @@ job_tick() {
852852 AUTOSTOPPER_PROJECT="PG4gqnzX"
853853 AUTOSTOPPER_SHA512="${FORGE_GAME_AUTOSTOPPER_SHA512:-066bbc8b7ac41d8f360cb28de41a78b260843cd0f10af328f49a51bf37e4c52c63b258bfd73c783d7c649e6fe233a1153f7f062aa8c2cf952bbc5192d265361c}"
854854
855 # The waits before a fetch that brought no file is tried again, in seconds; the last one repeats.
856 JAR_RETRY="${FORGE_GAME_JAR_RETRY:-300 900 3600}"
857 # How often curl itself asks again within one try, after 1, 2 and 4 s.
858 JAR_CURL_RETRY="${FORGE_GAME_JAR_CURL_RETRY:-3}"
859 # What was tried, links aside: these change at every sync.
860 jars_key() { jq -c '[.[] | [.name, .sha256, .url != ""]]' 2>/dev/null; }
861 # Wrong bytes that cannot be replaced go, or Docker's own restart of the proxy could load them. Never while it runs.
862 jar_wrong() {
863 local up
864 [ -f "$DIR/jars/$1" ] || return 0
865 # A Docker that does not answer is no word that the proxy is stopped.
866 if up="$(compose ps -q --status running velocity 2>/dev/null)" && [ -z "$up" ]; then
867 rm -f "$DIR/jars/$1"
868 echo "$1 had wrong bytes and was removed: the proxy does not start until it is back"
869 else
870 echo "$1 has wrong bytes and stays while the proxy runs"
871 fi
872 }
855873 # Every jar in place with its sha256, or 1. The image skips a file of the same name and size, so a name
856874 # holds its sha256's first 12 characters. A link can be signed: it is never on a command line or said.
857875 jars_ready() {
858 local name url sha next
876 local name url sha next list bad=0 none=0 n=0 rc waits
877 list="$(cat "$DIR/.jars.json")"
878 # How often this was tried already: .jars.retry is when it is due, and that count.
879 [ "$(jars_key <<<"$list")" = "$(cat "$DIR/.jars.tried" 2>/dev/null)" ] && n="$(cut -s -d' ' -f2 "$DIR/.jars.retry" 2>/dev/null)"
880 rm -f "$DIR/.jars.retry"
881 jars_key <<<"$list" >"$DIR/.jars.tried"
859882 jq -e 'type == "array" and length <= 8 and all(.[];
860 (.sha256 | test("\\A[0-9a-f]{64}\\z")) and (.url | test("\\Ahttps?://[^\\s\"\\\\]+\\z"))
883 (.sha256 | test("\\A[0-9a-f]{64}\\z")) and (.url | test("\\A(https?://[^\\s\"\\\\]+)?\\z"))
861884 and (.name | test("\\A[A-Za-z0-9][A-Za-z0-9._-]{0,99}[.]jar\\z")) and (.sha256[0:12] as $s | .name | contains($s)))' \
862 "$DIR/.jars.json" >/dev/null 2>&1 || { echo "the jars the forge named are not as they should be"; return 1; }
885 <<<"$list" >/dev/null 2>&1 || { echo "the jars the forge named are not as they should be"; return 1; }
863886 mkdir -p "$DIR/jars" && chmod 0755 "$DIR/jars" || return 1
864 while IFS=$'\t' read -r name url sha <&3; do
887 while IFS=$'\t' read -r name sha url <&3; do
865888 [ "$(sha256sum "$DIR/jars/$name" 2>/dev/null | cut -d' ' -f1)" = "$sha" ] && continue
889 [ -n "$url" ] || { jar_wrong "$name"; echo "$name is not on this box, and the forge has no copy"; bad=1; continue; }
866890 next="$DIR/.jar.next"
891 rm -f "$next"
867892 printf 'url = "%s"\n' "$url" >"$DIR/.jar.curl"
868 curl -fsSL --proto '=https,http' --max-filesize 67108864 -m 120 --retry 3 -K "$DIR/.jar.curl" -o "$next" 2>/dev/null
893 curl -fsSL --proto '=https,http' --max-filesize 67108864 -m 120 --retry "$JAR_CURL_RETRY" -K "$DIR/.jar.curl" -o "$next" 2>/dev/null
894 rc=$?
869895 rm -f "$DIR/.jar.curl"
870896 if [ "$(sha256sum "$next" 2>/dev/null | cut -d' ' -f1)" != "$sha" ]; then
871897 rm -f "$next"
872 echo "$name could not be fetched with sha256 $sha"
873 return 1
898 jar_wrong "$name"
899 # 63 is a file over the limit: that is an answer, as wrong bytes are.
900 if [ "$rc" = 0 ] || [ "$rc" = 63 ]; then echo "$name could not be fetched with sha256 $sha"; else
901 echo "$name could not be fetched (curl $rc): tried again later"
902 none=1
903 fi
904 bad=1
905 continue
874906 fi
875907 chmod 0644 "$next" && mv "$next" "$DIR/jars/$name" || return 1
876 done 3< <(jq -r '.[] | [.name, .url, .sha256] | @tsv' "$DIR/.jars.json")
908 done 3< <(jq -r '.[] | [.name, .sha256, .url] | @tsv' <<<"$list")
909 if [ "$none" = 1 ]; then
910 read -ra waits <<<"$JAR_RETRY"
911 n="${n:-0}"
912 [ "$n" -lt "${#waits[@]}" ] || n=$((${#waits[@]} - 1))
913 printf '%s %s\n' "$(($(date +%s) + waits[n]))" "$((n + 1))" >"$DIR/.jars.retry"
914 fi
915 return "$bad"
877916 }
878917 # Rename the AutoStopper the image fetched, in the proxy's plugins folder: from *$1 to what $2 makes of
879918 # it. A helper container has the proxy's volumes, running or not; only a regular file moves.
@@ -904,30 +943,63 @@ autostopper_back() {
904943 [ -f "$DIR/.jar.aside" ] || return 0
905944 autostopper_mv .jar.aside "\${f%.aside}" "put back" && rm -f "$DIR/.jar.aside"
906945 }
907 # `compose up …`, with the jars first when the forge named any.
946 # Whether nobody is on the network: the proxy is stopped, or its own count in the people sync (`glist all`) is
947 # a fresh 0. Not known is someone. An old 0 is read again at the next sync.
948 nobody_on() {
949 local up
950 up="$(capped 5 "$DOCKER" compose -p game --project-directory "$DIR" -f "$DIR/compose.yml" ps -q --status running velocity 2>/dev/null)" || return 1
951 [ -n "$up" ] || return 0
952 jq -e '.network | strings | gsub("\u001b\\[[0-9;]*m|\u00a7."; "")
953 | test("(^|[^0-9])0 players are currently connected") and (test("\\([1-9][0-9]*\\):") | not)' "$DIR/.people.json" >/dev/null 2>&1 || return 1
954 [ $(($(date +%s) - $(stat -c %Y "$DIR/.people.json" 2>/dev/null || echo 0))) -le 30 ] || { touch "$DIR/.people.due"; return 1; }
955 }
956 # `compose up …`, with the jars first when the forge named any. The first try for a compose file is a person's
957 # commit. A later one, with no commit, restarts the proxy only when nobody is on: .jars.late is the file that
958 # was held back, .jars.waits says its jars are here and it waits.
908959 up_job() {
909 local rc rest
960 local rc rest files text last="${*: -1}" waits=0
910961 if [ ! -s "$DIR/.jars.json" ]; then
962 rm -f "$DIR/.jars.rest" "$DIR/.jars.late" "$DIR/.jars.waits"
911963 compose "$@"
912964 return
913965 fi
914 if jars_ready && autostopper_aside; then
915 compose "$@"
916 rc=$?
917 if [ "$rc" = 0 ]; then rm -f "$DIR/.jar.aside"; else autostopper_back; fi
918 return "$rc"
966 text="$(sha256sum <"$DIR/compose.yml" | cut -d' ' -f1)"
967 if jars_ready; then
968 if [ "$last" = --remove-orphans ] && [ "$text" = "$(cat "$DIR/.jars.late" 2>/dev/null)" ] && ! nobody_on; then
969 waits=1
970 elif autostopper_aside; then
971 compose "$@"
972 rc=$?
973 rm -f "$DIR/.jars.rest"
974 if [ "$rc" = 0 ]; then rm -f "$DIR/.jar.aside"; else autostopper_back; fi
975 if [ "$rc" = 0 ] && [ -f "$DIR/.jars.late" ]; then
976 # A person's recreate of the proxy ends the wait too: the next up makes the commit current.
977 [ "$last" != velocity ] || rm -f "$DIR/.up.failed"
978 case "$last" in velocity | --remove-orphans) rm -f "$DIR/.jars.late" "$DIR/.jars.waits" ;; esac
979 fi
980 return "$rc"
981 fi
919982 fi
920983 autostopper_back
921984 echo "the proxy is left as it is"
922985 # An up of one service is a person's recreate: nothing else is touched for it.
923 [ "${*: -1}" = --remove-orphans ] || return 1
986 [ "$last" = --remove-orphans ] || return 1
987 printf '%s' "$text" >"$DIR/.jars.late"
988 if [ "$waits" = 1 ]; then : >"$DIR/.jars.waits"; else rm -f "$DIR/.jars.waits"; fi
924989 rest="$(compose config --services 2>/dev/null | grep -vx velocity)"
925 # shellcheck disable=SC2086 # service names, one word each
926 [ -z "$rest" ] || compose up -d --no-deps --remove-orphans $rest
990 # Once for the same files: a later try for the jar alone does nothing to the other servers.
991 files="$(cat "$DIR/compose.yml" "$DIR/.env" 2>/dev/null | sha256sum | cut -d' ' -f1)"
992 if [ "$files" != "$(cat "$DIR/.jars.rest" 2>/dev/null)" ]; then
993 # shellcheck disable=SC2086 # service names, one word each
994 [ -z "$rest" ] || compose up -d --no-deps --remove-orphans $rest || return 1
995 printf '%s' "$files" >"$DIR/.jars.rest"
996 fi
997 # The job's last line: the forge's pages read it (games/diag.ts, JARS_WAIT).
998 [ "$waits" = 0 ] || echo "the jar is here; the proxy restarts when nobody is on"
927999 return 1
9281000 }
929 export -f jars_ready autostopper_mv autostopper_aside autostopper_back up_job
930 export AUTOSTOPPER_PROJECT AUTOSTOPPER_SHA512
1001 export -f capped nobody_on jars_key jar_wrong jars_ready autostopper_mv autostopper_aside autostopper_back up_job
1002 export AUTOSTOPPER_PROJECT AUTOSTOPPER_SHA512 JAR_RETRY JAR_CURL_RETRY
9311003
9321004 # ---- the owner's shell (#17151 V4): `bash -lc` under `capped`, at most FORGE_GAME_SHELL_S
9331005 # seconds (30) with no terminal and no input, so an interactive program ends at once; its output,
@@ -965,6 +1037,15 @@ shell_tick() {
9651037 apply() {
9661038 local answer="$1" sha changed=0 changed_env=0 name
9671039 sha="$(jq -r '.composeSha // ""' <<<"$answer")"
1040 # A jar that was missing is there now: an up it held back is tried again, with no new commit.
1041 if jq -e '.jars | type == "array"' <<<"$answer" >/dev/null 2>&1; then
1042 jq -c '.jars' <<<"$answer" >"$DIR/.jars.json.next" && mv "$DIR/.jars.json.next" "$DIR/.jars.json"
1043 [ "$(jars_key <"$DIR/.jars.json")" = "$(cat "$DIR/.jars.tried" 2>/dev/null)" ] || rm -f "$DIR/.up.failed"
1044 # So is one whose fetch brought no file, once its wait is over.
1045 [ ! -s "$DIR/.jars.retry" ] || [ "$(date +%s)" -lt "$(cut -d' ' -f1 "$DIR/.jars.retry")" ] || rm -f "$DIR/.up.failed"
1046 # And one that waited for the last player to leave.
1047 if [ -f "$DIR/.jars.waits" ] && nobody_on; then rm -f "$DIR/.up.failed"; fi
1048 fi
9681049 if jq -e 'has("compose") and (.compose | type == "string")' <<<"$answer" >/dev/null 2>&1 &&
9691050 [ "$sha" != "$(cat "$DIR/.compose-sha" 2>/dev/null)" ] && [ "$sha" != "$(cat "$DIR/.up.failed" 2>/dev/null)" ]; then
9701051 jq -j '.compose' <<<"$answer" >"$DIR/compose.yml.next" && mv "$DIR/compose.yml.next" "$DIR/compose.yml"
@@ -1288,7 +1369,7 @@ sync() {
12881369 logs "$since" | json_or '{}' >"$DIR/.sync.logs"
12891370 json_or '[]' <"$DIR/.results" >"$DIR/.sync.results"
12901371 host | json_or '{}' >"$DIR/.sync.host"
1291 bounded_diag | jq -c --argjson hold "$(held)" '. + {hold: $hold}' 2>/dev/null | json_or '{}' >"$DIR/.sync.diag"
1372 bounded_diag | jq -c --argjson hold "$(held)" --argjson waits "$([ -f "$DIR/.jars.waits" ] && echo true || echo false)" '. + {hold: $hold} + (if $waits then {jarsWait: true} else {} end)' 2>/dev/null | json_or '{}' >"$DIR/.sync.diag"
12921373 people | json_or '{}' >"$DIR/.sync.people"
12931374 metrics | json_or '{}' >"$DIR/.sync.metrics"
12941375 jq -c 'if type == "object" then . else {} end' "$WORLDS/snapshots.json" 2>/dev/null | json_or '{}' >"$DIR/.sync.snapshots"
@@ -1757,6 +1838,8 @@ metadata_close
17571838 LIGHT_EVERY="${FORGE_GAME_LIGHT_EVERY:-1}"
17581839 # A whole number of seconds, at least 1: 0 or text would never let the wait end or grow.
17591840 [[ "$LIGHT_EVERY" =~ ^[1-9][0-9]{0,2}$ ]] || LIGHT_EVERY=1
1841 # How long such a second really is: shorter in tests, which wait for many syncs.
1842 LIGHT_SLEEP="${FORGE_GAME_LIGHT_SLEEP:-$LIGHT_EVERY}"
17601843 light_sync() {
17611844 local answer round
17621845 for round in 1 2; do
@@ -1778,7 +1861,7 @@ light_sync() {
17781861 wait_polling() {
17791862 local waited=0
17801863 while [ "$waited" -lt "$EVERY" ]; do
1781 sleep "$LIGHT_EVERY"
1864 sleep "$LIGHT_SLEEP"
17821865 waited=$((waited + LIGHT_EVERY))
17831866 # A failed poll (the forge is down or restarting) ends no wait early: the rest of EVERY is
17841867 # waited out, so a full sync never follows at once and boxes do not all come back together.
src/games/diag.ts +9 −1
@@ -22,8 +22,13 @@ export interface Diag {
2222 readonly versions?: { readonly docker?: string; readonly compose?: string };
2323 /** Why the agent starts nothing, as a code, and when it last looked; null when it is not held, and an older agent does not say. */
2424 readonly hold?: Hold | null;
25 /** The proxy's jars are on the box, and the proxy restarts for them when nobody is on. */
26 readonly jarsWait?: boolean;
2527 }
2628
29 /** The last line of the agent's `up` that waits for the last player to leave (`agent.sh`, `up_job`). */
30 export const JARS_WAIT = "the jar is here; the proxy restarts when nobody is on";
31
2732 const HOLDS = ["no-volume", "signature", "mount", "other-worlds"] as const;
2833 export interface Hold {
2934 readonly why: (typeof HOLDS)[number] | "unknown";
@@ -42,7 +47,7 @@ export function keptDiag(raw: unknown): string {
4247 if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return "{}";
4348 const text = JSON.stringify(raw);
4449 const hold = holdOf(raw);
45 return text.length <= DIAG_MOST ? text : JSON.stringify({ note: `the box sent ${text.length} bytes of diagnosis; at most ${DIAG_MOST} are kept`, ...(hold === undefined ? {} : { hold }) });
50 return text.length <= DIAG_MOST ? text : JSON.stringify({ note: `the box sent ${text.length} bytes of diagnosis; at most ${DIAG_MOST} are kept`, ...(hold === undefined ? {} : { hold }), ...((raw as Diag).jarsWait === true ? { jarsWait: true } : {}) });
4651 }
4752
4853 export function readDiag(text: string): Diag {
@@ -70,6 +75,7 @@ export function boxStatusShared(d: Diag): string[] {
7075 const out: string[] = [];
7176 const job = d.job ?? {};
7277 if (job.running === true) out.push(`${/pull/i.test(job.label ?? "") ? "Pulling" : "Applying"} since ${job.since ?? "?"}`);
78 else if (lastLine(d.upLog ?? "") === JARS_WAIT) out.push(`Waiting: ${JARS_WAIT}`);
7379 else if (job.last !== undefined && job.last !== "" && job.last !== "0") out.push("The box's last change did not apply; its owner can see why");
7480 const ps = d.ps ?? [];
7581 if (ps.length > 0) out.push(`${ps.filter((c) => c.state === "running").length} of ${ps.length} running`);
@@ -115,6 +121,8 @@ export function boxStatus(d: Diag): string[] {
115121 ? `Pulling${job.label ? ` (${job.label})` : ""} since ${job.since ?? "?"}${pulling === "" ? "" : `: ${pulling}`}`
116122 : `Applying (${job.label ?? "a job"}) since ${job.since ?? "?"}`,
117123 );
124 } else if (lastLine(log) === JARS_WAIT) {
125 out.push(`Waiting: ${JARS_WAIT}`);
118126 } else if (job.last !== undefined && job.last !== "" && job.last !== "0") {
119127 out.push(`${job.label || "compose up"} failed: ${lastLine(log, /error|failed|denied|no such|not found/i) || lastLine(log) || `exit ${job.last}`}`);
120128 }
src/games/proxy_jars.ts +4 −3
@@ -18,6 +18,7 @@ import {
1818 setServiceEnv,
1919 setServiceListItem,
2020 } from "./compose.ts";
21 import { JARS_WAIT } from "./diag.ts";
2122 import { OWN_AUTOSTOPPER, proxyImage, proxyOf, sleeping, syncSleep } from "./sleep.ts";
2223 import { keptJar, signedJarHref, type GameBox } from "./store.ts";
2324
@@ -83,7 +84,7 @@ const autoStoppers = (text: string, proxy: string): number =>
8384 /**
8485 * Why a compose change does not reach `box`, or not its proxy: an agent that does not check the jars
8586 * is sent no change at all; one that does leaves the proxy as it is when a jar is refused or was
86 * never uploaded, and tries again only when the file changes. "" when nothing is held back.
87 * never uploaded, and tries again once it is uploaded or pinned. "" when nothing is held back.
8788 */
8889 export function heldWords(
8990 app: App,
@@ -96,13 +97,13 @@ export function heldWords(
9697 if (proxy === undefined || !pluginUrls(compose.text, proxy).some((p) => p.startsWith(AT))) return "";
9798 if (box.holdsJars) {
9899 const bad = jarsOf(app, box, compose.text, "", pins).find((j) => j.sha256 === "" || j.url === "");
99 if (bad === undefined) return "";
100 if (bad === undefined) return box.diag.jarsWait === true ? `${proxy} is left as it is, and the other servers come up: ${JARS_WAIT}. A person's Recreate does not wait.` : "";
100101 const why =
101102 autoStoppers(compose.text, proxy) > 1
102103 ? "two AutoStoppers, and Velocity loads only one of them. Take one out of PLUGINS or MODRINTH_PROJECTS."
103104 : bad.sha256 === ""
104105 ? `${bad.name}, which this forge does not pin. Take it out of PLUGINS.`
105 : `${bad.name}, which nobody uploaded to ${box.name}. Upload it under Forge plugins on ${proxy}'s page, then commit a change to ${box.path}, a comment is enough: the box tries again only when there is a new commit.`;
106 : `${bad.name}, which nobody uploaded to ${box.name}. Upload it under Forge plugins on ${proxy}'s page: the box takes it at its next sync, with no new commit, and ${proxy} restarts when nobody is on. If ${proxy} stops before that, it may not start again until the jar is there.`;
106107 return `${proxy} is left as it is, and the other servers come up: ${box.path} names ${why}`;
107108 }
108109 return `No change to ${box.path} reaches ${box.name} until its agent updates: the file names a forge plugin, and this agent is older than the one that checks it. Nothing is lost: the agent updates itself when it syncs, and then the box takes the newest commit.`;
test/game-jars.test.ts +172 −7
@@ -10,6 +10,7 @@ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSyn
1010 import { rm } from "node:fs/promises";
1111 import { tmpdir } from "node:os";
1212 import { join } from "node:path";
13 import { JARS_WAIT } from "../src/games/diag.ts";
1314 import { AUTOSTOPPER, AUTOSTOPPER_SHA512 } from "../src/games/sleep.ts";
1415 import { pollUntil } from "./helpers/poll.ts";
1516
@@ -24,7 +25,7 @@ const JAR = "our AutoStopper";
2425 const NAME = `AutoStopper-${sha("sha256", JAR).slice(0, 12)}.jar`;
2526
2627 /** A box whose forge hands out `compose` and `jars`, and serves `served` as every jar. */
27 function made(o: { compose?: string; jars?: boolean; served?: string; upFails?: boolean; upTakes?: number; ours?: boolean; name?: string }) {
28 function made(o: { compose?: string; jars?: boolean; served?: string; status?: () => number; upFails?: boolean; upTakes?: number; running?: boolean | "unknown"; name?: string; ours?: boolean; glist?: () => string; reverted?: () => boolean; jar?: (port: number) => { url: string; sha256: string } }) {
2829 const root = mkdtempSync(join(tmpdir(), "forge-game-jars-"));
2930 const dir = join(root, "game");
3031 const plugins = join(root, "server/plugins");
@@ -32,12 +33,19 @@ function made(o: { compose?: string; jars?: boolean; served?: string; upFails?:
3233 writeFileSync(join(plugins, "AutoStopper-3.0.0.jar"), OLD);
3334 writeFileSync(join(plugins, "other.jar"), "another plugin");
3435 const fake = join(root, "docker");
36 // The proxy's console: what `glist all` answers.
37 const nsenter = join(root, "nsenter");
38 writeFileSync(nsenter, `#!/usr/bin/env bash\ncat "${root}/glist"\n`);
39 chmodSync(nsenter, 0o755);
40 writeFileSync(join(root, "glist"), o.glist?.() ?? "");
3541 writeFileSync(
3642 fake,
3743 `#!/usr/bin/env bash
3844 case "$*" in
3945 *" config --services"*) printf 'velocity\\nhub\\nsurvival\\n' ;;
40 *" ps -a -q velocity"*) echo c1 ;;
46 *" ps -a -q velocity"* | *" ps -q velocity"*) echo c1 ;;
47 "inspect -f "*) echo 1 ;;
48 *" ps -q --status running velocity"*) ${o.running === "unknown" ? "exit 1" : o.running === true ? "echo c1" : ":"} ;;
4149 "run "*"--volumes-from c1"*) cd "${root}/server" && exec sh -euc "\${@: -1}" ;;
4250 *" up "*)
4351 all="$*"
@@ -58,10 +66,12 @@ exit 0
5866 port: 0,
5967 hostname: "127.0.0.1",
6068 async fetch(req): Promise<Response> {
61 if (new URL(req.url).pathname === "/jar") return new Response(o.served ?? JAR);
69 if (new URL(req.url).pathname === "/jar") return new Response(o.served ?? JAR, { status: o.status?.() ?? 200 });
6270 bodies.push((await req.json()) as Record<string, any>);
63 const jars = [{ name: o.name ?? NAME, url: `http://127.0.0.1:${String(forge.port)}/jar?sig=secret`, sha256: sha("sha256", JAR) }];
64 return Response.json({ composeSha: sha("sha256", compose), compose, commands: [], ...(o.jars === false ? {} : { jars }) });
71 if (o.glist !== undefined) writeFileSync(join(root, "glist"), o.glist());
72 if (o.reverted?.() === true) return Response.json({ composeSha: "reverted", compose: "services: { old: {} }\n", commands: [], env: { ".env": "RCON_VELOCITY=pw\n" } });
73 const jars = [{ name: o.name ?? NAME, url: `http://127.0.0.1:${String(forge.port)}/jar?sig=secret`, sha256: sha("sha256", JAR), ...o.jar?.(forge.port ?? 0) }];
74 return Response.json({ composeSha: sha("sha256", compose), compose, commands: [], ...(o.glist === undefined ? {} : { env: { ".env": "RCON_VELOCITY=pw\n" } }), ...(o.jars === false ? {} : { jars }) });
6575 },
6676 });
6777 cleanups.push(async () => {
@@ -69,7 +79,7 @@ exit 0
6979 await rm(root, { recursive: true, force: true });
7080 });
7181 /** Run the agent until its first job has ended and been reaped. */
72 const run = async (env: Record<string, string> = {}): Promise<void> => {
82 const run = async (env: Record<string, string> = {}, until: () => boolean = () => existsSync(join(dir, ".job.last"))): Promise<void> => {
7383 const p = Bun.spawn(["bash", AGENT], {
7484 env: {
7585 PATH: process.env["PATH"] ?? "",
@@ -77,17 +87,22 @@ exit 0
7787 FORGE_GAME_TOKEN: "fgb_abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG",
7888 FORGE_GAME_DIR: dir,
7989 FORGE_GAME_DOCKER: fake,
90 FORGE_GAME_NSENTER: nsenter,
8091 FORGE_GAME_AUTOSTOPPER_SHA512: sha("sha512", OLD),
8192 FORGE_GAME_DIAG_S: "0",
8293 FORGE_GAME_VOLUME_CHECK: "0",
8394 FORGE_GAME_ONCE: "0",
95 // The clock alone: a full sync each 0.1 s, and curl's own second and third try left out.
96 FORGE_GAME_EVERY: "1",
97 FORGE_GAME_LIGHT_SLEEP: "0.1",
98 FORGE_GAME_JAR_CURL_RETRY: "0",
8499 ...env,
85100 },
86101 stdout: "ignore",
87102 stderr: "ignore",
88103 });
89104 try {
90 await pollUntil(() => existsSync(join(dir, ".job.last")), "the job to end", 30_000);
105 await pollUntil(until, "the job to end", 60_000);
91106 } finally {
92107 p.kill();
93108 await p.exited;
@@ -172,6 +187,156 @@ test("an up that fails on another service, after the proxy took our AutoStopper,
172187 expect(there).toEqual(["AutoStopper-3.0.0-forge.1.".concat(sha("sha256", JAR).slice(0, 12), ".jar"), "AutoStopper-3.0.0.jar.aside", "other.jar"].sort());
173188 });
174189
190 test("a kept jar with the right sha256 needs no address; one whose bytes changed goes away, and a folder Docker made is readable", async () => {
191 const kept = made({ jar: () => ({ url: "", sha256: sha("sha256", JAR) }) });
192 mkdirSync(join(kept.dir, "jars"), { recursive: true });
193 chmodSync(join(kept.dir, "jars"), 0o700);
194 writeFileSync(join(kept.dir, "jars", NAME), JAR);
195 await kept.run();
196 expect(kept.read("ups")).toBe("up -d --remove-orphans\n");
197 expect(statSync(join(kept.dir, "jars")).mode & 0o777).toBe(0o755);
198 const changed = made({ jar: () => ({ url: "", sha256: sha("sha256", JAR) }) });
199 mkdirSync(join(changed.dir, "jars"), { recursive: true });
200 writeFileSync(join(changed.dir, "jars", NAME), "changed");
201 await changed.run();
202 expect(changed.read("ups")).toBe("up -d --no-deps --remove-orphans hub survival\n");
203 expect(readdirSync(join(changed.dir, "jars"))).toEqual([]);
204 expect(changed.log()).toContain(`${NAME} is not on this box, and the forge has no copy`);
205 });
206
207 test.each([true, "unknown"] as const)("a kept jar with wrong bytes stays while the proxy runs, or Docker does not say (running: %p)", async (running) => {
208 const box = made({ running, jar: () => ({ url: "", sha256: sha("sha256", JAR) }) });
209 mkdirSync(join(box.dir, "jars"), { recursive: true });
210 writeFileSync(join(box.dir, "jars", NAME), "changed");
211 await box.run();
212 expect(readFileSync(join(box.dir, "jars", NAME), "utf8")).toBe("changed");
213 expect(box.log()).toContain(`${NAME} has wrong bytes and stays while the proxy runs`);
214 expect(box.read("ups")).toBe("up -d --no-deps --remove-orphans hub survival\n");
215 });
216
217 test("a jar the forge does not pin is refused, also when a file of its name is kept", async () => {
218 const box = made({ jar: () => ({ url: "", sha256: "" }) });
219 mkdirSync(join(box.dir, "jars"), { recursive: true });
220 writeFileSync(join(box.dir, "jars", NAME), JAR);
221 await box.run();
222 expect(box.read("ups")).toBe("up -d --no-deps --remove-orphans hub survival\n");
223 });
224
225 test("the proxy held back for a jar comes up once the jar is uploaded, with no new commit; a changed link alone is no reason", async () => {
226 let uploaded = false;
227 let links = 0;
228 const box = made({ jar: (port) => ({ url: uploaded ? `http://127.0.0.1:${port}/jar?sig=${++links}` : "", sha256: sha("sha256", JAR) }) });
229 const ups = () => box.read("ups").trim().split("\n");
230 await box.run();
231 expect(ups()).toEqual(["up -d --no-deps --remove-orphans hub survival"]);
232 uploaded = true;
233 await box.run({}, () => existsSync(join(box.dir, ".compose-sha")));
234 expect(ups()).toEqual(["up -d --no-deps --remove-orphans hub survival", "up -d --remove-orphans"]);
235 }, 60_000);
236
237 test("a fetch with no answer worth having is tried again after a wait that grows, with no new commit", async () => {
238 let up = false;
239 const box = made({ status: () => (up ? 200 : 503) });
240 const held = "up -d --no-deps --remove-orphans hub survival";
241 const ups = () => box.read("ups").trim().split("\n");
242 // No wait, then an hour: two tries, however many syncs follow.
243 const tries = () => Number(readFileSync(join(box.dir, ".jars.retry"), "utf8").split(" ")[1]);
244 const syncs = () => box.bodies.filter((b) => b["light"] !== true).length;
245 let after = Infinity;
246 await box.run({ FORGE_GAME_JAR_RETRY: "0 3600" }, () => {
247 if (after === Infinity && existsSync(join(box.dir, ".jars.retry")) && tries() === 2) after = syncs() + 3;
248 return syncs() >= after;
249 });
250 expect(tries()).toBe(2);
251 // The second try did nothing to the other servers.
252 expect(ups()).toEqual([held]);
253 // The wait is over and the forge is back.
254 up = true;
255 writeFileSync(join(box.dir, ".jars.retry"), "0 2\n");
256 await box.run({ FORGE_GAME_JAR_RETRY: "0 3600" }, () => existsSync(join(box.dir, ".compose-sha")));
257 expect(ups()).toEqual([held, "up -d --remove-orphans"]);
258 expect(existsSync(join(box.dir, ".jars.retry"))).toBe(false);
259 }, 120_000);
260
261 const REST = "up -d --no-deps --remove-orphans hub survival";
262 const SOMEONE = "[hub] (1): Alice\n1 player is currently connected to the proxy.\n";
263 const NOBODY = "\u00a7e0 players are currently connected to the proxy.\n";
264 /** A running proxy whose jar is uploaded after the commit that names it; the first try held it back. */
265 async function late(glist: () => string, reverted: () => boolean = () => false) {
266 let uploaded = false;
267 const box = made({ running: true, glist, reverted, jar: (port) => ({ url: uploaded ? `http://127.0.0.1:${port}/jar` : "", sha256: sha("sha256", JAR) }) });
268 const env = { FORGE_GAME_PEOPLE_EVERY: "0" };
269 const full = () => box.bodies.filter((b) => b["light"] !== true);
270 const ups = () => box.read("ups").trim().split("\n");
271 /** Run until `n` more full syncs after `first` holds. */
272 const more = async (n: number, first: () => boolean = () => true): Promise<void> => {
273 let at = Infinity;
274 await box.run(env, () => {
275 if (at === Infinity && first()) at = full().length + n;
276 return full().length >= at;
277 });
278 };
279 await more(0, () => existsSync(join(box.dir, ".up.failed")));
280 expect(ups()).toEqual([REST]);
281 uploaded = true;
282 return { box, full, ups, more, waits: () => existsSync(join(box.dir, ".jars.waits")) };
283 }
284
285 for (const [who, said] of [
286 ["someone is on", SOMEONE],
287 ["who is on is not known", ""],
288 ["ten are on", "[hub] (10): Alice\n10 players are currently connected to the proxy.\n"],
289 ] as const)
290 test(`a jar that came after the commit is fetched, and the proxy is not restarted while ${who}`, async () => {
291 let glist: string = said;
292 const b = await late(() => glist);
293 await b.more(4, b.waits);
294 expect(readFileSync(join(b.box.dir, "jars", NAME), "utf8")).toBe(JAR);
295 expect(b.ups()).toEqual([REST]);
296 expect(b.box.log().trim().split("\n").at(-1)).toBe(JARS_WAIT);
297 expect(b.full().at(-1)!["diag"].jarsWait).toBe(true);
298 // The last player leaves.
299 glist = NOBODY;
300 await b.more(0, () => existsSync(join(b.box.dir, ".compose-sha")));
301 expect(b.ups()).toEqual([REST, "up -d --remove-orphans"]);
302 expect(b.waits()).toBe(false);
303 }, 120_000);
304
305 test("a jar that came after the commit restarts the proxy when nobody is on", async () => {
306 const b = await late(() => NOBODY);
307 await b.more(0, () => existsSync(join(b.box.dir, ".compose-sha")));
308 expect(b.ups()).toEqual([REST, "up -d --remove-orphans"]);
309 }, 120_000);
310
311 test("the first try right after a commit does not wait for the players", async () => {
312 const box = made({ running: true, glist: () => SOMEONE });
313 await box.run({ FORGE_GAME_PEOPLE_EVERY: "0" });
314 expect(box.read("ups")).toBe("up -d --remove-orphans\n");
315 });
316
317 test("a revert ends the waiting: one ordinary up of the old file, and none when the players leave", async () => {
318 let reverted = false;
319 let glist = SOMEONE;
320 const b = await late(() => glist, () => reverted);
321 await b.more(1, b.waits);
322 reverted = true;
323 await b.more(1, () => existsSync(join(b.box.dir, ".compose-sha")));
324 expect(b.waits()).toBe(false);
325 expect(existsSync(join(b.box.dir, ".jars.late"))).toBe(false);
326 glist = NOBODY;
327 await b.more(4);
328 // No --force-recreate: compose leaves a proxy alone that already runs the old file.
329 expect(b.ups()).toEqual([REST, "up -d --remove-orphans"]);
330 expect(readFileSync(join(b.box.dir, "compose.yml"), "utf8")).toBe("services: { old: {} }\n");
331 }, 120_000);
332
333 test("a jar with wrong bytes is not tried at every sync, though its link changes each time", async () => {
334 let links = 0;
335 const box = made({ served: "something else", jar: (port) => ({ url: `http://127.0.0.1:${port}/jar?sig=${++links}`, sha256: sha("sha256", JAR) }) });
336 await box.run({ FORGE_GAME_JAR_RETRY: "0" }, () => box.bodies.filter((b) => b["light"] !== true).length >= 4);
337 expect(box.read("ups")).toBe("up -d --no-deps --remove-orphans hub survival\n");
338 }, 60_000);
339
175340 test("while the compose file still fetches AutoStopper, its jar stays", async () => {
176341 const box = made({ compose: `# MODRINTH_PROJECTS: ${AUTOSTOPPER}\nservices: {}\n` });
177342 await box.run();
test/game-proxy-jars.test.ts +11 −3
@@ -13,6 +13,7 @@ import { createApp, type App } from "../src/app.ts";
1313 import { createToken } from "../src/core/tokens.ts";
1414 import { createUser, getUserByName, type User } from "../src/core/users.ts";
1515 import { readCompose, serviceEnv } from "../src/games/compose.ts";
16 import { boxStatus, JARS_WAIT } from "../src/games/diag.ts";
1617 import { commitJar, heldWords, jarsOf, PINS, planJar, type Pin } from "../src/games/proxy_jars.ts";
1718 import { AGENT_SH } from "../src/games/boot.ts";
1819 import { AUTOSTOPPER, setPolicy, syncSleep } from "../src/games/sleep.ts";
@@ -185,7 +186,7 @@ test("a proxy left as it is for a jar nobody uploaded, one the forge does not pi
185186 for (const path of ["", "/velocity"]) {
186187 const html = await page(path);
187188 expect(html).toContain(`names ${pinned.name}, which nobody uploaded to mc. Upload it under Forge plugins`);
188 expect(html).toContain("then commit a change to docker-compose.yml");
189 expect(html).toContain("the box takes it at its next sync, with no new commit");
189190 }
190191 const words = (names: string[], more = "") => {
191192 const t = COMPOSE.replace("a.jar", ["a.jar", ...names.map((n) => `/forge-jars/${n}`)].join(",")).replace(" TYPE: VELOCITY\n", ` TYPE: VELOCITY\n${more}`);
@@ -196,6 +197,12 @@ test("a proxy left as it is for a jar nobody uploaded, one the forge does not pi
196197 // A jar the forge keeps, or the commit the box already runs: nothing to say.
197198 expect((await storeJar(app, box.id, new Blob([GOOD]), "kept.jar")).ok).toBe(true);
198199 expect(words([TALK.name])).toBe("");
200 // It is on the box, and the players are not cut off for it.
201 const was = box;
202 box = { ...was, diag: { jarsWait: true } };
203 expect(words([TALK.name])).toContain("the jar is here; the proxy restarts when nobody is on");
204 expect(boxStatus({ job: { label: "compose up", last: "1" }, upLog: `the proxy is left as it is\n${JARS_WAIT}\n` })).toEqual([`Waiting: ${JARS_WAIT}`]);
205 box = was;
199206 await sync({ composeSha: (await readCompose(app, box))!.sha, jars: true });
200207 expect(await page("/velocity")).not.toContain("which nobody uploaded");
201208 app.db.query("DELETE FROM game_jar").run();
@@ -347,7 +354,7 @@ test("a proxy the box's agent would not hold back is refused: it knows the servi
347354 expect(await planJar(app, box, TALK)).toMatchObject({ ok: false, error: expect.stringContaining("velocity") });
348355 });
349356
350 test("the agent's own check takes what the sync names, and refuses an empty sha256 or address", async () => {
357 test("the agent's own check takes what the sync names, also without an address, and refuses an empty sha256", async () => {
351358 const program = /jq -e '(type == "array" and length <= 8[^']+)'/.exec(AGENT_SH)?.[1];
352359 expect(program).toBeDefined();
353360 const takes = async (jars: unknown): Promise<boolean> =>
@@ -357,7 +364,8 @@ test("the agent's own check takes what the sync names, and refuses an empty sha2
357364 expect(good[0]!.url).toStartWith(ORIGIN);
358365 expect(await takes(good)).toBe(true);
359366 expect(await takes(jarsOf(app, box, named("mine.jar"), ORIGIN, pins))).toBe(false);
360 expect(await takes(jarsOf(app, { id: "another-box" }, named(TALK.name), ORIGIN, pins))).toBe(false);
367 // Nobody uploaded it there: a file the box kept with this sha256 will do (game-jars.test.ts).
368 expect(await takes(jarsOf(app, { id: "another-box" }, named(TALK.name), ORIGIN, pins))).toBe(true);
361369 // What the forge pins passes by name and number too.
362370 expect(await takes(PINS.map((p) => ({ name: p.name, url: `${ORIGIN}/x`, sha256: p.sha256 })))).toBe(true);
363371 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs