Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/internal/EVENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ because it owns no devices.
| Event | Payload (key fields) | Emitted when | Emitter | Status |
|---|---|---|---|---|
| `worker.connected` | worker id, label, worker's daemon version | a worker's uplink opened and its `hello` completed, so the gateway can drive it. A worker whose `hello` found no overlapping protocol range emits nothing: it is in the registry as `incompatible`, which is where an operator finds it | WorkerRegistry | implemented |
| `worker.rejected` | reason (`unauthenticated`/`forbidden`), worker id, label, occasionally a count | an uplink was turned away at the door, before any session existed: `unauthenticated` (`401`) for a missing or unrecognized join token — a revoked or mistyped one lands here — and `forbidden` (`403`) for a real token whose role is not `worker`. Version skew is deliberately not one of these: that uplink authenticated, so the worker enters the registry as `incompatible` and emits nothing (see the note below the table). A refused peer proves no identity, so `workerId` and `label` are only what the connection claimed and may be absent. `count`, present only above one, is how many identical (reason, claimed id) refusals the *previous* coalescing window absorbed — `GatewayService` computes it before calling into the registry, so a flood of refused dials collapses to one event per window rather than one per attempt, since the ring buffer they land in is bounded by count, not bytes | WorkerRegistry | implemented |
| `worker.rejected` | reason (`unauthenticated`/`forbidden`/`worker-mismatch`), worker id, label, occasionally a count | an uplink was turned away at the door, before any session existed: `unauthenticated` (`401`) for a missing or unrecognized join token — a revoked or mistyped one lands here — `forbidden` (`403`) for a real token whose role is not `worker`, and `worker-mismatch` (`403`) for a join token pinned to another worker id, a worker id another token is pinned to, or an empty claimed id (a token is pinned to the first worker id that joins with it; `token revoke` frees both). Version skew is deliberately not one of these: that uplink authenticated, so the worker enters the registry as `incompatible` and emits nothing (see the note below the table). A refused peer proves no identity, so `workerId` and `label` are only what the connection claimed and may be absent. `count`, present only above one, is how many identical (reason, claimed id) refusals the *previous* coalescing window absorbed — `GatewayService` computes it before calling into the registry, so a flood of refused dials collapses to one event per window rather than one per attempt, since the ring buffer they land in is bounded by count, not bytes | WorkerRegistry | implemented |
| `worker.disconnected` | worker id, label, lease count | a worker's uplink closed. `leaseCount` is what its view still shows it holding — how much is stranded, and why the view is kept rather than dropped, not ended: the gateway never guesses a lease is gone before the worker says so | WorkerRegistry | implemented |
| `worker.removed` | worker id, label, reason (operator/retention) | a disconnected worker's view was forgotten: by `simlock worker remove`, or because every gateway-issued lease on it had expired and `gateway.disconnectedRetentionMs` elapsed. Never emitted for a connected worker (`WORKER_CONNECTED` refuses that) | WorkerRegistry | implemented |
| `worker.drain-started` | worker id, label | `simlock worker drain` flagged a worker: it keeps its leases and receives no new dispatches | WorkerRegistry | implemented |
Expand Down
13 changes: 10 additions & 3 deletions docs/internal/adr/0005-gateway-and-worker-modes.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
- **Issue:** [#115](https://github.com/callstackincubator/simlock/issues/115)
(sub-issues #116–#120, one per sequenced PR)
- **Supersedes:** nothing
- **Amended:** §4 and requirement 22 by the maintainer's decision on the
join-token pin (PR #894): a join token is pinned to the first worker id
that uses it, and a mismatch is a third `worker.rejected` reason,
`worker-mismatch` (`403`).
- **Depends on:** [ADR 0004](0004-ttl-first-leases-on-every-transport.md)

> This record is a PRD and an ADR in one file: the first half says what the
Expand Down Expand Up @@ -139,7 +143,10 @@ physical machine.
its token store. The two ways that can fail are different facts and get
different answers, as everywhere else in the API: a **missing or
unrecognized token is `401`**, and a **valid token whose role is not
`worker` is `403`**. Either way nothing enters the worker registry and
`worker` is `403`**. A join token is pinned to the first worker id that
uses it: another claimed id, an id another token is pinned to, or no id
at all is `403` too, as `worker-mismatch`. Either way nothing enters the
worker registry and
the gateway emits `worker.rejected` (requirement 22), which is the only
trace an uplink refused at the door leaves.
5. Over the uplink the **gateway is the protocol client**: it sends `hello`
Expand Down Expand Up @@ -445,8 +452,8 @@ drive the device it leased.
(documented in `EVENTS.md` in the same change).
`worker.rejected` covers an uplink refused at the door (requirement 4):
payload `{ reason, workerId?, label?, protocol? }` with `reason` either
`unauthenticated` (`401`) or `forbidden` (`403`), everything else
optional because a dial that fails authentication proves no identity.
`unauthenticated` (`401`), `forbidden` (`403`) or `worker-mismatch`
(`403`), everything else optional because a dial that fails authentication proves no identity.
Without it a refused uplink leaves no trace at all, and "why did that
machine never appear" is exactly what an operator comes to the event
stream to answer. `device.exec` deliberately emits **no** event: running
Expand Down
2 changes: 1 addition & 1 deletion e2e/console/activity.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -703,7 +703,7 @@ test.describe("the Activity page", () => {
}) => {
const fleet = await startFleet([{ driverScript: { ios: IOS }, label: "worker-a" }]);
try {
const joinToken = fleet.gateway.tokens.worker;
const [joinToken = ""] = fleet.joinTokens;
await openEvents(page, fleet.gateway);
await expect(rows(page).filter({ hasText: "worker.connected" })).not.toHaveCount(0);
const events = await cliEvents(fleet.gateway);
Expand Down
20 changes: 16 additions & 4 deletions e2e/console/fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,14 @@ export async function startDaemon(
export interface Fleet {
readonly gateway: RunningDaemon;
readonly workers: readonly RunningDaemon[];
readonly joinTokens: readonly string[];
}

/** why: a gateway pins a join token to the first worker that joins with it, so each worker needs its own. */
export async function mintJoinToken(gateway: RunningDaemon): Promise<string> {
const minted = await gateway.cli(["token", "create", "--role", "worker"]);
expect(minted.code, minted.stderr).toBe(0);
return (minted.json as { secret: string }).secret;
}

/**
Expand All @@ -442,15 +450,18 @@ export async function startFleet(
options.gatewayConfig === undefined ? {} : { config: options.gatewayConfig },
);
const started: RunningDaemon[] = [];
const joinTokens: string[] = [];
try {
for (const worker of workers) {
const token = await mintJoinToken(gateway);
joinTokens.push(token);
started.push(
await startDaemon("worker", {
config: {
...worker.config,
gateway: {
label: worker.label,
token: gateway.tokens.worker,
token,
url: `ws://127.0.0.1:${gateway.port}`,
},
},
Expand Down Expand Up @@ -478,15 +489,15 @@ export async function startFleet(
},
{ label: "every worker connected to the gateway and read by it" },
);
return { gateway, workers: started };
return { gateway, joinTokens, workers: started };
} catch (error: unknown) {
await disposeFleet({ gateway, workers: started });
throw error;
}
}

export async function disposeFleet(
fleet: Fleet,
fleet: Pick<Fleet, "gateway" | "workers">,
options: { readonly preservePages?: readonly Page[] } = {},
): Promise<void> {
await Promise.all(fleet.workers.map((worker) => worker.dispose(options)));
Expand All @@ -506,9 +517,10 @@ export async function joinOldWorker(
gateway: RunningDaemon,
identity: { readonly id: string; readonly label: string },
): Promise<() => void> {
const token = await mintJoinToken(gateway);
const socket = new WebSocket(`ws://127.0.0.1:${gateway.port}/v1/uplink`, {
headers: {
authorization: `Bearer ${gateway.tokens.worker}`,
authorization: `Bearer ${token}`,
"x-simlock-worker-id": identity.id,
"x-simlock-worker-label": encodeURIComponent(identity.label),
},
Expand Down
12 changes: 10 additions & 2 deletions e2e/console/usage.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
import type { Page } from "@playwright/test";

import { waitFor } from "../helpers/wait.js";
import { expect, type RunningDaemon, settled, signIn, startDaemon, test } from "./fixtures.js";
import {
expect,
mintJoinToken,
type RunningDaemon,
settled,
signIn,
startDaemon,
test,
} from "./fixtures.js";
import { returnToTab } from "./tab.js";

const IOS = { availableOsVersions: ["18.4"], knownModels: ["iPhone 16"] };
Expand Down Expand Up @@ -240,7 +248,7 @@ test.describe("the Usage page", () => {
...ONE_DEVICE,
gateway: {
label,
token: gateway.tokens.worker,
token: await mintJoinToken(gateway),
url: `ws://127.0.0.1:${String(gateway.port)}`,
},
},
Expand Down
20 changes: 13 additions & 7 deletions e2e/gateway-component-install.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { describe, expect, it } from "vitest";

import { type TestEnv, waitFor, withDaemon, withHttpDaemon } from "./helpers/index.js";
import {
mintJoinToken,
type TestEnv,
waitFor,
withDaemon,
withHttpDaemon,
} from "./helpers/index.js";

interface WorkerView {
readonly id: string;
Expand Down Expand Up @@ -49,10 +55,7 @@ describe("simlock component install through a gateway", () => {
role: "gateway",
driver: "none",
}));
const minted = await gateway.cli(["token", "create", "--role", "worker"]);
expect(minted.code, minted.stderr).toBe(0);
const { secret } = minted.json as { secret: string };
const uplink = { token: secret, url: `ws://127.0.0.1:${port}` };
const url = `ws://127.0.0.1:${port}`;
const androidScript = {
android: {
availableOsVersions: ["34"],
Expand All @@ -63,11 +66,14 @@ describe("simlock component install through a gateway", () => {
},
};
await withDaemon({
configOverrides: { gateway: { ...uplink, label: "open" } },
configOverrides: { gateway: { label: "open", token: await mintJoinToken(gateway), url } },
driverScript: androidScript,
});
await withDaemon({
configOverrides: { downloads: { policy: "never" }, gateway: { ...uplink, label: "locked" } },
configOverrides: {
downloads: { policy: "never" },
gateway: { label: "locked", token: await mintJoinToken(gateway), url },
},
driverScript: androidScript,
});
let workers: readonly WorkerView[] = [];
Expand Down
12 changes: 5 additions & 7 deletions e2e/gateway-event-relay.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { describe, expect, it } from "vitest";

import { NodeIpcTransport } from "../src/ports/index.js";
import { SimlockWire } from "../src/simlock-client/wire.js";
import { waitFor, withDaemon, withHttpDaemon } from "./helpers/index.js";
import { mintJoinToken, waitFor, withDaemon, withHttpDaemon } from "./helpers/index.js";
import type { RecordedEvent } from "./helpers/events.js";

/**
Expand Down Expand Up @@ -198,7 +198,7 @@ describe("gateway event relay", () => {
});

it("a gateway pages its events by worker through GET /v1/events, and a worker answers its own id only", async () => {
const { first, gateway, port, read, second, secret } = await gatewayWithTwoWorkers();
const { first, gateway, port, read, second } = await gatewayWithTwoWorkers();
const holders = [
first.env.cliBackground(leaseArgs("by-worker-one-a")),
first.env.cliBackground(leaseArgs("by-worker-one-b")),
Expand Down Expand Up @@ -265,7 +265,6 @@ describe("gateway event relay", () => {
} finally {
await wire.close();
}
expect(secret).toBeDefined();
for (const holder of holders) {
holder.kill("SIGTERM");
await holder.waitForExit(15_000);
Expand Down Expand Up @@ -331,11 +330,10 @@ async function gatewayWithTwoWorkers() {
role: "gateway",
driver: "none",
}));
const minted = await gateway.cli(["token", "create", "--role", "worker"]);
const { secret } = minted.json as { secret: string };
const join = async (label: string): Promise<JoinedWorker> => {
const token = await mintJoinToken(gateway);
const env = await withDaemon({
configOverrides: { gateway: { label, token: secret, url: `ws://127.0.0.1:${port}` } },
configOverrides: { gateway: { label, token, url: `ws://127.0.0.1:${port}` } },
driverScript: { ios: { knownModels: ["iPhone 17"], availableOsVersions: ["18.4"] } },
});
let id: string | undefined;
Expand All @@ -361,7 +359,7 @@ async function gatewayWithTwoWorkers() {
expect(response.status, query).toBe(200);
return ((await response.json()) as { events: RecordedEvent[] }).events;
};
return { first, gateway, operator, port, read, second, secret };
return { first, gateway, operator, port, read, second };
}

const idsOf = (events: readonly RecordedEvent[]) => events.map((event) => event.id);
Expand Down
17 changes: 10 additions & 7 deletions e2e/gateway-fast-fail.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";

import { waitFor, withDaemon, withHttpDaemon } from "./helpers/index.js";
import { mintJoinToken, waitFor, withDaemon, withHttpDaemon } from "./helpers/index.js";
import type { CliResult, TestEnv } from "./helpers/index.js";
import type { FakeDriverScript } from "./fake-driver/types.js";

Expand Down Expand Up @@ -32,17 +32,20 @@ async function startGateway() {
role: "gateway",
driver: "none",
}));
const minted = await gateway.cli(["token", "create", "--role", "worker"]);
expect(minted.code, minted.stderr).toBe(0);
const { secret } = minted.json as { secret: string };
const uplink = { token: secret, url: `ws://127.0.0.1:${port}` };
return {
baseUrl: `http://127.0.0.1:${port}`,
gateway,
join: (label: string, script: FakeDriverScript, extraConfig: Record<string, unknown> = {}) =>
join: async (
label: string,
script: FakeDriverScript,
extraConfig: Record<string, unknown> = {},
) =>
// Seeded before the daemon starts: a worker reports its catalog as its uplink opens.
withDaemon({
configOverrides: { gateway: { ...uplink, label }, ...extraConfig },
configOverrides: {
gateway: { label, token: await mintJoinToken(gateway), url: `ws://127.0.0.1:${port}` },
...extraConfig,
},
driverScript: script,
fakeDriverPlatforms: ["ios"],
}),
Expand Down
Loading
Loading