diff --git a/sdk/js/src/session.ts b/sdk/js/src/session.ts index 24e53b4a..6698e351 100644 --- a/sdk/js/src/session.ts +++ b/sdk/js/src/session.ts @@ -245,6 +245,10 @@ export class MeshSession { #announced: string[] = []; #syncing: Promise | undefined; #refreshing: Promise | undefined; + /** A triggered pull is due and its timer has not fired yet. */ + #syncTriggered = false; + /** Counts sync timers fired; only the latest schedules the next periodic pull. */ + #syncRuns = 0; #keepingRelay: Promise | undefined; #keepRelayPending = false; readonly #heldRouterIds: Set; @@ -1061,19 +1065,30 @@ export class MeshSession { /** Asks for a pull soon, after a random delay so a fleet told at once does not pull at once. */ triggerSync(): void { - if (this.#closed) { + // A triggered pull already due covers this event too, like a one-slot + // channel: a burst of events does not keep pushing its timer back. + if (this.#closed || this.#syncTriggered) { return; } + this.#syncTriggered = true; this.#scheduleSync(Math.floor(Math.random() * (this.#syncJitterMs + 1))); } #scheduleSync(delayMs: number): void { clearTimeout(this.#syncTimer); this.#syncTimer = setTimeout(() => { - this.sync() + this.#syncTriggered = false; + const run = ++this.#syncRuns; + // A pull in flight may have read the control plane before this one was + // asked for, so it is not shared: this one starts when it ends. + (this.#syncing ?? Promise.resolve()) + .catch(() => {}) + .then(() => (this.#closed ? undefined : this.sync())) .catch(() => {}) .finally(() => { - if (!this.#closed && this.#syncIntervalMs > 0) { + // A trigger that came in meanwhile keeps its own, earlier timer, and + // a pull queued behind this one schedules the next when it ends. + if (!this.#closed && this.#syncIntervalMs > 0 && !this.#syncTriggered && run === this.#syncRuns) { // Stretched by up to a tenth so a fleet started together does not pull together. this.#scheduleSync(this.#syncIntervalMs + Math.floor(Math.random() * (this.#syncIntervalMs / 10 + 1))); } diff --git a/sdk/js/src/sync.test.ts b/sdk/js/src/sync.test.ts index 01d905b7..47d02ab1 100644 --- a/sdk/js/src/sync.test.ts +++ b/sdk/js/src/sync.test.ts @@ -30,7 +30,7 @@ import { tcp } from "@libp2p/tcp"; import { tls } from "@libp2p/tls"; import { createLibp2p } from "libp2p"; import assert from "node:assert/strict"; -import { after, before, test } from "node:test"; +import { after, before, test, type TestContext } from "node:test"; import { AUTH_PROTOCOL, authenticateWithPeer, authStreamHandler } from "./auth.ts"; import { ROLE_ROUTER, loadBiscuit, verifyPeerBiscuit } from "./biscuit.ts"; import { ROLE_NODE } from "./controlplane.ts"; @@ -49,6 +49,7 @@ import { } from "./gen/agentmesh_pb.ts"; import { Identity } from "./identity.ts"; import { AgentMesh } from "./mesh.ts"; +import type { MeshSession } from "./session.ts"; import { BanSet, EVENT_FRESHNESS_MS, verifyMeshEvent } from "./sync.ts"; type Wasm = Awaited>; @@ -82,6 +83,9 @@ class FakeControlPlane { keys: SigningKey[]; banned: string[] = []; refreshes = 0; + /** The /policies reads so far, one per pull; the hook may hold an answer. */ + policyReads = 0; + onPolicyRead: ((reads: number) => Promise) | undefined; constructor(initial: SigningKey) { this.keys = [initial]; } @@ -127,6 +131,8 @@ class FakeControlPlane { ); } if (req.method === "GET" && path === "/policies") { + this.policyReads++; + await this.onPolicyRead?.(this.policyReads); return proto(toBinary(PolicyConfigGetResponseSchema, create(PolicyConfigGetResponseSchema, { datalogRules: ['granted_publish_all_types(true) <- role("mesh:role:node")'] }))); } if (req.method === "POST" && path === "/refresh") { @@ -172,6 +178,9 @@ before(async () => { connectionEncrypters: [tls()], streamMuxers: [yamux()], services: { identify: identify(), relay: circuitRelayServer() }, + // Every member in these tests dials from 127.0.0.1; libp2p's default of + // five inbound connections per host per second would refuse later joins. + connectionManager: { inboundConnectionThreshold: 1_000 }, }); const routerBiscuit = cp.current.mint(router.peerId.toString(), ROLE_ROUTER); await router.handle(AUTH_PROTOCOL, authStreamHandler({ ownBiscuit: () => routerBiscuit, trustedKeys: () => cp.keys.map((k) => k.pub) })); @@ -339,3 +348,157 @@ test("a banned peer is hung up on and refused at the gate and the handshake", as await session.close(); } }); + +test("an event that arrives while a pull is in flight is followed by another pull", async () => { + const mesh = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", bootstrapToken: "sbt", fetch: cp.fetch }); + // No jitter, so a triggered pull is due at once; no periodic pull within the test. + const session = await mesh.join({ refreshLeadMs: 0, controlPlaneSyncIntervalMs: 3_600_000, controlPlaneSyncJitterMs: 0 }); + const start = cp.policyReads; + let secondPull!: () => void; + const pulledAgain = new Promise((resolve) => (secondPull = resolve)); + // The first triggered pull holds its /policies answer (it has read the + // control plane) while a second event triggers. The answer is released + // from a timer queued after the second trigger's, so that trigger comes + // due while the first pull is still in flight. + cp.onPolicyRead = (reads) => { + if (reads === start + 2) { + secondPull(); + } + if (reads !== start + 1) { + return Promise.resolve(); + } + return new Promise((release) => { + session.triggerSync(); + setTimeout(release, 0); + }); + }; + let deadline: ReturnType | undefined; + try { + session.triggerSync(); + await Promise.race([pulledAgain, new Promise((resolve) => (deadline = setTimeout(resolve, 5_000)))]); + assert.equal(cp.policyReads, start + 2, "the event that came during the pull was not followed by a pull of its own"); + } finally { + clearTimeout(deadline); + cp.onPolicyRead = undefined; + await session.close(); + } +}); + +/** Triggers a pull whose random delay is half the jitter; Math.random is mocked for this call only. */ +function triggerAtHalfJitter(t: TestContext, session: MeshSession): void { + const random = t.mock.method(Math, "random", () => 0.5); + try { + session.triggerSync(); + } finally { + random.mock.restore(); + } +} + +test("a burst of events does not push back the pull the first one asked for", async (t) => { + const mesh = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", bootstrapToken: "sbt", fetch: cp.fetch }); + const session = await mesh.join({ refreshLeadMs: 0, controlPlaneSyncIntervalMs: 3_600_000, controlPlaneSyncJitterMs: 200 }); + const start = cp.policyReads; + let pulled!: () => void; + const pulledOnce = new Promise((resolve) => (pulled = resolve)); + let burst: ReturnType | undefined; + cp.onPolicyRead = (reads) => { + if (reads === start + 1) { + clearInterval(burst); + pulled(); + } + return Promise.resolve(); + }; + let deadline: ReturnType | undefined; + try { + // Every event asks for a pull 100 ms after it, and they keep coming + // every 20 ms for well past the first one's delay. + triggerAtHalfJitter(t, session); + burst = setInterval(() => triggerAtHalfJitter(t, session), 20); + const outcome = await Promise.race([ + pulledOnce.then(() => "pulled"), + new Promise((resolve) => (deadline = setTimeout(() => resolve("burst over"), 5_000))), + ]); + assert.equal(outcome, "pulled", "the burst kept moving the triggered pull back"); + } finally { + clearInterval(burst); + clearTimeout(deadline); + cp.onPolicyRead = undefined; + await session.close(); + } +}); + +test("a pull that ends while a triggered one is still due leaves that one's timer alone", async (t) => { + const mesh = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", bootstrapToken: "sbt", fetch: cp.fetch }); + const session = await mesh.join({ refreshLeadMs: 0, controlPlaneSyncIntervalMs: 3_600_000, controlPlaneSyncJitterMs: 200 }); + const start = cp.policyReads; + let secondPull!: () => void; + const pulledAgain = new Promise((resolve) => (secondPull = resolve)); + // The second event arrives while the first pull is reading /policies, and + // that pull ends long before the second event's timer fires. + cp.onPolicyRead = (reads) => { + if (reads === start + 1) { + triggerAtHalfJitter(t, session); + } + if (reads === start + 2) { + secondPull(); + } + return Promise.resolve(); + }; + let deadline: ReturnType | undefined; + try { + // A triggered pull comes due 100 ms after its event. + triggerAtHalfJitter(t, session); + await Promise.race([pulledAgain, new Promise((resolve) => (deadline = setTimeout(resolve, 5_000)))]); + assert.equal(cp.policyReads, start + 2, "the first pull's end replaced the pending triggered pull with a periodic one"); + } finally { + clearTimeout(deadline); + cp.onPolicyRead = undefined; + await session.close(); + } +}); + +test("a pull queued behind another does not let the first one schedule a periodic pull", async () => { + const intervalMs = 200; + const mesh = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", bootstrapToken: "sbt", fetch: cp.fetch }); + const session = await mesh.join({ refreshLeadMs: 0, controlPlaneSyncIntervalMs: intervalMs, controlPlaneSyncJitterMs: 0 }); + const start = cp.policyReads; + let releasedAt = 0; + let thirdPull!: (at: number) => void; + const pulledThird = new Promise((resolve) => (thirdPull = resolve)); + cp.onPolicyRead = (reads) => { + if (reads === start + 1) { + // As in the test above: a second event comes due while this pull is + // in flight, so its pull is queued behind this one. + return new Promise((release) => { + session.triggerSync(); + setTimeout(release, 0); + }); + } + if (reads === start + 2) { + // The queued pull is slower than the periodic interval. + return new Promise((release) => + setTimeout(() => { + releasedAt = performance.now(); + release(); + }, 2 * intervalMs), + ); + } + if (reads === start + 3) { + thirdPull(performance.now()); + } + return Promise.resolve(); + }; + let deadline: ReturnType | undefined; + try { + session.triggerSync(); + const at = await Promise.race([pulledThird, new Promise((resolve) => (deadline = setTimeout(() => resolve(-1), 5_000)))]); + assert.notEqual(at, -1, "no periodic pull followed the queued one"); + // The next periodic pull is scheduled when the queued one ends, not by + // the first pull while the queued one is still running. + assert.ok(at - releasedAt >= intervalMs / 2, `a pull started ${Math.round(at - releasedAt)} ms after the queued one, want about ${intervalMs} ms`); + } finally { + clearTimeout(deadline); + cp.onPolicyRead = undefined; + await session.close(); + } +});