diff --git a/src/workerd/api/sql.c++ b/src/workerd/api/sql.c++ index 7a92b214f99..46cd28b62c7 100644 --- a/src/workerd/api/sql.c++ +++ b/src/workerd/api/sql.c++ @@ -309,6 +309,13 @@ jsg::JsValue SqlStorage::Cursor::one(jsg::Lock& js) { return result; } +void SqlStorage::Cursor::close() { + KJ_IF_SOME(s, state) { + endQuery(*s); + } + KJ_DASSERT(state == kj::none); +} + jsg::Ref SqlStorage::Cursor::rows(jsg::Lock& js) { return js.alloc(IteratorState{.cursor = JSG_THIS}); } @@ -408,8 +415,7 @@ kj::Maybe> SqlStorage::Cursor::iteratorImpl(jsg::Lock // GC'ed, which might prevent the cache from being effective in the meantime. // // Unfortunately, this does not help with the case where the application stops iterating with - // results still available from the cursor. There's not much we can do about that case since - // there's no way to know if the app might come back and try to use the cursor again later. + // results still available from the cursor. Such applications need to call close(). query.nextRow(); if (query.isDone()) { endQuery(stateRef); diff --git a/src/workerd/api/sql.h b/src/workerd/api/sql.h index 2818c42f9fd..74784df2596 100644 --- a/src/workerd/api/sql.h +++ b/src/workerd/api/sql.h @@ -205,6 +205,8 @@ class SqlStorage::Cursor final: public jsg::Object { JSG_METHOD(next); JSG_METHOD(toArray); JSG_METHOD(one); + JSG_METHOD(close); + JSG_DISPOSE(close); JSG_ITERABLE(rows); JSG_METHOD(raw); @@ -212,13 +214,16 @@ class SqlStorage::Cursor final: public jsg::Object { JSG_READONLY_PROTOTYPE_PROPERTY(rowsRead, getRowsRead); JSG_READONLY_PROTOTYPE_PROPERTY(rowsWritten, getRowsWritten); - JSG_TS_DEFINE(type SqlStorageValue = ArrayBuffer | string | number | null); + // Extends `Disposable` because TypeScript before 5.2 has no `Symbol.dispose`. + JSG_TS_DEFINE(type SqlStorageValue = ArrayBuffer | string | number | null; + interface SqlStorageCursor> extends Disposable {}); JSG_TS_OVERRIDE(> { [Symbol.iterator](): IterableIterator; raw(): IterableIterator; next(): IteratorResult; toArray(): T[]; one(): T; + close(): void; columnNames: string[]; }); @@ -244,6 +249,7 @@ class SqlStorage::Cursor final: public jsg::Object { RowIterator::Next next(jsg::Lock& js); jsg::JsArray toArray(jsg::Lock& js); jsg::JsValue one(jsg::Lock& js); + void close(); void visitForMemoryInfo(jsg::MemoryTracker& tracker) const { if (state != kj::none) { diff --git a/src/workerd/api/tests/sql-test-tail.js b/src/workerd/api/tests/sql-test-tail.js index e3db189ee61..d76125ea043 100644 --- a/src/workerd/api/tests/sql-test-tail.js +++ b/src/workerd/api/tests/sql-test-tail.js @@ -22,20 +22,20 @@ export const test = { return acc; }, {}); assert.deepStrictEqual(reduced, { - durable_object_storage_exec: 294, + durable_object_storage_exec: 341, durable_object_storage_ingest: 1030, durable_object_storage_getDatabaseSize: 3, durable_object_storage_put: 18, durable_object_storage_get: 18, durable_object_storage_transaction: 8, - durable_object_subrequest: 48, + durable_object_subrequest: 52, // Inner spans nested under durable_object_subrequest: jsRpcSession for RPC // dispatches (one per call, client-side only -- the server's jsrpc-typed // onset is its equivalent), fetch for fetch dispatches. - jsRpcSession: 36, + jsRpcSession: 40, fetch: 12, - // jsRpcCall: 36 client-side + 36 server-side. - jsRpcCall: 72, + // jsRpcCall: 40 client-side + 40 server-side. + jsRpcCall: 80, durable_object_storage_deleteAll: 1, createStringTable: 4, runActorFunc: 4, @@ -45,6 +45,10 @@ export const test = { testRollbackKvInit: 1, testRollbackAlarmInit: 1, testCursorUaf: 1, + testCursorClose: 1, + stashCursor: 1, + closeOtherCursor: 1, + closeStashedCursor: 1, durable_object_storage_setAlarm: 2, durable_object_storage_getAlarm: 1, testSessionsAPIBookmark: 20, diff --git a/src/workerd/api/tests/sql-test.js b/src/workerd/api/tests/sql-test.js index 0a316a4e17c..ff21c710322 100644 --- a/src/workerd/api/tests/sql-test.js +++ b/src/workerd/api/tests/sql-test.js @@ -9,6 +9,9 @@ import { DurableObject } from 'cloudflare:workers'; // it easier to keep the DO and test functions together in the test file: let actorFuncs = {}; +// Lets one Durable Object reach a cursor that another one created. +let stashedCursor; + async function test(state) { const storage = state.storage; const sql = storage.sql; @@ -1499,6 +1502,170 @@ export class DurableObjectExample extends DurableObject { const rows = cursor.toArray(); assert.deepEqual(rows, [{ value: 1 }, { value: 2 }, { value: 3 }]); } + + async testCursorClose() { + const sql = this.state.storage.sql; + sql.exec('CREATE TABLE close_big (id INTEGER PRIMARY KEY)'); + sql.exec(`INSERT INTO close_big (id) + WITH RECURSIVE t(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM t LIMIT 10) SELECT x FROM t`); + const selectBig = 'SELECT id FROM close_big ORDER BY id'; + + const createOther = () => { + sql.exec('CREATE TABLE close_other (v INTEGER)'); + sql.exec('CREATE INDEX close_other_v ON close_other (v)'); + }; + const dropOther = () => { + sql.exec('DROP INDEX close_other_v'); + sql.exec('DROP TABLE close_other'); + }; + + // Without close(), the DROP fails. + { + createOther(); + const cursor = sql.exec(selectBig); + cursor.next(); + assert.throws(() => dropOther(), /SQLITE_LOCKED/); + cursor.close(); + dropOther(); + } + + // close() after a partial for...of. + { + createOther(); + const cursor = sql.exec(selectBig); + for (const row of cursor) { + if (row.id === 3) break; + } + cursor.close(); + dropOther(); + } + + // `using` and break. + { + createOther(); + { + using cursor = sql.exec(selectBig); + for (const row of cursor.raw()) { + if (row[0] === 3) break; + } + } + dropOther(); + } + + // `using` and throw. + { + createOther(); + assert.throws(() => { + using cursor = sql.exec(selectBig); + cursor.next(); + throw new Error('stop'); + }, /^Error: stop$/); + dropOther(); + } + + // `using` in a generator whose consumer stops early. + { + createOther(); + function* ids() { + using cursor = sql.exec(selectBig); + for (const row of cursor) yield row.id; + } + for (const id of ids()) { + if (id === 3) break; + } + dropOther(); + } + + { + createOther(); + const cursor = sql.exec(selectBig); + cursor.next(); + cursor[Symbol.dispose](); + dropOther(); + } + + { + const cursor = sql.exec(selectBig); + cursor.next(); + cursor.next(); + cursor.close(); + assert.deepEqual(cursor.next(), { done: true }); + assert.deepEqual(cursor.toArray(), []); + assert.deepEqual([...cursor.raw()], []); + assert.throws(() => cursor.one(), /got no results/); + assert.deepEqual(cursor.columnNames, ['id']); + // The second next() stepped to the third row. + assert.equal(cursor.rowsRead, 3); + assert.equal(cursor.rowsWritten, 0); + + cursor.close(); + cursor[Symbol.dispose](); + assert.equal(cursor.rowsRead, 3); + } + + { + const cursor = sql.exec(selectBig); + assert.equal(cursor.toArray().length, 10); + cursor.close(); + assert.equal(cursor.rowsRead, 10); + } + + { + const cursor = sql.exec(selectBig); + cursor.next(); + cursor.close(); + using again = sql.exec(selectBig); + assert.equal(again.reusedCachedQueryForTest, true); + } + + // close() after a failed step. + { + createOther(); + const cursor = sql.exec( + `SELECT CASE WHEN id = 3 THEN json('not json') ELSE id END AS v FROM close_big ORDER BY id` + ); + cursor.next(); + // Reading the second row steps to the third, which fails. + assert.throws(() => cursor.next(), /malformed JSON/); + cursor.close(); + assert.deepEqual(cursor.next(), { done: true }); + dropOther(); + } + + sql.exec('DROP TABLE close_big'); + } + + async stashCursor() { + const sql = this.state.storage.sql; + sql.exec('CREATE TABLE close_stashed (id INTEGER PRIMARY KEY)'); + sql.exec('INSERT INTO close_stashed VALUES (1), (2), (3)'); + stashedCursor = sql.exec('SELECT id FROM close_stashed ORDER BY id'); + stashedCursor.next(); + } + + // Like the cursor's other methods, close() throws in another Durable Object. + async closeOtherCursor() { + const differentDo = /different Durable Object/; + assert.throws(() => stashedCursor.next(), differentDo); + assert.throws(() => stashedCursor.close(), differentDo); + assert.throws(() => stashedCursor[Symbol.dispose](), differentDo); + + const original = new Error('original'); + try { + using _cursor = stashedCursor; + throw original; + } catch (e) { + assert.ok(e instanceof SuppressedError); + assert.match(e.error.message, differentDo); + assert.equal(e.suppressed, original); + } + } + + async closeStashedCursor() { + stashedCursor.close(); + stashedCursor = undefined; + this.state.storage.sql.exec('DROP TABLE close_stashed'); + } } export default { @@ -1814,3 +1981,20 @@ export let testCursorUaf = { await stub.testCursorUaf(); }, }; + +export let testCursorClose = { + async test(ctrl, env, ctx) { + let stub = env.ns.get(env.ns.idFromName('cursor-close-test')); + await stub.testCursorClose(); + }, +}; + +export let testCursorCloseInOtherDurableObject = { + async test(ctrl, env, ctx) { + let owner = env.ns.get(env.ns.idFromName('cursor-close-owner')); + let other = env.ns.get(env.ns.idFromName('cursor-close-other')); + await owner.stashCursor(); + await other.closeOtherCursor(); + await owner.closeStashedCursor(); + }, +}; diff --git a/types/generated-snapshot/experimental/index.d.ts b/types/generated-snapshot/experimental/index.d.ts index d8089ae1bd1..8e698471d4d 100755 --- a/types/generated-snapshot/experimental/index.d.ts +++ b/types/generated-snapshot/experimental/index.d.ts @@ -3624,12 +3624,16 @@ interface SqlStorage { } declare abstract class SqlStorageStatement {} type SqlStorageValue = ArrayBuffer | string | number | null; +interface SqlStorageCursor< + T extends Record, +> extends Disposable {} declare abstract class SqlStorageCursor< T extends Record, > { next(): IteratorResult; toArray(): T[]; one(): T; + close(): void; raw(): IterableIterator; columnNames: string[]; get rowsRead(): number; diff --git a/types/generated-snapshot/experimental/index.ts b/types/generated-snapshot/experimental/index.ts index 9e6f0b86bdc..dbe78b792e2 100755 --- a/types/generated-snapshot/experimental/index.ts +++ b/types/generated-snapshot/experimental/index.ts @@ -3630,12 +3630,16 @@ export interface SqlStorage { } export declare abstract class SqlStorageStatement {} export type SqlStorageValue = ArrayBuffer | string | number | null; +export interface SqlStorageCursor< + T extends Record, +> extends Disposable {} export declare abstract class SqlStorageCursor< T extends Record, > { next(): IteratorResult; toArray(): T[]; one(): T; + close(): void; raw(): IterableIterator; columnNames: string[]; get rowsRead(): number; diff --git a/types/generated-snapshot/index.d.ts b/types/generated-snapshot/index.d.ts index 37e5054a77a..04439a6b683 100755 --- a/types/generated-snapshot/index.d.ts +++ b/types/generated-snapshot/index.d.ts @@ -3460,12 +3460,16 @@ interface SqlStorage { } declare abstract class SqlStorageStatement {} type SqlStorageValue = ArrayBuffer | string | number | null; +interface SqlStorageCursor< + T extends Record, +> extends Disposable {} declare abstract class SqlStorageCursor< T extends Record, > { next(): IteratorResult; toArray(): T[]; one(): T; + close(): void; raw(): IterableIterator; columnNames: string[]; get rowsRead(): number; diff --git a/types/generated-snapshot/index.ts b/types/generated-snapshot/index.ts index 856c8cd8f50..7baf1db4e8c 100755 --- a/types/generated-snapshot/index.ts +++ b/types/generated-snapshot/index.ts @@ -3469,12 +3469,16 @@ export interface SqlStorage { } export declare abstract class SqlStorageStatement {} export type SqlStorageValue = ArrayBuffer | string | number | null; +export interface SqlStorageCursor< + T extends Record, +> extends Disposable {} export declare abstract class SqlStorageCursor< T extends Record, > { next(): IteratorResult; toArray(): T[]; one(): T; + close(): void; raw(): IterableIterator; columnNames: string[]; get rowsRead(): number;