arcadible 1.0.39 → 1.0.40-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,58 @@
1
+ // the packed pages that load the SDK's 1.5 hosted script,
2
+ // /arcadible/sdk/v1.js, which stays as it was released for the builds
3
+ // released with it: a fact each page's markup says, read as a browser reads
4
+ // it, each `script` element's `src` by its path. A script a page adds by
5
+ // code isn't seen, on purpose: that would be a guess.
6
+ // [import]
7
+ import { WARNING } from "../../config/code.js";
8
+ import { sdkScriptOld } from "../../phrase/index.js";
9
+ import { attrsOf, childrenOf, parseDocument, tagOf, } from "../../util/tree.js";
10
+ // [declare]
11
+ // the SDK's 1.5 script, and the current SDK's.
12
+ const OLD = "/arcadible/sdk/v1.js";
13
+ const NOW = "/arcadible/lib/sdk.v1.js";
14
+ // how much is read, so a package of any size is checked quickly: the most
15
+ // pages, and the most of one. Past them a page isn't read, so a warning can
16
+ // be missed, never made up.
17
+ const MAX_PAGES = 200;
18
+ const MAX_PAGE = 1024 * 1024;
19
+ // [function]
20
+ // whether a script's `src` names the old script: its path, without its
21
+ // query or fragment, ending in `/arcadible/sdk/v1.js` exactly, from the
22
+ // root or from the page.
23
+ function isOld(src) {
24
+ const path = src.trim().split(/[?#]/u)[0] ?? "";
25
+ return `/${path}`.endsWith(OLD);
26
+ }
27
+ // [function]
28
+ // whether a document loads the old script: any `script` element's `src`,
29
+ // in the head or the body. A template's content and a comment aren't
30
+ // elements of the page, so they're never read.
31
+ function loads(node) {
32
+ if (tagOf(node) === "script" && "attrs" in node) {
33
+ const src = attrsOf(node).find((attr) => attr.name === "src");
34
+ if (src && isOld(src.value)) {
35
+ return true;
36
+ }
37
+ }
38
+ return childrenOf(node).some(loads);
39
+ }
40
+ // [function]
41
+ // each packed page that loads the old script, by its name in the package.
42
+ export function hosted(zip) {
43
+ const pages = zip
44
+ .entries()
45
+ .filter((entry) => entry.size <= MAX_PAGE && /\.html?$/iu.test(entry.name))
46
+ .slice(0, MAX_PAGES);
47
+ return pages.flatMap((page) => {
48
+ const html = zip.read(page.name)?.toString("utf8");
49
+ return html !== undefined && loads(parseDocument(html))
50
+ ? [
51
+ {
52
+ code: WARNING.SDK_SCRIPT_OLD,
53
+ message: sdkScriptOld(page.name, OLD, NOW),
54
+ },
55
+ ]
56
+ : [];
57
+ });
58
+ }
@@ -13,6 +13,7 @@ import { check, checkEntries, measure } from "./limits.js";
13
13
  import { favicon } from "../../util/favicon.js";
14
14
  import { handle, tool } from "../../config/product.js";
15
15
  import { toMb } from "../../util/size.js";
16
+ import { hosted } from "./hosted.js";
16
17
  import { unsound } from "./unsound.js";
17
18
  import { Zip } from "../../util/zip.js";
18
19
  // [use]
@@ -152,6 +153,7 @@ function pack(name, game, { deployDir, icon, inputPath, mediaPath, onWarning, ou
152
153
  .then((file) => {
153
154
  if (onWarning) {
154
155
  unsound(file.entries()).forEach(onWarning);
156
+ hosted(file).forEach(onWarning);
155
157
  }
156
158
  file.write(outputPath);
157
159
  return { path: outputPath, ...file.stat() };
@@ -127,6 +127,7 @@ export const WARNING = {
127
127
  PACKAGE_FILE_DEV: "package_file_dev",
128
128
  PACKAGE_FILE_PRIVATE: "package_file_private",
129
129
  SCREENSHOT_NAME_INVALID: "screenshot_name_invalid",
130
+ SDK_SCRIPT_OLD: "sdk_script_old",
130
131
  VERSION_UNCHECKED: "version_unchecked",
131
132
  };
132
133
  // every error code, for checking one exists.
@@ -4,8 +4,9 @@ import { domain, handle, protocol } from "./product.js";
4
4
  const DOMAIN = domain;
5
5
  const PROTOCOL = protocol;
6
6
  // [declare]
7
- // a build origin, where arc serve fetches the SDK's hosted script
8
- // (src/serve/remote.js): any of them serves it at /arcadible/sdk/. The play
7
+ // a build origin, where arc serve fetches the SDK's hosted scripts
8
+ // (src/serve/remote.js): any of them serves SDK 2's at /arcadible/lib/, and
9
+ // 1.5's at /arcadible/sdk/. The play
9
10
  // page's host comes from the play site, HOST_HTTP_PLAY.
10
11
  export const ARCADIBLE_SDK = `https://sdk.${handle}.io`;
11
12
  export const HOST_APP_PLAY = `${PROTOCOL}://play`;
@@ -11,6 +11,10 @@ export function packageFileDev(dir) {
11
11
  return `Packing ${dir}, a project's installed packages.\nSet deploy_dir to the folder your build writes.`;
12
12
  }
13
13
  // [function]
14
+ export function sdkScriptOld(page, old, now) {
15
+ return `${page} loads ${old}, the Arcadible SDK before 1.6, which gets no new calls.\nLoad ${now} instead, for the current SDK.`;
16
+ }
17
+ // [function]
14
18
  export function packageFilePrivate(file) {
15
19
  return `Packing ${file}, which anyone can download.\nLeave it out of the package unless it's meant to be public.`;
16
20
  }
@@ -15,7 +15,7 @@ export function portInUse(port) {
15
15
  }
16
16
  // [function]
17
17
  // what one of Arcadible's files is, for arc serve's warnings: `host`, the play
18
- // page's, or a path under /arcadible/, such as sdk/v1.js.
18
+ // page's, or a path under /arcadible/, such as lib/sdk.v1.js.
19
19
  function remoteName(name) {
20
20
  return name === "host" ? "the play page's host" : `/${HANDLE}/${name}`;
21
21
  }
@@ -13,6 +13,7 @@ import { readFile } from "node:fs/promises";
13
13
  import { endWith, pathOf } from "./game.js";
14
14
  import { FAVICON } from "../config/asset.js";
15
15
  import { isTable } from "../util/objs.js";
16
+ import { retryOf } from "./retry.js";
16
17
  import { originOf } from "./ticket.js";
17
18
  import { SCOPES, } from "./values.js";
18
19
  // [declare]
@@ -630,7 +631,7 @@ async function sendGameValues(req, res, verb, { player, values }) {
630
631
  // [function]
631
632
  // an answer in the API's own envelope, with how many when it's a list the
632
633
  // API counts.
633
- function sendData(req, res, status, data, count) {
634
+ function sendData(req, res, status, data, count, more = {}) {
634
635
  res.writeHead(status, {
635
636
  ...HEADERS,
636
637
  "content-type": "application/json; charset=utf-8",
@@ -638,6 +639,7 @@ function sendData(req, res, status, data, count) {
638
639
  const meta = {
639
640
  success: status === 200,
640
641
  ...(count === undefined ? {} : { count }),
642
+ ...more,
641
643
  };
642
644
  endWith(req, res, JSON.stringify({ data, meta }));
643
645
  }
@@ -684,9 +686,11 @@ function windowOf(pathname, named) {
684
686
  // for a conflict, the items it names.
685
687
  function sendRefusal(req, res, status, conflicts) {
686
688
  const [title, message] = REFUSALS[status] ?? ["", ""];
689
+ const code = REFUSAL_CODES[status] ?? "invalid";
687
690
  sendData(req, res, status, {
688
- code: REFUSAL_CODES[status] ?? "invalid",
691
+ code,
689
692
  message,
693
+ retry: retryOf(code),
690
694
  status,
691
695
  title,
692
696
  type: "HttpError",
@@ -812,8 +816,10 @@ async function sendServer(req, res, route, { game, tickets, values, wires, }) {
812
816
  sendData(req, res, 200, ids.map((id) => tickets.player(id)), ids.length);
813
817
  return;
814
818
  }
819
+ // no one deletes an account here: an empty feed, with no cursor, as
820
+ // the API answers one that's never listed anyone
815
821
  if (route === "/deleted_players") {
816
- sendData(req, res, 200, []);
822
+ sendData(req, res, 200, [], undefined, { next: null });
817
823
  return;
818
824
  }
819
825
  if (route.startsWith("/values/")) {
@@ -852,7 +858,8 @@ async function sendServer(req, res, route, { game, tickets, values, wires, }) {
852
858
  return;
853
859
  }
854
860
  const { data, status } = await tickets.check(asked["ticket"], asked["server"]);
855
- sendData(req, res, status, data);
861
+ // a ticket refused says whether to try again, as the API's refusals do
862
+ sendData(req, res, status, status === 200 ? data : { ...data, retry: retryOf(data.code) });
856
863
  }
857
864
  // [function]
858
865
  // the request handler for the page's origin. `reloads` keeps the pages
@@ -1,6 +1,7 @@
1
1
  // the files Arcadible serves itself, fetched from where Arcadible serves
2
2
  // them, so a fix reaches `arc serve` without a new CLI: the SDK's hosted
3
- // script, as every game's origin serves it at /arcadible/sdk/, and the play
3
+ // scripts, as every game's origin serves them, SDK 2's at /arcadible/lib/
4
+ // and 1.5's, frozen, at /arcadible/sdk/, and the play
4
5
  // page's host, as the play page runs it. Each is fetched once a session, and
5
6
  // the last copy is kept on disk for when Arcadible can't be reached, or
6
7
  // answers 403 or 404 for a file that's always there: the names this module
@@ -19,9 +20,10 @@ import { isTable } from "../util/objs.js";
19
20
  // the current copy. `v1` is the shape of the `arcadibleHost` global, which
20
21
  // this CLI calls: a breaking change to it is v2, beside v1.
21
22
  const HOST_PATH = "/asset/host.v1.min.js";
22
- // the files under /arcadible/ that Arcadible serves: the SDK's, such as
23
- // sdk/v1.js. Anything else there isn't found, as on Arcadible.
24
- const SDK_PATH = /^sdk\/[\w.-]+$/u;
23
+ // the files under /arcadible/ that Arcadible serves: the SDK's hosted
24
+ // scripts and their maps, lib/sdk.v1.js (SDK 2's) and sdk/v1.js (1.5's).
25
+ // Anything else there isn't found, as on Arcadible.
26
+ const SDK_PATH = /^(?:lib|sdk)\/[\w.-]+$/u;
25
27
  // [function]
26
28
  // a file kept from a fetch, or null.
27
29
  async function readKept(dir, name) {
@@ -59,7 +61,8 @@ async function keep(dir, name, { body, ...meta }) {
59
61
  }
60
62
  // [function]
61
63
  // the files from Arcadible. `host` is the play site's origin, `sdk` an
62
- // origin that serves /arcadible/sdk/, and `dir` where copies are kept.
64
+ // origin that serves /arcadible/lib/ and /arcadible/sdk/, and `dir` where
65
+ // copies are kept.
63
66
  // `get(name)` resolves with `{ body, type, fetchedAt, kept, refused? }`,
64
67
  // where `kept` says the copy is from disk because Arcadible couldn't be
65
68
  // reached, or answered `refused` (403 or 404); or null when Arcadible has
@@ -0,0 +1,44 @@
1
+ // Whether to try again after one of Arcadible's refusals, as `arc serve`
2
+ // answers it, beside the code: in the body of each refusal, and as a header
3
+ // on the function's and the wires' (plan/SDK2.md, Errors and codes). The
4
+ // same as Arcadible's own (the dispatcher's and the wires' Worker's
5
+ // `RETRIES`, the API's app/result.py's `RETRY`; ERRORS.md).
6
+ // [declare]
7
+ // the header that says it, beside the refusal's mark: dropped from what a
8
+ // function's code answers, as the mark is.
9
+ export const RETRY = "x-arcadible-retry";
10
+ // each code `arc serve` refuses with, and its answer.
11
+ const RETRIES = {
12
+ busy: "yes",
13
+ conflict: "later",
14
+ denied: "no",
15
+ expired: "later",
16
+ full: "later",
17
+ function_failed: "later",
18
+ invalid: "no",
19
+ method_not_allowed: "no",
20
+ no_function: "no",
21
+ not_found: "no",
22
+ too_large: "no",
23
+ unavailable: "yes",
24
+ };
25
+ // [function]
26
+ /**
27
+ * A refusal's retry, as Arcadible's parts say it (the dispatcher's and the
28
+ * wires' `retryOf`): a `401` "later" whatever its code, since its fix is a
29
+ * new ticket; otherwise the code's own, or, for a code that isn't there,
30
+ * its status's: a `429` or a `5xx` but `507` "yes", a `409` or a `507`
31
+ * "later", anything else (or no status) "no".
32
+ */
33
+ export function retryOf(code, status) {
34
+ if (status === 401)
35
+ return "later";
36
+ const own = RETRIES[code];
37
+ if (own !== undefined)
38
+ return own;
39
+ if (status === undefined)
40
+ return "no";
41
+ if (status === 429 || (status >= 500 && status !== 507))
42
+ return "yes";
43
+ return status === 409 || status === 507 ? "later" : "no";
44
+ }
@@ -15,6 +15,7 @@ import { dirname, join } from "node:path";
15
15
  // [import]
16
16
  import { bundle } from "../runner/bundle.js";
17
17
  import { ENTRY, ENTRY_MODULE, FUNCTION_MODULE } from "../runner/entry.js";
18
+ import { RETRY, retryOf } from "./retry.js";
18
19
  // [declare]
19
20
  // where a runner answers on the game's origin, as on Arcadible, where the
20
21
  // folder is Arcadible's own on every build's site: the path itself, and
@@ -70,6 +71,7 @@ const OUTBOUND = join(import.meta.dirname, "..", "runner", "outbound.js");
70
71
  // terminal's, where its developer is; what the code answers goes back
71
72
  // without the mark.
72
73
  const FRONT = `const REFUSAL = ${JSON.stringify(REFUSAL)};
74
+ const RETRY = ${JSON.stringify(RETRY)};
73
75
  export default {
74
76
  async fetch(request, env) {
75
77
  let answer;
@@ -78,13 +80,17 @@ export default {
78
80
  } catch (err) {
79
81
  console.error("The function threw:", String(err));
80
82
  return Response.json(
81
- { code: ${JSON.stringify(FAILED)} },
82
- { headers: { [REFUSAL]: ${JSON.stringify(FAILED)} }, status: 502 },
83
+ { code: ${JSON.stringify(FAILED)}, retry: ${JSON.stringify(retryOf(FAILED))} },
84
+ {
85
+ headers: { [REFUSAL]: ${JSON.stringify(FAILED)}, [RETRY]: ${JSON.stringify(retryOf(FAILED))} },
86
+ status: 502,
87
+ },
83
88
  );
84
89
  }
85
- if (!answer.headers.has(REFUSAL)) return answer;
90
+ if (!answer.headers.has(REFUSAL) && !answer.headers.has(RETRY)) return answer;
86
91
  const headers = new Headers(answer.headers);
87
92
  headers.delete(REFUSAL);
93
+ headers.delete(RETRY);
88
94
  return new Response(answer.body, { headers, status: answer.status, statusText: answer.statusText });
89
95
  },
90
96
  };
@@ -96,21 +102,23 @@ const READY_MS = 15000;
96
102
  const CORS = {
97
103
  "access-control-allow-headers": "authorization, content-type",
98
104
  // so a game on another origin (--url) reads Arcadible's refusal too
99
- "access-control-expose-headers": REFUSAL,
105
+ "access-control-expose-headers": `${REFUSAL}, ${RETRY}`,
100
106
  "access-control-allow-methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS",
101
107
  "access-control-allow-origin": "*",
102
108
  "access-control-max-age": "600",
103
109
  };
104
110
  // [function]
105
- // Arcadible's own answer, marked as the dispatcher marks it: a status, and
106
- // a code the SDK's `functions.fetch` rejects with.
111
+ // Arcadible's own answer, marked as the dispatcher marks it: a status, a
112
+ // code the SDK's `functions.fetch` rejects with, and whether to try again.
107
113
  function refuse(res, status, code) {
114
+ const retry = retryOf(code, status);
108
115
  res.writeHead(status, {
109
116
  ...CORS,
110
117
  "content-type": "application/json",
111
118
  [REFUSAL]: code,
119
+ [RETRY]: retry,
112
120
  });
113
- res.end(JSON.stringify({ code }));
121
+ res.end(JSON.stringify({ code, retry }));
114
122
  }
115
123
  // [function]
116
124
  /**
@@ -472,9 +480,10 @@ export async function runner({ dir, handler, hosts = [], main, origin, secrets =
472
480
  ...CORS,
473
481
  "content-type": "application/json",
474
482
  [REFUSAL]: FAILED,
483
+ [RETRY]: retryOf(FAILED),
475
484
  });
476
485
  }
477
- res.end(JSON.stringify({ code: FAILED }));
486
+ res.end(JSON.stringify({ code: FAILED, retry: retryOf(FAILED) }));
478
487
  };
479
488
  if (failed || !child) {
480
489
  fail();
@@ -10,7 +10,8 @@ import crypto from "node:crypto";
10
10
  // [import]
11
11
  import { WebSocketServer } from "ws";
12
12
  // [import]
13
- import { CLOSED, createRoom, LIMITS, PING, PONG, PROTOCOL, ticketClose, } from "../wires/room.js";
13
+ import { closeOf, createRoom, LIMITS, PING, PONG, protocolOf, PROTOCOLS, ticketClose, } from "../wires/room.js";
14
+ import { RETRY, retryOf } from "./retry.js";
14
15
  import { CHANNEL } from "./ticket.js";
15
16
  // [declare]
16
17
  // where wires answer on a build's own origin, as on Arcadible
@@ -28,7 +29,7 @@ const CORS = {
28
29
  "access-control-allow-headers": "authorization, content-type",
29
30
  "access-control-allow-methods": "POST, OPTIONS",
30
31
  "access-control-allow-origin": "*",
31
- "access-control-expose-headers": REFUSAL,
32
+ "access-control-expose-headers": `${REFUSAL}, ${RETRY}`,
32
33
  "access-control-max-age": "600",
33
34
  };
34
35
  // the largest frame a connection may send, Cloudflare's: a larger message
@@ -93,8 +94,12 @@ export function wires({ drop = null, game, origin, tickets, }) {
93
94
  }, LIMITS.idle);
94
95
  sweeper.unref();
95
96
  const server = new WebSocketServer({
96
- // the protocol's name is answered alone: the ticket beside it isn't one
97
- handleProtocols: (offered) => (offered.has(PROTOCOL) ? PROTOCOL : false),
97
+ // the protocol's name is answered alone, the newest offered: the
98
+ // ticket beside it isn't one
99
+ handleProtocols: (offered) => {
100
+ const protocol = protocolOf([...offered]);
101
+ return protocol === null ? false : PROTOCOLS[protocol];
102
+ },
98
103
  maxPayload: FRAME_MAX,
99
104
  noServer: true,
100
105
  });
@@ -138,12 +143,14 @@ export function wires({ drop = null, game, origin, tickets, }) {
138
143
  return;
139
144
  }
140
145
  const refuse = function (status, code) {
146
+ const retry = retryOf(code, status);
141
147
  res.writeHead(status, {
142
148
  ...CORS,
143
149
  "content-type": "application/json",
144
150
  [REFUSAL]: code,
151
+ [RETRY]: retry,
145
152
  });
146
- res.end(JSON.stringify({ code }));
153
+ res.end(JSON.stringify({ code, retry }));
147
154
  };
148
155
  if (req.method !== "POST") {
149
156
  refuse(405, "invalid");
@@ -173,23 +180,35 @@ export function wires({ drop = null, game, origin, tickets, }) {
173
180
  const offered = (req.headers["sec-websocket-protocol"] ?? "")
174
181
  .split(",")
175
182
  .map((each) => each.trim());
176
- const ticket = offered.find((each) => each !== PROTOCOL);
183
+ const protocol = protocolOf(offered) ?? 1;
184
+ const named = new Set(Object.values(PROTOCOLS));
185
+ const ticket = offered.find((each) => !named.has(each));
177
186
  server.handleUpgrade(req, socket, head, (ws) => {
178
- // a connection that's refused opens, and closes with why: a
179
- // browser is told nothing of one that never opens
180
- const refuse = (code) => ws.close(CLOSED[code], code);
187
+ // a connection that's refused opens, and closes with why, as its
188
+ // protocol says it: a browser is told nothing of one that never
189
+ // opens
190
+ const refuse = (code, number) => ws.close(...closeOf(code, protocol, number));
181
191
  ws.on("error", () => ws.terminate());
182
- if (!offered.includes(PROTOCOL) || !isOurs(id)) {
192
+ if (protocolOf(offered) === null || !isOurs(id)) {
183
193
  refuse("invalid");
184
194
  return;
185
195
  }
186
196
  void memberOf(ticket).then((who) => {
187
197
  if ("code" in who) {
188
- ws.close(ticketClose(who.code), who.code);
198
+ refuse(who.code, ticketClose(who.code));
199
+ return;
200
+ }
201
+ // the wires a player is on, counted here as Arcadible counts
202
+ // them: past them a wire is full (`too_many` in the first
203
+ // protocol)
204
+ const theirs = [...running].filter(([other, { on: those }]) => other !== id &&
205
+ [...those.values()].some((each) => each.member.id === who.member.id)).length;
206
+ if (theirs >= LIMITS.wires) {
207
+ refuse(protocol === 2 ? "full" : "too_many");
189
208
  return;
190
209
  }
191
210
  const { on, room } = wire(id);
192
- const refused = room.admit(who.member);
211
+ const refused = room.admit(who.member, protocol);
193
212
  if (refused) {
194
213
  if (on.size === 0)
195
214
  running.delete(id);
@@ -202,6 +221,7 @@ export function wires({ drop = null, game, origin, tickets, }) {
202
221
  heard: Date.now(),
203
222
  key,
204
223
  member: who.member,
224
+ protocol,
205
225
  socket: ws,
206
226
  };
207
227
  on.set(key, mine);
package/dist/util/tree.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // HTML as a browser reads it, with parse5 (the parser jsdom itself uses),
2
- // and the little the CLI asks of its tree: a README's parts (parser/), and
3
- // a description's tags, attributes, and comments (util/doc.ts).
2
+ // and the little the CLI asks of its tree: a README's parts (parser/), a
3
+ // description's tags, attributes, and comments (util/doc.ts), and a packed
4
+ // page's scripts (action/pack/hosted.ts).
4
5
  // [import]
5
6
  import { defaultTreeAdapter, html as spec, parse, parseFragment, serializeOuter, } from "parse5";
6
7
  // [function]
@@ -12,6 +13,11 @@ export function bodyOf(html) {
12
13
  return body ?? defaultTreeAdapter.createElement("body", spec.NS.HTML, []);
13
14
  }
14
15
  // [function]
16
+ // a whole document, as a browser builds it around `html`.
17
+ export function parseDocument(html) {
18
+ return parse(html);
19
+ }
20
+ // [function]
15
21
  // a fragment's nodes, as a template's content holds them.
16
22
  export function fragmentOf(html) {
17
23
  return parseFragment(html);
package/dist/util/zip.js CHANGED
@@ -62,6 +62,12 @@ export class Zip {
62
62
  }));
63
63
  }
64
64
  // [method]
65
+ // a file's content, by its name relative to the zip's folder, or null.
66
+ read(name) {
67
+ const entry = this.zip.getEntry(join(this.prefix, name));
68
+ return entry && !entry.isDirectory ? entry.getData() : null;
69
+ }
70
+ // [method]
65
71
  // every entry in the zip, files and folders.
66
72
  count() {
67
73
  return this.zip.getEntries().length;
@@ -5,17 +5,32 @@
5
5
  // wire in both. It holds no connection: whatever runs it says who's
6
6
  // connected (`list`), and it says what to send to whom (`deliver`) and whom
7
7
  // to drop (`drop`). It imports nothing, so a runtime runs it as it is.
8
+ //
9
+ // It speaks two protocols, each connection its own: the first,
10
+ // `arcadible-wire.v1`, frozen with the builds released on it, and the
11
+ // second, `arcadible-wire.v2` (plan/SDK2.md, A wire's protocol), whose
12
+ // welcome says the wire's limits, whose message says whether it's the
13
+ // server's, and whose refusals and closes say whether to try again.
8
14
  // [declare]
9
- /** The protocol a connection speaks, named as it opens. */
15
+ /** The first protocol, named as a connection opens: frozen with the builds released on it. */
10
16
  export const PROTOCOL = "arcadible-wire.v1";
17
+ /** The second protocol (plan/SDK2.md, A wire's protocol). */
18
+ export const PROTOCOL_V2 = "arcadible-wire.v2";
19
+ /** Each protocol's name, by its number. */
20
+ export const PROTOCOLS = {
21
+ 1: PROTOCOL,
22
+ 2: PROTOCOL_V2,
23
+ };
11
24
  /** What a connection sends to say it's there, and what it's answered. */
12
25
  export const PING = "ping";
13
26
  export const PONG = "pong";
14
27
  /**
15
28
  * A wire's limits (LIMITS.md): a message's size as JSON, in bytes; a
16
29
  * member's sends a second, and at once; the wire's, every member's
17
- * together; its members; one member's connections; and how long a
18
- * connection may go unheard, in milliseconds.
30
+ * together; its members; one member's connections; how long a connection
31
+ * may go unheard, in milliseconds; and the wires one player is on at once,
32
+ * on a game's channel, which whatever runs the wires counts, since a wire
33
+ * knows only itself.
19
34
  */
20
35
  export const LIMITS = {
21
36
  connections: 8,
@@ -25,6 +40,7 @@ export const LIMITS = {
25
40
  rate: 20,
26
41
  rateBurst: 40,
27
42
  wireRate: 200,
43
+ wires: 4,
28
44
  };
29
45
  /**
30
46
  * The code a connection is closed with, for each reason: in the range a
@@ -41,6 +57,45 @@ export const CLOSED = {
41
57
  };
42
58
  /** A connection that went unheard: closed, and free to come back. */
43
59
  export const IDLE = 4408;
60
+ /**
61
+ * The second protocol's closes, by the plan's ranges (plan/SDK2.md, A
62
+ * wire's protocol), which a copy that can't read a close's reason falls
63
+ * back on: what's final 4400 to 4499, and what's tried again 4500 and up.
64
+ * So beside the first's numbers for what's final, a ticket's close is
65
+ * `4501` (a new ticket, `later`), `unavailable` `4503`, `full` `4507`
66
+ * (where the first says `too_many`), `idle` `4508`, and `busy` `4529`. The
67
+ * first protocol keeps its own, which its copies hold a table of.
68
+ */
69
+ export const CLOSED_V2 = {
70
+ busy: 4529,
71
+ denied: 4403,
72
+ expired: 4501,
73
+ full: 4507,
74
+ idle: 4508,
75
+ invalid: 4400,
76
+ too_large: 4413,
77
+ too_many: 4409,
78
+ unavailable: 4503,
79
+ };
80
+ /** The second protocol's close for a thing that's full. */
81
+ export const FULL = CLOSED_V2.full;
82
+ /**
83
+ * Whether to try again after each refusal and close, as the second protocol
84
+ * says it beside the code (ERRORS.md, Wires): "yes", after a moment;
85
+ * "later", once something changes (a new ticket, a seat free); "no", not as
86
+ * it is.
87
+ */
88
+ export const RETRIES = {
89
+ busy: "yes",
90
+ denied: "no",
91
+ expired: "later",
92
+ full: "later",
93
+ idle: "yes",
94
+ invalid: "no",
95
+ too_large: "no",
96
+ too_many: "no",
97
+ unavailable: "yes",
98
+ };
44
99
  // [function]
45
100
  /**
46
101
  * The close for a ticket a wire didn't take, by why: `4401` for one that ran
@@ -49,9 +104,43 @@ export const IDLE = 4408;
49
104
  * be checked `4503`. The close's reason says which.
50
105
  */
51
106
  export function ticketClose(code) {
107
+ if (code === "full")
108
+ return FULL;
52
109
  return code === "invalid" ? CLOSED.expired : CLOSED[code];
53
110
  }
54
111
  // [function]
112
+ /**
113
+ * The protocol a connection asks for, of those it offers as it opens: the
114
+ * newest a wire speaks, or null for none. Whatever else it offers (its
115
+ * ticket) isn't one.
116
+ */
117
+ export function protocolOf(offered) {
118
+ if (offered.includes(PROTOCOL_V2))
119
+ return 2;
120
+ if (offered.includes(PROTOCOL))
121
+ return 1;
122
+ return null;
123
+ }
124
+ // [function]
125
+ /**
126
+ * A close, as a protocol says it: its number, and its reason. In the first,
127
+ * the first's number (`number`, where it isn't the code's: a ticket's,
128
+ * `ticketClose`) and the code. In the second, `CLOSED_V2`'s and
129
+ * "<code> <retry>" (`full later`); a ticket's close, the first's `4401`, is
130
+ * the second's `4501`, "later" whatever its code, since its fix is a new
131
+ * ticket, as an HTTP `401`'s is.
132
+ */
133
+ export function closeOf(code, protocol = 1, number) {
134
+ if (protocol === 1) {
135
+ const said = number ??
136
+ (code === "idle" ? IDLE : code === "full" ? FULL : CLOSED[code]);
137
+ return [said, code];
138
+ }
139
+ if (number === CLOSED.expired)
140
+ return [CLOSED_V2.expired, `${code} later`];
141
+ return [CLOSED_V2[code], `${code} ${RETRIES[code]}`];
142
+ }
143
+ // [function]
55
144
  // tokens that refill at `rate` a second, up to `burst`: whether one is
56
145
  // there to take, at `at`.
57
146
  function bucket(rate, burst) {
@@ -97,12 +186,16 @@ export function memberOf(value) {
97
186
  }
98
187
  // [function]
99
188
  /**
100
- * A wire. Frames are JSON text, one thing each: to a connection,
101
- * `{ welcome: { you, members } }` as it comes on, then
189
+ * A wire. Frames are JSON text, one thing each. In the first protocol, to
190
+ * a connection, `{ welcome: { you, members } }` as it comes on, then
102
191
  * `{ message: { data, from, at } }`, `{ join: member }`, `{ leave: member }`,
103
192
  * and `{ refused: code }` for a send that wasn't taken; from one,
104
- * `{ send: data }`. A member is a player, however many connections they
105
- * have: the rest hear `join` at their first and `leave` at their last.
193
+ * `{ send: data }`. In the second, to a connection,
194
+ * `{ welcome: { you, members, limits: { rate, size } } }`, then
195
+ * `{ message: { data, from, server, at } }`, `{ join }`, `{ leave }`, and
196
+ * `{ refused: { code, retry } }`; from one, a message's data itself. A
197
+ * member is a player, however many connections they have: the rest hear
198
+ * `join` at their first and `leave` at their last.
106
199
  */
107
200
  export function createRoom(options) {
108
201
  const now = options.now ?? (() => Date.now());
@@ -111,6 +204,9 @@ export function createRoom(options) {
111
204
  // for long
112
205
  const sends = new Map();
113
206
  const wire = bucket(LIMITS.wireRate, LIMITS.wireRate);
207
+ // what the second protocol's welcome says of the wire's limits: a
208
+ // member's sends a second, and a message's size, in bytes of its text
209
+ const limits = { rate: LIMITS.rate, size: LIMITS.message };
114
210
  // who's on: each member once, in the order they came
115
211
  const members = function () {
116
212
  const seen = new Map();
@@ -120,27 +216,45 @@ export function createRoom(options) {
120
216
  }
121
217
  return [...seen.values()];
122
218
  };
123
- const all = function (frame, but) {
124
- const text = JSON.stringify(frame);
219
+ // a frame to every connection but one, each in its protocol: made as
220
+ // text once for each
221
+ const all = function (frames, but) {
222
+ const texts = new Map();
125
223
  for (const each of options.list()) {
126
- if (each.key !== but)
127
- options.deliver(each.key, text);
224
+ if (each.key === but)
225
+ continue;
226
+ const protocol = each.protocol ?? 1;
227
+ let text = texts.get(protocol);
228
+ if (text === undefined) {
229
+ text = JSON.stringify(frames[protocol]);
230
+ texts.set(protocol, text);
231
+ }
232
+ options.deliver(each.key, text);
128
233
  }
129
234
  };
130
235
  // one message, to everyone on the wire, the sender included, stamped
131
236
  // here: the order they're sent in is the wire's order
132
237
  const message = function (data, from) {
133
- all({ message: { at: new Date(now()).toISOString(), data, from } });
238
+ const at = new Date(now()).toISOString();
239
+ all({
240
+ 1: { message: { at, data, from } },
241
+ // the function is the only sender that isn't a player, for now: a
242
+ // later kind of sender with no `from` must not be read as its word
243
+ 2: { message: { at, data, from, server: from === null } },
244
+ });
134
245
  options.passed?.();
135
246
  };
136
247
  return {
137
- admit(member) {
248
+ admit(member, protocol = 1) {
138
249
  const on = options.list();
139
250
  const theirs = on.filter((each) => each.member.id === member.id).length;
251
+ // a thing that's full is `full` in the second protocol, and the
252
+ // first's `too_many` in the first
253
+ const full = protocol === 2 ? "full" : "too_many";
140
254
  if (theirs >= LIMITS.connections)
141
- return "too_many";
255
+ return full;
142
256
  if (theirs === 0 && members().length >= LIMITS.members)
143
- return "too_many";
257
+ return full;
144
258
  return null;
145
259
  },
146
260
  joined(key) {
@@ -148,11 +262,14 @@ export function createRoom(options) {
148
262
  const mine = on.find((each) => each.key === key);
149
263
  if (!mine)
150
264
  return;
151
- options.deliver(key, JSON.stringify({ welcome: { members: members(), you: mine.member } }));
265
+ const welcome = { members: members(), you: mine.member };
266
+ options.deliver(key, JSON.stringify({
267
+ welcome: mine.protocol === 2 ? { ...welcome, limits } : welcome,
268
+ }));
152
269
  // their first connection: the rest hear they came
153
270
  const first = !on.some((each) => each.key !== key && each.member.id === mine.member.id);
154
271
  if (first)
155
- all({ join: mine.member }, key);
272
+ all({ 1: { join: mine.member }, 2: { join: mine.member } }, key);
156
273
  },
157
274
  left(member) {
158
275
  // their last connection: the rest hear they went
@@ -160,16 +277,21 @@ export function createRoom(options) {
160
277
  // their rate is kept, so leaving and coming back never starts it full
161
278
  // (servers:21a)
162
279
  if (!still)
163
- all({ leave: member });
280
+ all({ 1: { leave: member }, 2: { leave: member } });
164
281
  },
165
282
  said(key, text) {
166
283
  const mine = options.list().find((each) => each.key === key);
167
284
  if (!mine)
168
285
  return;
169
- const refuse = (code) => options.deliver(key, JSON.stringify({ refused: code }));
170
- // a frame is `{"send":<data>}`: its data's size, as JSON, is the
171
- // frame's less what's around it
172
- if (size(text) - '{"send":}'.length > LIMITS.message) {
286
+ const second = mine.protocol === 2;
287
+ const refuse = (code) => options.deliver(key, JSON.stringify({
288
+ refused: second ? { code, retry: RETRIES[code] } : code,
289
+ }));
290
+ // in the first, a frame is `{"send":<data>}`: its data's size, as
291
+ // JSON, is the frame's less what's around it; in the second, the
292
+ // frame is the data
293
+ const around = second ? 0 : '{"send":}'.length;
294
+ if (size(text) - around > LIMITS.message) {
173
295
  refuse("too_large");
174
296
  return;
175
297
  }
@@ -178,11 +300,13 @@ export function createRoom(options) {
178
300
  frame = JSON.parse(text);
179
301
  }
180
302
  catch {
181
- frame = null;
303
+ refuse("invalid");
304
+ return;
182
305
  }
183
- if (typeof frame !== "object" ||
184
- frame === null ||
185
- !Object.hasOwn(frame, "send")) {
306
+ if (!second &&
307
+ (typeof frame !== "object" ||
308
+ frame === null ||
309
+ !Object.hasOwn(frame, "send"))) {
186
310
  refuse("invalid");
187
311
  return;
188
312
  }
@@ -198,7 +322,7 @@ export function createRoom(options) {
198
322
  refuse("busy");
199
323
  return;
200
324
  }
201
- message(frame.send, mine.member);
325
+ message(second ? frame : frame.send, mine.member);
202
326
  },
203
327
  server(data) {
204
328
  if (data === undefined)
@@ -213,8 +337,9 @@ export function createRoom(options) {
213
337
  let stay = 0;
214
338
  // as it stood: dropping one changes who's listed
215
339
  for (const each of [...options.list()]) {
216
- if (at - each.heard > LIMITS.idle)
217
- options.drop(each.key, IDLE, "idle");
340
+ if (at - each.heard > LIMITS.idle) {
341
+ options.drop(each.key, ...closeOf("idle", each.protocol ?? 1));
342
+ }
218
343
  else
219
344
  stay += 1;
220
345
  }
@@ -42,7 +42,7 @@
42
42
  },
43
43
  "license": "Apache-2.0",
44
44
  "name": "arcadible",
45
- "version": "1.0.39"
45
+ "version": "1.0.40-next.0"
46
46
  },
47
47
  "node_modules/@cacheable/memory": {
48
48
  "dependencies": {
@@ -2433,5 +2433,5 @@
2433
2433
  }
2434
2434
  },
2435
2435
  "requires": true,
2436
- "version": "1.0.39"
2436
+ "version": "1.0.40-next.0"
2437
2437
  }
package/package.json CHANGED
@@ -66,5 +66,5 @@
66
66
  "test": "tsc && npm run lint && node --test \"test/**/*.test.js\" \"test/**/*.test.mjs\""
67
67
  },
68
68
  "type": "module",
69
- "version": "1.0.39"
69
+ "version": "1.0.40-next.0"
70
70
  }