From b73b584d2d38657e5c9cff8ce293e1285ac13bf0 Mon Sep 17 00:00:00 2001 From: bbassie <17990055+bbassie@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:21:09 +0000 Subject: [PATCH] Add a TAP test suite alongside mocha Tests live in tests/, mirroring each package's src, and in plugins/*/test/*.test.ts. They are TypeScript run by Node's type stripping, so the @tapjs/typescript plugin is disabled and `pnpm install` runs tap build to apply that. The first tests cover the largest lib files: link, subscriptions, config classes and prometheus. A shared helper checks the JSON serialisable class pattern, and one test runs it on every serialisable class lib exports, with samples generated from each class's schema. Known bugs the new tests found are marked todo. Mocha, codecov and the existing CI matrix are unchanged; tap.yml runs the new suite on the latest Node.js and Factorio. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/tap.yml | 38 + .gitignore | 1 + .taprc | 6 + CONTRIBUTING.md | 6 +- package.json | 14 +- pnpm-workspace.yaml | 3 + scripts/clean.js | 2 +- tests/README.md | 104 ++ tests/lib/config/classes.test.ts | 1158 ++++++++++++++++++ tests/lib/data/json_serialisable.test.ts | 48 + tests/lib/link/link.test.ts | 1208 +++++++++++++++++++ tests/lib/prometheus.test.ts | 1096 +++++++++++++++++ tests/lib/subscriptions.test.ts | 1390 ++++++++++++++++++++++ tests/shared/json_serialisable.ts | 192 +++ tests/shared/link.ts | 72 ++ tests/tsconfig.json | 15 + 16 files changed, 5348 insertions(+), 5 deletions(-) create mode 100644 .github/workflows/tap.yml create mode 100644 .taprc create mode 100644 tests/README.md create mode 100644 tests/lib/config/classes.test.ts create mode 100644 tests/lib/data/json_serialisable.test.ts create mode 100644 tests/lib/link/link.test.ts create mode 100644 tests/lib/prometheus.test.ts create mode 100644 tests/lib/subscriptions.test.ts create mode 100644 tests/shared/json_serialisable.ts create mode 100644 tests/shared/link.ts create mode 100644 tests/tsconfig.json diff --git a/.github/workflows/tap.yml b/.github/workflows/tap.yml new file mode 100644 index 00000000..6289a5a8 --- /dev/null +++ b/.github/workflows/tap.yml @@ -0,0 +1,38 @@ +# TAP test suite, run alongside the mocha suite in node.js.yml until it reaches +# similar coverage. Only the latest Node.js and Factorio are tested here. + +name: TAP tests + +on: + push: + pull_request: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref == 'refs/heads/master' && github.sha || github.ref }} + cancel-in-progress: true + +env: + NODE_VERSION: 26.x + FACTORIO_VERSION: 2.1.17 + +jobs: + changes: + uses: ./.github/workflows/ci-changes.yml + + test: + needs: changes + if: ${{ !cancelled() && needs.changes.outputs.build_and_test != 'false' }} + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v7 + - name: Prepare and install + uses: ./.github/actions/pnpm-install + with: + node-version: ${{ env.NODE_VERSION }} + - name: Use Factorio ${{ env.FACTORIO_VERSION }} + run: wget -q -O factorio.tar.gz https://www.factorio.com/get-download/${{ env.FACTORIO_VERSION }}/headless/linux64 && tar -xf factorio.tar.gz && rm factorio.tar.gz + - name: Type check tests + run: pnpm run test:typecheck + - name: Run tests + run: pnpm run test:tap diff --git a/.gitignore b/.gitignore index 682add85..686598cd 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,7 @@ lib-cov # Coverage directories used by tools like c8 and codecov coverage +/.tap/ # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) .grunt diff --git a/.taprc b/.taprc new file mode 100644 index 00000000..f959d4b8 --- /dev/null +++ b/.taprc @@ -0,0 +1,6 @@ +# Node.js strips the types itself, see tests/README.md +plugin: + - "!@tapjs/typescript" +include: + - "tests/**/*.test.ts" + - "plugins/*/test/**/*.test.ts" diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d1376371..392fd766 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -50,6 +50,7 @@ Clusterio manages distributed Factorio servers through a controller, hosts, and | `packages/host/modules/` | Lua modules injected into saves. | | `packages/host/lua/` | Factorio mod sources, including `clusterio_lib`. | | `test/` | Root test suite, fixtures, helpers, integration harness, and manual tests. Plugin tests also live under `plugins/*/test/`. | +| `tests/` | TAP test suite replacing `test/`, see [its readme](tests/README.md). | Start with [how it works](../how-it-works.md), [communication](communication.md), and the [config system](config-system.md) for architecture. See [writing plugins](writing-plugins.md) and [developing for Clusterio](developing-for-clusterio.md) for plugin and Factorio contracts. @@ -213,6 +214,9 @@ NODE_EXTRA_CA_CERTS="$PWD/test/file/tls/cert.pem" pnpm exec mocha \ ``` Replace the example file with the relevant test; use `--grep` to narrow it further. + +A TAP suite in `tests/` is replacing the Mocha suite one area at a time. +New unit tests go there; see [the TAP test readme](tests/README.md) for layout, conventions and commands. Preserve the test TLS CA configuration for HTTPS integration tests. Use `--require ./test/setup_logging.js` when an isolated test needs the shared logger configured. Some tests import `test/integration/index.js`, which installs root hooks and starts a controller and host even for a targeted invocation. @@ -234,7 +238,7 @@ Inspect `node scripts/clean.js --help` and preview the selected scope with `--dr | Command | Removal scope | | --- | --- | | `node scripts/clean.js --dry-run` | Preview workspace package/plugin build output and Vite dependency caches; omit `--dry-run` to clean, or use `pnpm clean`. | -| `node scripts/clean.js tests --dry-run` | Also preview root `.nyc_output/`, `coverage/`, the whole `temp/` directory, and `static/`. | +| `node scripts/clean.js tests --dry-run` | Also preview root `.nyc_output/`, `.tap/`, `coverage/`, the whole `temp/` directory, and `static/`. | | `node scripts/clean.js all --dry-run` | Also preview runtime databases, instances, logs, mods, local configs, `FactorioAdminToken.txt`, and `plugin-list.json`. | `all` deletes cluster runtime data, including configurations and saves; back up anything you want to keep before using it. diff --git a/package.json b/package.json index 485cf328..1f4f8e89 100644 --- a/package.json +++ b/package.json @@ -15,10 +15,17 @@ "cover": "c8 pnpm test", "fast-cover": "FAST_TEST=y c8 pnpm test", "ci-cover": "c8 --reporter=lcovonly pnpm test", - "lint": "oxlint packages plugins test", - "lint-fix": "oxlint --fix packages plugins test", + "test:tap": "pnpm run build && tap --disable-coverage", + "test:unit": "pnpm run build && tap --disable-coverage \"tests/!(integrations|shared)/**/*.test.ts\"", + "test:integration": "pnpm run build && tap --disable-coverage tests/integrations", + "test:plugins": "pnpm run build && tap --disable-coverage \"plugins/*/test/**/*.test.ts\"", + "test:coverage": "pnpm run build && tap --allow-incomplete-coverage --coverage-report=text --coverage-report=html --no-browser", + "test:typecheck": "tsc -p tests", + "lint": "oxlint packages plugins test tests", + "lint-fix": "oxlint --fix packages plugins test tests", "clean": "node ./scripts/clean.js", - "bundle-dependencies": "bundle-dependencies" + "bundle-dependencies": "bundle-dependencies", + "prepare": "tap build" }, "c8": { "exclude": [ @@ -49,6 +56,7 @@ "jsonwebtoken": "catalog:", "mocha": "^12.0.3", "oxlint": "^1.88.0", + "tap": "^21.8.1", "typescript": "catalog:", "yargs": "catalog:", "yauzl": "catalog:", diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index f1a60dd6..52247aca 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -47,3 +47,6 @@ autoInstallPeers: false linkWorkspacePackages: true shellEmulator: true + +allowBuilds: + '@swc/core': false diff --git a/scripts/clean.js b/scripts/clean.js index e4137b54..dec66b39 100644 --- a/scripts/clean.js +++ b/scripts/clean.js @@ -62,7 +62,7 @@ async function removeBuildArtifacts() { */ async function removeTestArtifacts() { const artifacts = [ - ".nyc_output", "coverage", "temp", "static", + ".nyc_output", ".tap", "coverage", "temp", "static", ]; await Promise.all(artifacts.map(artifact => tryRemove(path.resolve(artifact)))); diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 00000000..8197bda0 --- /dev/null +++ b/tests/README.md @@ -0,0 +1,104 @@ +# TAP tests + +This suite uses [node-tap](https://node-tap.org/) and runs next to the Mocha suite in `test/`. +Mocha is removed once this suite has similar coverage. +Write new unit tests here. + +Tests are TypeScript, run by Node.js directly with type stripping. +The `@tapjs/typescript` plugin is disabled in `.taprc`, so only [erasable syntax](https://www.typescriptlang.org/tsconfig/#erasableSyntaxOnly) works: no enums, parameter properties or namespaces. +Relative imports use the `.ts` extension. +Packages are imported by name, which resolves to their compiled output, so build before running. + + +## Layout + +``` +tests/ +├── integrations/ # Cross-package and host integration tests +├── / # Unit tests, mirroring the package's src/ +└── shared/ # Test utilities and fixtures + +plugins/ +└── / + └── test/ # Plugin-owned tests, named *.test.ts +``` + +Only files ending in `.test.ts` are run. +For example the tests for `packages/lib/src/link/link.ts` are in `tests/lib/link/link.test.ts`. + + +## Writing tests + +Nest tests as `file > class > method > test name`, or `file > function > test name` for plain functions. +Name the imported instance `t` and the nested contexts `t1`, `t2`, `t3`. + +```ts +import t from "tap"; +import * as lib from "@clusterio/lib"; + +t.test("RoleMapping", async t1 => { + t1.test("add()", async t2 => { + t2.test("adds a role", async t3 => { + // ... + }); + }); + t1.test("remove()", async t2 => { + t2.test("removes an existing role", async t3 => { + // ... + }); + }); +}); +``` + +- Use the real classes wherever practical. +- Mock single functions and methods with `t.intercept`, `t.capture` or `t.mockImport`, not whole classes. +- Mock external boundaries such as the network, timers and other nondeterministic sources. +- Each test creates the mutable state it needs. + No test may depend on another test having run or passed. +- Share immutable fixtures and expensive read-only resources at module scope. +- Mark known bugs with `{ todo: "reason" }` so they show up without failing the run. + +Each test file runs in its own process, in parallel with the others. +Keep files independent of each other. +Parallel subtests (`t.jobs`) are for independent asynchronous work within one file. +Tests that need an exclusive resource such as a fixed port go in a directory marked with `serial` in `.taprc`. + + +### Common tests + +`shared/` builds tests that apply to many classes. +`shared/json_serialisable.ts` tests the [JSON serialisable class pattern](../docs/devs/json-serialisable-classes.md): a value survives `JSON.stringify` and `fromJSON`, and the serialised form matches `jsonSchema`. +Samples are generated from the schema, with and without optional properties. +`lib/data/json_serialisable.test.ts` runs it for every serialisable class exported by `@clusterio/lib`, so new data classes and messages are covered without adding a test. +Schemas the generator cannot satisfy, such as strings that must parse as a mod dependency, get hand written samples in that file. + + +## Running + +| Command | Runs | +| --- | --- | +| `pnpm test:tap` | Every TAP test in one shared worker pool, as CI does. | +| `pnpm test:unit` | `tests//`. | +| `pnpm test:integration` | `tests/integrations/`. | +| `pnpm test:plugins` | `plugins/*/test/**/*.test.ts`. | +| `pnpm test:coverage` | Every TAP test with a text and HTML coverage report in `.tap/report/`. | +| `pnpm test:typecheck` | `tsc` over the tests. | + +These scripts build first. +For a single package or file, build and call tap directly: + +```sh +pnpm build +pnpm exec tap --disable-coverage tests/lib +pnpm exec tap --disable-coverage tests/lib/link/link.test.ts +``` + +`--grep` selects subtests by name, one pattern per level. +`--jobs=` sets the number of test files run at once, which defaults to the number of CPUs. +Run tap from the root rather than through `pnpm -r`, which would run a worker pool per package. + +`pnpm install` runs `tap build` to apply the plugin list in `.taprc`. +Run it again after changing that list. + +CI runs this suite in `.github/workflows/tap.yml` on the latest Node.js and Factorio only. +Coverage reported to Codecov still comes from the Mocha suite. diff --git a/tests/lib/config/classes.test.ts b/tests/lib/config/classes.test.ts new file mode 100644 index 00000000..477ce530 --- /dev/null +++ b/tests/lib/config/classes.test.ts @@ -0,0 +1,1158 @@ +import t, { type Test } from "tap"; +import fs from "node:fs/promises"; +import path from "node:path"; +import * as lib from "@clusterio/lib"; +import { testJsonSerialisable } from "../../shared/json_serialisable.ts"; + +const CA = lib.ConfigAccess; + +// "controller" plays the local side and "host" the remote side in most tests. +class TestConfig extends lib.Config { + static defaultAccess: lib.ConfigLocation[] = ["controller", "host"]; + + static migrations(config: any) { + if (Object.hasOwn(config, "test.migration")) { + config["alpha.foo"] = config["test.migration"]; + delete config["test.migration"]; + } + return config; + } + + static fieldDefinitions: lib.ConfigDefs = { + "alpha.foo": { type: "string", optional: true }, + "beta.bar": { type: "object", initialValue: {} }, + "test.enum": { + type: "string", + title: "Enum", + restartRequired: true, + enum: ["a", "b", "c"], + optional: true, + initialValue: "b", + }, + "test.test": { type: "string", optional: true }, + "test.func": { type: "number", initialValue: () => 42 }, + "test.bool": { type: "boolean", initialValue: false, optional: true }, + "test.json": { type: "object", initialValue: {}, optional: true }, + "test.rest": { type: "object", initialValue: {}, optional: true, restartRequired: true }, + "test.priv": { access: ["controller"], type: "string", optional: true }, + "test.cred": { credential: ["controller"], type: "string", optional: true }, + "test.rdo": { readonly: ["controller"], type: "string", optional: true }, + "test.base": { type: "number", initialValue: 1 }, + "test.dependent": { + type: "number", + initialValue: 1, + dependsOn: ["test.base", "test.objDependent"], + validator(value: number, config: lib.Config) { + if (value < config.get("test.base")) { + throw new Error("dependent must be >= base"); + } + if (config.get("test.objDependent")?.base === 0) { + throw new Error("objDependent cannot be 0"); + } + }, + }, + "test.objDependent": { + type: "object", + initialValue: {}, + dependsOn: ["test.base"], + validator(value: any, config: lib.Config) { + if (value.base && value.base !== config.get("test.base")) { + throw new Error("base prop must match test.base"); + } + }, + }, + "test.validated": { + type: "number", + optional: true, + validator(value: number | null) { + if (value !== null && value < 0) { + throw new Error("must be positive"); + } + }, + }, + "test.objValidated": { + type: "object", + initialValue: {}, + validator(value: any) { + if (value && value.bad !== undefined) { + throw new Error("bad key"); + } + }, + }, + // Calls the named mutating method on the config it is given + "test.badValidator": { + type: "string", + optional: true, + dependsOn: ["test.base"], + validator(value: string | null, config: lib.Config) { + if (config.get("test.base") < 1) { + return; + } + if (value === "set") { + config.set("alpha.foo", "BAD"); + } else if (value === "setProp") { + config.setProp("beta.bar", "baz", "BAD"); + } else if (value === "stage") { + config.stage("alpha.foo", "BAD"); + } else if (value === "stageProp") { + config.stageProp("beta.bar", "baz", "BAD"); + } else if (value === "commitStaging") { + config.commitStaging(); + } else if (value === "revertStaging") { + config.revertStaging(); + } + }, + }, + }; +} + +// Serialised form of a default TestConfig at "controller" +const defaults: Record = { + "alpha.foo": null, + "beta.bar": {}, + "test.enum": "b", + "test.test": null, + "test.func": 42, + "test.bool": false, + "test.json": {}, + "test.rest": {}, + "test.priv": null, + "test.cred": null, + "test.rdo": null, + "test.base": 1, + "test.dependent": 1, + "test.objDependent": {}, + "test.validated": null, + "test.objValidated": {}, + "test.badValidator": null, +}; + +// Every field set to a non default value plus unknown fields +const full: Record = { + "alpha.foo": "foo", + "beta.bar": { value: 20 }, + "test.enum": "a", + "test.test": "blah", + "test.func": 50, + "test.bool": true, + "test.json": { nested: { deep: [1, 2] } }, + "test.rest": { a: 1 }, + "test.priv": "priv", + "test.cred": "cred", + "test.rdo": "rdo", + "test.base": 2, + "test.dependent": 3, + "test.objDependent": { base: 2 }, + "test.validated": 5, + "test.objValidated": { good: true }, + "test.badValidator": "none", + "extra.blah": true, + "extra.spam": "foobar", + "extra.null": null, + "extra.obj": { a: 1 }, +}; + +const loaded = { "test.enum": "a", "test.test": "blah", "test.func": 27 }; + +function testConfig(location: lib.ConfigLocation = "controller", fields?: Record, filepath?: string) { + return new TestConfig(location, fields as any, filepath); +} + +/** Record fieldChanged events emitted by a config */ +function fieldChanges(config: lib.Config) { + const changes: unknown[][] = []; + config.on("fieldChanged", (name, curr, prev) => changes.push([name, curr, prev])); + return changes; +} + +/** Log [name, value] for every validator call on TestConfig fields during this test, in call order */ +function validatorLog(tt: Test) { + const log: [string, unknown][] = []; + for (const [name, def] of Object.entries(TestConfig.fieldDefinitions)) { + const original = def.validator; + if (original) { + tt.capture(def as any, "validator", function(this: any, value: unknown, config: any) { + log.push([name, value]); + return original.call(this, value, config); + }); + } + } + return log; +} + +/** Error object matcher for t.throws, compares class and message */ +function error(Class: new (message: string) => Error, message: string | RegExp) { + return { constructor: Class, message }; +} + +t.test("Config", async t1 => { + t1.test("constructor", async t2 => { + t2.test("throws if location is not a string", async t3 => { + t3.throws(() => new TestConfig(undefined as any), error(Error, "location must be a string")); + }); + t2.test("initialises every readable field", async t3 => { + t3.strictSame(testConfig().toJSON(), defaults); + }); + t2.test("leaves out fields the location cannot read", async t3 => { + const config = testConfig("host") as any; + t3.equal(config.fields["test.enum"], "b"); + t3.notOk("test.priv" in config.fields); + t3.notOk("test.cred" in config.fields); + t3.ok("test.rdo" in config.fields); + }); + t2.test("loads valid fields", async t3 => { + const config = testConfig("controller", { ...loaded, "test.bool": null, "test.json": { valid: true } }); + t3.equal(config.get("test.enum"), "a"); + t3.equal(config.get("test.test"), "blah"); + t3.equal(config.get("test.func"), 27); + t3.equal(config.get("test.bool"), null); + t3.strictSame(config.get("test.json"), { valid: true }); + }); + t2.test("ignores fields the location cannot write", async t3 => { + const config = testConfig("host", { "test.priv": "bad", "test.rdo": "bad", "test.test": "ok" }) as any; + t3.notOk("test.priv" in config.fields); + t3.equal(config.fields["test.rdo"], null); + t3.equal(config.fields["test.test"], "ok"); + }); + t2.test("calls initialValue functions after loading stored fields", async t3 => { + class DerivedConfig extends lib.Config { + static defaultAccess: lib.ConfigLocation[] = ["controller"]; + static fieldDefinitions: lib.ConfigDefs = { + "test.base": { type: "number", initialValue: 1 }, + "test.derived": { type: "number", initialValue: (config: any) => config.get("test.base") * 2 }, + }; + } + t3.equal(new DerivedConfig("controller").get("test.derived"), 2); + t3.equal(new DerivedConfig("controller", { "test.base": 5 }).get("test.derived"), 10); + t3.equal(new DerivedConfig("controller", { "test.base": 5, "test.derived": 3 }).get("test.derived"), 3); + t3.equal( + new DerivedConfig("controller", { "test.base": 5, "test.derived": "x" }).get("test.derived"), 10, + "invalid stored value falls back to initialValue", + ); + }); + t2.test("applies migrations", async t3 => { + const config = testConfig("controller", { "test.migration": "foo" }); + t3.equal(config.get("alpha.foo"), "foo"); + t3.notOk("test.migration" in config.toJSON()); + }); + t2.test("applies plugin migrations after migrations", async t3 => { + class HookedConfig extends TestConfig { + static pluginMigrations = new lib.SyncHook(); + } + HookedConfig.pluginMigrations.attach( + "plugin", fields => ({ ...fields, "test.test": `migrated ${fields["alpha.foo"]}` }), + ); + const config = new HookedConfig("controller", { "test.migration": "foo" }); + t3.equal(config.get("test.test"), "migrated foo"); + t3.equal(new HookedConfig("controller").get("test.test"), null, "not run without stored fields"); + }); + t2.test("writes plugin versions", async t3 => { + class VersionedConfig extends TestConfig { + static pluginVersions = new Map([["alpha", "1.2.3"], ["missing", "4.5.6"]]); + static fieldDefinitions: lib.ConfigDefs = { + ...TestConfig.fieldDefinitions, + "alpha.version": { type: "string", optional: true }, + }; + } + t3.test("marks a loaded config dirty when the version changes", async t4 => { + const config = new VersionedConfig("controller", { "alpha.version": "1.0.0" }); + t4.equal(config.get("alpha.version"), "1.2.3"); + t4.notOk("missing.version" in config.toJSON()); + t4.equal(config.dirty, true); + }); + t3.test("leaves a loaded config clean when the version matches", async t4 => { + const config = new VersionedConfig("controller", { "alpha.version": "1.2.3" }); + t4.equal(config.dirty, false); + }); + t3.test("leaves a new config clean", async t4 => { + const config = new VersionedConfig("controller"); + t4.equal(config.get("alpha.version"), "1.2.3"); + t4.equal(config.dirty, false); + }); + }); + t2.test("stores the filepath", async t3 => { + t3.equal(testConfig("controller", undefined, "filepath").filepath, "filepath"); + }); + const required = { todo: "required fields are left null instead" }; + t2.test("throws if a required field has no initialValue", required, async t3 => { + class BrokenConfig extends lib.Config { + static fieldDefinitions: lib.ConfigDefs = { + "test.required": { type: "string" }, + }; + } + t3.throws(() => new BrokenConfig("controller")); + }); + }); + + t1.test("filepath", async t2 => { + t2.test("returns the filepath", async t3 => { + t3.equal(testConfig("controller", undefined, "foo/bar").filepath, "foo/bar"); + }); + t2.test("sets the filepath and the dirty flag", async t3 => { + const config = testConfig(); + t3.equal(config.filepath, undefined); + t3.equal(config.dirty, false); + config.filepath = "foo/bar"; + t3.equal(config.filepath, "foo/bar"); + t3.equal(config.dirty, true); + }); + }); + + t1.test("Config.fieldDependents", async t2 => { + t2.test("maps fields to the validated fields that depend on them", async t3 => { + const dependents = TestConfig.fieldDependents; + t3.strictSame([...dependents.keys()].sort(), ["test.base", "test.objDependent"]); + t3.strictSame(dependents.get("test.base")!.map((d: { name: string }) => d.name), [ + "test.dependent", "test.objDependent", "test.badValidator", + ]); + t3.equal(TestConfig.fieldDependents, dependents, "cached"); + }); + t2.test("ignores dependsOn without a validator", async t3 => { + class NoValidatorConfig extends lib.Config { + static fieldDefinitions: lib.ConfigDefs = { + "a": { type: "number", initialValue: 1 }, + "b": { type: "number", initialValue: 1, dependsOn: ["a"] }, + }; + } + t3.equal(NoValidatorConfig.fieldDependents.size, 0); + }); + t2.test("is computed per subclass", { todo: "subclass reads the parent's cached map" }, async t3 => { + class ParentConfig extends lib.Config { + static fieldDefinitions: lib.ConfigDefs = { + "a": { type: "number", initialValue: 1 }, + }; + } + class ChildConfig extends ParentConfig { + static fieldDefinitions: lib.ConfigDefs = { + ...ParentConfig.fieldDefinitions, + "b": { type: "number", initialValue: 1, dependsOn: ["a"], validator() {} }, + }; + } + t3.equal(ParentConfig.fieldDependents.size, 0); + t3.equal(ChildConfig.fieldDependents.get("a")?.[0].name, "b"); + }); + }); + + t1.test("Config.fromJSON()", async t2 => { + t2.test("throws on input that is not an object", async t3 => { + for (const json of [null, undefined, [], "a", 1]) { + t3.throws(() => TestConfig.fromJSON(json as any, "controller"), error(Error, "Invalid config")); + } + }); + t2.test("throws on field values that are arrays", async t3 => { + t3.throws(() => TestConfig.fromJSON({ "a": [] as any }, "controller"), error(Error, "Invalid config")); + }); + t2.test("loads defaults for missing fields", async t3 => { + const config = TestConfig.fromJSON({ "alpha.foo": "a", "test.enum": "a" }, "controller"); + t3.strictSame(config.toJSON(), { ...defaults, "alpha.foo": "a", "test.enum": "a" }); + }); + t2.test("preserves unknown fields", async t3 => { + t3.strictSame(TestConfig.fromJSON(full as any, "controller").toJSON(), full); + }); + t2.test("ignores inaccessible fields", async t3 => { + const config = TestConfig.fromJSON({ "test.priv": "bad" }, "host") as any; + t3.notOk("test.priv" in config.fields); + t3.equal(config.fields["test.func"], 42); + }); + t2.test("migrates the pre alpha 14 groups format", async t3 => { + const config: lib.Config = TestConfig.fromJSON({ + groups: [ + { name: "alpha", fields: { foo: "a" } }, + { name: "test", fields: { func: 7, other: "x" } }, + ], + } as any, "controller"); + t3.equal(config.get("alpha.foo"), "a"); + t3.equal(config.get("test.func"), 7); + t3.equal(config.toJSON()["test.other"], "x"); + t3.notOk("groups" in config.toJSON()); + }); + t2.test("stores the filepath", async t3 => { + t3.equal(TestConfig.fromJSON({}, "controller", "filepath").filepath, "filepath"); + }); + }); + + t1.test("Config.fromFile()", async t2 => { + t2.test("rejects unreadable and invalid files", async t3 => { + const dir = t3.testdir({ "bad.json": "abc", "null.json": "null", "array.json": "[]" }); + await t3.rejects(TestConfig.fromFile("controller", path.join(dir, "missing.json")), { code: "ENOENT" }); + await t3.rejects(TestConfig.fromFile("controller", path.join(dir, "bad.json")), SyntaxError); + for (const file of ["null.json", "array.json"]) { + const filepath = path.join(dir, file); + await t3.rejects(TestConfig.fromFile("controller", filepath), error(Error, "Invalid config"), file); + } + }); + t2.test("loads fields and stores the filepath", async t3 => { + const dir = t3.testdir({ "config.json": JSON.stringify(full) }); + const filepath = path.join(dir, "config.json"); + const config = await TestConfig.fromFile("controller", filepath); + t3.strictSame(config.toJSON(), full); + t3.equal(config.filepath, filepath); + t3.equal(config.dirty, false); + }); + }); + + t1.test("save()", async t2 => { + const exists = (file: string) => fs.access(file).then(() => true, () => false); + + t2.test("throws if there is no filepath", async t3 => { + const config = testConfig(); + config.set("alpha.foo", "b"); + await t3.rejects(config.save(), error(Error, "Cannot save config which has no filepath")); + }); + t2.test("does nothing when not dirty", async t3 => { + const filepath = path.join(t3.testdir(), "config.json"); + await testConfig("controller", {}, filepath).save(); + t3.equal(await exists(filepath), false); + }); + t2.test("saves when forced", async t3 => { + const filepath = path.join(t3.testdir(), "config.json"); + await testConfig("controller", {}, filepath).save(true); + t3.strictSame(JSON.parse(await fs.readFile(filepath, "utf8")), defaults); + }); + t2.test("writes the config as JSON", async t3 => { + const filepath = path.join(t3.testdir(), "config.json"); + const config = testConfig("controller", full, filepath); + config.set("alpha.foo", "b"); + await config.save(); + t3.strictSame(JSON.parse(await fs.readFile(filepath, "utf8")), { ...full, "alpha.foo": "b" }); + }); + t2.test("writes the file readable by the owner only", { skip: process.platform === "win32" }, async t3 => { + const filepath = path.join(t3.testdir(), "config.json"); + const config = testConfig("controller", {}, filepath); + config.set("alpha.foo", "b"); + await config.save(); + t3.equal((await fs.stat(filepath)).mode & 0o777, 0o600); + }); + t2.test("clears the dirty flag", async t3 => { + const filepath = path.join(t3.testdir(), "config.json"); + const config = testConfig("controller", {}, filepath); + config.set("alpha.foo", "b"); + await config.save(); + t3.equal(config.dirty, false); + await fs.rm(filepath); + await config.save(); + t3.equal(await exists(filepath), false); + }); + t2.test("round trips through fromFile()", async t3 => { + const filepath = path.join(t3.testdir(), "config.json"); + const config = testConfig("controller", full, filepath); + config.set("alpha.foo", "b"); + await config.save(); + const reloaded = await TestConfig.fromFile("controller", filepath); + t3.strictSame(reloaded.toJSON(), config.toJSON()); + }); + }); + + t1.test("toJSON()", async t2 => { + t2.test("serialises a default config", async t3 => { + t3.strictSame(testConfig().toJSON(), defaults); + }); + t2.test("leaves out fields the location cannot write", async t3 => { + const json = testConfig("host").toJSON(); + t3.notOk("test.rdo" in json); + t3.notOk("test.priv" in json); + t3.notOk("test.cred" in json); + }); + }); + + t1.test("toRemote()", async t2 => { + t2.test("leaves out fields the remote cannot read", async t3 => { + const { "test.cred": _cred, "test.priv": _priv, ...expected } = defaults; + t3.strictSame(testConfig().toRemote("host"), expected); + }); + t2.test("filters fields", async t3 => { + t3.strictSame(testConfig().toRemote("controller", ["alpha.foo"]), { "alpha.foo": null }); + }); + t2.test("skips the local write check at control", async t3 => { + // control is not in defaultAccess, so nothing is readable or writable there + const config = testConfig("control") as any; + config.fields["alpha.foo"] = "x"; + t3.strictSame(config.toRemote("control"), { "alpha.foo": "x" }); + t3.strictSame(config.toRemote("controller"), { "alpha.foo": "x" }); + }); + t2.test("includes unknown fields regardless of filter", async t3 => { + const config = testConfig("controller", { "extra.a": 1 }); + t3.strictSame(config.toRemote("host", ["alpha.foo"]), { "alpha.foo": null, "extra.a": 1 }); + }); + }); + + t1.test("update()", async t2 => { + t2.test("updates fields and keeps unknown ones", async t3 => { + const config = testConfig(); + config.update({ "extra.blah": true, "extra.spam": "baz", "beta.bar": { value: 30 } }, false); + t3.strictSame(config.toJSON(), { + ...defaults, "extra.blah": true, "extra.spam": "baz", "beta.bar": { value: 30 }, + }); + }); + t2.test("skips invalid values", async t3 => { + const config = testConfig(); + config.update({ + "test.enum": "wrong", + "test.test": 3, + "test.func": null, + "test.bool": "true", + "beta.bar": null, + }, false); + t3.strictSame(config.toJSON(), defaults); + }); + t2.test("accepts null for optional fields", async t3 => { + const config = testConfig("controller", { "test.bool": true }); + config.update({ "test.bool": null }, false); + t3.equal(config.get("test.bool"), null); + }); + t2.test("skips fields the remote cannot write", async t3 => { + const config = testConfig(); + config.update({ "test.test": "a", "test.priv": "bad", "test.rdo": "bad" }, false, "host"); + t3.equal(config.get("test.test"), "a"); + t3.equal(config.get("test.priv"), null); + t3.equal(config.get("test.rdo"), null); + }); + t2.test("skips the access check at control", async t3 => { + const config = testConfig("control") as any; + config.update({ "alpha.foo": "x" }, false, "host"); + t3.equal(config.fields["alpha.foo"], "x"); + }); + t2.test("throws on invalid input", async t3 => { + const config = testConfig(); + for (const json of [undefined, null, [], "a"]) { + t3.throws(() => config.update(json as any, false), error(Error, "Invalid config")); + } + }); + t2.test("emits fieldChanged only when notify is true", async t3 => { + const config = testConfig(); + const changes = fieldChanges(config); + config.update({ "extra.blah": true, "alpha.foo": "baz", "beta.bar": { value: 30 } }, false); + t3.strictSame(changes, []); + config.update({ "extra.blah": false, "alpha.foo": "bam", "beta.bar": { value: 45 } }, true); + t3.strictSame(changes, [ + ["alpha.foo", "bam", "baz"], + ["beta.bar", { value: 45 }, { value: 30 }], + ]); + }); + t2.test("does not emit for deep equal values", async t3 => { + const config = testConfig("controller", { "beta.bar": { a: [1] } }); + const changes = fieldChanges(config); + config.update({ "beta.bar": { a: [1] } }, true); + t3.strictSame(changes, []); + t3.equal(config.dirty, false); + }); + t2.test("sets the dirty flag only when notify is true", async t3 => { + const config = testConfig(); + config.update({ "alpha.foo": "baz" }, false); + t3.equal(config.dirty, false); + config.update({ "alpha.foo": "bam" }, true); + t3.equal(config.dirty, true); + }); + t2.test("sets restartRequired only for restart required fields", async t3 => { + const config = testConfig(); + config.update({ "test.enum": "a" }, false); + t3.equal(config.restartRequired, false, "notify false"); + config.update({ "alpha.foo": "bam" }, true); + t3.equal(config.restartRequired, false, "plain field"); + config.update({ "test.enum": "b" }, true); + t3.equal(config.restartRequired, true, "restart field"); + }); + }); + + t1.test("canAccess()", async t2 => { + t2.test("throws if the field does not exist", async t3 => { + t3.throws( + () => testConfig().canAccess("invalid", CA.read), + error(lib.InvalidFieldError, "No field named 'invalid'"), + ); + }); + t2.test("throws if mode is not passed", async t3 => { + t3.throws( + () => (testConfig() as any).canAccess("alpha.foo"), + error(TypeError, "mode argument is required to canAccess"), + ); + }); + // field => [read, write, readWrite] from host, all are fully accessible from controller + const expected: Record = { + "alpha.foo": [true, true, true], + "test.enum": [true, true, true], + "test.priv": [false, false, false], + "test.cred": [false, true, false], + "test.rdo": [true, false, false], + }; + for (const [field, [read, write, readWrite]] of Object.entries(expected)) { + t2.test(`checks access to ${field}`, async t3 => { + const config = testConfig(); + for (const mode of [CA.read, CA.write, CA.readWrite]) { + t3.equal(config.canAccess(field, mode), true, `mode ${mode} locally`); + t3.equal(config.canAccess(field, mode, "controller"), true, `mode ${mode} from controller`); + } + t3.equal(config.canAccess(field, CA.read, "host"), read, "read from host"); + t3.equal(config.canAccess(field, CA.write, "host"), write, "write from host"); + t3.equal(config.canAccess(field, CA.readWrite, "host"), readWrite, "readWrite from host"); + }); + } + t2.test("uses defaultAccess for fields without access", async t3 => { + t3.equal(testConfig().canAccess("alpha.foo", CA.read, "control"), false); + }); + }); + + t1.test("get()", async t2 => { + t2.test("throws if the field does not exist", async t3 => { + t3.throws(() => testConfig().get("invalid"), error(lib.InvalidFieldError, "No field named 'invalid'")); + }); + t2.test("returns the field value", async t3 => { + const config = testConfig("controller", { ...loaded, "test.priv": "blah" }); + t3.equal(config.get("test.enum"), "a"); + t3.equal(config.get("test.priv"), "blah"); + t3.equal(config.get("test.func"), 27); + }); + t2.test("throws if the field is remotely inaccessible", async t3 => { + t3.throws( + () => testConfig().get("test.priv", "host"), + error(lib.InvalidAccessError, "Field 'test.priv' is not accessible from host"), + ); + }); + t2.test("throws if the field is locally inaccessible", async t3 => { + t3.throws( + () => testConfig("host").get("test.priv"), + error(lib.InvalidAccessError, "Field 'test.priv' is not accessible from host"), + ); + }); + t2.test("returns write only fields locally", async t3 => { + const config = testConfig("host"); + config.set("test.cred", "secret"); + t3.equal(config.get("test.cred"), "secret"); + }); + }); + + // Behaviour shared by set() and stage(), get reads back where the value went + function testSetValue( + tt: Test, + set: (config: lib.Config, name: string, value: unknown, remote?: lib.ConfigLocation) => void, + get: (config: lib.Config, name: string) => unknown, + ) { + tt.test("sets the value", async t3 => { + const config = testConfig("controller", loaded); + set(config, "alpha.foo", "new value"); + t3.equal(get(config, "alpha.foo"), "new value"); + }); + tt.test("throws if the field does not exist", async t3 => { + t3.throws( + () => set(testConfig(), "test.bar", 1), + error(lib.InvalidFieldError, "No field named 'test.bar'"), + ); + }); + tt.test("throws if the field is remotely inaccessible", async t3 => { + t3.throws( + () => set(testConfig(), "test.priv", "bad", "host"), + error(lib.InvalidAccessError, "Field 'test.priv' is not accessible from host"), + ); + }); + tt.test("throws if the field is locally inaccessible", async t3 => { + t3.throws( + () => set(testConfig("host"), "test.priv", "bad", "controller"), + error(lib.InvalidAccessError, "Field 'test.priv' is not accessible from host"), + ); + }); + tt.test("throws if the value is not in enum", async t3 => { + t3.throws( + () => set(testConfig(), "test.enum", "bar"), + error(lib.InvalidValueError, "Expected one of [a, b, c], not bar"), + ); + }); + tt.test("accepts a value in enum", async t3 => { + const config = testConfig(); + set(config, "test.enum", "c"); + t3.equal(get(config, "test.enum"), "c"); + }); + tt.test("throws on null for a required field", async t3 => { + t3.throws( + () => set(testConfig(), "test.func", null), + error(lib.InvalidValueError, "Field test.func cannot be null"), + ); + }); + tt.test("accepts null for an optional field", async t3 => { + const config = testConfig("controller", loaded); + set(config, "test.test", null); + t3.equal(get(config, "test.test"), null); + }); + tt.test("throws on the wrong type", async t3 => { + t3.throws( + () => set(testConfig(), "test.test", 1), + error(lib.InvalidValueError, "Expected type of test.test to be string, not number"), + ); + }); + tt.test("treats empty string as null", async t3 => { + const config = testConfig("controller", loaded); + set(config, "test.test", ""); + t3.equal(get(config, "test.test"), null); + }); + tt.test("converts strings to booleans", async t3 => { + const config = testConfig(); + set(config, "test.bool", "true"); + t3.equal(get(config, "test.bool"), true); + set(config, "test.bool", "false"); + t3.equal(get(config, "test.bool"), false); + t3.throws( + () => set(config, "test.bool", "blah"), + error(lib.InvalidValueError, "Expected type of test.bool to be boolean, not string"), + ); + }); + tt.test("converts strings to numbers", async t3 => { + const config = testConfig(); + for (const s of ["1", "+23", ".23e5", "-.1e-2", "100.0001", "1.", " 7 "]) { + set(config, "test.func", s); + t3.equal(get(config, "test.func"), Number.parseFloat(s), s); + } + for (const s of ["blah", "1x", "0x10", "NaN", "1e"]) { + t3.throws( + () => set(config, "test.func", s), + error(lib.InvalidValueError, "Expected type of test.func to be number, not string"), + s, + ); + } + }); + tt.test( + "rejects Infinity", + { todo: "Infinity is accepted, then fails the JSON schema so staging and every later set() throw" }, + async t3 => { + const config = testConfig(); + t3.throws(() => set(config, "test.func", "Infinity"), lib.InvalidValueError); + set(config, "test.func", 1); + t3.equal(get(config, "test.func"), 1); + }, + ); + tt.test("converts strings to objects", async t3 => { + const config = testConfig(); + set(config, "test.json", "{\"json\": true}"); + t3.strictSame(get(config, "test.json"), { json: true }); + t3.throws( + () => set(config, "test.json", "blah"), + error(lib.InvalidValueError, /^Error parsing value for test\.json: /), + ); + t3.throws( + () => set(config, "test.json", "[]"), + error(lib.InvalidValueError, "Expected type of test.json to be object, not array"), + ); + }); + } + + // Behaviour shared by setProp() and stageProp() + function testSetProp( + tt: Test, + setProp: ( + config: lib.Config, name: string, prop: string, value?: unknown, remote?: lib.ConfigLocation, + ) => void, + get: (config: lib.Config, name: string) => unknown, + ) { + tt.test("throws if the field does not exist", async t3 => { + t3.throws( + () => setProp(testConfig(), "test.bar", "prop", 1), + error(lib.InvalidFieldError, "No field named 'test.bar'"), + ); + }); + tt.test("throws if the field is remotely inaccessible", async t3 => { + t3.throws( + () => setProp(testConfig(), "test.priv", "prop", "bad", "host"), + error(lib.InvalidAccessError, "Field 'test.priv' is not accessible from host"), + ); + }); + tt.test("throws if the field is locally inaccessible", async t3 => { + t3.throws( + () => setProp(testConfig("host"), "test.priv", "prop", "bad", "controller"), + error(lib.InvalidAccessError, "Field 'test.priv' is not accessible from host"), + ); + }); + tt.test("throws if the field is not an object", async t3 => { + t3.throws( + () => setProp(testConfig(), "test.enum", "prop", "a"), + error(lib.InvalidValueError, "Cannot set property on non-object field 'test.enum'"), + ); + }); + tt.test("sets a property", async t3 => { + const config = testConfig("controller", { "test.json": { prev: 32, test: false } }); + setProp(config, "test.json", "test", true); + t3.strictSame(get(config, "test.json"), { prev: 32, test: true }); + }); + tt.test("handles the field being null", async t3 => { + const config = testConfig("controller", { "test.json": null }); + setProp(config, "test.json", "test", true); + t3.strictSame(get(config, "test.json"), { test: true }); + }); + tt.test("deletes the property when value is undefined", async t3 => { + const config = testConfig("controller", { "test.json": { test: true, extra: "yes" } }); + setProp(config, "test.json", "extra", undefined); + t3.strictSame(get(config, "test.json"), { test: true }); + }); + tt.test("does not mutate the previous object", async t3 => { + const config = testConfig("controller", { "test.json": { a: 1 } }); + const prev = config.get("test.json"); + setProp(config, "test.json", "b", 2); + t3.strictSame(prev, { a: 1 }); + }); + } + + t1.test("set()", async t2 => { + testSetValue(t2, (c, ...a) => c.set(...a as [any, any, any]), (c, name) => c.get(name)); + t2.test("emits fieldChanged", async t3 => { + const config = testConfig("controller", loaded); + const changes = fieldChanges(config); + config.set("test.test", "foo"); + config.set("test.test", "foo"); + t3.strictSame(changes, [["test.test", "foo", "blah"]], "not emitted when unchanged"); + }); + t2.test("sets the dirty flag", async t3 => { + const config = testConfig("controller", loaded); + config.set("test.test", "foo"); + t3.equal(config.dirty, true); + }); + t2.test("sets restartRequired only for restart required fields", async t3 => { + const config = testConfig("controller", loaded); + config.set("test.test", "foo"); + t3.equal(config.restartRequired, false); + config.set("test.enum", "b"); + t3.equal(config.restartRequired, true); + }); + t2.test("runs the field validator", async t3 => { + const log = validatorLog(t3); + const config = testConfig(); + config.set("test.validated", 5); + t3.equal(config.get("test.validated"), 5); + t3.strictSame(log, [["test.validated", 5]]); + }); + t2.test("throws if the validator fails", async t3 => { + const log = validatorLog(t3); + const config = testConfig(); + t3.throws( + () => config.set("test.validated", -1), + error(lib.InvalidValueError, "Failed validation of test.validated: must be positive"), + ); + t3.equal(config.get("test.validated"), null); + t3.strictSame(log, [["test.validated", -1]]); + }); + t2.test("validates dependent fields against the new value", async t3 => { + const log = validatorLog(t3); + const config = testConfig(); + config.set("test.dependent", 10); + config.set("test.base", 5); + t3.equal(config.get("test.dependent"), 10); + t3.equal(config.get("test.base"), 5); + t3.strictSame(log, [ + ["test.dependent", 10], + ["test.dependent", 10], + ["test.objDependent", {}], + ["test.badValidator", null], + ]); + }); + t2.test("throws if a dependent validator fails", async t3 => { + const log = validatorLog(t3); + const config = testConfig(); + t3.throws( + () => config.set("test.base", 5), + error( + lib.InvalidValueError, + "Failed validation of dependent test.dependent: dependent must be >= base", + ), + ); + t3.equal(config.get("test.base"), 1); + t3.strictSame(log, [["test.dependent", 1]]); + }); + t2.test( + "validates dependents the remote cannot read", + { todo: "dependent values are read with the remote's access, so this throws InvalidAccessError" }, + async t3 => { + class CredentialConfig extends lib.Config { + static fieldDefinitions: lib.ConfigDefs = { + "a": { type: "number", initialValue: 1 }, + "b": { + type: "number", initialValue: 1, credential: ["controller"], dependsOn: ["a"], + validator(value: number, config: lib.Config) { + if (value < config.get("a")) { throw new Error("b must be >= a"); } + }, + }, + }; + } + const config = new CredentialConfig("controller"); + t3.doesNotThrow(() => config.set("a", 0, "host")); + t3.equal(config.get("a"), 0); + }, + ); + t2.test("discards staged changes", async t3 => { + const config = testConfig(); + config.stage("alpha.foo", "staged"); + config.set("test.test", "set"); + t3.equal(config.staging.get("alpha.foo"), null); + }); + }); + + t1.test("setProp()", async t2 => { + testSetProp(t2, (c, ...a) => c.setProp(...a as [any, any, any, any]), (c, name) => c.get(name)); + t2.test("emits fieldChanged", async t3 => { + const config = testConfig(); + const changes = fieldChanges(config); + config.setProp("test.json", "test", true); + t3.strictSame(changes, [["test.json", { test: true }, {}]]); + }); + t2.test("sets the dirty flag", async t3 => { + const config = testConfig(); + config.setProp("test.json", "test", true); + t3.equal(config.dirty, true); + }); + t2.test("sets restartRequired only for restart required fields", async t3 => { + const config = testConfig(); + config.setProp("test.json", "test", true); + t3.equal(config.restartRequired, false); + config.setProp("test.rest", "test", true); + t3.equal(config.restartRequired, true); + }); + t2.test("runs the field validator", async t3 => { + const log = validatorLog(t3); + const config = testConfig(); + config.setProp("test.objValidated", "good", true); + t3.strictSame(config.get("test.objValidated"), { good: true }); + t3.strictSame(log, [["test.objValidated", { good: true }]]); + }); + t2.test("throws if the validator fails", async t3 => { + const log = validatorLog(t3); + const config = testConfig(); + t3.throws( + () => config.setProp("test.objValidated", "bad", true), + error(lib.InvalidValueError, "Failed validation of test.objValidated: bad key"), + ); + t3.strictSame(config.get("test.objValidated"), {}); + t3.strictSame(log, [["test.objValidated", { bad: true }]]); + }); + t2.test("validates dependent fields", async t3 => { + const log = validatorLog(t3); + const config = testConfig(); + config.setProp("test.objDependent", "base", 1); + t3.strictSame(config.get("test.objDependent"), { base: 1 }); + t3.strictSame(log, [ + ["test.objDependent", { base: 1 }], + ["test.dependent", 1], + ]); + }); + t2.test("throws if a dependent validator fails", async t3 => { + const config = testConfig("controller", { "test.base": 0 }); + const log = validatorLog(t3); + t3.throws( + () => config.setProp("test.objDependent", "base", 0), + error(lib.InvalidValueError, "Failed validation of dependent test.dependent: objDependent cannot be 0"), + ); + t3.strictSame(config.get("test.objDependent"), {}); + t3.strictSame(log, [ + ["test.objDependent", { base: 0 }], + ["test.dependent", 1], + ]); + }); + }); + + t1.test("staging", async t2 => { + t2.test("is reused until invalidated", async t3 => { + const config = testConfig(); + const first = config.staging; + t3.equal(config.staging, first); + config.set("alpha.foo", "value"); + t3.not(config.staging, first); + }); + t2.test("copies the current field values", async t3 => { + const config = testConfig("controller", full); + const { "extra.blah": _a, "extra.spam": _b, "extra.null": _c, "extra.obj": _d, ...known } = full; + t3.strictSame(config.staging.toJSON(), known, "unknown fields are not copied"); + }); + }); + + t1.test("stage()", async t2 => { + testSetValue(t2, (c, ...a) => c.stage(...a as [any, any, any]), (c, name) => c.staging.get(name)); + t2.test("does not change the live value", async t3 => { + const config = testConfig(); + const changes = fieldChanges(config); + config.stage("alpha.foo", "value"); + t3.equal(config.get("alpha.foo"), null); + t3.equal(config.staging.get("alpha.foo"), "value"); + t3.strictSame(changes, []); + t3.equal(config.dirty, false); + }); + t2.test("skips validators", async t3 => { + const log = validatorLog(t3); + const config = testConfig(); + config.stage("test.validated", -1); + t3.strictSame(log, []); + }); + }); + + t1.test("stageProp()", async t2 => { + testSetProp(t2, (c, ...a) => c.stageProp(...a as [any, any, any, any]), (c, name) => c.staging.get(name)); + t2.test("does not change the live value", async t3 => { + const config = testConfig("controller", { "test.json": { a: 1 } }); + config.stageProp("test.json", "prop", true); + config.stageProp("test.json", "a", undefined); + t3.strictSame(config.get("test.json"), { a: 1 }); + t3.strictSame(config.staging.get("test.json"), { prop: true }); + }); + }); + + t1.test("commitStaging()", async t2 => { + t2.test("does nothing without staging", async t3 => { + const log = validatorLog(t3); + const config = testConfig(); + config.commitStaging(); + t3.strictSame(config.toJSON(), defaults); + t3.strictSame(log, []); + }); + t2.test("commits staged values after running every validator once", async t3 => { + const log = validatorLog(t3); + const config = testConfig(); + config.stage("alpha.foo", "value"); + t3.equal(config.get("alpha.foo"), null); + config.commitStaging(); + t3.equal(config.get("alpha.foo"), "value"); + t3.strictSame(log, [ + ["test.dependent", 1], + ["test.objDependent", {}], + ["test.validated", null], + ["test.objValidated", {}], + ["test.badValidator", null], + ]); + }); + t2.test("throws and keeps live values if a validator fails", async t3 => { + const log = validatorLog(t3); + const config = testConfig(); + config.stage("test.validated", -1); + t3.throws( + () => config.commitStaging(), + error(lib.InvalidValueError, "Failed validation of test.validated: must be positive"), + ); + t3.equal(config.get("test.validated"), null); + t3.equal(config.staging.get("test.validated"), -1, "staging is kept"); + t3.strictSame(log, [ + ["test.dependent", 1], + ["test.objDependent", {}], + ["test.validated", -1], + ]); + }); + t2.test("validates the staged values together", async t3 => { + const config = testConfig(); + t3.throws(() => config.set("test.base", 10), error(lib.InvalidValueError, /dependent must be >= base/)); + config.stage("test.base", 10); + config.stage("test.dependent", 15); + config.commitStaging(); + t3.equal(config.get("test.base"), 10); + t3.equal(config.get("test.dependent"), 15); + }); + t2.test("emits fieldChanged for changed fields", async t3 => { + const config = testConfig(); + const changes = fieldChanges(config); + config.stage("alpha.foo", "foo"); + config.stage("test.test", "bar"); + config.stage("test.enum", "b"); + config.commitStaging(); + t3.strictSame(changes, [ + ["alpha.foo", "foo", null], + ["test.test", "bar", null], + ]); + }); + t2.test("sets the dirty flag", async t3 => { + const config = testConfig(); + config.stage("test.test", "foo"); + config.commitStaging(); + t3.equal(config.dirty, true); + }); + t2.test("sets restartRequired only for restart required fields", async t3 => { + const config = testConfig(); + config.stage("test.test", "foo"); + config.commitStaging(); + t3.equal(config.restartRequired, false); + config.stage("test.enum", "a"); + config.commitStaging(); + t3.equal(config.restartRequired, true); + }); + }); + + t1.test("revertStaging()", async t2 => { + t2.test("discards staged changes", async t3 => { + const config = testConfig(); + config.stage("alpha.foo", "value"); + config.revertStaging(); + t3.equal(config.staging.get("alpha.foo"), null); + t3.equal(config.get("alpha.foo"), null); + }); + }); + + t1.test("validators", async t2 => { + for (const method of ["set", "setProp", "stage", "stageProp", "commitStaging", "revertStaging"]) { + t2.test(`cannot call ${method}()`, async t3 => { + const config = testConfig(); + t3.throws( + () => config.set("test.badValidator", method), + error(lib.InvalidValueError, /config is readonly and cannot have values changed/), + ); + t3.equal(config.get("alpha.foo"), null); + t3.strictSame(config.get("beta.bar"), {}); + }); + t2.test(`cannot call ${method}() as a dependent validator`, async t3 => { + const config = testConfig("controller", { "test.base": 0 }); + config.set("test.badValidator", method); + t3.throws( + () => config.set("test.base", 1), + error(lib.InvalidValueError, /config is readonly and cannot have values changed/), + ); + }); + } + t2.test("leave the config writable after they throw", async t3 => { + const config = testConfig(); + t3.throws(() => config.set("test.validated", -1)); + t3.throws(() => config.set("test.base", 5)); + config.set("alpha.foo", "ok"); + config.stage("test.test", "ok"); + config.commitStaging(); + t3.equal(config.get("test.test"), "ok"); + }); + }); +}); + +t.test("Config._coerceValue()", async t1 => { + t1.test("checks enum before converting strings", async t2 => { + const def: lib.FieldDefinition = { type: "number", enum: [1, 2] }; + t2.equal(lib.Config._coerceValue("n", def, 1), 1); + t2.throws( + () => lib.Config._coerceValue("n", def, "1"), + error(lib.InvalidValueError, "Expected one of [1, 2], not 1"), + ); + }); + t1.test("passes through non string values of the right type", async t2 => { + t2.strictSame(lib.Config._coerceValue("o", { type: "object" }, { a: 1 }), { a: 1 }); + t2.equal(lib.Config._coerceValue("b", { type: "boolean" }, true), true); + }); +}); + +// The Config classes are excluded from the generic JSON round trip because fromJSON needs a location. +t.test("JSON round trip", async t1 => { + function bound(Class: typeof lib.Config, location: lib.ConfigLocation) { + return { + name: Class.name, + jsonSchema: Class.jsonSchema, + fromJSON: (json: any) => Class.fromJSON(json, location), + }; + } + + t1.test("TestConfig", async t2 => { + testJsonSerialisable(t2, bound(TestConfig, "controller"), [ + ["empty sample", {}], + ["full sample", full], + ]); + }); + + const classes: [typeof lib.Config, lib.ConfigLocation[]][] = [ + [lib.ControllerConfig, ["controller"]], + [lib.HostConfig, ["host"]], + [lib.InstanceConfig, ["controller", "host"]], + [lib.CtlConfig, ["control"]], + ]; + for (const [Class, locations] of classes) { + for (const location of locations) { + t1.test(`${Class.name} at ${location}`, async t2 => { + testJsonSerialisable(t2, bound(Class, location), [ + ["empty sample", {}], + ["default sample", new Class(location).toJSON()], + ]); + }); + } + } +}); diff --git a/tests/lib/data/json_serialisable.test.ts b/tests/lib/data/json_serialisable.test.ts new file mode 100644 index 00000000..95e026b1 --- /dev/null +++ b/tests/lib/data/json_serialisable.test.ts @@ -0,0 +1,48 @@ +import t from "tap"; +import * as lib from "@clusterio/lib"; +import { + type KnownSamples, jsonSamples, jsonSerialisableClasses, testJsonSerialisable, +} from "../../shared/json_serialisable.ts"; + +// Every JSON serialisable class exported by lib gets the common tests, so new +// classes are covered without adding anything here. Schemas the sample +// generator cannot satisfy get hand written samples, minimal first. +const known: KnownSamples = new Map([ + [lib.ModInfo.jsonSchema, [ + { name: "a", version: "1.0.0", title: "A", author: "b" }, + { + name: "a", version: "1.0.0", title: "A", author: "b", contact: "c", homepage: "h", description: "d", + factorio_version: "2.0", dependencies: ["base >= 2.0", "? b", "! c", "(?) d", "~ e"], + size: 1, mtime_ms: 2, sha1: "s", updated_at_ms: 3, is_deleted: true, + }, + ]], + [lib.ModDependency.jsonSchema, ["base", "? a > 1.0.0"]], + [lib.ModVersionEquality.jsonSchema, ["= 1.0.0", ">= 2.1.0"]], + [lib.SubscriptionRequest.jsonSchema, [ + ["InstanceDetailsUpdatesEvent", "subscribe", 0], + ["InstanceDetailsUpdatesEvent", "replace", 10, ["a", "b"]], + ]], +]); + +// Classes whose fromJSON needs more than the JSON value, they have their own tests. +const excluded = new Set([ + "Config", + "ControllerConfig", + "CtlConfig", + "HostConfig", + "InstanceConfig", +]); + +// Known failures, reported as todo until fixed. +const todo = new Map([ + ["InstanceDetailsChangedEvent", "has no toJSON, so it serialises as { details } instead of InstanceDetails"], +]); + +for (const [name, Class] of jsonSerialisableClasses(lib)) { + if (excluded.has(name)) { + continue; + } + t.test(name, { todo: todo.get(name) }, async t1 => { + testJsonSerialisable(t1, Class, jsonSamples(Class, known)); + }); +} diff --git a/tests/lib/link/link.test.ts b/tests/lib/link/link.test.ts new file mode 100644 index 00000000..01dfb565 --- /dev/null +++ b/tests/lib/link/link.test.ts @@ -0,0 +1,1208 @@ +import t from "tap"; +import * as lib from "@clusterio/lib"; +import { + TestWebSocketConnector, addr, linkPair, nextMessage, recordedLink, settle, +} from "../../shared/link.ts"; + +const control = addr({ controlId: 1 }); +const controller = addr("controller"); +const host = addr({ hostId: 1 }); +const allControls = addr("allControls"); + +// Test messages, registered once here and never changed after. +class SimpleRequest { + declare ["constructor"]: typeof SimpleRequest; + static type = "request" as const; + static src = ["controller", "control"] as const; + static dst = ["controller", "control"] as const; + static permission = null; +} +class NumberResponse { + value: number; + constructor(value: number) { this.value = value; } + static jsonSchema = { type: "number" }; + toJSON() { return this.value; } + static fromJSON(json: number) { return new this(json); } +} +class NumberRequest { + declare ["constructor"]: typeof NumberRequest; + static type = "request" as const; + static src = ["controller", "control"] as const; + static dst = ["controller", "control"] as const; + static permission = null; + value: number; + constructor(value: number) { this.value = value; } + static jsonSchema = { type: "number" }; + toJSON() { return this.value; } + static fromJSON(json: number) { return new this(json); } + static Response = NumberResponse; +} +class HostRequest { + declare ["constructor"]: typeof HostRequest; + static type = "request" as const; + static src = "control" as const; + static dst = "host" as const; + static permission = null; +} +class SimpleEvent { + declare ["constructor"]: typeof SimpleEvent; + static type = "event" as const; + static src = ["controller", "control"] as const; + static dst = ["controller", "control"] as const; + static permission = null; +} +class NumberEvent { + declare ["constructor"]: typeof NumberEvent; + static type = "event" as const; + static src = ["controller", "control"] as const; + static dst = ["controller", "control"] as const; + static permission = null; + value: number; + constructor(value: number) { this.value = value; } + static jsonSchema = { type: "number" }; + toJSON() { return this.value; } + static fromJSON(json: number) { return new this(json); } +} +class HostEvent { + declare ["constructor"]: typeof HostEvent; + static type = "event" as const; + static src = "controller" as const; + static dst = "host" as const; +} +class PluginRequest { + declare ["constructor"]: typeof PluginRequest; + static type = "request" as const; + static src = ["controller", "control"] as const; + static dst = ["controller", "control"] as const; + static permission = null; + static plugin = "link_test"; +} +class TestPluginError extends lib.ConflictError { + static plugin = "link_test"; +} +for (const Class of [SimpleRequest, NumberRequest, HostRequest, SimpleEvent, NumberEvent, HostEvent]) { + lib.Link.register(Class as any); +} +lib.registerPluginMessages([ + { name: "link_test", messages: [PluginRequest], errors: [TestPluginError] } as any, +]); + +// Link at a control, the other end is the controller. +function controlSide() { + const setup = recordedLink(control, controller); + const receive = (message: any) => { setup.connector.emit("message", message); }; + return { ...setup, receive }; +} + +// Link at the controller, the other end is a control. Permissions are checked here. +function controllerSide() { + const setup = recordedLink(controller, control); + const receive = (message: any) => { setup.connector.emit("message", message); }; + return { ...setup, receive }; +} + +function errorStack(message: string) { + const err = new Error(message); + err.stack = message; + return err; +} + +t.test("Link", async t1 => { + t1.test("constructor()", async t2 => { + t2.test("handles PingRequest", async t3 => { + const { link } = linkPair(control, controller); + t3.equal(await link.send(new lib.PingRequest()), undefined); + }); + + t2.test("logs invalid messages instead of throwing", async t3 => { + const errors = t3.capture(lib.logger, "error"); + const { receive, sent } = controlSide(); + receive({ type: "unknown" }); + t3.strictSame(errors.args(), [["Unhandled message type unknown"]]); + t3.strictSame(sent, []); + }); + + t2.test("logs the validation errors of invalid messages", async t3 => { + const errors = t3.capture(lib.logger, "error"); + const { link, receive } = controlSide(); + link.handle(NumberEvent, async () => {}); + receive(new lib.MessageEvent(1, controller, control, "NumberEvent", "not a number")); + const args = errors.args(); + t3.equal(args.length, 2); + t3.equal(args[0][0], "Event NumberEvent failed validation"); + t3.match(args[1][0], /"message": "must be number"/); + }); + + t2.test("emits unexpected errors on the connector", async t3 => { + const { link, connector, receive } = controlSide(); + t3.capture(link, "_processMessage", () => { throw new Error("boom"); }); + const emitted: Error[] = []; + connector.on("error", err => { emitted.push(err); }); + receive(new lib.MessageEvent(1, controller, control, "SimpleEvent")); + t3.match(emitted, [{ message: "boom" }]); + }); + + t2.test("rejects pending requests on close", async t3 => { + const { link, connector } = controlSide(); + const pending = link.send(new SimpleRequest()); + connector.emit("close"); + await t3.rejects(pending, { constructor: lib.SessionLost, message: "Session Closed" }); + t3.equal(link.pendingRequestCount, 0); + }); + + t2.test("rejects pending requests on invalidate", async t3 => { + const { link, connector } = controlSide(); + const pending = link.send(new SimpleRequest()); + connector.emit("invalidate"); + await t3.rejects(pending, { constructor: lib.SessionLost, message: "Session Lost" }); + }); + + t2.test("sends disconnect ready on disconnectPrepare", async t3 => { + const connector = new TestWebSocketConnector(control, controller); + connector._state = "connected"; + const link = new lib.Link(connector); + link.connector.emit("disconnectPrepare"); + await settle(); + t3.strictSame(connector.sentText.map(text => JSON.parse(text)), [{ type: "disconnect", data: "ready" }]); + }); + + t2.test("sends disconnect ready if prepareDisconnect fails", async t3 => { + const errors = t3.capture(lib.logger, "error"); + const connector = new TestWebSocketConnector(control, controller); + connector._state = "connected"; + const link = new lib.Link(connector); + t3.capture(link, "prepareDisconnect", async () => { throw errorStack("Error occured"); }); + connector.emit("disconnectPrepare"); + await settle(); + t3.equal(connector.sentText.length, 1); + t3.strictSame(errors.args(), [["Unexpected error preparing disconnect:\nError occured"]]); + }); + + t2.test("does not send disconnect ready without a session", async t3 => { + const connector = new TestWebSocketConnector(control, controller); + const link = new lib.Link(connector); + link.connector.emit("disconnectPrepare"); + await settle(); + t3.strictSame(connector.sentText, []); + }); + }); + + t1.test("pendingRequestCount", async t2 => { + t2.test("counts sent and forwarded requests", async t3 => { + const { link } = controlSide(); + t3.equal(link.pendingRequestCount, 0); + link.send(new SimpleRequest()).catch(() => {}); + link.forwardRequest(new lib.MessageRequest(1, addr({ controlId: 2 }), controller, "SimpleRequest"), link); + t3.equal(link.pendingRequestCount, 2); + }); + }); + + t1.test("send()", async t2 => { + t2.test("sends a request to the other end", async t3 => { + const { link, sent } = controlSide(); + link.send(new SimpleRequest()); + t3.strictSame(sent, [ + new lib.MessageRequest(1, new lib.Address(lib.Address.control, 1, 1), controller, "SimpleRequest"), + ]); + }); + + t2.test("sends the data of a request", async t3 => { + const { link, sent } = controlSide(); + link.send(new NumberRequest(22)); + t3.strictSame(sent, [new lib.MessageRequest( + 1, new lib.Address(lib.Address.control, 1, 1), controller, "NumberRequest", new NumberRequest(22), + )]); + }); + + t2.test("prefixes the name of plugin requests", async t3 => { + const { link, sent } = controlSide(); + link.send(new PluginRequest()); + t3.equal(sent[0].name, "link_test:PluginRequest"); + }); + + t2.test("gives each request its own id", async t3 => { + const { link, sent } = controlSide(); + link.send(new SimpleRequest()); + link.send(new SimpleRequest()); + t3.strictSame(sent.map(message => message.src.requestId), [1, 2]); + }); + + t2.test("resolves with the response from the other end", async t3 => { + const { link, peer } = linkPair(control, controller); + peer.handle(NumberRequest, async (request, src, dst) => { + t3.strictSame([src.type, dst], [lib.Address.control, controller]); + return new NumberResponse(request.value * 2); + }); + t3.strictSame(await link.send(new NumberRequest(21)), new NumberResponse(42)); + t3.equal(link.pendingRequestCount, 0); + }); + + t2.test("resolves with undefined for requests without a Response", async t3 => { + const { link, peer } = linkPair(control, controller); + peer.handle(SimpleRequest, async () => {}); + t3.equal(await link.send(new SimpleRequest()), undefined); + }); + + t2.test("rejects with the error response from the other end", async t3 => { + const { link, receive, sent } = controlSide(); + const pending = link.send(new SimpleRequest()); + receive(new lib.MessageResponseError(1, controller, sent[0].src, new lib.ResponseError("Error"))); + await t3.rejects(pending, { constructor: lib.InternalServerError, message: "Error" }); + t3.equal(link.pendingRequestCount, 0); + }); + + t2.test("rejects when the response fails validation", async t3 => { + const { link, receive, sent } = controlSide(); + const pending = link.send(new NumberRequest(1)); + receive(new lib.MessageResponse(1, controller, sent[0].src, "not a number")); + await t3.rejects( + pending, + { constructor: lib.InvalidMessage, message: "Response for request NumberRequest failed validation" }, + ); + }); + + t2.test("throws on data failing validation without sending", async t3 => { + const { link, sent } = controlSide(); + t3.throws( + () => link.send(new NumberRequest("bad" as any)), + { message: "Request NumberRequest failed validation" }, + ); + t3.throws( + () => link.send(new NumberEvent("bad" as any)), + { message: "Event NumberEvent failed validation" }, + ); + t3.strictSame(sent, []); + }); + + t2.test("skips validation when validateSent is false", async t3 => { + const { link, sent } = controlSide(); + link.validateSent = false; + link.send(new NumberRequest("bad" as any)); + link.send(new NumberEvent("bad" as any)); + t3.equal(sent.length, 2); + }); + + t2.test("sends an event to the other end", async t3 => { + const { link, sent } = controlSide(); + t3.equal(link.send(new SimpleEvent()), undefined); + t3.strictSame(sent, [new lib.MessageEvent(1, control, controller, "SimpleEvent")]); + }); + + t2.test("sends the data of an event", async t3 => { + const { link, sent } = controlSide(); + link.send(new NumberEvent(22)); + t3.strictSame(sent, [new lib.MessageEvent(1, control, controller, "NumberEvent", new NumberEvent(22))]); + }); + + t2.test("throws for unregistered requests and events", async t3 => { + class UnregisteredRequest { + static type = "request" as const; + static src = "control" as const; + static dst = "controller" as const; + } + class UnregisteredEvent { + static type = "event" as const; + static src = "control" as const; + static dst = "controller" as const; + } + const { link, sent } = controlSide(); + t3.throws( + () => link.send(new UnregisteredRequest() as any), + { message: "Attempt to send unregistered Request UnregisteredRequest" }, + ); + t3.throws( + () => link.send(new UnregisteredEvent() as any), + { message: "Attempt to send unregistered Event UnregisteredEvent" }, + ); + t3.strictSame(sent, []); + }); + }); + + t1.test("sendTo()", async t2 => { + t2.test("sends to the given address", async t3 => { + const { link, sent } = controlSide(); + link.sendTo("allControls", new SimpleEvent()); + link.sendTo({ controlId: 2 }, new SimpleRequest()).catch(() => {}); + t3.strictSame(sent.map(message => message.dst), [allControls, addr({ controlId: 2 })]); + }); + + t2.test("throws when the message would return to the sender", async t3 => { + const { link, sent } = controlSide(); + t3.throws( + () => link.sendTo(control, new SimpleRequest()), + { message: `Message would return back to sender ${control}.` }, + ); + t3.throws( + () => link.sendTo(control, new SimpleEvent()), + { message: `Message would return back to sender ${control}.` }, + ); + t3.equal(link.pendingRequestCount, 0); + t3.strictSame(sent, []); + }); + + t2.test("throws for objects that are not requests or events", async t3 => { + class NotAMessage { static type = "other"; } + const { link } = controlSide(); + t3.throws( + () => link.sendTo(controller, new NotAMessage() as any), + { message: "Expected request or event but got type other" }, + ); + }); + }); + + t1.test("handle()", async t2 => { + t2.test("handles requests", async t3 => { + const { link, receive, peer } = controlSide(); + const calls: unknown[] = []; + link.handle(NumberRequest, async (request, src, dst) => { + calls.push([request, src, dst]); + return new NumberResponse(request.value + 4); + }); + const response = nextMessage(peer); + receive(new lib.MessageRequest(1, controller, control, "NumberRequest", 1)); + t3.strictSame(calls, [[new NumberRequest(1), controller, control]]); + t3.strictSame(await response, new lib.MessageResponse(1, control, controller, new NumberResponse(5))); + }); + + t2.test("accepts handlers not returning a promise", async t3 => { + const { link, receive, peer } = controlSide(); + link.handle(NumberRequest, ((request: NumberRequest) => new NumberResponse(request.value)) as any); + const response = nextMessage(peer); + receive(new lib.MessageRequest(1, controller, control, "NumberRequest", 3)); + t3.match(await response, { type: "response", data: { value: 3 } }); + }); + + t2.test("sends an error response when the handler throws", async t3 => { + const errors = t3.capture(lib.logger, "error"); + const { link, receive, peer } = controlSide(); + link.handle(SimpleRequest, async () => { throw errorStack("Error"); }); + const response = nextMessage(peer); + receive(new lib.MessageRequest(1, controller, control, "SimpleRequest")); + t3.strictSame(await response, new lib.MessageResponseError( + 1, control, controller, new lib.ResponseError("Error", "InternalServerError", "Error"), + )); + t3.strictSame(errors.args(), [["Unexpected error responding to SimpleRequest:\nError"]]); + }); + + t2.test("sends an error response when the handler throws synchronously", async t3 => { + t3.capture(lib.logger, "error"); + const { link, receive, peer } = controlSide(); + link.handle(SimpleRequest, (() => { throw errorStack("Sync"); }) as any); + const response = nextMessage(peer); + receive(new lib.MessageRequest(1, controller, control, "SimpleRequest")); + t3.match(await response, { type: "responseError", data: { message: "Sync" } }); + }); + + t2.test("does not log registered errors thrown by the handler", async t3 => { + const errors = t3.capture(lib.logger, "error"); + const { link, receive, peer } = controlSide(); + link.handle(SimpleRequest, async () => { throw new lib.NotFoundError("Missing"); }); + const response = nextMessage(peer); + receive(new lib.MessageRequest(1, controller, control, "SimpleRequest")); + t3.match(await response, { data: { message: "Missing", code: "NotFoundError" } }); + t3.strictSame(errors.args(), []); + }); + + t2.test("sends an error response when the request fails validation", async t3 => { + const errors = t3.capture(lib.logger, "error"); + const { link, receive, peer } = controlSide(); + let called = false; + link.handle(NumberRequest, async () => { called = true; return new NumberResponse(1); }); + const response = nextMessage(peer); + receive(new lib.MessageRequest(1, controller, control, "NumberRequest", "not a number")); + t3.match(await response, { + type: "responseError", + data: { message: "Request NumberRequest failed validation", code: "InvalidMessage" }, + }); + t3.equal(called, false); + const args = errors.args(); + t3.equal(args[0][0], "Request NumberRequest failed validation"); + t3.match(args[1][0], /must be number/); + }); + + t2.test("sends an error response when the response fails validation", async t3 => { + t3.capture(lib.logger, "error"); + const { link, receive, peer } = controlSide(); + link.handle(NumberRequest, async () => "not a number" as any); + const response = nextMessage(peer); + receive(new lib.MessageRequest(1, controller, control, "NumberRequest", 1)); + t3.match(await response, { + type: "responseError", + data: { message: "Response for request NumberRequest failed validation", code: "InvalidMessage" }, + }); + }); + + t2.test("sends an error response when a request without Response gets a value", async t3 => { + t3.capture(lib.logger, "error"); + const { link, receive, peer } = controlSide(); + link.handle(SimpleRequest, async () => 1 as any); + const response = nextMessage(peer); + receive(new lib.MessageRequest(1, controller, control, "SimpleRequest")); + t3.match(await response, { + type: "responseError", + data: { message: "Expected empty response from SimpleRequest handler", code: "InternalServerError" }, + }); + }); + + t2.test("sends the response unchecked when validateSent is false", async t3 => { + const { link, receive, peer } = controlSide(); + link.validateSent = false; + link.handle(SimpleRequest, async () => 1 as any); + const response = nextMessage(peer); + receive(new lib.MessageRequest(1, controller, control, "SimpleRequest")); + t3.match(await response, { type: "response", data: 1 }); + }); + + t2.test("logs when sending the error response fails", async t3 => { + const errors = t3.capture(lib.logger, "error"); + const { link, connector, receive } = controlSide(); + link.handle(SimpleRequest, async () => { throw new lib.NotFoundError("Missing"); }); + t3.capture(connector, "sendResponseError", () => { throw errorStack("Send failed"); }); + receive(new lib.MessageRequest(1, controller, control, "SimpleRequest")); + await settle(); + t3.strictSame(errors.args(), [["Unexpected error sending error response for SimpleRequest:\nSend failed"]]); + }); + + t2.test("sends an error response for requests without a handler", async t3 => { + const { receive, sent } = controlSide(); + receive(new lib.MessageRequest(1, controller, control, "SimpleRequest")); + t3.strictSame(sent, [new lib.MessageResponseError( + 1, control, controller, new lib.ResponseError("No handler for SimpleRequest"), + )]); + }); + + t2.test("handles events", async t3 => { + const { link, receive, sent } = controlSide(); + const calls: unknown[] = []; + link.handle(NumberEvent, async (event, src, dst) => { calls.push([event, src, dst]); }); + receive(new lib.MessageEvent(1, controller, control, "NumberEvent", 9)); + t3.strictSame(calls, [[new NumberEvent(9), controller, control]]); + t3.strictSame(sent, []); + }); + + t2.test("logs errors from event handlers", async t3 => { + const errors = t3.capture(lib.logger, "error"); + const { link, receive } = controlSide(); + link.handle(SimpleEvent, async () => { throw errorStack("Error"); }); + receive(new lib.MessageEvent(1, controller, control, "SimpleEvent")); + await settle(); + t3.strictSame(errors.args(), [["Unexpected error handling SimpleEvent:\nError"]]); + }); + + t2.test("logs the message of event handler errors without a stack", async t3 => { + const errors = t3.capture(lib.logger, "error"); + const { link, receive } = controlSide(); + link.handle(SimpleEvent, async () => { + const err = new Error("no stack"); + err.stack = undefined; + throw err; + }); + receive(new lib.MessageEvent(1, controller, control, "SimpleEvent")); + await settle(); + t3.strictSame(errors.args(), [["Unexpected error handling SimpleEvent:\nno stack"]]); + }); + + t2.test("logs events without a handler", async t3 => { + const errors = t3.capture(lib.logger, "error"); + const { receive, sent } = controlSide(); + receive(new lib.MessageEvent(1, controller, control, "SimpleEvent")); + t3.strictSame(errors.args(), [["Unhandled event SimpleEvent"]]); + t3.strictSame(sent, []); + }); + + t2.test("throws on classes of unknown type", async t3 => { + const { link } = controlSide(); + t3.throws( + () => link.handle({ name: "Bad", type: "bad" } as any, async () => {}), + { message: "Class Bad has unrecognized type bad" }, + ); + }); + + t2.test("throws when a handler is already set", async t3 => { + const { link } = controlSide(); + link.handle(SimpleRequest, async () => {}); + t3.throws( + () => link.handle(SimpleRequest, async () => {}), + { message: "Request SimpleRequest is already registered" }, + ); + link.handle(SimpleEvent, async () => {}); + t3.throws( + () => link.handle(SimpleEvent, async () => {}), + { message: "Event SimpleEvent is already registered" }, + ); + }); + }); + + t1.test("handleRequest()", async t2 => { + t2.test("throws for unregistered requests", async t3 => { + class Unregistered { static type = "request" as const; } + const { link } = controlSide(); + t3.throws( + () => link.handleRequest(Unregistered as any, async () => {}), + { message: "Unregistered Request class Unregistered" }, + ); + }); + }); + + t1.test("handleEvent()", async t2 => { + t2.test("throws for unregistered events", async t3 => { + class Unregistered { static type = "event" as const; } + const { link } = controlSide(); + t3.throws( + () => link.handleEvent(Unregistered as any, async () => {}), + { message: "Unregistered Event class Unregistered" }, + ); + }); + }); + + t1.test("fallbackRequest()", async t2 => { + t2.test("throws for unregistered requests", async t3 => { + class Unregistered { static type = "request" as const; } + const { link } = controlSide(); + t3.throws( + () => link.fallbackRequest(Unregistered as any, async () => {}), + { message: "Unregistered Request class Unregistered" }, + ); + }); + + t2.test("throws when a fallback is already set", async t3 => { + const { link } = controlSide(); + link.fallbackRequest(SimpleRequest, async () => {}); + t3.throws( + () => link.fallbackRequest(SimpleRequest, async () => {}), + { message: "Request SimpleRequest is already fallbacked" }, + ); + }); + }); + + t1.test("snoopEvent()", async t2 => { + t2.test("sees events before the handler", async t3 => { + const { link, receive } = controlSide(); + const calls: string[] = []; + link.snoopEvent(NumberEvent, async event => { calls.push(`snoop ${event.value}`); }); + link.handle(NumberEvent, async event => { calls.push(`handle ${event.value}`); }); + receive(new lib.MessageEvent(1, controller, control, "NumberEvent", 2)); + t3.strictSame(calls, ["snoop 2", "handle 2"]); + }); + + t2.test("sees events addressed elsewhere", async t3 => { + const { link, receive } = controlSide(); + let snooped = false; + link.snoopEvent(SimpleEvent, async () => { snooped = true; }); + link.router = { forwardMessage: () => true }; + receive(new lib.MessageEvent(1, controller, addr({ controlId: 2 }), "SimpleEvent")); + t3.equal(snooped, true); + }); + + t2.test("logs errors from the snooper", async t3 => { + const errors = t3.capture(lib.logger, "error"); + const { link, receive } = controlSide(); + link.handle(SimpleEvent, async () => {}); + link.snoopEvent(SimpleEvent, async () => { throw errorStack("Error"); }); + receive(new lib.MessageEvent(1, controller, control, "SimpleEvent")); + await settle(); + t3.strictSame(errors.args(), [["Unexpected error snooping SimpleEvent:\nError"]]); + }); + + t2.test("logs the message of snooper errors without a stack", async t3 => { + const errors = t3.capture(lib.logger, "error"); + const { link, receive } = controlSide(); + link.handle(SimpleEvent, async () => {}); + link.snoopEvent(SimpleEvent, async () => { + const err = new Error("no stack"); + err.stack = undefined; + throw err; + }); + receive(new lib.MessageEvent(1, controller, control, "SimpleEvent")); + await settle(); + t3.strictSame(errors.args(), [["Unexpected error snooping SimpleEvent:\nno stack"]]); + }); + + t2.test("throws for unregistered events", async t3 => { + class Unregistered { static type = "event" as const; } + const { link } = controlSide(); + t3.throws( + () => link.snoopEvent(Unregistered as any, async () => {}), + { message: "Unregistered Event class Unregistered" }, + ); + }); + + t2.test("throws when a snooper is already set", async t3 => { + const { link } = controlSide(); + link.snoopEvent(SimpleEvent, async () => {}); + t3.throws( + () => link.snoopEvent(SimpleEvent, async () => {}), + { message: "Event SimpleEvent is already snooped" }, + ); + }); + }); + + t1.test("_processMessage()", async t2 => { + t2.test("throws on unknown message types", async t3 => { + const { link } = controlSide(); + t3.throws( + () => link._processMessage({ type: "invalid" } as any), + { constructor: lib.InvalidMessage, message: "Unhandled message type invalid" }, + ); + }); + + t2.test("request validation", async t3 => { + const cases: [string, lib.Address, lib.Address, string, string][] = [ + ["unrecognized requests", controller, control, "Unknown", "Unrecognized request Unknown"], + [ + "a src not allowed", + host, + control, + "SimpleRequest", + `Source ${host} is not allowed for SimpleRequest`, + ], + [ + "a dst not allowed", + controller, + host, + "SimpleRequest", + `Destination ${host} is not allowed for SimpleRequest`, + ], + ["a broadcast src", allControls, control, "SimpleRequest", "Message src may not be broadcast"], + [ + "a broadcast dst", + controller, + allControls, + "SimpleRequest", + `Destination ${allControls} is not allowed for SimpleRequest`, + ], + ]; + for (const [name, src, dst, request, error] of cases) { + t3.test(`answers ${name} with an error response`, async t4 => { + const errors = t4.capture(lib.logger, "error"); + const { link, receive, sent } = controlSide(); + let called = false; + link.handle(SimpleRequest, async () => { called = true; }); + receive(new lib.MessageRequest(1, src, dst, request)); + t4.strictSame(sent, [new lib.MessageResponseError( + 1, control, src, new lib.ResponseError(error, "InvalidMessage"), + )]); + t4.strictSame(errors.args(), [[error]]); + t4.equal(called, false); + }); + } + }); + + t2.test("event validation", async t3 => { + const cases: [string, lib.Address, lib.Address, string, string][] = [ + ["unrecognized events", controller, control, "Unknown", "Unrecognized event Unknown"], + ["a src not allowed", host, control, "SimpleEvent", `Source ${host} is not allowed for SimpleEvent`], + [ + "a dst not allowed", + controller, + host, + "SimpleEvent", + `Destination ${host} is not allowed for SimpleEvent`, + ], + ["a broadcast src", allControls, control, "SimpleEvent", "Message src may not be broadcast"], + [ + "a broadcast dst not allowed", + controller, + addr("allHosts"), + "SimpleEvent", + `Destination ${addr("allHosts")} is not allowed for SimpleEvent`, + ], + ]; + for (const [name, src, dst, event, error] of cases) { + t3.test(`drops ${name}`, async t4 => { + const errors = t4.capture(lib.logger, "error"); + const { link, receive, sent } = controlSide(); + let called = false; + link.snoopEvent(SimpleEvent, async () => { called = true; }); + link.handle(SimpleEvent, async () => { called = true; }); + receive(new lib.MessageEvent(1, src, dst, event)); + t4.strictSame(errors.args(), [[error]]); + t4.strictSame(sent, []); + t4.equal(called, false); + }); + } + }); + + t2.test("answers requests rejected by validateIngress with an error response", async t3 => { + t3.capture(lib.logger, "error"); + const { link, receive, sent } = controlSide(); + t3.capture(link, "validateIngress", () => { throw new lib.InvalidMessage("Not from here"); }); + receive(new lib.MessageRequest(1, controller, control, "SimpleRequest")); + receive(new lib.MessageEvent(2, controller, control, "SimpleEvent")); + t3.strictSame(sent, [new lib.MessageResponseError( + 1, control, controller, new lib.ResponseError("Not from here", "InvalidMessage"), + )]); + }); + + t2.test("handles a broadcast event addressed to this link", async t3 => { + const { link, receive } = controlSide(); + let handled = false; + link.handle(SimpleEvent, async () => { handled = true; }); + receive(new lib.MessageEvent(1, controller, allControls, "SimpleEvent")); + t3.equal(handled, true); + }); + + t2.test("routes a broadcast event as well as handling it", async t3 => { + const { link, receive } = controlSide(); + const routed: unknown[] = []; + let handled = false; + link.router = { forwardMessage: (...args) => { routed.push(args); return true; } }; + link.handle(SimpleEvent, async () => { handled = true; }); + const message = new lib.MessageEvent(1, controller, allControls, "SimpleEvent"); + receive(message); + t3.strictSame(routed, [[link, message, lib.Link._eventsByClass.get(SimpleEvent as any), false]]); + t3.equal(handled, true); + }); + + t2.test("does not route a non broadcast addressed to this link", async t3 => { + const { link, receive } = controlSide(); + let routed = false; + link.router = { forwardMessage: () => { routed = true; return true; } }; + link.handle(SimpleEvent, async () => {}); + receive(new lib.MessageEvent(1, controller, control, "SimpleEvent")); + t3.equal(routed, false); + }); + + t2.test("rejects requests addressed elsewhere on a link which does not route", async t3 => { + const errors = t3.capture(lib.logger, "error"); + const { receive, sent } = controllerSide(); + receive(new lib.MessageRequest(1, control, host, "HostRequest")); + const error = `Received message addressed to ${host} but this link does not route messages`; + t3.strictSame(sent, [new lib.MessageResponseError( + 1, controller, control, new lib.ResponseError(error, "InvalidMessage"), + )]); + t3.strictSame(errors.args(), [[error]]); + }); + + t2.test("drops events addressed elsewhere on a link which does not route", async t3 => { + const errors = t3.capture(lib.logger, "error"); + const { receive, sent } = controlSide(); + receive(new lib.MessageEvent(1, controller, addr({ controlId: 2 }), "SimpleEvent")); + t3.equal(errors.args().length, 1); + t3.strictSame(sent, []); + }); + + t2.test("passes messages addressed elsewhere to the router", async t3 => { + const { link, receive } = controllerSide(); + const routed: unknown[] = []; + link.router = { forwardMessage: (...args) => { routed.push(args); return true; } }; + const message = new lib.MessageRequest(1, control, host, "HostRequest"); + receive(message); + t3.strictSame(routed, [[link, message, lib.Link._requestsByClass.get(HostRequest as any), false]]); + }); + + t2.test("uses the fallback handler when the router declines", async t3 => { + const { link, receive, peer } = controllerSide(); + const calls: unknown[] = []; + link.router = { + forwardMessage: (_origin, _message, _entry, fallback) => { calls.push(fallback); return false; }, + }; + link.fallbackRequest(HostRequest, async (_request, src, dst) => { calls.push([src, dst]); }); + const response = nextMessage(peer); + receive(new lib.MessageRequest(1, control, host, "HostRequest")); + t3.strictSame(calls, [true, [control, host]]); + t3.strictSame(await response, new lib.MessageResponse(1, host, control), "response is sent as from dst"); + }); + + t2.test("emits an error when the router declines without a fallback", async t3 => { + const { link, connector, receive } = controllerSide(); + const emitted: Error[] = []; + connector.on("error", err => { emitted.push(err); }); + link.router = { forwardMessage: () => false }; + receive(new lib.MessageRequest(1, control, host, "HostRequest")); + t3.match(emitted, [{ message: "Router requested fallback handling when fallback is unavailable" }]); + }); + + t2.test("forgets the forwarded request when its response passes", async t3 => { + const { link, receive } = controllerSide(); + link.router = { forwardMessage: () => true }; + const requestSrc = new lib.Address(lib.Address.control, 1, 7); + link.forwardRequest(new lib.MessageRequest(1, requestSrc, host, "HostRequest"), link); + t3.equal(link.pendingRequestCount, 1); + receive(new lib.MessageResponse(1, host, requestSrc)); + t3.equal(link.pendingRequestCount, 0); + }); + + t2.test("logs responses without a pending request", async t3 => { + const errors = t3.capture(lib.logger, "error"); + const { receive } = controlSide(); + const dst = new lib.Address(lib.Address.control, 1, 5); + receive(new lib.MessageResponse(1, controller, dst)); + receive(new lib.MessageResponseError(2, controller, dst, new lib.ResponseError("Error"))); + t3.strictSame(errors.args(), [ + [`Received response 5 from ${controller} without a pending request`], + [`Received error response 5 from ${controller} without a pending request`], + ]); + }); + + t2.test("ignores responses from a different address than the request went to", async t3 => { + const errors = t3.capture(lib.logger, "error"); + const { link, receive, sent } = controlSide(); + const pending = link.sendTo(addr({ controlId: 2 }), new SimpleRequest()); + receive(new lib.MessageResponse(1, addr({ controlId: 3 }), sent[0].src)); + t3.equal(link.pendingRequestCount, 1); + t3.match(errors.args(), [[/^Received reply from \[Address control:3\] for message sent to/]]); + receive(new lib.MessageResponse(2, addr({ controlId: 2 }), sent[0].src)); + await pending; + }); + + t2.test("permissions", async t3 => { + t3.test("checks requests and events received from a control", async t4 => { + const { link, receive } = controllerSide(); + const checks = t4.capture(link, "validatePermission"); + let handled = 0; + link.handle(SimpleRequest, async () => { handled += 1; }); + link.handle(SimpleEvent, async () => { handled += 1; }); + receive(new lib.MessageRequest(1, control, controller, "SimpleRequest")); + receive(new lib.MessageEvent(2, control, controller, "SimpleEvent")); + t4.strictSame(checks.args().map(([message, entry]) => [message.name, entry.name]), [ + ["SimpleRequest", "SimpleRequest"], ["SimpleEvent", "SimpleEvent"], + ]); + t4.equal(handled, 2); + }); + + t3.test("does not check messages on other links", async t4 => { + const { link, receive } = controlSide(); + const checks = t4.capture(link, "validatePermission"); + link.handle(SimpleEvent, async () => {}); + receive(new lib.MessageEvent(1, controller, control, "SimpleEvent")); + t4.strictSame(checks.args(), []); + }); + + t3.test("silently drops messages denied with a ClientError", async t4 => { + const errors = t4.capture(lib.logger, "error"); + const { link, connector, receive, sent } = controllerSide(); + const emitted: Error[] = []; + connector.on("error", err => { emitted.push(err); }); + t4.capture(link, "validatePermission", () => { throw new lib.PermissionError("Denied"); }); + let handled = false; + link.handle(SimpleRequest, async () => { handled = true; }); + receive(new lib.MessageRequest(1, control, controller, "SimpleRequest")); + t4.equal(handled, false); + t4.strictSame(emitted, []); + t4.strictSame(sent, []); + t4.strictSame(errors.args(), []); + }); + + t3.test("logs and drops messages when the check throws another error", async t4 => { + const errors = t4.capture(lib.logger, "error"); + const { link, connector, receive } = controllerSide(); + const emitted: Error[] = []; + connector.on("error", err => { emitted.push(err); }); + t4.capture(link, "validatePermission", () => { throw errorStack("check is broken"); }); + let handled = false; + link.handle(SimpleRequest, async () => { handled = true; }); + receive(new lib.MessageRequest(1, control, controller, "SimpleRequest")); + t4.equal(handled, false); + t4.strictSame(emitted, []); + t4.strictSame( + errors.args(), + [["Unexpected error checking permission for SimpleRequest:\ncheck is broken"]], + ); + }); + + t3.test("logs the message of non-ClientErrors without a stack", async t4 => { + const errors = t4.capture(lib.logger, "error"); + const { link, receive } = controllerSide(); + t4.capture(link, "validatePermission", () => { + const err = new Error("no stack"); + err.stack = undefined; + throw err; + }); + receive(new lib.MessageEvent(1, control, controller, "SimpleEvent")); + t4.strictSame(errors.args(), [["Unexpected error checking permission for SimpleEvent:\nno stack"]]); + }); + }); + }); + + t1.test("forwardRequest()", async t2 => { + // The request is recorded so its response can be sent back the way it came, see #650. + function forwarding() { + const origin = recordedLink(controller, control); + const nextHop = recordedLink(controller, host); + const message = new lib.MessageRequest(1, new lib.Address(lib.Address.control, 1, 3), host, "HostRequest"); + return { origin, nextHop, message }; + } + + t2.test("sends the request on and records it", async t3 => { + const { origin, nextHop, message } = forwarding(); + nextHop.link.forwardRequest(message, origin.link); + t3.equal(nextHop.link.pendingRequestCount, 1); + t3.strictSame(nextHop.sent, [message]); + }); + + t2.test("does not record a request it failed to forward", async t3 => { + const { origin, nextHop, message } = forwarding(); + t3.capture(nextHop.connector, "forward", () => { throw new Error("Session Closed"); }); + t3.throws(() => nextHop.link.forwardRequest(message, origin.link), { message: "Session Closed" }); + t3.equal(nextHop.link.pendingRequestCount, 0); + nextHop.connector.emit("close"); + t3.strictSame(origin.sent, [], "failed request is not answered again on close"); + }); + }); + + t1.test("prepareDisconnect()", async t2 => { + t2.test("waits for pending requests to settle", async t3 => { + const { link, receive, sent } = controlSide(); + const answered = link.send(new SimpleRequest()); + const failed = link.send(new SimpleRequest()); + failed.catch(() => {}); + let done = false; + const prepared = link.prepareDisconnect().then(() => { done = true; }); + await settle(); + t3.equal(done, false); + receive(new lib.MessageResponse(1, controller, sent[0].src)); + receive(new lib.MessageResponseError(2, controller, sent[1].src, new lib.ResponseError("Error"))); + await prepared; + await answered; + t3.equal(done, true); + }); + }); + + t1.test("_clearPendingRequests()", async t2 => { + t2.test("answers forwarded requests with the error", async t3 => { + const origin = recordedLink(controller, control); + const nextHop = recordedLink(controller, host); + const requestSrc = new lib.Address(lib.Address.control, 1, 3); + nextHop.link.forwardRequest(new lib.MessageRequest(1, requestSrc, host, "HostRequest"), origin.link); + nextHop.link._clearPendingRequests(new lib.SessionLost("Session Lost")); + t3.strictSame(origin.sent, [new lib.MessageResponseError( + 1, host, requestSrc, new lib.ResponseError("Session Lost", "SessionLost"), + )]); + t3.equal(nextHop.link.pendingRequestCount, 0); + }); + + t2.test("does not answer origins whose WebSocket session has ended", async t3 => { + const originConnector = new TestWebSocketConnector(controller, control); + const origin = new lib.Link(originConnector); + const nextHop = recordedLink(controller, host); + const requestSrc = new lib.Address(lib.Address.control, 1, 3); + nextHop.link.forwardRequest(new lib.MessageRequest(1, requestSrc, host, "HostRequest"), origin); + nextHop.link._clearPendingRequests(new lib.SessionLost("Session Lost")); + t3.strictSame(originConnector.sentText, []); + t3.equal(nextHop.link.pendingRequestCount, 0); + }); + }); + + t1.test("routing", async t2 => { + // control 1 <-> controller <-> host 1, with the controller forwarding between the two + function chain() { + const client = linkPair(control, controller); + const hostLinks = linkPair(controller, host); + const controlSideLink = client.peer; + const hostSideLink = hostLinks.link; + controlSideLink.router = { + forwardMessage(origin, message) { + hostSideLink.forwardRequest(message as lib.MessageRequest, origin); + return true; + }, + }; + hostSideLink.router = { + forwardMessage(_origin, message) { + controlSideLink.connector.forward(message); + return true; + }, + }; + return { client: client.link, host: hostLinks.peer, hostSideLink }; + } + + t2.test("delivers a request and its response through a router", async t3 => { + const { client, host: hostLink, hostSideLink } = chain(); + hostLink.handle(HostRequest, async (_request, src) => { t3.equal(src.type, lib.Address.control); }); + await client.sendTo(host, new HostRequest()); + t3.equal(hostSideLink.pendingRequestCount, 0); + }); + + class UnregisteredConflict extends lib.ConflictError { } + const errorCases: [string, Error, Function, number][] = [ + ["the class thrown by the handler", new lib.NotFoundError("Thing does not exist"), lib.NotFoundError, 0], + ["a registered plugin error class", new TestPluginError("Plugin conflict"), TestPluginError, 0], + ["the closest registered class", new UnregisteredConflict("Busy"), lib.ConflictError, 0], + ["InternalServerError for unregistered", new TypeError("x is not a function"), lib.InternalServerError, 1], + ]; + for (const [name, err, Expected, logged] of errorCases) { + t2.test(`rejects with ${name}`, async t3 => { + const errors = t3.capture(lib.logger, "error"); + const { client, host: hostLink } = chain(); + hostLink.handle(HostRequest, async () => { throw err; }); + await t3.rejects( + client.sendTo(host, new HostRequest()), + { constructor: Expected, message: err.message, stack: err.stack }, + ); + t3.equal(errors.args().length, logged, "logged unexpected errors only"); + }); + } + }); + + t1.test("Link.register()", async t2 => { + t2.test("registers requests by name and class", async t3 => { + const entry = lib.Link._requestsByName.get("NumberRequest")!; + t3.equal(lib.Link._requestsByClass.get(NumberRequest as any), entry); + t3.strictSame(entry.allowedSrcTypes, new Set([lib.Address.controller, lib.Address.control])); + t3.equal(entry.Response, NumberResponse); + }); + + t2.test("registers plugin messages with the plugin prefix", async t3 => { + t3.equal(lib.Link._requestsByName.get("link_test:PluginRequest")?.Request, PluginRequest); + t3.equal(lib.Link._requestsByName.has("PluginRequest"), false); + }); + + t2.test("accepts a single type for src and dst", async t3 => { + t3.strictSame(lib.Link._eventsByName.get("HostEvent")!.allowedDstTypes, new Set([lib.Address.host])); + }); + + const base = { src: "controller", dst: "control" }; + const failures: [string, object, string][] = [ + ["an unknown type", { type: "bad" }, "Data class Bad has unknown type bad"], + [ + "a request already registered", + { name: "SimpleRequest", type: "request" }, + "Request SimpleRequest is already registered", + ], + [ + "an event already registered", + { name: "SimpleEvent", type: "event" }, + "Event SimpleEvent is already registered", + ], + [ + "a request with jsonSchema but no fromJSON", + { type: "request", jsonSchema: {} }, + "Request Bad has static jsonSchema but is missing static fromJSON", + ], + [ + "a request with fromJSON but no jsonSchema", + { type: "request", fromJSON() {} }, + "Request Bad has static fromJSON but is missing static jsonSchema", + ], + [ + "an event with jsonSchema but no fromJSON", + { type: "event", jsonSchema: {} }, + "Event Bad has static jsonSchema but is missing static fromJSON", + ], + [ + "an event with fromJSON but no jsonSchema", + { type: "event", fromJSON() {} }, + "Event Bad has static fromJSON but is missing static jsonSchema", + ], + [ + "a Response without jsonSchema", + { type: "request", Response: { fromJSON() {} } }, + "Response for Request Bad is missing static jsonSchema", + ], + [ + "a Response without fromJSON", + { type: "request", Response: { jsonSchema: {} } }, + "Response for Request Bad is missing static fromJSON", + ], + ["a missing src", { type: "event", src: undefined }, "Missing src specification in Bad"], + ["a missing dst", { type: "request", dst: undefined }, "Missing dst specification in Bad"], + [ + "an invalid address type", + { type: "event", src: ["controller", "nowhere"] }, + "Invalid type nowhere in src specification of Bad", + ], + [ + "a broadcast address type", + { type: "request", dst: "broadcast" }, + "dst specification may not use the broadcast type in Bad", + ], + [ + "a request from control without permission", + { type: "request", src: "control" }, + "Invalid permission specification undefined on Bad", + ], + [ + "an event from control with a bad permission", + { type: "event", src: "control", permission: 1 }, + "Invalid permission specification number on Bad", + ], + ]; + for (const [name, props, message] of failures) { + t2.test(`throws for ${name}`, async t3 => { + const { name: className = "Bad", ...rest } = props as { name?: string }; + const Class = Object.assign(class Bad {}, base, rest); + Object.defineProperty(Class, "name", { value: className }); + const requests = lib.Link._requestsByName.size; + const events = lib.Link._eventsByName.size; + t3.throws(() => lib.Link.register(Class as any), { message }); + t3.equal(lib.Link._requestsByName.size, requests, "no request registered"); + t3.equal(lib.Link._eventsByName.size, events, "no event registered"); + }); + } + }); + + t1.test("Link.registerError()", async t2 => { + t2.test("throws when the name is already registered", async t3 => { + t3.throws( + () => lib.Link.registerError(lib.NotFoundError), + { message: "Error NotFoundError is already registered" }, + ); + }); + }); + + t1.test("Link.errorName()", async t2 => { + t2.test("returns the registered name of the closest class", async t3 => { + class Unregistered extends lib.NotFoundError { } + t3.equal(lib.Link.errorName(new lib.NotFoundError("a")), "NotFoundError"); + t3.equal(lib.Link.errorName(new Unregistered("a")), "NotFoundError"); + t3.equal(lib.Link.errorName(new TestPluginError("a")), "link_test:TestPluginError"); + t3.equal(lib.Link.errorName(new Error("a")), undefined); + }); + }); + + t1.test("Link.errorToResponse()", async t2 => { + t2.test("includes the stack unless told not to", async t3 => { + const err = new lib.NotFoundError("Missing"); + t3.strictSame(lib.Link.errorToResponse(err), new lib.ResponseError("Missing", "NotFoundError", err.stack)); + t3.strictSame(lib.Link.errorToResponse(err, false), new lib.ResponseError("Missing", "NotFoundError")); + }); + + t2.test("uses InternalServerError for unregistered errors", async t3 => { + t3.equal(lib.Link.errorToResponse(new Error("a")).code, "InternalServerError"); + }); + }); + + t1.test("Link.errorFromResponse()", async t2 => { + t2.test("creates the registered class", async t3 => { + const err = lib.Link.errorFromResponse(new lib.ResponseError("Missing", "NotFoundError", "stack")); + t3.type(err, lib.NotFoundError); + t3.match(err, { message: "Missing", stack: "stack" }); + }); + + t2.test("keeps the local stack when the response has none", async t3 => { + const err = lib.Link.errorFromResponse(new lib.ResponseError("Missing", "NotFoundError")); + t3.match(err.stack, /^Error: Missing\n\s+at /); + }); + + t2.test("uses InternalServerError for unknown and missing names", async t3 => { + t3.type( + lib.Link.errorFromResponse(new lib.ResponseError("Gone", "other_plugin:GoneError")), + lib.InternalServerError, + ); + t3.type(lib.Link.errorFromResponse(new lib.ResponseError("Gone")), lib.InternalServerError); + }); + }); +}); + +t.test("registerPluginMessages()", async t1 => { + t1.test("requires messages to set the plugin property", async t2 => { + class MissingPluginEvent { + static type = "event" as const; + static src = "controller" as const; + static dst = "host" as const; + } + t2.throws( + () => lib.registerPluginMessages([{ name: "other", messages: [MissingPluginEvent] } as any]), + { message: /^Expected message MissingPluginEvent from other to have a static plugin property/ }, + ); + t2.equal(lib.Link._eventsByClass.has(MissingPluginEvent as any), false); + }); + + t1.test("requires errors to set the plugin property", async t2 => { + class MissingPluginError extends lib.ClientError { } + t2.throws( + () => lib.registerPluginMessages([{ name: "other", errors: [MissingPluginError] } as any]), + { message: /^Expected error MissingPluginError from other to have a static plugin property/ }, + ); + }); +}); diff --git a/tests/lib/prometheus.test.ts b/tests/lib/prometheus.test.ts new file mode 100644 index 00000000..fe87ba1a --- /dev/null +++ b/tests/lib/prometheus.test.ts @@ -0,0 +1,1096 @@ +import t from "tap"; +import * as lib from "@clusterio/lib"; + +type Result = lib.CollectorResult; + +async function collectAll(iterable: AsyncIterable) { + const results: Result[] = []; + for await (const result of iterable) { + results.push(result); + } + return results; +} + +// Known bugs, reported as todo until fixed +const staleChildTodo = "a cached child writes undefined + n, exporting NaN"; +const backslashNTodo = "keyToLabels unescapes \\n before \\\\"; +const emptyValueTodo = "keyToLabels regex needs one or more characters in a value"; +const emptyAddLabelsTodo = "appends a trailing comma to the key"; +const nonFiniteTodo = "JSON turns Infinity and NaN into null"; + +// Register collectors to a fresh registry and return its exposition +async function expose(...collectors: lib.Collector[]) { + const registry = new lib.CollectorRegistry(); + for (const collector of collectors) { + registry.register(collector); + } + return lib.exposition(registry.collect()); +} + +function labeledGauge() { + return new lib.Gauge("test", "Help", { register: false, labels: ["a", "b"] }); +} + +// Stub process.hrtime.bigint so durations are exact +function fakeHrtime(t1: any, ...times: bigint[]) { + const queue = [...times]; + return t1.capture(process.hrtime, "bigint", () => queue.shift()); +} + +// Every ASCII codepoint plus characters from the basic and supplementary planes +const specialLabel = `${Array.from({ length: 128 }, (_, i) => String.fromCodePoint(i)).join("")}©💣`; + +t.test("Metric", async t1 => { + t1.test("constructor", async t2 => { + t2.test("stores type, name, help and labels", async t3 => { + const metric = new lib.Metric("gauge", "a_b:c", "Help", ["x", "_y"]); + t3.equal(metric.type, "gauge"); + t3.equal(metric.name, "a_b:c"); + t3.equal(metric.help, "Help"); + t3.strictSame(metric.labels, ["x", "_y"]); + }); + t2.test("defaults to no labels", async t3 => { + t3.strictSame(new lib.Metric("gauge", "a", "Help").labels, []); + }); + t2.test("rejects a name that is not a string", async t3 => { + t3.throws(() => new (lib.Metric as any)("gauge", 1, "Help"), new Error("Expected name to be a string")); + }); + t2.test("rejects help that is not a string", async t3 => { + t3.throws(() => new (lib.Metric as any)("gauge", "a"), new Error("Expected help to be a string")); + }); + t2.test("rejects invalid names", async t3 => { + for (const name of ["", " ", "0a", "$a", "a-b"]) { + t3.throws(() => new lib.Metric("gauge", name, "Help"), new Error(`Invalid name '${name}'`)); + } + }); + t2.test("rejects invalid label names", async t3 => { + for (const label of ["", " ", "0a", "$a", "a:"]) { + t3.throws(() => new lib.Metric("gauge", "a", "Help", [label]), new Error(`Invalid label '${label}'`)); + } + }); + t2.test("rejects reserved label names", async t3 => { + t3.throws( + () => new lib.Metric("gauge", "a", "Help", ["x", "le"], ["le"]), + new Error("Reserved label 'le'"), + ); + }); + }); +}); + +t.test("Collector", async t1 => { + t1.test("constructor", async t2 => { + t2.test("registers to the default registry by default", async t3 => { + const collector = new lib.Collector(); + t3.teardown(() => lib.defaultRegistry.unregister(collector)); + t3.ok(lib.defaultRegistry.collectors.includes(collector)); + }); + t2.test("does not register when register is false", async t3 => { + const collector = new lib.Collector(false); + t3.notOk(lib.defaultRegistry.collectors.includes(collector)); + }); + }); + t1.test("collect()", async t2 => { + t2.test("yields no results", async t3 => { + t3.strictSame(await collectAll(new lib.Collector(false).collect()), []); + }); + }); +}); + +t.test("LabeledCollector", async t1 => { + t1.test("constructor", async t2 => { + t2.test("rejects unrecognized options", async t3 => { + t3.throws( + () => new lib.Gauge("test", "Help", { invalid: 1 } as any), + new Error("Unrecognized option 'invalid'"), + ); + }); + t2.test("does not register when the metric is invalid", async t3 => { + const count = lib.defaultRegistry.collectors.length; + t3.throws(() => new lib.Gauge("0", "Help")); + t3.equal(lib.defaultRegistry.collectors.length, count); + }); + t2.test("registers to the default registry by default", async t3 => { + const gauge = new lib.Gauge("test", "Help"); + t3.teardown(() => lib.defaultRegistry.unregister(gauge)); + t3.ok(lib.defaultRegistry.collectors.includes(gauge)); + }); + }); + + t1.test("labels()", async t2 => { + t2.test("requires every label and no extras", async t3 => { + const gauge = labeledGauge(); + t3.throws(() => gauge.labels({ a: "1" }), new Error("Missing label 'b'")); + t3.throws(() => gauge.labels({ b: "1" }), new Error("Missing label 'a'")); + t3.throws(() => gauge.labels({ a: "1", b: "2", c: "3" }), new Error("Extra label 'c'")); + t3.throws(() => gauge.labels("1"), new Error("Missing label 'b'")); + t3.throws(() => gauge.labels("1", "2", "3"), new Error("Extra positional label")); + }); + t2.test("rejects label values that are not strings", async t3 => { + const gauge = labeledGauge(); + const error = new Error("Expected value for label 'b' to be a string"); + t3.throws(() => gauge.labels({ a: "1", b: 2 } as any), error); + t3.throws(() => gauge.labels("1", 2 as any), error); + }); + t2.test("initialises a value for the label set", async t3 => { + const gauge = labeledGauge(); + gauge.labels({ a: "1", b: "2" }); + gauge.labels("4", "5"); + t3.strictSame(gauge._values, new Map([['a="1",b="2"', 0], ['a="4",b="5"', 0]])); + }); + t2.test("orders label object keys by the metric labels", async t3 => { + const gauge = labeledGauge(); + gauge.labels({ b: "y", a: "x" }); + t3.strictSame([...gauge._values.keys()], ['a="x",b="y"']); + }); + t2.test("returns the same child for the same labels", async t3 => { + const gauge = labeledGauge(); + const child = gauge.labels("1", "2"); + t3.equal(gauge.labels("1", "2"), child); + t3.equal(gauge.labels({ a: "1", b: "2" }), child); + t3.not(gauge.labels("1", "3"), child); + }); + t2.test("escapes backslash, quote and newline in values", async t3 => { + const gauge = new lib.Gauge("test", "Help", { register: false, labels: ["a"] }); + gauge.labels('x\\y"z\nw'); + t3.strictSame([...gauge._values.keys()], ['a="x\\\\y\\"z\\nw"']); + }); + }); + + t1.test("remove()", async t2 => { + t2.test("removes a label set and its value", async t3 => { + const gauge = labeledGauge(); + const child = gauge.labels({ a: "1", b: "2" }); + gauge.labels("3", "4"); + t3.equal(gauge.remove({ a: "1", b: "2" }), 'a="1",b="2"'); + t3.strictSame([...gauge._values.keys()], ['a="3",b="4"']); + t3.not(gauge.labels("1", "2"), child, "creates a new child afterwards"); + }); + t2.test("accepts positional labels", async t3 => { + const gauge = labeledGauge(); + gauge.labels("1", "2"); + gauge.remove("1", "2"); + t3.equal(gauge._values.size, 0); + }); + t2.test("rejects the empty label set", async t3 => { + const gauge = new lib.Gauge("test", "Help", { register: false }); + t3.throws(() => gauge.remove({}), new Error("labels cannot be empty")); + t3.equal(gauge.get(), 0, "default value is kept"); + }); + t2.test("does not re-export the series from a stale child", { todo: staleChildTodo }, async t3 => { + const gauge = labeledGauge(); + const child = gauge.labels("1", "2"); + gauge.remove("1", "2"); + child.inc(); + t3.equal(gauge._values.size, 0); + }); + }); + + t1.test("removeAll()", async t2 => { + t2.test("removes label sets matching a partial label set", async t3 => { + const gauge = labeledGauge(); + gauge.labels("1", "2"); + gauge.labels("1", "3"); + gauge.labels("4", "6"); + gauge.removeAll({ a: "1" }); + t3.strictSame(gauge._values, new Map([['a="4",b="6"', 0]])); + }); + t2.test("removes the children of matching label sets", async t3 => { + const gauge = labeledGauge(); + const child = gauge.labels("1", "2"); + gauge.removeAll({ a: "1" }); + t3.not(gauge.labels("1", "2"), child); + }); + t2.test("requires every given label to match", async t3 => { + const gauge = labeledGauge(); + gauge.labels("1", "2"); + gauge.labels("1", "3"); + gauge.removeAll({ a: "1", b: "3" }); + t3.strictSame([...gauge._values.keys()], ['a="1",b="2"']); + }); + t2.test("rejects the empty label set", async t3 => { + const gauge = new lib.Gauge("test", "Help", { register: false }); + t3.throws(() => gauge.removeAll({}), new Error("labels cannot be empty")); + }); + t2.test("matches values with special characters", async t3 => { + const gauge = labeledGauge(); + gauge.labels(specialLabel, "2"); + gauge.removeAll({ a: specialLabel }); + t3.equal(gauge._values.size, 0); + gauge.labels("1", specialLabel); + gauge.removeAll({ a: "1" }); + t3.equal(gauge._values.size, 0); + }); + t2.test("matches a literal backslash followed by n", { todo: backslashNTodo }, async t3 => { + const gauge = labeledGauge(); + gauge.labels("\\n", "2"); + gauge.removeAll({ a: "\\n" }); + t3.equal(gauge._values.size, 0); + }); + t2.test("handles empty label values", { todo: emptyValueTodo }, async t3 => { + const gauge = labeledGauge(); + gauge.labels("", "2"); + t3.doesNotThrow(() => gauge.removeAll({ b: "2" })); + t3.equal(gauge._values.size, 0); + }); + }); + + t1.test("clear()", async t2 => { + t2.test("removes all label sets", async t3 => { + const gauge = labeledGauge(); + const child = gauge.labels({ a: "1", b: "2" }); + gauge.labels({ a: "3", b: "4" }); + gauge.clear(); + t3.equal(gauge._values.size, 0); + t3.not(gauge.labels("1", "2"), child); + }); + t2.test("rejects an unlabeled metric", async t3 => { + const gauge = new lib.Gauge("test", "Help", { register: false }); + t3.throws(() => gauge.clear(), new Error("Cannot clear unlabeled metric")); + }); + }); +}); + +t.test("ValueCollector", async t1 => { + t1.test("get()", async t2 => { + t2.test("returns the current value", async t3 => { + const gauge = new lib.Gauge("test", "Help", { register: false }); + gauge.set(11); + t3.equal(gauge.get(), 11); + }); + }); + t1.test("collect()", async t2 => { + t2.test("yields the metric and its values", async t3 => { + const gauge = labeledGauge(); + gauge.labels("1", "2").set(3); + const results = await collectAll(gauge.collect()); + t3.equal(results.length, 1); + t3.equal(results[0].metric, gauge.metric); + t3.strictSame(results[0].samples, new Map([["", new Map([['a="1",b="2"', 3]])]])); + }); + t2.test("awaits the callback before yielding", async t3 => { + const gauge = new lib.Gauge("test", "Help", { + register: false, + callback: async collector => { + await new Promise(resolve => setImmediate(resolve)); + collector.set(5); + }, + }); + const results = await collectAll(gauge.collect()); + t3.equal(results[0].samples.get("")!.get(""), 5); + }); + t2.test("passes the collector to the callback", async t3 => { + let received; + const counter = new lib.Counter("test", "Help", { + register: false, + callback: collector => { received = collector; }, + }); + await collectAll(counter.collect()); + t3.equal(received, counter); + }); + }); +}); + +t.test("Counter", async t1 => { + const counter = () => new lib.Counter("test", "Help", { register: false }); + + t1.test("constructor", async t2 => { + t2.test("initialises the value to 0", async t3 => { + t3.equal(counter().get(), 0); + }); + t2.test("sets the metric type to counter", async t3 => { + t3.equal(counter().metric.type, "counter"); + }); + t2.test("has no default value when labeled", async t3 => { + const labeled = new lib.Counter("test", "Help", { register: false, labels: ["a"] }); + t3.equal(labeled._values.size, 0); + }); + }); + + t1.test("inc()", async t2 => { + t2.test("increments by 1 by default", async t3 => { + const c = counter(); + c.inc(); + c.inc(); + t3.equal(c.get(), 2); + }); + t2.test("increments by the given value", async t3 => { + const c = counter(); + c.inc(3.2); + t3.equal(c.get(), 3.2); + }); + t2.test("accepts 0 and Infinity", async t3 => { + const c = counter(); + c.inc(0); + t3.equal(c.get(), 0); + c.inc(Infinity); + t3.equal(c.get(), Infinity); + }); + t2.test("rejects negative values and NaN", async t3 => { + const c = counter(); + for (const value of [-1, -Infinity, NaN]) { + t3.throws(() => c.inc(value), new Error("Expected value to be a positive number")); + } + t3.equal(c.get(), 0); + }); + t2.test("increments a labeled child", async t3 => { + const c = new lib.Counter("test", "Help", { register: false, labels: ["a"] }); + c.labels("x").inc(2); + t3.equal(c.labels("x").get(), 2); + t3.throws(() => c.labels("x").inc(-1)); + }); + }); +}); + +t.test("Gauge", async t1 => { + const gauge = () => new lib.Gauge("test", "Help", { register: false }); + const labeled = () => new lib.Gauge("test", "Help", { register: false, labels: ["a"] }); + + t1.test("constructor", async t2 => { + t2.test("initialises the value to 0", async t3 => { + t3.equal(gauge().get(), 0); + }); + t2.test("sets the metric type to gauge", async t3 => { + t3.equal(gauge().metric.type, "gauge"); + }); + }); + + t1.test("inc()", async t2 => { + t2.test("increments by 1 by default", async t3 => { + const g = gauge(); + g.inc(); + t3.equal(g.get(), 1); + }); + t2.test("increments by the given value", async t3 => { + const g = gauge(); + g.inc(3.2); + t3.equal(g.get(), 3.2); + }); + t2.test("decrements on a negative value", async t3 => { + const g = gauge(); + g.inc(-2); + t3.equal(g.get(), -2); + }); + t2.test("increments a labeled child", async t3 => { + const g = labeled(); + g.labels("x").inc(); + g.labels("x").inc(2); + t3.equal(g.labels("x").get(), 3); + }); + }); + + t1.test("dec()", async t2 => { + t2.test("decrements by 1 by default", async t3 => { + const g = gauge(); + g.dec(); + t3.equal(g.get(), -1); + }); + t2.test("decrements by the given value", async t3 => { + const g = gauge(); + g.dec(3.2); + t3.equal(g.get(), -3.2); + }); + t2.test("increments on a negative value", async t3 => { + const g = gauge(); + g.dec(-2); + t3.equal(g.get(), 2); + }); + t2.test("decrements a labeled child", async t3 => { + const g = labeled(); + g.labels("x").dec(); + g.labels("x").dec(2); + t3.equal(g.labels("x").get(), -3); + }); + }); + + t1.test("set()", async t2 => { + t2.test("sets the value", async t3 => { + const g = gauge(); + g.set(7); + t3.equal(g.get(), 7); + }); + t2.test("sets a labeled child", async t3 => { + const g = labeled(); + g.labels("x").set(7); + g.labels("y").set(8); + t3.strictSame(g._values, new Map([['a="x"', 7], ['a="y"', 8]])); + }); + }); + + t1.test("setToCurrentTime()", async t2 => { + t2.test("sets the value to the unix time in seconds", async t3 => { + t3.capture(Date, "now", () => 1_700_000_123_456); + const g = gauge(); + g.setToCurrentTime(); + t3.equal(g.get(), 1_700_000_123.456); + }); + t2.test("sets a labeled child", async t3 => { + t3.capture(Date, "now", () => 2000); + const g = labeled(); + g.labels("x").setToCurrentTime(); + t3.equal(g.labels("x").get(), 2); + }); + }); + + t1.test("startTimer()", async t2 => { + t2.test("sets the duration in seconds when the returned function is called", async t3 => { + fakeHrtime(t3, 1_000_000_000n, 3_500_000_000n); + const g = gauge(); + const setDuration = g.startTimer(); + t3.equal(g.get(), 0, "unchanged until called"); + setDuration(); + t3.equal(g.get(), 2.5); + }); + t2.test("sets the duration on a labeled child", async t3 => { + fakeHrtime(t3, 0n, 250_000_000n); + const g = labeled(); + g.labels("x").startTimer()(); + t3.equal(g.labels("x").get(), 0.25); + }); + t2.test("measures a real duration", async t3 => { + const g = gauge(); + const setDuration = g.startTimer(); + setDuration(); + t3.ok(g.get() > 0 && g.get() < 1, `got ${g.get()}`); + }); + }); +}); + +t.test("Summary", async t1 => { + const summary = () => new lib.Summary("test", "Help", { register: false }); + const labeled = () => new lib.Summary("test", "Help", { register: false, labels: ["a", "b"] }); + + t1.test("constructor", async t2 => { + t2.test("initialises sum and count to 0", async t3 => { + const s = summary(); + t3.equal(s.sum, 0); + t3.equal(s.count, 0); + t3.equal(s.metric.type, "summary"); + }); + t2.test("rejects unrecognized options", async t3 => { + t3.throws( + () => new lib.Summary("test", "Help", { invalid: 1 } as any), + new Error("Unrecognized option 'invalid'"), + ); + }); + t2.test("has no default value when labeled", async t3 => { + const s = labeled(); + t3.equal(s._sumValues.size, 0); + t3.equal(s._countValues.size, 0); + }); + }); + + t1.test("observe()", async t2 => { + t2.test("adds to sum and count", async t3 => { + const s = summary(); + s.observe(2); + t3.equal(s.sum, 2); + t3.equal(s.count, 1); + s.observe(4); + t3.equal(s.sum, 6); + t3.equal(s.count, 2); + }); + t2.test("observes into a labeled child", async t3 => { + const s = labeled(); + const child = s.labels("1", "2"); + child.observe(3); + child.observe(4); + t3.equal(child.sum, 7); + t3.equal(child.count, 2); + t3.equal(s.labels({ a: "1", b: "2" }), child); + }); + }); + + t1.test("startTimer()", async t2 => { + t2.test("observes the duration each time the returned function is called", async t3 => { + fakeHrtime(t3, 0n, 1_000_000_000n, 3_000_000_000n); + const s = summary(); + const observe = s.startTimer(); + t3.equal(s.count, 0); + observe(); + observe(); + t3.equal(s.count, 2); + t3.equal(s.sum, 4); + }); + t2.test("observes into a labeled child", async t3 => { + fakeHrtime(t3, 0n, 500_000_000n); + const s = labeled(); + s.labels("1", "2").startTimer()(); + t3.equal(s.labels("1", "2").sum, 0.5); + t3.equal(s.labels("1", "2").count, 1); + }); + }); + + t1.test("labels()", async t2 => { + t2.test("initialises sum and count for the label set", async t3 => { + const s = labeled(); + s.labels({ a: "1", b: "2" }); + s.labels("4", "5"); + const expected = new Map([['a="1",b="2"', 0], ['a="4",b="5"', 0]]); + t3.strictSame(s._sumValues, expected); + t3.strictSame(s._countValues, expected); + }); + }); + + t1.test("collect()", async t2 => { + t2.test("yields _sum and _count samples after the callback", async t3 => { + const s = new lib.Summary("test", "Help", { + register: false, + callback: collector => { collector.observe(3); }, + }); + const [result] = await collectAll(s.collect()); + t3.equal(result.metric, s.metric); + t3.strictSame(result.samples, new Map([ + ["_sum", new Map([["", 3]])], + ["_count", new Map([["", 1]])], + ])); + }); + }); + + t1.test("remove()", async t2 => { + t2.test("removes sum and count for the label set", async t3 => { + const s = labeled(); + s.labels("1", "2"); + s.labels("3", "4"); + t3.equal(s.remove("1", "2"), 'a="1",b="2"'); + t3.strictSame([...s._sumValues.keys()], ['a="3",b="4"']); + t3.strictSame([...s._countValues.keys()], ['a="3",b="4"']); + }); + }); + + t1.test("removeAll()", async t2 => { + t2.test("removes label sets matching a partial label set", async t3 => { + const s = labeled(); + s.labels("1", "2"); + s.labels("1", "3"); + s.labels("4", "6"); + s.removeAll({ a: "1" }); + t3.strictSame(s._sumValues, new Map([['a="4",b="6"', 0]])); + t3.strictSame(s._countValues, new Map([['a="4",b="6"', 0]])); + }); + }); + + t1.test("clear()", async t2 => { + t2.test("removes all label sets", async t3 => { + const s = labeled(); + s.labels("1", "2"); + s.labels("4", "6"); + s.clear(); + t3.equal(s._sumValues.size, 0); + t3.equal(s._countValues.size, 0); + }); + t2.test("rejects an unlabeled summary", async t3 => { + t3.throws(() => summary().clear(), new Error("Cannot clear unlabeled metric")); + }); + }); +}); + +t.test("Histogram", async t1 => { + const histogram = () => new lib.Histogram("test", "Help", { register: false, buckets: [1, 2, 3, 4, Infinity] }); + const labeled = () => new lib.Histogram( + "test", "Help", { register: false, buckets: [1, Infinity], labels: ["a", "b"] }, + ); + + t1.test("constructor", async t2 => { + t2.test("initialises buckets, sum and count to 0", async t3 => { + const h = histogram(); + t3.strictSame(h.buckets, new Map([[1, 0], [2, 0], [3, 0], [4, 0], [Infinity, 0]])); + t3.equal(h.sum, 0); + t3.equal(h.count, 0); + t3.equal(h.metric.type, "histogram"); + }); + t2.test("uses the Python client buckets by default", async t3 => { + const h = new lib.Histogram("test", "Help", { register: false }); + t3.strictSame( + h._buckets, + [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10, Infinity], + ); + }); + t2.test("appends an Infinity bucket if missing", async t3 => { + t3.strictSame(new lib.Histogram("test", "Help", { register: false, buckets: [1] })._buckets, [1, Infinity]); + t3.strictSame(new lib.Histogram("test", "Help", { register: false, buckets: [] })._buckets, [Infinity]); + }); + t2.test("does not mutate the buckets option", async t3 => { + const buckets = [1]; + void new lib.Histogram("test", "Help", { register: false, buckets }); + t3.strictSame(buckets, [1]); + }); + t2.test("rejects unrecognized options", async t3 => { + t3.throws( + () => new lib.Histogram("test", "Help", { invalid: 1 } as any), + new Error("Unrecognized option 'invalid'"), + ); + }); + t2.test("rejects le as a label", async t3 => { + t3.throws( + () => new lib.Histogram("test", "Help", { register: false, labels: ["le", "test"] }), + new Error("Reserved label 'le'"), + ); + }); + }); + + t1.test("observe()", async t2 => { + t2.test("increments every bucket with a bound at or above the value", async t3 => { + const h = histogram(); + h.observe(2); + t3.strictSame(h.buckets, new Map([[1, 0], [2, 1], [3, 1], [4, 1], [Infinity, 1]])); + t3.equal(h.sum, 2); + t3.equal(h.count, 1); + h.observe(4); + t3.strictSame(h.buckets, new Map([[1, 0], [2, 1], [3, 1], [4, 2], [Infinity, 2]])); + t3.equal(h.sum, 6); + t3.equal(h.count, 2); + }); + t2.test("counts values above every finite bound in +Inf only", async t3 => { + const h = histogram(); + h.observe(100); + t3.strictSame(h.buckets, new Map([[1, 0], [2, 0], [3, 0], [4, 0], [Infinity, 1]])); + }); + t2.test("observes into a labeled child", async t3 => { + const h = labeled(); + const child = h.labels("1", "2"); + child.observe(0.5); + child.observe(2); + t3.strictSame(child.buckets, new Map([[1, 1], [Infinity, 2]])); + t3.equal(child.sum, 2.5); + t3.equal(child.count, 2); + }); + }); + + t1.test("startTimer()", async t2 => { + t2.test("observes the duration each time the returned function is called", async t3 => { + fakeHrtime(t3, 0n, 1_500_000_000n, 2_500_000_000n); + const h = histogram(); + const observe = h.startTimer(); + t3.equal(h.count, 0); + observe(); + observe(); + t3.equal(h.count, 2); + t3.equal(h.sum, 4); + t3.strictSame(h.buckets, new Map([[1, 0], [2, 1], [3, 2], [4, 2], [Infinity, 2]])); + }); + t2.test("observes into a labeled child", async t3 => { + fakeHrtime(t3, 0n, 500_000_000n); + const h = labeled(); + h.labels("1", "2").startTimer()(); + t3.strictSame(h.labels("1", "2").buckets, new Map([[1, 1], [Infinity, 1]])); + }); + }); + + t1.test("linear()", async t2 => { + t2.test("returns count buckets spaced by width", async t3 => { + t3.strictSame(lib.Histogram.linear(1, 2, 3), [1, 3, 5]); + t3.strictSame(lib.Histogram.linear(-1, 4, 3), [-1, 3, 7]); + t3.strictSame(lib.Histogram.linear(1, 1, 4), [1, 2, 3, 4]); + t3.strictSame(lib.Histogram.linear(1, 1, 0), []); + }); + }); + + t1.test("exponential()", async t2 => { + t2.test("returns count buckets multiplied by factor", async t3 => { + t3.strictSame(lib.Histogram.exponential(1, 2, 3), [1, 2, 4]); + t3.strictSame(lib.Histogram.exponential(2, 10, 3), [2, 20, 200]); + t3.strictSame(lib.Histogram.exponential(1, 1.5, 4), [1, 1.5, 2.25, 3.375]); + t3.strictSame(lib.Histogram.exponential(1, 2, 0), []); + }); + }); + + t1.test("labels()", async t2 => { + t2.test("initialises buckets, sum and count for the label set", async t3 => { + const h = labeled(); + h.labels({ a: "1", b: "2" }); + t3.strictSame(h._bucketValues, new Map([['a="1",b="2",le="1"', 0], ['a="1",b="2",le="+Inf"', 0]])); + t3.strictSame(h._sumValues, new Map([['a="1",b="2"', 0]])); + t3.strictSame(h._countValues, new Map([['a="1",b="2"', 0]])); + }); + t2.test("returns the same child for the same labels", async t3 => { + const h = labeled(); + const child = h.labels("1", "2"); + t3.equal(h.labels({ a: "1", b: "2" }), child); + }); + }); + + t1.test("collect()", async t2 => { + t2.test("yields _bucket, _sum and _count samples after the callback", async t3 => { + const h = new lib.Histogram("test", "Help", { + register: false, + buckets: [1], + callback: collector => { collector.observe(0.5); }, + }); + const [result] = await collectAll(h.collect()); + t3.strictSame(result.samples, new Map([ + ["_bucket", new Map([['le="1"', 1], ['le="+Inf"', 1]])], + ["_sum", new Map([["", 0.5]])], + ["_count", new Map([["", 1]])], + ])); + }); + }); + + t1.test("remove()", async t2 => { + t2.test("removes buckets, sum and count for the label set", async t3 => { + const h = labeled(); + h.labels("1", "2"); + h.labels("3", "4"); + t3.equal(h.remove("1", "2"), 'a="1",b="2"'); + t3.strictSame([...h._bucketValues.keys()], ['a="3",b="4",le="1"', 'a="3",b="4",le="+Inf"']); + t3.strictSame([...h._sumValues.keys()], ['a="3",b="4"']); + t3.strictSame([...h._countValues.keys()], ['a="3",b="4"']); + }); + }); + + t1.test("removeAll()", async t2 => { + t2.test("removes label sets matching a partial label set", async t3 => { + const h = labeled(); + h.labels("1", "2"); + h.labels("1", "3"); + h.labels("4", "6"); + h.removeAll({ a: "1" }); + t3.strictSame(h._bucketValues, new Map([['a="4",b="6",le="1"', 0], ['a="4",b="6",le="+Inf"', 0]])); + t3.strictSame(h._sumValues, new Map([['a="4",b="6"', 0]])); + t3.strictSame(h._countValues, new Map([['a="4",b="6"', 0]])); + }); + }); + + t1.test("clear()", async t2 => { + t2.test("removes all label sets", async t3 => { + const h = labeled(); + h.labels("1", "2"); + h.labels("4", "6"); + h.clear(); + t3.equal(h._bucketValues.size, 0); + t3.equal(h._sumValues.size, 0); + t3.equal(h._countValues.size, 0); + }); + }); +}); + +t.test("CollectorRegistry", async t1 => { + t1.test("register()", async t2 => { + t2.test("adds the collector", async t3 => { + const registry = new lib.CollectorRegistry(); + const collector = new lib.Collector(false); + registry.register(collector); + t3.strictSame(registry.collectors, [collector]); + }); + t2.test("rejects a collector that is already registered", async t3 => { + const registry = new lib.CollectorRegistry(); + const collector = new lib.Collector(false); + registry.register(collector); + t3.throws( + () => registry.register(collector), + new Error("Collector is already registered in this registry."), + ); + }); + t2.test("allows the same collector in several registries", async t3 => { + const first = new lib.CollectorRegistry(); + const second = new lib.CollectorRegistry(); + const collector = new lib.Collector(false); + first.register(collector); + second.register(collector); + t3.ok(first.collectors.includes(collector)); + t3.ok(second.collectors.includes(collector)); + }); + }); + + t1.test("unregister()", async t2 => { + t2.test("removes the collector", async t3 => { + const registry = new lib.CollectorRegistry(); + const kept = new lib.Collector(false); + const removed = new lib.Collector(false); + registry.register(kept); + registry.register(removed); + registry.unregister(removed); + t3.strictSame(registry.collectors, [kept]); + }); + t2.test("rejects a collector that is not registered", async t3 => { + const registry = new lib.CollectorRegistry(); + t3.throws( + () => registry.unregister(new lib.Collector(false)), + new Error("Collector is not registered in this registry."), + ); + }); + }); + + t1.test("collect()", async t2 => { + t2.test("yields results from every collector in order", async t3 => { + const registry = new lib.CollectorRegistry(); + const a = new lib.Counter("a", "Help", { register: false }); + const b = new lib.Gauge("b", "Help", { register: false }); + registry.register(a); + registry.register(new lib.Collector(false)); + registry.register(b); + const results = await collectAll(registry.collect()); + t3.strictSame(results.map(r => r.metric), [a.metric, b.metric]); + }); + }); +}); + +t.test("defaultRegistry", async t1 => { + t1.test("contains the default collectors", async t2 => { + for (const [name, collector] of Object.entries(lib.defaultCollectors)) { + t2.ok(lib.defaultRegistry.collectors.includes(collector), `${name} is registered`); + } + }); +}); + +t.test("defaultCollectors", async t1 => { + async function value(collector: lib.Gauge) { + const [result] = await collectAll(collector.collect()); + return result.samples.get("")!.get(""); + } + + t1.test("processCpuSecondsTotal", async t2 => { + t2.test("sums user and system CPU time in seconds", async t3 => { + t3.capture(process, "cpuUsage", () => ({ user: 1_500_000, system: 500_000 })); + t3.equal(await value(lib.defaultCollectors.processCpuSecondsTotal), 2); + }); + }); + t1.test("processResidentMemoryBytes", async t2 => { + t2.test("reports the resident set size", async t3 => { + t3.capture(process, "memoryUsage", () => ({ rss: 1234, heapUsed: 56 }) as any); + t3.equal(await value(lib.defaultCollectors.processResidentMemoryBytes), 1234); + }); + }); + t1.test("processHeapBytes", async t2 => { + t2.test("reports the heap used", async t3 => { + t3.capture(process, "memoryUsage", () => ({ rss: 1234, heapUsed: 56 }) as any); + t3.equal(await value(lib.defaultCollectors.processHeapBytes), 56); + }); + }); + t1.test("processStartTimeSeconds", async t2 => { + t2.test("is the time the module loaded", async t3 => { + const start = await value(lib.defaultCollectors.processStartTimeSeconds); + const now = Date.now() / 1000; + t3.ok(start! <= now && start! > now - 60, `got ${start}, now ${now}`); + }); + }); +}); + +t.test("exposition()", async t1 => { + t1.test("formats unlabeled metrics separated by a blank line", async t2 => { + const exposition = await expose( + new lib.Counter("a", "Help", { register: false }), + new lib.Gauge("b", "Help", { register: false }), + ); + t2.equal(exposition, + "# HELP a Help\n" + + "# TYPE a counter\n" + + "a 0\n" + + "\n" + + "# HELP b Help\n" + + "# TYPE b gauge\n" + + "b 0\n", + ); + }); + t1.test("formats labeled metrics", async t2 => { + const gauge = labeledGauge(); + gauge.labels({ a: "1", b: "2" }); + gauge.labels({ b: "y", a: "x" }).set(3); + t2.equal(await expose(gauge), + "# HELP test Help\n" + + "# TYPE test gauge\n" + + 'test{a="1",b="2"} 0\n' + + 'test{a="x",b="y"} 3\n', + ); + }); + t1.test("formats histograms", async t2 => { + const histogram = new lib.Histogram("test", "Help", { register: false, buckets: [1, 2, 3, 4] }); + for (const value of [2, 2, 5, 2]) { + histogram.observe(value); + } + t2.equal(await expose(histogram), + "# HELP test Help\n" + + "# TYPE test histogram\n" + + 'test_bucket{le="1"} 0\n' + + 'test_bucket{le="2"} 3\n' + + 'test_bucket{le="3"} 3\n' + + 'test_bucket{le="4"} 3\n' + + 'test_bucket{le="+Inf"} 4\n' + + "test_sum 11\n" + + "test_count 4\n", + ); + }); + t1.test("formats labeled histograms", async t2 => { + const histogram = new lib.Histogram("test", "Help", { register: false, buckets: [1], labels: ["l"] }); + for (const [value, label] of [[1, "a"], [2, "b"], [3, "b"]] as const) { + histogram.labels(label).observe(value); + } + histogram.labels("c"); + t2.equal(await expose(histogram), + "# HELP test Help\n" + + "# TYPE test histogram\n" + + 'test_bucket{l="a",le="1"} 1\n' + + 'test_bucket{l="a",le="+Inf"} 1\n' + + 'test_bucket{l="b",le="1"} 0\n' + + 'test_bucket{l="b",le="+Inf"} 2\n' + + 'test_bucket{l="c",le="1"} 0\n' + + 'test_bucket{l="c",le="+Inf"} 0\n' + + 'test_sum{l="a"} 1\n' + + 'test_sum{l="b"} 5\n' + + 'test_sum{l="c"} 0\n' + + 'test_count{l="a"} 1\n' + + 'test_count{l="b"} 2\n' + + 'test_count{l="c"} 0\n', + ); + }); + t1.test("formats summaries", async t2 => { + const summary = new lib.Summary("test", "Help", { register: false }); + summary.observe(1.5); + t2.equal(await expose(summary), + "# HELP test Help\n" + + "# TYPE test summary\n" + + "test_sum 1.5\n" + + "test_count 1\n", + ); + }); + t1.test("formats Infinity and NaN", async t2 => { + const gauge = new lib.Gauge("test", "Help", { register: false, labels: ["n"] }); + gauge.labels({ n: "1" }).set(Infinity); + gauge.labels({ n: "2" }).set(-Infinity); + gauge.labels({ n: "3" }).set(NaN); + t2.equal(await expose(gauge), + "# HELP test Help\n" + + "# TYPE test gauge\n" + + 'test{n="1"} +Inf\n' + + 'test{n="2"} -Inf\n' + + 'test{n="3"} NaN\n', + ); + }); + t1.test("escapes help text and label values", async t2 => { + const gauge = new lib.Gauge("test", 'a\\b\nc "d"', { register: false, labels: ["l"] }); + gauge.labels('x\\y"z\nw'); + t2.equal(await expose(gauge), + '# HELP test a\\\\b\\nc "d"\n' + + "# TYPE test gauge\n" + + 'test{l="x\\\\y\\"z\\nw"} 0\n', + ); + }); + t1.test("formats nothing for no results", async t2 => { + t2.equal(await lib.exposition([]), ""); + }); + t1.test("accepts a synchronous iterable of results", async t2 => { + const counter = new lib.Counter("a", "Help", { register: false }); + const results = await collectAll(counter.collect()); + t2.equal(await lib.exposition(results), "# HELP a Help\n# TYPE a counter\na 0\n"); + }); + t1.test("collects the default registry by default", async t2 => { + const gauge = new lib.Gauge("exposition_default_test", "Help"); + t2.teardown(() => lib.defaultRegistry.unregister(gauge)); + const text = await lib.exposition(); + t2.match(text, /^# TYPE process_cpu_seconds_total gauge$/m); + t2.match(text, /^exposition_default_test 0$/m); + }); +}); + +t.test("expositionContentType", async t1 => { + t1.equal(lib.expositionContentType, "text/plain; version=0.0.4"); +}); + +t.test("serializeResult()", async t1 => { + const validate = lib.compile(lib.CollectorResultSerialized as any); + const result = (labels: string[] = [], samples: [string, [string, number][]][] = [["", [["", 2]]]]): Result => ({ + metric: new lib.Metric("gauge", "name", "Help", labels), + samples: new Map(samples.map(([suffix, values]) => [suffix, new Map(values)])), + }); + + t1.test("converts collected results into plain objects", async t2 => { + const registry = new lib.CollectorRegistry(); + const counter = new lib.Counter("a_counter", "Counter", { register: false }); + const gauge = new lib.Gauge("a_gauge", "Gauge", { register: false, labels: ["a", "b"] }); + registry.register(counter); + registry.register(gauge); + counter.inc(3); + gauge.labels("1", "2").set(1); + gauge.labels("3", "4").set(5); + + const serialized = (await collectAll(registry.collect())).map(r => lib.serializeResult(r)); + t2.strictSame(serialized, [ + { + metric: { type: "counter", name: "a_counter", help: "Counter", labels: [] }, + samples: [["", [["", 3]]]], + }, + { + metric: { type: "gauge", name: "a_gauge", help: "Gauge", labels: ["a", "b"] }, + samples: [["", [['a="1",b="2"', 1], ['a="3",b="4"', 5]]]], + }, + ]); + for (const item of serialized) { + t2.ok(validate(item), "matches CollectorResultSerialized", { errors: validate.errors }); + } + }); + t1.test("adds labels to unlabeled and labeled samples", async t2 => { + t2.strictSame(lib.serializeResult(result([], [["_sum", [["", 2]]]]), { addLabels: { c: "8" } }), { + metric: { type: "gauge", name: "name", help: "Help", labels: ["c"] }, + samples: [["_sum", [['c="8"', 2]]]], + }); + t2.strictSame(lib.serializeResult(result(["a"], [["", [['a="4"', 3]]]]), { addLabels: { c: "8", d: '"' } }), { + metric: { type: "gauge", name: "name", help: "Help", labels: ["a", "c", "d"] }, + samples: [["", [['a="4",c="8",d="\\""', 3]]]], + }); + }); + t1.test("does not modify the result when adding labels", async t2 => { + const original = result(["a"], [["", [['a="4"', 3]]]]); + lib.serializeResult(original, { addLabels: { c: "8" } }); + t2.strictSame(original.samples, new Map([["", new Map([['a="4"', 3]])]])); + t2.strictSame(original.metric.labels, ["a"]); + }); + t1.test("leaves labeled samples unchanged for an empty addLabels", { todo: emptyAddLabelsTodo }, async t2 => { + t2.strictSame(lib.serializeResult(result(["a"], [["", [['a="4"', 3]]]]), { addLabels: {} }).samples, [ + ["", [['a="4"', 3]]], + ]); + }); + t1.test("overrides name and help", async t2 => { + t2.strictSame(lib.serializeResult(result(), { metricName: "new" }).metric.name, "new"); + t2.strictSame(lib.serializeResult(result(), { metricHelp: "other" }).metric.help, "other"); + }); + t1.test("rejects unrecognized options", async t2 => { + t2.throws( + () => lib.serializeResult(result(), { invalid: true } as any), + new Error("Unrecognized option 'invalid'"), + ); + }); +}); + +t.test("deserializeResult()", async t1 => { + t1.test("converts a plain object into a result", async t2 => { + const deserialized = lib.deserializeResult({ + metric: { type: "gauge", name: "name", help: "Help", labels: ["a", "b"] }, + samples: [["", [['a="1",b="2"', 1], ['a="3",b="4"', 5]]]], + }); + t2.ok(deserialized.metric instanceof lib.Metric); + t2.strictSame(deserialized, { + metric: new lib.Metric("gauge", "name", "Help", ["a", "b"]), + samples: new Map([["", new Map([['a="1",b="2"', 1], ['a="3",b="4"', 5]])]]), + }); + }); + t1.test("rejects an invalid metric name", async t2 => { + t2.throws(() => lib.deserializeResult({ + metric: { type: "gauge", name: "0", help: "Help", labels: [] }, + samples: [], + }), new Error("Invalid name '0'")); + }); + t1.test("round trips results through JSON with the same exposition", async t2 => { + const histogram = new lib.Histogram("test", "Help", { register: false, buckets: [1], labels: ["l"] }); + for (const [value, label] of [[1, "a"], [2, "b"], [3, 'b\n"\\']] as const) { + histogram.labels(label).observe(value); + } + const summary = new lib.Summary("s", "Help\nline", { register: false }); + summary.observe(1.5); + const registry = new lib.CollectorRegistry(); + registry.register(histogram); + registry.register(summary); + + const results = await collectAll(registry.collect()); + const json = JSON.parse(JSON.stringify(results.map(r => lib.serializeResult(r)))); + const deserialized = json.map((r: any) => lib.deserializeResult(r)); + t2.strictSame(deserialized, results); + t2.equal(await lib.exposition(deserialized), await lib.exposition(results)); + }); + t1.test("round trips non-finite values through JSON", { todo: nonFiniteTodo }, async t2 => { + const gauge = new lib.Gauge("test", "Help", { register: false, labels: ["n"] }); + gauge.labels("1").set(Infinity); + gauge.labels("2").set(NaN); + const results = await collectAll(gauge.collect()); + const json = JSON.parse(JSON.stringify(results.map(r => lib.serializeResult(r)))); + t2.equal(await lib.exposition(json.map((r: any) => lib.deserializeResult(r))), await lib.exposition(results)); + }); +}); diff --git a/tests/lib/subscriptions.test.ts b/tests/lib/subscriptions.test.ts new file mode 100644 index 00000000..b7885cbd --- /dev/null +++ b/tests/lib/subscriptions.test.ts @@ -0,0 +1,1390 @@ +import t from "tap"; +import * as lib from "@clusterio/lib"; +import { TestWebSocketConnector, addr, linkPair, recordedLink, settle } from "../shared/link.ts"; + +const controller = addr("controller"); +const control1 = addr({ controlId: 1 }); +const control2 = addr({ controlId: 2 }); + +type Item = { id: number, updatedAtMs: number, isDeleted: boolean, [key: string]: unknown }; + +// Test events, registered once here and never changed after. +class TestEvent { + declare ["constructor"]: typeof TestEvent; + static type = "event" as const; + static src = "controller" as const; + static dst = "control" as const; + filters?: string | string[]; + constructor(filters?: string | string[]) { + if (filters !== undefined) { + this.filters = filters; + } + } +} +class StringPermissionEvent { + declare ["constructor"]: typeof StringPermissionEvent; + static type = "event" as const; + static src = "controller" as const; + static dst = "control" as const; + static permission = "StringPermission"; +} +class FunctionPermissionEvent { + declare ["constructor"]: typeof FunctionPermissionEvent; + static type = "event" as const; + static src = "controller" as const; + static dst = "control" as const; + static permission(user: lib.IUser, _message: lib.MessageRequest) { + user.checkPermission("FunctionPermission" as any); + } +} +class ValueEvent { + declare ["constructor"]: typeof ValueEvent; + static type = "event" as const; + static src = "controller" as const; + static dst = "control" as const; + value: Item; + constructor(value: Item) { this.value = value; } + static jsonSchema = { type: "object", properties: { value: { type: "object" } }, required: ["value"] }; + static fromJSON(json: any) { return new this(json.value); } +} +class MapEvent { + declare ["constructor"]: typeof MapEvent; + static type = "event" as const; + static src = "controller" as const; + static dst = "control" as const; + updates: Item[]; + constructor(updates: Item[]) { this.updates = updates; } + static jsonSchema = { type: "object", properties: { updates: { type: "array" } }, required: ["updates"] }; + static fromJSON(json: any) { return new this(json.updates); } +} +class UnregisteredEvent { + declare ["constructor"]: typeof UnregisteredEvent; + static type = "event" as const; + static src = "controller" as const; + static dst = "control" as const; +} +for (const Event of [TestEvent, StringPermissionEvent, FunctionPermissionEvent, ValueEvent, MapEvent]) { + lib.Link.register(Event as any); +} + +const filters = (shorthand?: string | string[]) => lib.SubscriptionFilters.fromShorthand(shorthand); +const all = () => lib.SubscriptionFilters.all(); +const empty = () => lib.SubscriptionFilters.empty(); +const item = (id: number, updatedAtMs: number, extra: object = {}): Item => ({ + id, updatedAtMs, isDeleted: false, ...extra, +}); + +/** User denying one permission and recording the checks */ +function testUser(denied?: string) { + const checked: string[] = []; + const user = { + checkPermission(permission: string) { + checked.push(permission); + if (permission === denied) { + throw new lib.PermissionError("Permission denied"); + } + }, + } as unknown as lib.IUser; + return { user, checked }; +} + +t.test("SubscriptionFilters", async t1 => { + t1.test("SubscriptionFilters.all()", async t2 => { + t2.test("accepts everything", async t3 => { + const f = lib.SubscriptionFilters.all(); + t3.equal(f.isAll(), true); + t3.equal(f.isEmpty(), false); + t3.equal(f.accepts("foo"), true); + }); + }); + + t1.test("SubscriptionFilters.empty()", async t2 => { + t2.test("accepts nothing", async t3 => { + const f = lib.SubscriptionFilters.empty(); + t3.equal(f.isAll(), false); + t3.equal(f.isEmpty(), true); + t3.equal(f.accepts("foo"), false); + }); + }); + + t1.test("SubscriptionFilters.fromShorthand()", async t2 => { + t2.test("treats undefined as all", async t3 => { + t3.equal(filters(undefined).isAll(), true); + }); + + t2.test("accepts a string", async t3 => { + const f = filters("foo"); + t3.equal(f.isAll(), false); + t3.strictSame(f.toJSON(), ["foo"]); + }); + + t2.test("accepts an array", async t3 => { + t3.strictSame(filters(["foo", "bar"]).toJSON(), ["foo", "bar"]); + }); + + t2.test("treats an empty array as empty", async t3 => { + t3.equal(filters([]).isEmpty(), true); + }); + }); + + t1.test("SubscriptionFilters.fromJSON()", async t2 => { + t2.test("round trips filters", async t3 => { + const f = lib.SubscriptionFilters.fromJSON(JSON.parse(JSON.stringify(filters(["foo", "bar"])))); + t3.strictSame(f.toJSON(), ["foo", "bar"]); + }); + + t2.test("does not preserve all", async t3 => { + // SubscriptionRequest leaves the filters out to mean all + const f = lib.SubscriptionFilters.fromJSON(JSON.parse(JSON.stringify(lib.SubscriptionFilters.all()))); + t3.equal(f.isAll(), false); + t3.equal(f.isEmpty(), true); + }); + }); + + t1.test("toString()", async t2 => { + t2.test("describes the filter", async t3 => { + t3.equal(lib.SubscriptionFilters.all().toString(), "[SubscriptionFilters All]"); + t3.equal(lib.SubscriptionFilters.empty().toString(), "[SubscriptionFilters Empty]"); + t3.equal(filters("foo").toString(), "[SubscriptionFilters Set<1>]"); + t3.equal(filters(["foo", "bar"]).toString(), "[SubscriptionFilters Set<2>]"); + }); + }); + + t1.test("accepts()", async t2 => { + t2.test("matches exact values", async t3 => { + const f = filters("foo"); + t3.equal(f.accepts("foo"), true); + t3.equal(f.accepts("fo"), false); + }); + }); + + t1.test("extends()", async t2 => { + const cases: [string, () => lib.SubscriptionFilters, () => lib.SubscriptionFilters, boolean][] = [ + ["all extends a set", all, () => filters("foo"), true], + ["all extends all", all, all, true], + ["a superset extends a set", () => filters(["foo", "bar"]), () => filters("foo"), true], + ["a set extends empty", () => filters("foo"), empty, true], + ["a subset does not extend a set", () => filters("foo"), () => filters(["foo", "bar"]), false], + ["a set does not extend all", () => filters("foo"), all, false], + ]; + for (const [name, a, b, expected] of cases) { + t2.test(name, async t3 => { + t3.equal(a().extends(b()), expected); + }); + } + }); + + t1.test("intersects()", async t2 => { + const cases: [string, () => lib.SubscriptionFilters, () => lib.SubscriptionFilters, boolean][] = [ + ["sets sharing a value", () => filters("foo"), () => filters(["foo", "bar"]), true], + ["disjoint sets", () => filters("foo"), () => filters("bar"), false], + ["all and a set", all, () => filters("foo"), true], + ["all and all", all, all, true], + ["all and empty", all, empty, false], + ]; + for (const [name, a, b, expected] of cases) { + t2.test(`is ${expected} for ${name} either way round`, async t3 => { + t3.equal(a().intersects(b()), expected); + t3.equal(b().intersects(a()), expected); + }); + } + }); + + t1.test("union()", async t2 => { + t2.test("merges sets", async t3 => { + const f = filters("foo"); + f.union(filters("bar")); + t3.strictSame(f.toJSON(), ["foo", "bar"]); + }); + + t2.test("becomes all with all", async t3 => { + const f = filters("foo"); + f.union(lib.SubscriptionFilters.all()); + t3.equal(f.isAll(), true); + t3.strictSame(f.toJSON(), []); + }); + + t2.test("stays all", async t3 => { + const f = lib.SubscriptionFilters.all(); + f.union(filters("foo")); + t3.equal(f.isAll(), true); + t3.strictSame(f.toJSON(), []); + }); + }); + + t1.test("subtract()", async t2 => { + t2.test("removes values", async t3 => { + const f = filters(["foo", "bar"]); + f.subtract(filters(["foo", "baz"])); + t3.strictSame(f.toJSON(), ["bar"]); + }); + + t2.test("becomes empty when subtracting all", async t3 => { + const f = filters("foo"); + f.subtract(lib.SubscriptionFilters.all()); + t3.equal(f.isEmpty(), true); + const g = lib.SubscriptionFilters.all(); + g.subtract(lib.SubscriptionFilters.all()); + t3.equal(g.isEmpty(), true); + }); + + t2.test("leaves all unchanged when subtracting a set", async t3 => { + const f = lib.SubscriptionFilters.all(); + f.subtract(filters("foo")); + t3.equal(f.isAll(), true); + }); + }); +}); + +t.test("SubscriptionRequest", async t1 => { + t1.test("constructor()", async t2 => { + t2.test("maps the deprecated boolean action", async t3 => { + t3.equal(new lib.SubscriptionRequest("TestEvent", true, 0).action, "subscribe"); + t3.equal(new lib.SubscriptionRequest("TestEvent", false, 0).action, "unsubscribe"); + }); + + t2.test("converts shorthand filters", async t3 => { + t3.strictSame(new lib.SubscriptionRequest("TestEvent", true, 0, "foo").filters.toJSON(), ["foo"]); + t3.strictSame(new lib.SubscriptionRequest("TestEvent", true, 0, ["a", "b"]).filters.toJSON(), ["a", "b"]); + t3.equal(new lib.SubscriptionRequest("TestEvent", true, 0).filters.isAll(), true); + }); + + t2.test("uses SubscriptionFilters as given", async t3 => { + const f = filters("foo"); + t3.equal(new lib.SubscriptionRequest("TestEvent", "replace", 0, f).filters, f); + }); + + t2.test("defaults lastRequestTimeMs to 0", async t3 => { + t3.equal(new lib.SubscriptionRequest("TestEvent", "subscribe", undefined).lastRequestTimeMs, 0); + }); + + t2.test("throws for unregistered events", async t3 => { + t3.throws( + () => new lib.SubscriptionRequest("UnregisteredEvent", "subscribe", 0), + { message: "Unregistered Event class UnregisteredEvent" }, + ); + }); + }); + + t1.test("toJSON()", async t2 => { + t2.test("leaves out filters accepting all", async t3 => { + t3.strictSame( + new lib.SubscriptionRequest("TestEvent", "subscribe", 5).toJSON(), + ["TestEvent", "subscribe", 5], + ); + }); + + t2.test("includes other filters", async t3 => { + t3.strictSame( + new lib.SubscriptionRequest("TestEvent", "replace", 5, lib.SubscriptionFilters.empty()).toJSON(), + ["TestEvent", "replace", 5, []], + ); + }); + }); + + t1.test("fromJSON()", async t2 => { + t2.test("round trips every action and filter kind", async t3 => { + for (const action of ["subscribe", "unsubscribe", "replace"] as const) { + for (const f of [lib.SubscriptionFilters.all(), lib.SubscriptionFilters.empty(), filters(["a", "b"])]) { + const request = new lib.SubscriptionRequest("TestEvent", action, 7, f); + const copy = lib.SubscriptionRequest.fromJSON(JSON.parse(JSON.stringify(request))); + t3.strictSame(copy, request, `${action} ${f}`); + } + } + }); + + t2.test("throws for unregistered events", async t3 => { + t3.throws( + () => lib.SubscriptionRequest.fromJSON(["UnregisteredEvent", "subscribe", 0]), + { message: "Unregistered Event class UnregisteredEvent" }, + ); + }); + }); + + t1.test("SubscriptionRequest.permission()", async t2 => { + function check(data: unknown, denied?: string) { + const { user, checked } = testUser(denied); + const message = new lib.MessageRequest(1, control1, controller, "SubscriptionRequest", data); + lib.SubscriptionRequest.permission(user, message); + return checked; + } + + t2.test("checks a string permission of the event", async t3 => { + t3.strictSame(check(["StringPermissionEvent", "subscribe", 0]), ["StringPermission"]); + t3.throws( + () => check(["StringPermissionEvent", "subscribe", 0], "StringPermission"), + { constructor: lib.PermissionError, message: "Permission denied" }, + ); + }); + + t2.test("calls a function permission of the event", async t3 => { + t3.strictSame(check(["FunctionPermissionEvent", "subscribe", 0]), ["FunctionPermission"]); + }); + + t2.test("checks nothing for events without a permission", async t3 => { + t3.strictSame(check(["TestEvent", "subscribe", 0]), []); + }); + + t2.test("checks nothing for unknown events or missing data", async t3 => { + t3.strictSame(check(["UnregisteredEvent", "subscribe", 0]), []); + t3.strictSame(check(undefined), []); + t3.strictSame(check(null), []); + }); + }); +}); + +t.test("SubscriptionController", async t1 => { + // Controller with two controls connected, each records the events it receives. + function setup(maxFilters?: number) { + const subscriptions = new lib.SubscriptionController(maxFilters); + const controls = [control1, control2].map(address => { + const { link, connector, sent } = recordedLink(controller, address); + const events = () => sent.filter(message => message.type === "event").map(message => message.name); + return { link, connector, address, sent, events }; + }); + const request = (index: number, ...args: [string, any, number?, any?]) => subscriptions.handleRequest( + controls[index].link, new lib.SubscriptionRequest(...args), controls[index].address, controller, + ); + return { subscriptions, controls, request }; + } + + t1.test("handle()", async t2 => { + t2.test("throws for unregistered events", async t3 => { + const { subscriptions } = setup(); + t3.throws( + () => subscriptions.handle(UnregisteredEvent), + { message: "Unregistered Event class UnregisteredEvent" }, + ); + }); + + t2.test("throws for events already handled", async t3 => { + const { subscriptions } = setup(); + subscriptions.handle(TestEvent); + t3.throws(() => subscriptions.handle(TestEvent), { message: "Event TestEvent is already registered" }); + }); + }); + + t1.test("broadcast()", async t2 => { + t2.test("throws for unregistered events", async t3 => { + const { subscriptions } = setup(); + t3.throws( + () => subscriptions.broadcast(new UnregisteredEvent() as any), + { message: "Unregistered Event class UnregisteredEvent" }, + ); + }); + + t2.test("throws for events not handled", async t3 => { + const { subscriptions } = setup(); + t3.throws( + () => subscriptions.broadcast(new TestEvent() as any), + { message: "Event TestEvent is not a registered as subscribable" }, + ); + }); + + t2.test("sends the event to every subscriber", async t3 => { + const { subscriptions, controls, request } = setup(); + subscriptions.handle(TestEvent); + await request(0, "TestEvent", "subscribe", 0); + await request(1, "TestEvent", "subscribe", 0); + subscriptions.broadcast(new TestEvent() as any); + t3.strictSame(controls.map(c => c.events()), [["TestEvent"], ["TestEvent"]]); + t3.strictSame(controls[0].sent[0].dst, control1); + }); + + t2.test("sends only to subscribers whose filters match", async t3 => { + const { subscriptions, controls, request } = setup(); + subscriptions.handle(TestEvent); + await request(0, "TestEvent", "replace", 0, "foo"); + await request(1, "TestEvent", "replace", 0, "bar"); + subscriptions.broadcast(new TestEvent() as any, "foo"); + t3.strictSame(controls.map(c => c.events()), [["TestEvent"], []]); + subscriptions.broadcast(new TestEvent() as any, ["bar", "baz"]); + t3.strictSame(controls.map(c => c.events()), [["TestEvent"], ["TestEvent"]]); + }); + + t2.test("sends filtered events to subscribers without filters", async t3 => { + const { subscriptions, controls, request } = setup(); + subscriptions.handle(TestEvent); + await request(0, "TestEvent", "subscribe", 0); + subscriptions.broadcast(new TestEvent() as any, "foo"); + t3.strictSame(controls[0].events(), ["TestEvent"]); + }); + + t2.test("uses the filters property of the event", async t3 => { + const { subscriptions, controls, request } = setup(); + subscriptions.handle(TestEvent); + await request(0, "TestEvent", "replace", 0, "foo"); + await request(1, "TestEvent", "replace", 0, "bar"); + subscriptions.broadcast(new TestEvent("foo") as any); + t3.strictSame(controls.map(c => c.events()), [["TestEvent"], []]); + }); + + t2.test("prefers the filters argument over the property", async t3 => { + const { subscriptions, controls, request } = setup(); + subscriptions.handle(TestEvent); + await request(0, "TestEvent", "replace", 0, "foo"); + subscriptions.broadcast(new TestEvent("foo") as any, "bar"); + t3.strictSame(controls[0].events(), []); + }); + + t2.test("drops subscribers whose connector is closing", async t3 => { + const subscriptions = new lib.SubscriptionController(); + subscriptions.handle(TestEvent); + const closed = new lib.Link(new TestWebSocketConnector(controller, control1)); + const request = new lib.SubscriptionRequest("TestEvent", "subscribe", 0); + await subscriptions.handleRequest(closed, request, control1, controller); + t3.equal(subscriptions._events.get("TestEvent")!.subscriptions.size, 1); + subscriptions.broadcast(new TestEvent() as any); + t3.equal(subscriptions._events.get("TestEvent")!.subscriptions.size, 0); + }); + }); + + t1.test("unsubscribeLink()", async t2 => { + t2.test("removes every subscription of the link", async t3 => { + const { subscriptions, controls, request } = setup(); + subscriptions.handle(TestEvent); + subscriptions.handle(MapEvent); + await request(0, "TestEvent", "subscribe", 0); + await request(0, "MapEvent", "subscribe", 0); + await request(1, "TestEvent", "subscribe", 0); + subscriptions.unsubscribeLink(controls[0].link); + subscriptions.broadcast(new TestEvent() as any); + subscriptions.broadcast(new MapEvent([]) as any); + t3.strictSame(controls.map(c => c.events()), [[], ["TestEvent"]]); + }); + }); + + t1.test("unsubscribeAddress()", async t2 => { + t2.test("removes every subscription of the address", async t3 => { + const { subscriptions, controls, request } = setup(); + subscriptions.handle(TestEvent); + await request(0, "TestEvent", "subscribe", 0); + await request(1, "TestEvent", "subscribe", 0); + subscriptions.unsubscribeAddress(new lib.Address(lib.Address.control, 1, 99)); + subscriptions.broadcast(new TestEvent() as any); + t3.strictSame(controls.map(c => c.events()), [[], ["TestEvent"]]); + }); + }); + + t1.test("checkLinkPermissions()", async t2 => { + async function permissionSetup() { + const setupResult = setup(); + const { subscriptions, request } = setupResult; + subscriptions.handle(TestEvent); + subscriptions.handle(StringPermissionEvent); + subscriptions.handle(FunctionPermissionEvent); + for (const index of [0, 1]) { + for (const name of ["TestEvent", "StringPermissionEvent", "FunctionPermissionEvent"]) { + await request(index, name, "subscribe", 0); + } + } + const broadcastAll = () => { + for (const Event of [TestEvent, StringPermissionEvent, FunctionPermissionEvent]) { + subscriptions.broadcast(new Event() as any); + } + }; + return { ...setupResult, broadcastAll }; + } + + t2.test("removes subscriptions with a string permission the user lost", async t3 => { + const { subscriptions, controls, broadcastAll } = await permissionSetup(); + subscriptions.checkLinkPermissions(controls[0].link, testUser("StringPermission").user); + broadcastAll(); + t3.strictSame(controls[0].events(), ["TestEvent", "FunctionPermissionEvent"]); + t3.equal(controls[1].events().length, 3, "other links keep their subscriptions"); + }); + + t2.test("removes subscriptions with a function permission the user lost", async t3 => { + const { subscriptions, controls, broadcastAll } = await permissionSetup(); + subscriptions.checkLinkPermissions(controls[0].link, testUser("FunctionPermission").user); + broadcastAll(); + t3.strictSame(controls[0].events(), ["TestEvent", "StringPermissionEvent"]); + }); + + t2.test("keeps subscriptions the user has permission for", async t3 => { + const { subscriptions, controls, broadcastAll } = await permissionSetup(); + const { user, checked } = testUser(); + subscriptions.checkLinkPermissions(controls[0].link, user); + broadcastAll(); + t3.equal(controls[0].events().length, 3); + t3.strictSame(checked, ["StringPermission", "FunctionPermission"]); + }); + }); + + t1.test("handleRequest()", async t2 => { + t2.test("rejects unregistered events", async t3 => { + const { subscriptions, controls } = setup(); + const request = new lib.SubscriptionRequest("TestEvent", "subscribe", 0); + request.eventName = "UnregisteredEvent"; + await t3.rejects( + subscriptions.handleRequest(controls[0].link, request, control1, controller), + { message: "Event UnregisteredEvent is not a registered event" }, + ); + }); + + t2.test("rejects events not handled", async t3 => { + const { request } = setup(); + await t3.rejects( + request(0, "TestEvent", "subscribe", 0), + { message: "Event TestEvent is not a registered as subscribable" }, + ); + }); + + t2.test("rejects unknown actions", async t3 => { + const { subscriptions, request } = setup(); + subscriptions.handle(TestEvent); + await t3.rejects(request(0, "TestEvent", "bad" as any, 0), { message: "unreachable case: bad" }); + }); + + t2.test("resolves to whether a replay was sent", async t3 => { + const { subscriptions, controls, request } = setup(); + subscriptions.handle(TestEvent, async () => new TestEvent() as any); + subscriptions.handle(MapEvent, async () => null); + subscriptions.handle(StringPermissionEvent); + t3.equal(await request(0, "TestEvent", "subscribe", 0), true); + t3.equal(await request(0, "MapEvent", "subscribe", 0), false); + t3.equal(await request(0, "StringPermissionEvent", "subscribe", 0), false); + t3.strictSame(controls[0].events(), ["TestEvent"]); + }); + + t2.test("passes the request to the update handler", async t3 => { + const { subscriptions, request } = setup(); + const calls: unknown[] = []; + subscriptions.handle(TestEvent, async (req, src, dst) => { + calls.push([req.toJSON(), src, dst]); + return null; + }); + await request(0, "TestEvent", "replace", 12, "foo"); + t3.strictSame(calls, [[["TestEvent", "replace", 12, ["foo"]], control1, controller]]); + }); + + t2.test("stores the subscriber without the request id", async t3 => { + const { subscriptions, controls } = setup(); + subscriptions.handle(TestEvent, async () => new TestEvent() as any); + const src = new lib.Address(lib.Address.control, 1, 213); + for (const action of ["subscribe", "replace"] as const) { + const request = new lib.SubscriptionRequest("TestEvent", action, 0, filters("a")); + await subscriptions.handleRequest(controls[0].link, request, src, controller); + } + subscriptions.broadcast(new TestEvent() as any, "a"); + t3.strictSame(controls[0].sent.map(message => message.dst), [control1, control1, control1]); + }); + + t2.test("subscribe", async t3 => { + t3.test("unions filters of an existing subscriber", async t4 => { + const { subscriptions, controls, request } = setup(); + subscriptions.handle(TestEvent); + await request(0, "TestEvent", "subscribe", 0, "foo"); + await request(0, "TestEvent", "subscribe", 0, "bar"); + for (const f of ["foo", "bar", "baz"]) { + subscriptions.broadcast(new TestEvent(f) as any); + } + t4.equal(controls[0].events().length, 2); + }); + + t3.test("unions with all when no filters are given", async t4 => { + const { subscriptions, controls, request } = setup(); + subscriptions.handle(TestEvent); + await request(0, "TestEvent", "subscribe", 0, "foo"); + await request(0, "TestEvent", "subscribe", 0); + subscriptions.broadcast(new TestEvent("baz") as any); + t4.equal(controls[0].events().length, 1); + }); + + t3.test("rejects going over the filter limit", async t4 => { + const { subscriptions, controls, request } = setup(2); + subscriptions.handle(TestEvent); + await t4.rejects( + request(0, "TestEvent", "subscribe", 0, ["a", "b", "c"]), + { constructor: lib.ValidationError, message: "Subscription exceeds the limit of 2 filters" }, + ); + await request(0, "TestEvent", "subscribe", 0, ["a", "b"]); + await t4.rejects( + request(0, "TestEvent", "subscribe", 0, "c"), + { constructor: lib.ValidationError, message: "Subscription exceeds the limit of 2 filters" }, + ); + subscriptions.broadcast(new TestEvent("c") as any); + t4.strictSame(controls[0].events(), []); + }); + + t3.test("does not count filters already held towards the limit", async t4 => { + const { request, subscriptions } = setup(2); + subscriptions.handle(TestEvent); + await request(0, "TestEvent", "subscribe", 0, ["a", "b"]); + t4.equal(await request(0, "TestEvent", "subscribe", 0, ["a", "b"]), false); + }); + + t3.test("does not limit a subscriber to all", async t4 => { + const { request, subscriptions } = setup(2); + subscriptions.handle(TestEvent); + await request(0, "TestEvent", "subscribe", 0); + t4.equal(await request(0, "TestEvent", "subscribe", 0, ["a", "b", "c"]), false); + }); + + t3.test("does not limit filters when the limit is 0", async t4 => { + const { request, subscriptions } = setup(); + subscriptions.handle(TestEvent); + t4.equal(await request(0, "TestEvent", "subscribe", 0, ["a", "b", "c"]), false); + }); + }); + + t2.test("unsubscribe", async t3 => { + t3.test("does nothing without a subscription", async t4 => { + const { subscriptions, request } = setup(); + const calls: unknown[] = []; + subscriptions.handle(TestEvent, async () => { calls.push(1); return null; }); + t4.equal(await request(0, "TestEvent", "unsubscribe", 0), false); + t4.strictSame(calls, [], "update handler is not called"); + }); + + t3.test("removes a subscription to all", async t4 => { + const { subscriptions, controls, request } = setup(); + subscriptions.handle(TestEvent); + await request(0, "TestEvent", "subscribe", 0); + await request(0, "TestEvent", "unsubscribe", 0); + subscriptions.broadcast(new TestEvent() as any); + t4.strictSame(controls[0].events(), []); + }); + + t3.test("subtracts filters", async t4 => { + const { subscriptions, controls, request } = setup(); + subscriptions.handle(TestEvent); + await request(0, "TestEvent", "subscribe", 0, ["foo", "bar"]); + await request(0, "TestEvent", "unsubscribe", 0, "foo"); + subscriptions.broadcast(new TestEvent("foo") as any); + t4.strictSame(controls[0].events(), []); + subscriptions.broadcast(new TestEvent("bar") as any); + t4.strictSame(controls[0].events(), ["TestEvent"]); + }); + + t3.test("removes the subscriber when no filters are left", async t4 => { + const { subscriptions, request } = setup(); + subscriptions.handle(TestEvent); + await request(0, "TestEvent", "subscribe", 0, "foo"); + await request(0, "TestEvent", "unsubscribe", 0, "foo"); + t4.equal(subscriptions._events.get("TestEvent")!.subscriptions.size, 0); + }); + + t3.test("keeps a subscription to all when subtracting a filter", async t4 => { + const { subscriptions, controls, request } = setup(); + subscriptions.handle(TestEvent); + await request(0, "TestEvent", "subscribe", 0); + await request(0, "TestEvent", "unsubscribe", 0, "foo"); + subscriptions.broadcast(new TestEvent("foo") as any); + t4.strictSame(controls[0].events(), ["TestEvent"]); + }); + }); + + t2.test("replace", async t3 => { + t3.test("replaces existing filters", async t4 => { + const { subscriptions, controls, request } = setup(); + subscriptions.handle(TestEvent); + await request(0, "TestEvent", "subscribe", 0, "foo"); + await request(0, "TestEvent", "replace", 0, "bar"); + subscriptions.broadcast(new TestEvent("foo") as any); + t4.strictSame(controls[0].events(), []); + subscriptions.broadcast(new TestEvent("bar") as any); + t4.strictSame(controls[0].events(), ["TestEvent"]); + }); + + t3.test("subscribes when there is no subscriber", async t4 => { + const { subscriptions, controls, request } = setup(); + subscriptions.handle(TestEvent); + await request(0, "TestEvent", "replace", 0, "foo"); + subscriptions.broadcast(new TestEvent("foo") as any); + t4.strictSame(controls[0].events(), ["TestEvent"]); + }); + + t3.test("removes the subscriber when replacing with empty", async t4 => { + const { subscriptions, request } = setup(); + subscriptions.handle(TestEvent); + await request(0, "TestEvent", "subscribe", 0, "foo"); + t4.equal(await request(0, "TestEvent", "replace", 0, []), false); + t4.equal(subscriptions._events.get("TestEvent")!.subscriptions.size, 0); + }); + + t3.test("does nothing when replacing with empty and there is no subscriber", async t4 => { + const { subscriptions, request } = setup(); + const calls: unknown[] = []; + subscriptions.handle(TestEvent, async () => { calls.push(1); return null; }); + t4.equal(await request(0, "TestEvent", "replace", 0, []), false); + t4.strictSame(calls, []); + t4.equal(subscriptions._events.get("TestEvent")!.subscriptions.size, 0); + }); + + t3.test("rejects going over the filter limit", async t4 => { + const { subscriptions, request } = setup(2); + subscriptions.handle(TestEvent); + await request(0, "TestEvent", "subscribe", 0, ["a"]); + await t4.rejects( + request(0, "TestEvent", "replace", 0, ["a", "b", "c"]), + { constructor: lib.ValidationError, message: "Subscription exceeds the limit of 2 filters" }, + ); + t4.strictSame(subscriptions._events.get("TestEvent")!.subscriptions.get("4:1" as any), undefined); + }); + }); + }); +}); + +// Control connected to a controller that serves subscriptions through a SubscriptionController. +function connected() { + const { link: control, peer: controllerLink } = linkPair(control1, controller); + const subscriptions = new lib.SubscriptionController(); + controllerLink.handle(lib.SubscriptionRequest, (request, src, dst) => subscriptions.handleRequest( + controllerLink, request, src, dst, + )); + return { control, controllerLink, subscriptions }; +} + +// Control whose requests are recorded, answered with respond(). +function recorded() { + const { link: control, connector, sent } = recordedLink(control1, controller); + const requests = () => sent.filter(m => m.name === "SubscriptionRequest").map(m => m.data.toJSON()); + const respond = (value: boolean, index = -1) => { + connector.emit("message", new lib.MessageResponse(1, controller, sent.at(index).src, value)); + }; + return { control, connector, sent, requests, respond }; +} + +// Known bug, see the todo tests in getSnapshot() +const snapshotTodo = "snapshot is only remade when lastUpdatedMs changes"; + +const nextTimeout = () => new Promise(resolve => { setTimeout(resolve); }); + +t.test("EventSubscriber", async t1 => { + t1.test("constructor()", async t2 => { + t2.test("handles the event on the control", async t3 => { + const { control } = recorded(); + const subscriber = new lib.EventSubscriber(TestEvent, control); + t3.equal(subscriber.control, control); + t3.equal(control._eventHandlers.has(TestEvent as any), true); + }); + + t2.test("throws for unregistered events", async t3 => { + const { control } = recorded(); + t3.throws( + () => new lib.EventSubscriber(UnregisteredEvent, control), + { message: "Unregistered Event class UnregisteredEvent" }, + ); + }); + + t2.test("shares one connect and close listener per connector", async t3 => { + const { control, connector } = recorded(); + const listeners = () => [connector.listenerCount("connect"), connector.listenerCount("close")]; + const subscribers: lib.EventSubscriber[] = [new lib.EventSubscriber(TestEvent, control)]; + const counts = listeners(); + subscribers.push(new lib.EventSubscriber(MapEvent, control), new lib.EventSubscriber(ValueEvent, control)); + t3.equal(subscribers.length, 3); + t3.strictSame(listeners(), counts); + }); + + t2.test("passes connect and close to every subscriber on the connector only", async t3 => { + const { control, connector } = recorded(); + const other = recorded(); + const received: string[] = []; + const cases = [ + ["a", control, TestEvent], ["b", control, MapEvent], ["c", other.control, TestEvent], + ] as const; + for (const [name, link, Event] of cases) { + const subscriber = new lib.EventSubscriber(Event as any, link); + t3.capture(subscriber, "handleConnectionEvent", event => { received.push(`${name} ${event}`); }); + } + connector.emit("close"); + connector.emit("connect"); + t3.strictSame(received, ["a close", "b close", "a connect", "b connect"]); + }); + + t2.test("listens for account updates when the control reports them", async t3 => { + const { control, requests } = recorded(); + const handlers: (() => void)[] = []; + (control as any).onAccountUpdate = (handler: () => void) => { handlers.push(handler); }; + const subscriber = new lib.EventSubscriber(TestEvent, control); + t3.equal(handlers.length, 1); + subscriber.subscribe(() => {}); + handlers[0](); + await settle(); + t3.strictSame(requests(), [["TestEvent", "subscribe", -1], ["TestEvent", "replace", -1]]); + }); + }); + + t1.test("subscribe()", async t2 => { + t2.test("subscribes to all on the first callback only", async t3 => { + const { control, requests } = recorded(); + const subscriber = new lib.EventSubscriber(TestEvent, control); + subscriber.subscribe(() => {}); + subscriber.subscribe(() => {}); + t3.strictSame(requests(), [["TestEvent", "subscribe", -1]]); + }); + + t2.test("replaces with the filters when the last callback unsubscribes", async t3 => { + const { control, requests } = recorded(); + const subscriber = new lib.EventSubscriber(TestEvent, control); + const unsubscribe1 = subscriber.subscribe(() => {}); + const unsubscribe2 = subscriber.subscribe(() => {}); + unsubscribe1(); + await nextTimeout(); + t3.equal(requests().length, 1); + unsubscribe2(); + await nextTimeout(); + t3.strictSame(requests().at(-1), ["TestEvent", "replace", -1, []]); + }); + + t2.test("delays unsubscribing so a resubscribe in the same tick sends nothing", async t3 => { + const { control, requests } = recorded(); + const subscriber = new lib.EventSubscriber(TestEvent, control); + const unsubscribe = subscriber.subscribe(() => {}); + unsubscribe(); + subscriber.subscribe(() => {}); + await nextTimeout(); + t3.equal(requests().length, 1); + }); + + t2.test("unsubscribes without setImmediate, which browsers lack", async t3 => { + const { control, requests } = recorded(); + const subscriber = new lib.EventSubscriber(TestEvent, control); + const unsubscribe = subscriber.subscribe(() => {}); + const original = globalThis.setImmediate; + delete (globalThis as any).setImmediate; + try { + unsubscribe(); + } finally { + globalThis.setImmediate = original; + } + await nextTimeout(); + t3.equal(requests().length, 2); + }); + + t2.test("ignores repeated calls of the returned function", async t3 => { + const { control, requests } = recorded(); + const subscriber = new lib.EventSubscriber(TestEvent, control); + const unsubscribe = subscriber.subscribe(() => {}); + unsubscribe(); + await nextTimeout(); + unsubscribe(); + await nextTimeout(); + t3.equal(requests().length, 2); + }); + + t2.test("calls every subscribed callback with received events", async t3 => { + const { control, subscriptions } = connected(); + subscriptions.handle(TestEvent); + const subscriber = new lib.EventSubscriber(TestEvent, control); + const calls: unknown[] = []; + const unsubscribe = subscriber.subscribe((event, synced) => { calls.push(["a", event, synced]); }); + subscriber.subscribe((event, synced) => { calls.push(["b", event, synced]); }); + await settle(); + calls.length = 0; + unsubscribe(); + await nextTimeout(); + subscriptions.broadcast(new TestEvent() as any); + t3.strictSame(calls, [["b", new TestEvent(), true]]); + }); + }); + + t1.test("addFilters()", async t2 => { + t2.test("sends subscribe with the added filters", async t3 => { + const { control, requests } = recorded(); + const subscriber = new lib.EventSubscriber(TestEvent, control); + subscriber.addFilters("foo"); + subscriber.addFilters(["bar", "baz"]); + subscriber.addFilters(filters("qux")); + t3.strictSame(requests(), [ + ["TestEvent", "subscribe", -1, ["foo"]], + ["TestEvent", "subscribe", -1, ["bar", "baz"]], + ["TestEvent", "subscribe", -1, ["qux"]], + ]); + }); + + t2.test("receives only events matching the filters", async t3 => { + const { control, subscriptions } = connected(); + subscriptions.handle(TestEvent); + const calls: unknown[] = []; + const handler = (event: TestEvent | null, synced: boolean) => { calls.push([event, synced]); }; + const subscriber = new lib.EventSubscriber(TestEvent, control, handler); + subscriber.addFilters("foo"); + await settle(); + t3.strictSame(calls, [[null, true]], "notified as synced"); + subscriptions.broadcast(new TestEvent("bar") as any); + subscriptions.broadcast(new TestEvent("foo") as any); + t3.equal(calls.length, 2); + }); + }); + + t1.test("removeFilters()", async t2 => { + t2.test("sends unsubscribe with the removed filters", async t3 => { + const { control, requests } = recorded(); + const subscriber = new lib.EventSubscriber(TestEvent, control); + subscriber.addFilters(["foo", "bar"]); + subscriber.removeFilters("foo"); + subscriber.removeFilters(filters(["bar"])); + t3.strictSame(requests().slice(1), [ + ["TestEvent", "unsubscribe", -1, ["foo"]], + ["TestEvent", "unsubscribe", -1, ["bar"]], + ]); + t3.equal(subscriber.hasFilters("bar"), false); + }); + }); + + t1.test("hasFilters()", async t2 => { + t2.test("is true only when every filter was added", async t3 => { + const { control } = recorded(); + const subscriber = new lib.EventSubscriber(TestEvent, control); + subscriber.addFilters(["foo", "bar"]); + t3.equal(subscriber.hasFilters("foo"), true); + t3.equal(subscriber.hasFilters(filters(["foo", "bar"])), true); + t3.equal(subscriber.hasFilters(["foo", "baz"]), false); + }); + }); + + t1.test("clearFilters()", async t2 => { + t2.test("unsubscribes from all without callbacks", async t3 => { + const { control, requests } = recorded(); + const subscriber = new lib.EventSubscriber(TestEvent, control); + subscriber.addFilters("foo"); + subscriber.clearFilters(); + t3.strictSame(requests().at(-1), ["TestEvent", "unsubscribe", -1]); + t3.equal(subscriber.hasFilters("foo"), false); + }); + + t2.test("sends nothing while there are callbacks", async t3 => { + const { control, requests } = recorded(); + const subscriber = new lib.EventSubscriber(TestEvent, control); + subscriber.subscribe(() => {}); + subscriber.addFilters("foo"); + subscriber.clearFilters(); + t3.equal(requests().length, 2); + }); + + t2.test("stops calling the filtered handler", async t3 => { + const { control, subscriptions } = connected(); + subscriptions.handle(TestEvent); + const calls: unknown[] = []; + const subscriber = new lib.EventSubscriber(TestEvent, control, event => { calls.push(event); }); + subscriber.subscribe(() => {}); + subscriber.addFilters("foo"); + await settle(); + calls.length = 0; + subscriber.clearFilters(); + subscriptions.broadcast(new TestEvent("foo") as any); + t3.strictSame(calls, []); + }); + }); + + t1.test("handleConnectionEvent()", async t2 => { + for (const event of ["connect", "resume"] as const) { + t2.test(`resends the subscription on ${event}`, async t3 => { + const { control, requests } = recorded(); + const callbacks = new lib.EventSubscriber(TestEvent, control); + const filtered = new lib.EventSubscriber(MapEvent, control); + callbacks.subscribe(() => {}); + filtered.addFilters("foo"); + callbacks.handleConnectionEvent(event); + filtered.handleConnectionEvent(event); + await settle(); + t3.strictSame( + requests().slice(2), + [["TestEvent", "replace", -1], ["MapEvent", "replace", -1, ["foo"]]], + ); + }); + } + + t2.test("resends on connect from the connector", async t3 => { + const { control, connector, requests } = recorded(); + const subscriber = new lib.EventSubscriber(TestEvent, control); + subscriber.subscribe(() => {}); + connector.emit("connect"); + await settle(); + t3.strictSame(requests().at(-1), ["TestEvent", "replace", -1]); + }); + + for (const event of ["drop", "close"] as const) { + t2.test(`marks the subscriber unsynced on ${event}`, async t3 => { + const { control, subscriptions } = connected(); + subscriptions.handle(TestEvent); + const subscriber = new lib.EventSubscriber(TestEvent, control); + const calls: unknown[] = []; + subscriber.subscribe((e, synced) => { calls.push([e, synced]); }); + await settle(); + t3.equal(subscriber.synced, true); + subscriber.handleConnectionEvent(event); + t3.equal(subscriber.synced, false); + t3.strictSame(calls.at(-1), [null, false]); + subscriber.handleConnectionEvent(event); + t3.equal(calls.length, 2, "notified once"); + }); + } + + t2.test("marks the subscriber unsynced on close from the connector", async t3 => { + const { control, connector } = recorded(); + const subscriber = new lib.EventSubscriber(TestEvent, control); + subscriber.synced = true; + connector.emit("close"); + t3.equal(subscriber.synced, false); + }); + }); + + t1.test("handleAccountEvent()", async t2 => { + t2.test("resends the subscription if subscribed", async t3 => { + const { control, requests } = recorded(); + const callbacks = new lib.EventSubscriber(TestEvent, control); + const filtered = new lib.EventSubscriber(MapEvent, control); + callbacks.subscribe(() => {}); + filtered.addFilters("foo"); + callbacks.handleAccountEvent(); + filtered.handleAccountEvent(); + await settle(); + t3.strictSame(requests().slice(2), [["TestEvent", "replace", -1], ["MapEvent", "replace", -1, ["foo"]]]); + }); + + t2.test("sends nothing if not subscribed", async t3 => { + const { control, sent } = recorded(); + new lib.EventSubscriber(TestEvent, control).handleAccountEvent(); + await settle(); + t3.strictSame(sent, []); + }); + + t2.test("sends once when the account is reported while connecting", async t3 => { + const { control, connector, requests } = recorded(); + const subscriber = new lib.EventSubscriber(TestEvent, control); + subscriber.subscribe(() => {}); + subscriber.handleAccountEvent(); + connector.emit("connect"); + await settle(); + t3.equal(requests().length, 2); + }); + }); + + t1.test("permitted", async t2 => { + t2.test("sends nothing while not permitted", async t3 => { + const { control, connector, sent } = recorded(); + const subscriber = new lib.EventSubscriber(TestEvent, control, undefined, () => false); + subscriber.subscribe(() => {}); + subscriber.addFilters("foo"); + connector.emit("connect"); + subscriber.handleConnectionEvent("resume"); + subscriber.handleAccountEvent(); + await settle(); + t3.strictSame(sent, []); + }); + + t2.test("subscribes when the account becomes permitted", async t3 => { + const { control, requests } = recorded(); + let permitted = false; + const subscriber = new lib.EventSubscriber(TestEvent, control, undefined, () => permitted); + subscriber.subscribe(() => {}); + permitted = true; + subscriber.handleAccountEvent(); + await settle(); + t3.strictSame(requests(), [["TestEvent", "replace", -1]]); + }); + }); + + t1.test("_sendRequest()", async t2 => { + t2.test("sends nothing when the connector is not valid", async t3 => { + const { control, connector, sent } = recorded(); + Object.defineProperty(connector, "valid", { value: false }); + new lib.EventSubscriber(TestEvent, control).subscribe(() => {}); + await settle(); + t3.strictSame(sent, []); + }); + + t2.test("sends the time of the last update", async t3 => { + const { control, requests } = recorded(); + const subscriber = new lib.EventSubscriber(TestEvent, control); + subscriber.lastUpdatedMs = 1234; + subscriber.subscribe(() => {}); + t3.strictSame(requests(), [["TestEvent", "subscribe", 1234]]); + }); + + t2.test("notifies synced when no updates were sent", async t3 => { + const { control, respond } = recorded(); + const subscriber = new lib.EventSubscriber(TestEvent, control); + const calls: unknown[] = []; + subscriber.subscribe((event, synced) => { calls.push([event, synced]); }); + respond(false); + await settle(); + t3.strictSame(calls, [[null, true]]); + t3.equal(subscriber.synced, true); + }); + + t2.test("waits for the event when updates were sent", async t3 => { + const { control, connector, respond } = recorded(); + const subscriber = new lib.EventSubscriber(TestEvent, control); + const calls: unknown[] = []; + subscriber.subscribe((event, synced) => { calls.push([event, synced]); }); + respond(true); + await settle(); + t3.strictSame(calls, []); + t3.equal(subscriber.synced, false); + connector.emit("message", new lib.MessageEvent(2, controller, control1, "TestEvent")); + t3.strictSame(calls, [[new TestEvent(), true]]); + t3.equal(subscriber.synced, true); + }); + + t2.test("logs unexpected errors and stores them", async t3 => { + const errors = t3.capture(lib.logger, "error"); + const { control } = recorded(); + t3.capture(control, "sendTo", async () => { throw new Error("boom"); }); + const subscriber = new lib.EventSubscriber(TestEvent, control); + const calls: unknown[] = []; + subscriber.subscribe((event, synced) => { calls.push([event, synced]); }); + await settle(); + t3.match(errors.args(), [[/^Unexpected error updating TestEvent subscription:\nError: boom/]]); + t3.match(subscriber.error, { message: "boom" }); + t3.strictSame(calls, [[null, false]]); + }); + + t2.test("does not log SessionLost", async t3 => { + const errors = t3.capture(lib.logger, "error"); + const { control, connector } = recorded(); + const subscriber = new lib.EventSubscriber(TestEvent, control); + subscriber.subscribe(() => {}); + connector.emit("close"); + await settle(); + t3.strictSame(errors.args(), []); + t3.type(subscriber.error, lib.SessionLost); + }); + + t2.test("ignores thrown values that are not errors", async t3 => { + t3.capture(lib.logger, "error"); + const { control } = recorded(); + // eslint-disable-next-line prefer-promise-reject-errors + t3.capture(control, "sendTo", () => Promise.reject("not an error")); + const subscriber = new lib.EventSubscriber(TestEvent, control); + subscriber.subscribe(() => {}); + await settle(); + t3.equal(subscriber.error, null); + t3.equal(subscriber.synced, false); + }); + + t2.test("unsyncs on a permission error from the controller", async t3 => { + t3.capture(lib.logger, "error"); + const { control, controllerLink, subscriptions } = connected(); + subscriptions.handle(StringPermissionEvent); + let denied = false; + t3.capture(controllerLink, "validatePermission", (message: any) => { + if (denied) { + // ControlConnection answers denied requests itself + const err = new lib.PermissionError("Permission denied"); + controllerLink.connector.sendResponseError(lib.Link.errorToResponse(err, false), message.src); + throw err; + } + }); + const subscriber = new lib.EventSubscriber(StringPermissionEvent, control); + const calls: unknown[] = []; + subscriber.subscribe((event, synced) => { calls.push([event, synced]); }); + await settle(); + t3.equal(subscriber.synced, true); + denied = true; + subscriber.handleAccountEvent(); + await settle(); + t3.equal(subscriber.synced, false); + t3.strictSame(calls.at(-1), [null, false]); + t3.type(subscriber.error, lib.PermissionError); + t3.equal(lib.Link.errorName(subscriber.error!), "PermissionError"); + }); + + t2.test("clears the error after a successful request", async t3 => { + const { control, respond } = recorded(); + const subscriber = new lib.EventSubscriber(TestEvent, control); + subscriber.error = new Error("old"); + subscriber.subscribe(() => {}); + respond(false); + await settle(); + t3.equal(subscriber.error, null); + }); + }); + + t1.test("getSnapshot()", async t2 => { + t2.test("returns the same snapshot until the state changes", async t3 => { + const { control } = recorded(); + const subscriber = new lib.EventSubscriber(TestEvent, control); + const snap1 = subscriber.getSnapshot(); + t3.strictSame(snap1, [null, false, null]); + t3.equal(subscriber.getSnapshot(), snap1); + + subscriber.lastUpdatedMs = 5; + const snap2 = subscriber.getSnapshot(); + t3.not(snap2, snap1, "changes with lastUpdatedMs"); + + subscriber.synced = true; + const snap3 = subscriber.getSnapshot(); + t3.not(snap3, snap2, "changes with synced"); + t3.equal(snap3[1], true); + + subscriber.error = new Error("x"); + const snap4 = subscriber.getSnapshot(); + t3.not(snap4, snap3, "changes with error"); + t3.equal(snap4[2], subscriber.error); + t3.equal(subscriber.getSnapshot(), snap4); + }); + }); +}); + +t.test("ValueSubscriber", async t1 => { + function valueSetup() { + const { control, connector } = recorded(); + const subscriber = new lib.ValueSubscriber(ValueEvent, control); + const receive = (value: Item) => { + connector.emit("message", new lib.MessageEvent(1, controller, control1, "ValueEvent", { value })); + }; + return { subscriber, receive }; + } + + t1.test("_handleEvent()", async t2 => { + t2.test("stores the value and its update time", async t3 => { + const { subscriber, receive } = valueSetup(); + receive(item(1, 100)); + t3.strictSame(subscriber.value, item(1, 100)); + t3.equal(subscriber.lastUpdatedMs, 100); + receive(item(1, 200)); + t3.equal(subscriber.value!.updatedAtMs, 200); + }); + + t2.test("does not move lastUpdatedMs back for an older value", async t3 => { + const { subscriber, receive } = valueSetup(); + receive(item(1, 200)); + receive(item(1, 100)); + t3.equal(subscriber.lastUpdatedMs, 200); + }); + }); + + t1.test("getSnapshot()", async t2 => { + const todo = "the base class makes the first snapshot before value is set"; + t2.test("returns null before a value is received", { todo }, async t3 => { + const { subscriber } = valueSetup(); + t3.strictSame(subscriber.getSnapshot(), [null, false, null]); + }); + + t2.test("returns the value", async t3 => { + const { subscriber, receive } = valueSetup(); + receive(item(1, 50)); + t3.strictSame(subscriber.getSnapshot(), [item(1, 50), false, null]); + }); + + t2.test("updates when the value changes in the same millisecond", { todo: snapshotTodo }, async t3 => { + const { subscriber, receive } = valueSetup(); + receive(item(1, 50, { name: "a" })); + subscriber.getSnapshot(); + receive(item(1, 50, { name: "b" })); + t3.match(subscriber.getSnapshot()[0], { name: "b" }); + }); + }); + + t1.test("receives values from the controller", async t2 => { + const { control, subscriptions } = connected(); + subscriptions.handle(ValueEvent, async () => new ValueEvent(item(1, 10)) as any); + const subscriber = new lib.ValueSubscriber(ValueEvent, control); + subscriber.subscribe(() => {}); + await settle(); + t2.strictSame(subscriber.getSnapshot(), [item(1, 10), true, null]); + subscriptions.broadcast(new ValueEvent(item(1, 20)) as any); + t2.equal(subscriber.value!.updatedAtMs, 20); + }); +}); + +t.test("MapSubscriber", async t1 => { + function mapSetup() { + const { control, connector, requests } = recorded(); + const subscriber = new lib.MapSubscriber(MapEvent, control); + const receive = (...updates: Item[]) => { + connector.emit("message", new lib.MessageEvent(1, controller, control1, "MapEvent", { updates })); + }; + return { subscriber, receive, connector, requests }; + } + + t1.test("_handleEvent()", async t2 => { + t2.test("adds, updates and deletes values", async t3 => { + const { subscriber, receive } = mapSetup(); + receive(item(1, 10), item(2, 20)); + t3.strictSame([...subscriber.values.keys()], [1, 2]); + receive(item(1, 30), { ...item(2, 40), isDeleted: true }); + t3.strictSame([...subscriber.values], [[1, item(1, 30)]]); + }); + + t2.test("sets lastUpdatedMs to the newest update", async t3 => { + const { subscriber, receive } = mapSetup(); + receive(item(1, 10), item(2, 50), item(3, 20)); + t3.equal(subscriber.lastUpdatedMs, 50); + receive(item(1, 30)); + t3.equal(subscriber.lastUpdatedMs, 50); + }); + + t2.test("warns about changed content with the same timestamp", async t3 => { + const warnings = t3.capture(lib.logger, "warn"); + const { receive } = mapSetup(); + receive(item(1, 10, { foo: "a" })); + receive(item(1, 10, { foo: "a" })); + t3.strictSame(warnings.args(), [], "identical updates are fine"); + receive(item(1, 10, { foo: "b" })); + t3.strictSame(warnings.args(), [[ + "MapEvent contains update for value with id 1 that has an identical updatedAtMs timestamp " + + "but differing content", + ]]); + }); + }); + + t1.test("getSnapshot()", async t2 => { + t2.test("returns a copy that later events do not change", async t3 => { + const { subscriber, receive } = mapSetup(); + receive(item(1, 10)); + const [snap1] = subscriber.getSnapshot(); + t3.strictSame(snap1, subscriber.values); + t3.not(snap1, subscriber.values); + receive(item(2, 20)); + const [snap2] = subscriber.getSnapshot(); + t3.equal(snap1.has(2), false); + t3.equal(snap2.has(2), true); + }); + + t2.test("updates when a value changes in the same millisecond", { todo: snapshotTodo }, async t3 => { + const { subscriber, receive } = mapSetup(); + receive(item(1, 10)); + subscriber.getSnapshot(); + receive(item(2, 10)); + t3.equal(subscriber.getSnapshot()[0].has(2), true); + }); + }); + + t1.test("handleConnectionEvent()", async t2 => { + t2.test("fetches everything again on connect", async t3 => { + const { subscriber, receive, connector, requests } = mapSetup(); + subscriber.subscribe(() => {}); + receive(item(1, 10)); + const [before] = subscriber.getSnapshot(); + connector.emit("connect"); + t3.equal(subscriber.values.size, 0); + t3.equal(subscriber.lastUpdatedMs, -1); + t3.not(subscriber.getSnapshot()[0], before); + await settle(); + t3.strictSame(requests().at(-1), ["MapEvent", "replace", -1]); + }); + + t2.test("keeps values when a session is resumed", async t3 => { + const { subscriber, receive } = mapSetup(); + receive(item(1, 10)); + subscriber.handleConnectionEvent("drop"); + subscriber.handleConnectionEvent("resume"); + t3.equal(subscriber.values.size, 1); + t3.equal(subscriber.lastUpdatedMs, 10); + }); + }); + + t1.test("tracks values from the controller", async t2 => { + const { control, subscriptions } = connected(); + let stored = [item(1, 10), item(2, 20)]; + subscriptions.handle(MapEvent, async request => new MapEvent( + stored.filter(value => value.updatedAtMs > request.lastRequestTimeMs), + ) as any); + const subscriber = new lib.MapSubscriber(MapEvent, control); + subscriber.subscribe(() => {}); + await settle(); + t2.strictSame([...subscriber.values.keys()], [1, 2]); + t2.equal(subscriber.synced, true); + + stored = [item(1, 10), { ...item(2, 30), isDeleted: true }]; + subscriptions.broadcast(new MapEvent([stored[1]]) as any); + t2.strictSame([...subscriber.values.keys()], [1]); + t2.equal(subscriber.lastUpdatedMs, 30); + }); +}); diff --git a/tests/shared/json_serialisable.ts b/tests/shared/json_serialisable.ts new file mode 100644 index 00000000..0975c575 --- /dev/null +++ b/tests/shared/json_serialisable.ts @@ -0,0 +1,192 @@ +import type { Test } from "tap"; +import { compile } from "@clusterio/lib"; + +/** A class following the JSON serialisable data class pattern, see docs/devs/json-serialisable-classes.md */ +export interface JsonSerialisableClass { + name: string; + jsonSchema: object; + fromJSON(json: any): any; +} + +export function isJsonSerialisableClass(value: unknown): value is JsonSerialisableClass { + return typeof value === "function" + && typeof (value as any).jsonSchema === "object" + && typeof (value as any).fromJSON === "function"; +} + +/** + * Collect the JSON serialisable classes exported by a module, including the + * Response classes of messages that are not exported on their own. + * + * @param module - Module namespace to search. + * @returns Map of display name to class. + */ +export function jsonSerialisableClasses(module: Record) { + const classes = new Map(); + const exported = new Set(Object.values(module)); + for (const [name, value] of Object.entries(module)) { + if (isJsonSerialisableClass(value)) { + classes.set(name, value); + } + const response = (value as any)?.Response; + if (typeof value === "function" && isJsonSerialisableClass(response) && !exported.has(response)) { + classes.set(`${name}.Response`, response); + } + } + return classes; +} + +/** Hand written JSON samples keyed by the schema object they match, minimal first and full last */ +export type KnownSamples = Map; + +// Strings tried in order for a schema with a pattern +const patternCandidates = ["a", "1", "1.0", "1.0.0", "a-b", "a.b", "a_b", "A", "ffffff", "0.0.0"]; + +/** + * Create a JSON value matching a JSON schema. + * + * Only required properties are created unless `full` is set, in which case + * every declared property is created. Throws for schemas it cannot satisfy, + * these need a hand written sample in `known` instead. + * + * @param schema - JSON schema to create a value for. + * @param full - Include optional properties. + * @param known - Samples to use for specific schema objects, wherever they appear. + * @returns Value matching the schema. + */ +export function sampleFromSchema(schema: any, full = false, known?: KnownSamples): unknown { + if (known?.has(schema)) { + const samples = known.get(schema)!; + return structuredClone(full ? samples.at(-1) : samples[0]); + } + if (schema === true || schema === undefined || Object.keys(schema).length === 0) { + return null; + } + if ("const" in schema) { + return schema.const; + } + if (schema.enum) { + return schema.enum[0]; + } + if ("default" in schema) { + return structuredClone(schema.default); + } + for (const key of ["anyOf", "oneOf"]) { + if (schema[key]) { + // Prefer a branch that is not null so the sample says more + const branch = schema[key].find((s: any) => s.type !== "null") ?? schema[key][0]; + return sampleFromSchema(branch, full, known); + } + } + if (schema.allOf) { + return Object.assign({}, ...schema.allOf.map((s: any) => sampleFromSchema(s, full, known))); + } + + const type = Array.isArray(schema.type) ? schema.type.find((t: string) => t !== "null") : schema.type; + switch (type) { + case "null": + return null; + case "boolean": + return false; + case "integer": + case "number": + return schema.minimum ?? (schema.exclusiveMinimum !== undefined ? schema.exclusiveMinimum + 1 : 0); + case "string": + return sampleString(schema); + case "array": + return sampleArray(schema, full, known); + case "object": + return sampleObject(schema, full, known); + default: + throw new Error(`Unsupported schema ${JSON.stringify(schema)}`); + } +} + +function sampleString(schema: any) { + if (schema.pattern) { + const pattern = new RegExp(schema.pattern, "u"); + const match = patternCandidates.find(c => pattern.test(c)); + if (match === undefined) { + throw new Error(`No sample string matches pattern ${schema.pattern}`); + } + return match; + } + if (schema.format) { + throw new Error(`No sample string for format ${schema.format}`); + } + return "a".repeat(schema.minLength ?? 0); +} + +function sampleArray(schema: any, full: boolean, known?: KnownSamples) { + if (Array.isArray(schema.items) || schema.prefixItems) { + const items: any[] = schema.prefixItems ?? schema.items; + const count = full ? items.length : schema.minItems ?? 0; + return items.slice(0, count).map(item => sampleFromSchema(item, full, known)); + } + const count = Math.max(schema.minItems ?? 0, full ? 1 : 0); + return Array.from({ length: count }, () => sampleFromSchema(schema.items, full, known)); +} + +function sampleObject(schema: any, full: boolean, known?: KnownSamples) { + const required = new Set(schema.required ?? []); + const result: Record = {}; + for (const [key, property] of Object.entries(schema.properties ?? {})) { + if (full || required.has(key)) { + result[key] = sampleFromSchema(property, full, known); + } + } + return result; +} + +/** + * Minimal and full JSON samples for a class generated from its schema. + * + * @param Class - Class to create samples for. + * @param known - Hand written samples for schemas that cannot be generated. + * @returns Named JSON samples. + */ +export function jsonSamples(Class: JsonSerialisableClass, known?: KnownSamples) { + return [ + ["minimal sample", sampleFromSchema(Class.jsonSchema, false, known)], + ["full sample", sampleFromSchema(Class.jsonSchema, true, known)], + ] as const; +} + +/** + * Common tests for a JSON serialisable class. + * + * Each sample is deserialised with fromJSON, serialised with JSON.stringify, + * then checked against the class schema and deserialised again. + * + * @param t - Test to add the fromJSON() and toJSON() subtests to. + * @param Class - Class under test. + * @param samples - Named JSON samples, see {@link jsonSamples}. + */ +export function testJsonSerialisable( + t: Test, + Class: JsonSerialisableClass, + samples: ReadonlyArray, +) { + const validate = compile(Class.jsonSchema as any); + const serialise = (value: unknown) => JSON.parse(JSON.stringify(value)); + + t.test("toJSON()", async t1 => { + for (const [name, json] of samples) { + t1.test(`matches jsonSchema for ${name}`, async t2 => { + const serialised = serialise(Class.fromJSON(structuredClone(json))); + t2.ok(validate(serialised), "serialised value is valid", { errors: validate.errors, serialised }); + }); + } + }); + + t.test("fromJSON()", async t1 => { + for (const [name, json] of samples) { + t1.test(`round trips ${name}`, async t2 => { + const original = Class.fromJSON(structuredClone(json)); + const reconstructed = Class.fromJSON(serialise(original)); + t2.strictSame(reconstructed, original); + t2.same(serialise(reconstructed), serialise(original)); + }); + } + }); +} diff --git a/tests/shared/link.ts b/tests/shared/link.ts new file mode 100644 index 00000000..b8cc0e99 --- /dev/null +++ b/tests/shared/link.ts @@ -0,0 +1,72 @@ +import events from "node:events"; +import * as lib from "@clusterio/lib"; + +export const addr = lib.Address.fromShorthand; + +/** + * Link on one end of a VirtualConnector pair with nothing but a recorder on + * the other end. + * + * @param src - Address of the link. + * @param dst - Address of the other end. + * @returns the link, its connector, the peer connector and the messages + * that arrived at the peer. + */ +export function recordedLink(src: lib.Address, dst: lib.Address) { + const [connector, peer] = lib.VirtualConnector.makePair(src, dst); + const link = new lib.Link(connector); + const sent: any[] = []; + peer.on("message", message => { sent.push(message); }); + return { link, connector, peer, sent }; +} + +/** VirtualConnector which sends messages through JSON like a WebSocket would */ +export class JsonVirtualConnector extends lib.VirtualConnector { + send(message: lib.Message) { + this.other.emit("message", lib.Message.fromJSON(JSON.parse(JSON.stringify(message)))); + } +} + +/** + * Two links joined by a JsonVirtualConnector pair. + * + * @param src - Address of the first link. + * @param dst - Address of the second link. + * @returns both links. + */ +export function linkPair(src: lib.Address, dst: lib.Address) { + const [connector, peerConnector] = JsonVirtualConnector.makePair(src, dst); + return { link: new lib.Link(connector), peer: new lib.Link(peerConnector) }; +} + +/** + * WebSocket connector with the socket replaced by an array of sent text. + * Starts out closed, set `_state` to "connected" to give it a session. + */ +export class TestWebSocketConnector extends lib.WebSocketBaseConnector { + sentText: string[] = []; + + constructor(src: lib.Address, dst: lib.Address) { + super(src, dst); + this._socket = { send: (text: string) => { this.sentText.push(text); } } as any; + } + + setClosing() { + this._closing = true; + } + + async close() { + this._state = "closed"; + } +} + +/** Resolves with the next message to arrive at a connector */ +export async function nextMessage(connector: lib.BaseConnector): Promise { + const [message] = await events.once(connector as events.EventEmitter, "message"); + return message; +} + +/** Resolves once pending promise callbacks and I/O callbacks have run */ +export function settle() { + return new Promise(resolve => { setImmediate(resolve); }); +} diff --git a/tests/tsconfig.json b/tests/tsconfig.json new file mode 100644 index 00000000..13fefe37 --- /dev/null +++ b/tests/tsconfig.json @@ -0,0 +1,15 @@ +// Type checks the TAP tests, which Node.js runs directly by stripping the types. +{ + "extends": "../tsconfig.node.json", + "compilerOptions": { + "composite": false, + "declaration": false, + "declarationMap": false, + "incremental": false, + "noEmit": true, + "allowImportingTsExtensions": true, + "erasableSyntaxOnly": true, + "verbatimModuleSyntax": true, + }, + "include": ["./**/*.ts", "../plugins/*/test/**/*.test.ts"], +}