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
123 changes: 123 additions & 0 deletions sdk/js/src/platform/state.browser.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
// 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}`, { timeout: 5000 }, async (t) => {
const opened = { result: { transaction: () => transaction }, onsuccess: () => {} };
const stored = { onsuccess: () => {} };
let signalPut!: () => void;
const queued = new Promise<void>((resolve) => { signalPut = resolve; });
const failure = new DOMException("commit failed", "QuotaExceededError");
const transaction = {
objectStore: () => ({
put: () => {
signalPut();
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 queued;
stored.onsuccess();
await new Promise<void>((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);
}
});
}

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);

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);
});
11 changes: 9 additions & 2 deletions sdk/js/src/platform/state.browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,10 @@ function openDatabase(name: string): Promise<IDBDatabase> {
/** The store for a state location: a database named after it. */
export function openState(location: string): StateStore {
let db: Promise<IDBDatabase> | 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");
Expand All @@ -47,7 +50,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<void>((resolve, reject) => {
tx.oncomplete = () => resolve();
tx.onabort = () => reject(tx.error ?? new Error("IndexedDB write transaction aborted"));
tx.objectStore(STORE).put(new Uint8Array(data), name);
});
Comment on lines +53 to +57

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

In IndexedDB, if a request inside a transaction fails, the error event bubbles up to the transaction, then to the database, and finally to the global scope (triggering window.onerror or unhandled rejection handlers) unless preventDefault() is called on the event. To prevent transaction failures from polluting the global error logs or causing test runner failures, it is highly recommended to add an onerror handler to the transaction that calls event.preventDefault().

      await new Promise<void>((resolve, reject) => {
        tx.oncomplete = () => resolve();
        tx.onabort = () => reject(tx.error ?? new Error("IndexedDB write transaction aborted"));
        tx.onerror = (event) => event.preventDefault();
        tx.objectStore(STORE).put(new Uint8Array(data), name);
      });

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd rather not take this one: calling preventDefault() on the request's error event changes what the write reports, not only what gets logged.

Per the IndexedDB spec, when a request fails the error event is dispatched with the request, the transaction and the connection in its path; if no listener cancels it, the transaction is aborted. With tx.onerror = (event) => event.preventDefault(), a failed put (for example a QuotaExceededError) no longer aborts the transaction, so it goes on to commit, oncomplete fires, and write() resolves as if the record had been stored. That is the silent lost write this change exists to remove.

As written, a failed put aborts the transaction and onabort rejects write() with tx.error, which is what the caller needs to see. The error event's path also ends at the IDBDatabase; it is not dispatched to window, so there is no global onerror noise to suppress.

},
async remove(name) {
const tx = (await open()).transaction(STORE, "readwrite");
Expand Down
79 changes: 79 additions & 0 deletions sdk/js/src/platform/state.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// 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));
const rename = fs.rename;
let signalReady!: () => void;
let allowRename!: () => void;
const ready = new Promise<void>((resolve) => { signalReady = resolve; });
const release = new Promise<void>((resolve) => { allowRename = resolve; });
let paused = false;
const intercepted = t.mock.method(fs, "rename", async (...paths: Parameters<typeof rename>) => {
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"]);
});
14 changes: 9 additions & 5 deletions sdk/js/src/platform/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -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 });
Expand Down
Loading