diff --git a/src/browser/webapi/storage/idb/IDBFactory.zig b/src/browser/webapi/storage/idb/IDBFactory.zig index 1cb5aa8b4..118a75984 100644 --- a/src/browser/webapi/storage/idb/IDBFactory.zig +++ b/src/browser/webapi/storage/idb/IDBFactory.zig @@ -55,6 +55,10 @@ pub fn open(_: *IDBFactory, name: []const u8, version: ?u64, exec: *Execution) ! ._gate_waiter = .{ .ctx = exec.js, .wake = OpenContext.wakeUp, .cancel = OpenContext.cancelParked }, }); + // Take the strong ref before scheduling: once scheduled, the event fires whatever we return. + try request.strongRef(exec); + errdefer if (request.takeRef()) |s| s.release(); + try exec.js.scheduler.add(ctx, OpenContext.run, 0, .{ .name = "IDBFactory.open", .finalizer = OpenContext.cancelled, @@ -311,6 +315,10 @@ pub fn deleteDatabase(_: *IDBFactory, name: []const u8, exec: *Execution) !*IDBR ._gate_waiter = .{ .ctx = exec.js, .wake = DeleteContext.wakeUp, .cancel = DeleteContext.cancelParked }, }); + // See open. + try request.strongRef(exec); + errdefer if (request.takeRef()) |s| s.release(); + try exec.js.scheduler.add(ctx, DeleteContext.run, 0, .{ .name = "IDBFactory.deleteDatabase", .finalizer = DeleteContext.cancelled, diff --git a/src/browser/webapi/storage/idb/IDBRequest.zig b/src/browser/webapi/storage/idb/IDBRequest.zig index 5536069cd..3048c3fe2 100644 --- a/src/browser/webapi/storage/idb/IDBRequest.zig +++ b/src/browser/webapi/storage/idb/IDBRequest.zig @@ -58,6 +58,12 @@ _result: Result = .{ .none = js.Undefined{} }, // whether or not we own th result value, if we do, we can free it once we know // it cannot be used _result_owned: bool = false, +// A strong handle on our JS object while an event is pending. The identity map +// only holds JS objects weakly, so without it a request that JS stopped +// referencing can be collected before its event fires, and the event would +// then target a fresh JS object, losing any expando on the old one (e.g. +// Zone.js stores the real listeners there). +_strong_ref: ?*js.GlobalSlot = null, const ReadyState = enum { pending, @@ -206,6 +212,28 @@ pub fn failWithAbort(self: *IDBRequest) void { self._error = error.AbortError; } +// Keep our JS object alive until the pending success/error event fires. +// No-op if a strong ref is already held. +pub fn strongRef(self: *IDBRequest, exec: *Execution) !void { + if (self._strong_ref != null) { + return; + } + // Page-tracked, not txn.persist: release() hands the slot back to the + // page's pool, so a cursor re-armed on every iteration reuses one slot + // instead of piling them up in txn._globals. + const js_obj = try exec.js.local.?.zigValueToJs(self, .{}); + self._strong_ref = try js.newTrackedSlot(exec.js, js_obj.handle); +} + +// Move the strong ref out; the caller releases it. The fire functions call it +// before dispatching and release it after, so a handler re-arming the request +// (cursor.continue()) can call strongRef again. Also used to undo strongRef when +// queueing the request fails. +pub fn takeRef(self: *IDBRequest) ?*js.GlobalSlot { + defer self._strong_ref = null; + return self._strong_ref; +} + pub fn deliver(self: *IDBRequest, exec: *Execution) !void { self._ready_state = .done; if (self._error != null) { @@ -242,6 +270,9 @@ pub fn fireUpgradeNeeded(self: *IDBRequest, exec: *Execution, old_version: u64, } pub fn fireSuccess(self: *IDBRequest, exec: *Execution) !void { + const strong_ref = self.takeRef(); + defer if (strong_ref) |s| s.release(); + self._ready_state = .done; const event = try Event.initTrusted(comptime .wrap("success"), null, exec.page); @@ -266,6 +297,9 @@ pub fn fireSuccess(self: *IDBRequest, exec: *Execution) !void { } fn fireError(self: *IDBRequest, exec: *Execution) !void { + const strong_ref = self.takeRef(); + defer if (strong_ref) |s| s.release(); + // Requests created inside a transaction own an abortable transaction; open/ // delete requests (and the borrowed upgrade-transaction view) do not. const txn: ?*IDBTransaction = switch (self._txn) { @@ -415,7 +449,12 @@ pub fn submit(self: *IDBRequest, op: Operation, exec: *Execution) !*IDBRequest { self._op = op; self._source = op.source(); const txn = self._txn.owned; - try txn.enqueue(self); + // Take the strong ref before queueing: once queued, the event fires whatever we return. + try self.strongRef(exec); + txn.enqueue(self) catch |err| { + if (self.takeRef()) |s| s.release(); + return err; + }; if (txn.getMode() == .versionchange) { // for "upgradeneeded" we run them immediately (and still queue them, but diff --git a/src/browser/webapi/storage/idb/idb.zig b/src/browser/webapi/storage/idb/idb.zig index 942443126..cb06621a2 100644 --- a/src/browser/webapi/storage/idb/idb.zig +++ b/src/browser/webapi/storage/idb/idb.zig @@ -75,3 +75,65 @@ const testing = @import("../../../../testing.zig"); test "WebApi: IndexedDB" { try testing.htmlRunner("indexeddb.html", .{}); } + +test "WebApi: IndexedDB pending request keeps its JS object alive" { + // Zone.js registers one shared listener and reads the real callbacks from + // an expando on `this`. A pending request JS no longer references must + // survive a GC, or its event reaches a fresh JS object without the expando. + const frame = try testing.createFrame(); + defer testing.test_session.closeAllPages(); + + // IndexedDB needs a non-opaque origin. + try frame.navigate("http://localhost:9582/", .{}); + try testing.waitForFrame(); + + { + var ls: js.Local.Scope = undefined; + frame.js.localScope(&ls); + defer ls.deinit(); + _ = try ls.local.exec( + \\globalThis.fired = []; + \\globalThis.zoneListener = function(e) { + \\ for (const cb of this.__tasks || []) cb(e); + \\}; + \\globalThis.zoneAdd = function(target, type, cb) { + \\ (target.__tasks ||= []).push(cb); + \\ target.addEventListener(type, zoneListener); + \\}; + \\{ + \\ const req = indexedDB.open('gc_pin', 1); + \\ req.onupgradeneeded = () => req.result.createObjectStore('s'); + \\ req.onsuccess = () => { globalThis.db = req.result; }; + \\} + , null); + } + try testing.waitForFrame(); + + { + var ls: js.Local.Scope = undefined; + frame.js.localScope(&ls); + defer ls.deinit(); + _ = try ls.local.exec( + \\(() => { + \\ const store = db.transaction('s', 'readwrite').objectStore('s'); + \\ zoneAdd(store.put(1, 'k'), 'success', () => fired.push('put')); + \\ zoneAdd(indexedDB.open('gc_pin_2'), 'success', () => fired.push('open')); + \\ zoneAdd(indexedDB.deleteDatabase('gc_pin_3'), 'success', () => fired.push('delete')); + \\})(); + , null); + } + + // Not env.memoryPressureNotification: it skips small heaps. + const isolate = testing.test_session.browser.env.isolate; + for (0..3) |_| { + isolate.memoryPressureNotification(.critical); + } + + try testing.waitForFrame(); + + var ls: js.Local.Scope = undefined; + frame.js.localScope(&ls); + defer ls.deinit(); + const fired = try ls.local.exec("fired.sort().join(',')", null); + try testing.expectEqual("delete,open,put", try fired.toStringSlice()); +}