From e6ee5fbd7228606af45c4a273e8667e6da2d16b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ersin=20KO=C3=87?= Date: Tue, 24 Nov 2026 23:33:14 +0200 Subject: [PATCH 1/4] sdk/js: wait for browser state writes to commit --- sdk/js/src/platform/state.browser.test.ts | 69 +++++++++++++++++++++++ sdk/js/src/platform/state.browser.ts | 6 +- 2 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 sdk/js/src/platform/state.browser.test.ts diff --git a/sdk/js/src/platform/state.browser.test.ts b/sdk/js/src/platform/state.browser.test.ts new file mode 100644 index 00000000..0cbc9e2e --- /dev/null +++ b/sdk/js/src/platform/state.browser.test.ts @@ -0,0 +1,69 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { openState } from "./state.browser.ts"; + +for (const outcome of ["commit", "abort", "abort without a reason"] as const) { + test(`browser state write waits for transaction ${outcome}`, async (t) => { + const opened = { result: { transaction: () => transaction }, onsuccess: () => {} }; + const stored = { onsuccess: () => {} }; + let queued = false; + const failure = new DOMException("commit failed", "QuotaExceededError"); + const transaction = { + objectStore: () => ({ + put: () => { + queued = true; + return stored; + }, + }), + error: outcome === "abort" ? failure : null, + oncomplete: () => {}, + onabort: () => {}, + }; + Object.defineProperty(globalThis, "indexedDB", { + configurable: true, + value: { open: () => opened }, + }); + t.after(() => Reflect.deleteProperty(globalThis, "indexedDB")); + + let settled = false; + const result = openState("test").write("credential", Uint8Array.of(1)).then( + () => { settled = true; }, + (error: unknown) => { + settled = true; + return error; + }, + ); + opened.onsuccess(); + await Promise.resolve(); // let write queue its put request + assert.equal(queued, true); + console.log("CONTROL OK"); + stored.onsuccess(); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(settled, false, "write settled before the transaction finished"); + if (outcome === "commit") { + transaction.oncomplete(); + } else { + transaction.onabort(); + } + const error = await result; + if (outcome === "abort without a reason") { + assert.match(String(error), /IndexedDB write transaction aborted/); + } else { + assert.equal(error, outcome === "abort" ? failure : undefined); + } + }); +} diff --git a/sdk/js/src/platform/state.browser.ts b/sdk/js/src/platform/state.browser.ts index 0864d1cc..657fe9f8 100644 --- a/sdk/js/src/platform/state.browser.ts +++ b/sdk/js/src/platform/state.browser.ts @@ -47,7 +47,11 @@ export function openState(location: string): StateStore { }, async write(name, data) { const tx = (await open()).transaction(STORE, "readwrite"); - await request(tx.objectStore(STORE).put(new Uint8Array(data), name)); + await new Promise((resolve, reject) => { + tx.oncomplete = () => resolve(); + tx.onabort = () => reject(tx.error ?? new Error("IndexedDB write transaction aborted")); + tx.objectStore(STORE).put(new Uint8Array(data), name); + }); }, async remove(name) { const tx = (await open()).transaction(STORE, "readwrite"); From 76213d5add4fb7715c1755e51aebea279102215d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ersin=20KO=C3=87?= Date: Tue, 24 Nov 2026 23:33:17 +0200 Subject: [PATCH 2/4] sdk/js: isolate temporary files for node state writes --- sdk/js/src/platform/state.test.ts | 80 +++++++++++++++++++++++++++++++ sdk/js/src/platform/state.ts | 14 ++++-- 2 files changed, 89 insertions(+), 5 deletions(-) create mode 100644 sdk/js/src/platform/state.test.ts diff --git a/sdk/js/src/platform/state.test.ts b/sdk/js/src/platform/state.test.ts new file mode 100644 index 00000000..95ad93ae --- /dev/null +++ b/sdk/js/src/platform/state.test.ts @@ -0,0 +1,80 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import assert from "node:assert/strict"; +import fs from "node:fs/promises"; +import { syncBuiltinESMExports } from "node:module"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { test } from "node:test"; +import { openState } from "./state.ts"; + +test("overlapping state writes publish their own bytes", { timeout: 5000 }, async (t) => { + const dir = await fs.mkdtemp(join(tmpdir(), "agentmesh-state-")); + t.after(() => fs.rm(dir, { recursive: true, force: true })); + const state = openState(dir); + await state.write("credential", Uint8Array.of(0)); + assert.deepEqual(await state.read("credential"), Uint8Array.of(0)); + console.log("CONTROL OK"); + const rename = fs.rename; + let signalReady!: () => void; + let allowRename!: () => void; + const ready = new Promise((resolve) => { signalReady = resolve; }); + const release = new Promise((resolve) => { allowRename = resolve; }); + let paused = false; + const intercepted = t.mock.method(fs, "rename", async (...paths: Parameters) => { + if (!paused) { + paused = true; + signalReady(); + await release; + } + await rename(...paths); + }); + syncBuiltinESMExports(); + t.after(() => { + allowRename(); + intercepted.mock.restore(); + syncBuiltinESMExports(); + }); + + const first = state.write("credential", Uint8Array.of(1)); + await ready; + try { + await openState(dir).write("credential", Uint8Array.of(2)); + assert.deepEqual(await state.read("credential"), Uint8Array.of(2)); + } finally { + allowRename(); + await first; + } + assert.deepEqual(await state.read("credential"), Uint8Array.of(1)); + assert.deepEqual(await fs.readdir(dir), ["credential"]); +}); + +test("state write can replace an existing value with empty bytes", async (t) => { + const dir = await fs.mkdtemp(join(tmpdir(), "agentmesh-state-")); + t.after(() => fs.rm(dir, { recursive: true, force: true })); + const state = openState(dir); + await state.write("credential", Uint8Array.of(1)); + await state.write("credential", new Uint8Array()); + assert.deepEqual(await state.read("credential"), new Uint8Array()); + assert.deepEqual(await fs.readdir(dir), ["credential"]); +}); + +test("state write removes its temporary file if publish fails", async (t) => { + const dir = await fs.mkdtemp(join(tmpdir(), "agentmesh-state-")); + t.after(() => fs.rm(dir, { recursive: true, force: true })); + await fs.mkdir(join(dir, "credential")); + await assert.rejects(openState(dir).write("credential", Uint8Array.of(1))); + assert.deepEqual(await fs.readdir(dir), ["credential"]); +}); diff --git a/sdk/js/src/platform/state.ts b/sdk/js/src/platform/state.ts index 420168da..f3f76852 100644 --- a/sdk/js/src/platform/state.ts +++ b/sdk/js/src/platform/state.ts @@ -15,7 +15,7 @@ // State on Node: a directory, one file per name, owner-only, written to a // temporary name and renamed into place. Where a token file is read from. -import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises"; import { join } from "node:path"; import type { StateStore } from "./types.ts"; @@ -34,10 +34,14 @@ export function openState(location: string): StateStore { }, async write(name, data) { await mkdir(location, { recursive: true, mode: 0o700 }); - const path = join(location, name); - const tmp = `${path}.tmp`; - await writeFile(tmp, data, { mode: 0o600 }); - await rename(tmp, path); + const dir = await mkdtemp(join(location, ".write-")); + const tmp = join(dir, "value"); + try { + await writeFile(tmp, data, { mode: 0o600 }); + await rename(tmp, join(location, name)); + } finally { + await rm(dir, { recursive: true, force: true }); + } }, async remove(name) { await rm(join(location, name), { force: true }); From d9d8e3ab04fa432bd1154a30e142eb4e8a30d957 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ersin=20KO=C3=87?= Date: Tue, 24 Nov 2026 23:36:30 +0200 Subject: [PATCH 3/4] sdk/js: retry browser state open after failures --- sdk/js/src/platform/state.browser.test.ts | 66 +++++++++++++++++++++-- sdk/js/src/platform/state.browser.ts | 5 +- 2 files changed, 65 insertions(+), 6 deletions(-) diff --git a/sdk/js/src/platform/state.browser.test.ts b/sdk/js/src/platform/state.browser.test.ts index 0cbc9e2e..eb256da6 100644 --- a/sdk/js/src/platform/state.browser.test.ts +++ b/sdk/js/src/platform/state.browser.test.ts @@ -17,15 +17,16 @@ import { test } from "node:test"; import { openState } from "./state.browser.ts"; for (const outcome of ["commit", "abort", "abort without a reason"] as const) { - test(`browser state write waits for transaction ${outcome}`, async (t) => { + test(`browser state write waits for transaction ${outcome}`, { timeout: 5000 }, async (t) => { const opened = { result: { transaction: () => transaction }, onsuccess: () => {} }; const stored = { onsuccess: () => {} }; - let queued = false; + let signalPut!: () => void; + const queued = new Promise((resolve) => { signalPut = resolve; }); const failure = new DOMException("commit failed", "QuotaExceededError"); const transaction = { objectStore: () => ({ put: () => { - queued = true; + signalPut(); return stored; }, }), @@ -48,8 +49,7 @@ for (const outcome of ["commit", "abort", "abort without a reason"] as const) { }, ); opened.onsuccess(); - await Promise.resolve(); // let write queue its put request - assert.equal(queued, true); + await queued; console.log("CONTROL OK"); stored.onsuccess(); await new Promise((resolve) => setImmediate(resolve)); @@ -67,3 +67,59 @@ for (const outcome of ["commit", "abort", "abort without a reason"] as const) { } }); } + +test("browser state retries an unsuccessful database open", async (t) => { + const failure = new DOMException("database temporarily unavailable", "UnknownError"); + const data = Uint8Array.of(5); + const db = { + transaction: () => ({ + objectStore: () => ({ + get: () => { + const request = { result: data, onsuccess: () => {} }; + queueMicrotask(() => request.onsuccess()); + return request; + }, + }), + }), + }; + let opens = 0; + Object.defineProperty(globalThis, "indexedDB", { + configurable: true, + value: { + open: () => { + const request = { result: db, error: failure, onsuccess: () => {}, onerror: () => {} }; + opens++; + const fail = opens === 2; + queueMicrotask(() => { + if (fail) { + request.onerror(); + } else { + request.onsuccess(); + } + }); + return request; + }, + }, + }); + t.after(() => Reflect.deleteProperty(globalThis, "indexedDB")); + + const working = openState("working"); + assert.deepEqual(await working.read("credential"), data); + assert.deepEqual(await working.read("credential"), data); + assert.equal(opens, 1); + console.log("CONTROL OK"); + + const recovering = openState("recovering"); + await assert.rejects(recovering.read("credential"), failure); + const retried = await Promise.allSettled([ + recovering.read("credential"), + recovering.read("credential"), + ]); + assert.equal(opens, 3, "database open was not retried once"); + assert.deepEqual(retried, [ + { status: "fulfilled", value: data }, + { status: "fulfilled", value: data }, + ]); + assert.deepEqual(await recovering.read("credential"), data); + assert.equal(opens, 3); +}); diff --git a/sdk/js/src/platform/state.browser.ts b/sdk/js/src/platform/state.browser.ts index 657fe9f8..3d6aa2ce 100644 --- a/sdk/js/src/platform/state.browser.ts +++ b/sdk/js/src/platform/state.browser.ts @@ -38,7 +38,10 @@ function openDatabase(name: string): Promise { /** The store for a state location: a database named after it. */ export function openState(location: string): StateStore { let db: Promise | undefined; - const open = () => (db ??= openDatabase(location)); + const open = () => (db ??= openDatabase(location).catch((error: unknown) => { + db = undefined; + throw error; + })); return { async read(name) { const tx = (await open()).transaction(STORE, "readonly"); From 1960c5b0f2e3ca5eab90b4dfe2613a411f79aa54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ersin=20KO=C3=87?= Date: Sat, 28 Nov 2026 15:26:59 +0200 Subject: [PATCH 4/4] sdk/js: drop leftover CONTROL OK logs from the state tests --- sdk/js/src/platform/state.browser.test.ts | 2 -- sdk/js/src/platform/state.test.ts | 1 - 2 files changed, 3 deletions(-) diff --git a/sdk/js/src/platform/state.browser.test.ts b/sdk/js/src/platform/state.browser.test.ts index eb256da6..01745ad7 100644 --- a/sdk/js/src/platform/state.browser.test.ts +++ b/sdk/js/src/platform/state.browser.test.ts @@ -50,7 +50,6 @@ for (const outcome of ["commit", "abort", "abort without a reason"] as const) { ); opened.onsuccess(); await queued; - console.log("CONTROL OK"); stored.onsuccess(); await new Promise((resolve) => setImmediate(resolve)); assert.equal(settled, false, "write settled before the transaction finished"); @@ -107,7 +106,6 @@ test("browser state retries an unsuccessful database open", async (t) => { assert.deepEqual(await working.read("credential"), data); assert.deepEqual(await working.read("credential"), data); assert.equal(opens, 1); - console.log("CONTROL OK"); const recovering = openState("recovering"); await assert.rejects(recovering.read("credential"), failure); diff --git a/sdk/js/src/platform/state.test.ts b/sdk/js/src/platform/state.test.ts index 95ad93ae..7110f82f 100644 --- a/sdk/js/src/platform/state.test.ts +++ b/sdk/js/src/platform/state.test.ts @@ -26,7 +26,6 @@ test("overlapping state writes publish their own bytes", { timeout: 5000 }, asyn const state = openState(dir); await state.write("credential", Uint8Array.of(0)); assert.deepEqual(await state.read("credential"), Uint8Array.of(0)); - console.log("CONTROL OK"); const rename = fs.rename; let signalReady!: () => void; let allowRename!: () => void;