| 1 | import assert from "node:assert/strict"; |
| 2 | import test from "node:test"; |
| 3 | |
| 4 | import { isNetworkFailure, refreshesCurrent, retriable, retryDelay } from "./resilient-fetch.ts"; |
| 5 | import { reconnectDelay } from "./reconnect.ts"; |
| 6 | |
| 7 | const ORIGIN = "https://g1t.sh"; |
| 8 | const url = (path: string) => new URL(path, ORIGIN); |
| 9 | |
| 10 | test("a request that got no answer, in each browser's words, is a network failure", () => { |
| 11 | assert.equal(isNetworkFailure(new TypeError("Failed to fetch")), true); |
| 12 | assert.equal(isNetworkFailure(new TypeError("NetworkError when attempting to fetch resource.")), true); |
| 13 | assert.equal(isNetworkFailure(new TypeError("Load failed")), true); |
| 14 | }); |
| 15 | |
| 16 | test("a stale build, an abort or a server's error is not", () => { |
| 17 | assert.equal(isNetworkFailure(new TypeError("Failed to fetch dynamically imported module: https://g1t.sh/assets/a.js")), false); |
| 18 | assert.equal(isNetworkFailure(new DOMException("The user aborted a request.", "AbortError")), false); |
| 19 | assert.equal(isNetworkFailure(new Error("Failed to fetch")), false); |
| 20 | assert.equal(isNetworkFailure({ status: 500 }), false); |
| 21 | }); |
| 22 | |
| 23 | test("only the router's own reads are sent again", () => { |
| 24 | assert.equal(retriable(url("/flagon-io/g1t/settings/repository.data?_routes=root"), "GET", ORIGIN), true); |
| 25 | assert.equal(retriable(url("/__manifest?p=/a"), "get", ORIGIN), true); |
| 26 | assert.equal(retriable(url("/flagon-io/g1t/settings/repository.data"), "POST", ORIGIN), false); |
| 27 | assert.equal(retriable(url("/-/notify"), "GET", ORIGIN), false); |
| 28 | assert.equal(retriable(new URL("https://otel.g1t.sh/x.data"), "GET", ORIGIN), false); |
| 29 | }); |
| 30 | |
| 31 | test("a read for the page already showing is a refresh; one for another page is a navigation", () => { |
| 32 | const here = { pathname: "/flagon-io/g1t/settings/repository", search: "" }; |
| 33 | assert.equal(refreshesCurrent(url("/flagon-io/g1t/settings/repository.data?_routes=root,routes/repo/layout"), here), true); |
| 34 | assert.equal(refreshesCurrent(url("/flagon-io/g1t/issues.data"), here), false); |
| 35 | assert.equal(refreshesCurrent(url("/_root.data"), { pathname: "/", search: "" }), true); |
| 36 | assert.equal(refreshesCurrent(url("/a.data?tab=open&_routes=x"), { pathname: "/a", search: "?tab=open" }), true); |
| 37 | assert.equal(refreshesCurrent(url("/a.data?tab=closed"), { pathname: "/a", search: "?tab=open" }), false); |
| 38 | }); |
| 39 | |
| 40 | test("retries come quickly at first, then settle", () => { |
| 41 | assert.deepEqual([1, 2, 3, 4, 5, 9].map(retryDelay), [250, 500, 1000, 2000, 4000, 5000]); |
| 42 | assert.deepEqual([1, 2, 3, 4, 8].map(reconnectDelay), [3000, 6000, 12000, 24000, 30000]); |
| 43 | }); |