@hulla/db 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +263 -2
- package/THIRD_PARTY_NOTICES.md +850 -0
- package/dist/aggregate.d.ts +63 -0
- package/dist/aggregate.js +147 -0
- package/dist/auth.d.ts +10 -0
- package/dist/auth.js +22 -0
- package/dist/bindings.d.ts +56 -0
- package/dist/bindings.js +277 -0
- package/dist/browser.d.ts +12 -0
- package/dist/browser.js +24 -0
- package/dist/callable.d.ts +48 -0
- package/dist/callable.js +142 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +65 -0
- package/dist/codec.d.ts +32 -0
- package/dist/codec.js +129 -0
- package/dist/codegen.d.ts +19 -0
- package/dist/codegen.js +275 -0
- package/dist/config.d.ts +70 -0
- package/dist/config.js +100 -0
- package/dist/contracts.d.ts +109 -0
- package/dist/contracts.js +1 -0
- package/dist/database-builder.d.ts +19 -0
- package/dist/database-builder.js +183 -0
- package/dist/database.d.ts +69 -0
- package/dist/database.js +128 -0
- package/dist/declarations.d.ts +91 -0
- package/dist/declarations.js +141 -0
- package/dist/dev-worker.d.ts +1 -0
- package/dist/dev-worker.js +47 -0
- package/dist/dev.d.ts +5 -0
- package/dist/dev.js +148 -0
- package/dist/error.d.ts +20 -0
- package/dist/error.js +82 -0
- package/dist/fields.d.ts +36 -0
- package/dist/fields.js +63 -0
- package/dist/filters.d.ts +93 -0
- package/dist/filters.js +220 -0
- package/dist/function-shapes.d.ts +7 -0
- package/dist/function-shapes.js +150 -0
- package/dist/handles.d.ts +27 -0
- package/dist/handles.js +387 -0
- package/dist/http/protocol.d.ts +64 -0
- package/dist/http/protocol.js +77 -0
- package/dist/http/sse.d.ts +7 -0
- package/dist/http/sse.js +70 -0
- package/dist/http.d.ts +44 -0
- package/dist/http.js +911 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +1 -0
- package/dist/internal/client.d.ts +6 -0
- package/dist/internal/client.js +5 -0
- package/dist/json-value.d.ts +21 -0
- package/dist/json-value.js +79 -0
- package/dist/names.d.ts +2 -0
- package/dist/names.js +10 -0
- package/dist/native.d.ts +3 -0
- package/dist/native.js +42 -0
- package/dist/notifications.d.ts +8 -0
- package/dist/notifications.js +70 -0
- package/dist/optimistic.d.ts +46 -0
- package/dist/optimistic.js +140 -0
- package/dist/page.d.ts +11 -0
- package/dist/page.js +1 -0
- package/dist/pagination.d.ts +17 -0
- package/dist/pagination.js +262 -0
- package/dist/project-codegen.d.ts +2 -0
- package/dist/project-codegen.js +68 -0
- package/dist/projection.d.ts +19 -0
- package/dist/projection.js +31 -0
- package/dist/runtime-conditions.d.ts +2 -0
- package/dist/runtime-conditions.js +10 -0
- package/dist/runtime.d.ts +13 -0
- package/dist/runtime.js +47 -0
- package/dist/schema-codegen.d.ts +16 -0
- package/dist/schema-codegen.js +212 -0
- package/dist/schema-contract.d.ts +4 -0
- package/dist/schema-contract.js +42 -0
- package/dist/schema.d.ts +356 -0
- package/dist/schema.js +720 -0
- package/dist/server-database.d.ts +14 -0
- package/dist/server-database.js +386 -0
- package/dist/server.d.ts +7 -0
- package/dist/server.js +1 -0
- package/dist/service.d.ts +13 -0
- package/dist/service.js +206 -0
- package/dist/sql-check.d.ts +28 -0
- package/dist/sql-check.js +59 -0
- package/dist/validation.d.ts +43 -0
- package/dist/validation.js +21 -0
- package/dist/worker-codegen.d.ts +3 -0
- package/dist/worker-codegen.js +44 -0
- package/dist/worker.d.ts +9 -0
- package/dist/worker.js +92 -0
- package/dist/write-expression.d.ts +72 -0
- package/dist/write-expression.js +122 -0
- package/dist/zod.d.ts +28 -0
- package/dist/zod.js +102 -0
- package/licenses/allocator-api2-0.2.21/LICENSE-APACHE +176 -0
- package/licenses/allocator-api2-0.2.21/LICENSE-MIT +23 -0
- package/licenses/async-trait-0.1.92/LICENSE-APACHE +176 -0
- package/licenses/async-trait-0.1.92/LICENSE-MIT +23 -0
- package/licenses/atomic-waker-1.1.2/LICENSE-APACHE +201 -0
- package/licenses/atomic-waker-1.1.2/LICENSE-MIT +23 -0
- package/licenses/atomic-waker-1.1.2/LICENSE-THIRD-PARTY +45 -0
- package/licenses/axum-0.8.9/LICENSE +25 -0
- package/licenses/axum-core-0.5.6/LICENSE +27 -0
- package/licenses/base64-0.22.1/LICENSE-APACHE +201 -0
- package/licenses/base64-0.22.1/LICENSE-MIT +21 -0
- package/licenses/bitflags-2.13.2/LICENSE-APACHE +201 -0
- package/licenses/bitflags-2.13.2/LICENSE-MIT +25 -0
- package/licenses/block-buffer-0.12.1/LICENSE-APACHE +201 -0
- package/licenses/block-buffer-0.12.1/LICENSE-MIT +25 -0
- package/licenses/byteorder-1.5.0/COPYING +3 -0
- package/licenses/byteorder-1.5.0/LICENSE-MIT +21 -0
- package/licenses/bytes-1.12.1/LICENSE +25 -0
- package/licenses/cc-1.6.0/LICENSE-APACHE +201 -0
- package/licenses/cc-1.6.0/LICENSE-MIT +25 -0
- package/licenses/cfg-if-1.0.5/LICENSE-APACHE +201 -0
- package/licenses/cfg-if-1.0.5/LICENSE-MIT +25 -0
- package/licenses/chacha20-0.10.2/LICENSE-APACHE +201 -0
- package/licenses/chacha20-0.10.2/LICENSE-MIT +25 -0
- package/licenses/cmov-0.5.4/LICENSE-APACHE +202 -0
- package/licenses/cmov-0.5.4/LICENSE-MIT +25 -0
- package/licenses/const-oid-0.10.2/LICENSE-APACHE +201 -0
- package/licenses/const-oid-0.10.2/LICENSE-MIT +25 -0
- package/licenses/const-oid-0.9.6/LICENSE-APACHE +201 -0
- package/licenses/const-oid-0.9.6/LICENSE-MIT +25 -0
- package/licenses/cpufeatures-0.3.1/LICENSE-APACHE +201 -0
- package/licenses/cpufeatures-0.3.1/LICENSE-MIT +25 -0
- package/licenses/crypto-common-0.2.2/LICENSE-APACHE +201 -0
- package/licenses/crypto-common-0.2.2/LICENSE-MIT +25 -0
- package/licenses/ctutils-0.4.2/LICENSE-APACHE +202 -0
- package/licenses/ctutils-0.4.2/LICENSE-MIT +25 -0
- package/licenses/der-0.7.10/LICENSE-APACHE +201 -0
- package/licenses/der-0.7.10/LICENSE-MIT +25 -0
- package/licenses/der_derive-0.7.3/LICENSE-APACHE +201 -0
- package/licenses/der_derive-0.7.3/LICENSE-MIT +25 -0
- package/licenses/deranged-0.5.8/LICENSE-Apache +202 -0
- package/licenses/deranged-0.5.8/LICENSE-MIT +19 -0
- package/licenses/digest-0.11.3/LICENSE-APACHE +201 -0
- package/licenses/digest-0.11.3/LICENSE-MIT +26 -0
- package/licenses/equivalent-1.0.3/LICENSE-APACHE +201 -0
- package/licenses/equivalent-1.0.3/LICENSE-MIT +25 -0
- package/licenses/errno-0.3.14/LICENSE-APACHE +201 -0
- package/licenses/errno-0.3.14/LICENSE-MIT +25 -0
- package/licenses/fallible-iterator-0.2.0/LICENSE-APACHE +202 -0
- package/licenses/fallible-iterator-0.2.0/LICENSE-MIT +19 -0
- package/licenses/find-msvc-tools-0.1.14/LICENSE-APACHE +201 -0
- package/licenses/find-msvc-tools-0.1.14/LICENSE-MIT +25 -0
- package/licenses/flagset-0.4.7/LICENSE +202 -0
- package/licenses/foldhash-0.2.0/LICENSE +19 -0
- package/licenses/futures-channel-0.3.34/LICENSE-APACHE +202 -0
- package/licenses/futures-channel-0.3.34/LICENSE-MIT +26 -0
- package/licenses/futures-core-0.3.34/LICENSE-APACHE +202 -0
- package/licenses/futures-core-0.3.34/LICENSE-MIT +26 -0
- package/licenses/futures-sink-0.3.34/LICENSE-APACHE +202 -0
- package/licenses/futures-sink-0.3.34/LICENSE-MIT +26 -0
- package/licenses/futures-task-0.3.34/LICENSE-APACHE +202 -0
- package/licenses/futures-task-0.3.34/LICENSE-MIT +26 -0
- package/licenses/futures-util-0.3.34/LICENSE-APACHE +202 -0
- package/licenses/futures-util-0.3.34/LICENSE-MIT +26 -0
- package/licenses/getrandom-0.2.17/LICENSE-APACHE +201 -0
- package/licenses/getrandom-0.2.17/LICENSE-MIT +26 -0
- package/licenses/getrandom-0.4.3/LICENSE-APACHE +201 -0
- package/licenses/getrandom-0.4.3/LICENSE-MIT +26 -0
- package/licenses/hashbrown-0.17.1/LICENSE-APACHE +201 -0
- package/licenses/hashbrown-0.17.1/LICENSE-MIT +25 -0
- package/licenses/hmac-0.13.0/LICENSE-APACHE +201 -0
- package/licenses/hmac-0.13.0/LICENSE-MIT +25 -0
- package/licenses/http-1.5.0/LICENSE-APACHE +201 -0
- package/licenses/http-1.5.0/LICENSE-MIT +25 -0
- package/licenses/http-body-1.1.0/LICENSE +25 -0
- package/licenses/http-body-util-0.1.5/LICENSE +25 -0
- package/licenses/httparse-1.10.1/LICENSE-APACHE +201 -0
- package/licenses/httparse-1.10.1/LICENSE-MIT +20 -0
- package/licenses/httpdate-1.0.3/LICENSE-APACHE +201 -0
- package/licenses/httpdate-1.0.3/LICENSE-MIT +19 -0
- package/licenses/hybrid-array-0.4.15/LICENSE-APACHE +201 -0
- package/licenses/hybrid-array-0.4.15/LICENSE-MIT +25 -0
- package/licenses/hyper-1.11.1/LICENSE +19 -0
- package/licenses/hyper-util-0.1.21/LICENSE +19 -0
- package/licenses/itoa-1.0.18/LICENSE-APACHE +176 -0
- package/licenses/itoa-1.0.18/LICENSE-MIT +23 -0
- package/licenses/libc-0.2.189/LICENSE-APACHE +176 -0
- package/licenses/libc-0.2.189/LICENSE-MIT +25 -0
- package/licenses/lock_api-0.4.14/LICENSE-APACHE +201 -0
- package/licenses/lock_api-0.4.14/LICENSE-MIT +25 -0
- package/licenses/log-0.4.34/LICENSE-APACHE +201 -0
- package/licenses/log-0.4.34/LICENSE-MIT +25 -0
- package/licenses/matchit-0.8.4/LICENSE +21 -0
- package/licenses/matchit-0.8.4/LICENSE.httprouter +29 -0
- package/licenses/md-5-0.11.0/LICENSE-APACHE +201 -0
- package/licenses/md-5-0.11.0/LICENSE-MIT +28 -0
- package/licenses/memchr-2.8.3/COPYING +3 -0
- package/licenses/memchr-2.8.3/LICENSE-MIT +21 -0
- package/licenses/mime-0.3.17/LICENSE-APACHE +201 -0
- package/licenses/mime-0.3.17/LICENSE-MIT +20 -0
- package/licenses/mio-1.2.3/LICENSE +19 -0
- package/licenses/num-conv-0.2.2/LICENSE-Apache +177 -0
- package/licenses/num-conv-0.2.2/LICENSE-MIT +19 -0
- package/licenses/objc2-core-foundation-0.3.2/LICENSE.md +34 -0
- package/licenses/objc2-system-configuration-0.3.2/LICENSE.md +34 -0
- package/licenses/once_cell-1.21.4/LICENSE-APACHE +201 -0
- package/licenses/once_cell-1.21.4/LICENSE-MIT +23 -0
- package/licenses/parking_lot-0.12.5/LICENSE-APACHE +201 -0
- package/licenses/parking_lot-0.12.5/LICENSE-MIT +25 -0
- package/licenses/parking_lot_core-0.9.12/LICENSE-APACHE +201 -0
- package/licenses/parking_lot_core-0.9.12/LICENSE-MIT +25 -0
- package/licenses/percent-encoding-2.3.2/LICENSE-APACHE +201 -0
- package/licenses/percent-encoding-2.3.2/LICENSE-MIT +25 -0
- package/licenses/phf-0.13.1/LICENSE +20 -0
- package/licenses/phf_shared-0.13.1/LICENSE +20 -0
- package/licenses/pin-project-lite-0.2.17/LICENSE-APACHE +177 -0
- package/licenses/pin-project-lite-0.2.17/LICENSE-MIT +23 -0
- package/licenses/postgres-protocol-0.6.12/LICENSE-APACHE +201 -0
- package/licenses/postgres-protocol-0.6.12/LICENSE-MIT +22 -0
- package/licenses/postgres-types-0.2.14/LICENSE-APACHE +201 -0
- package/licenses/postgres-types-0.2.14/LICENSE-MIT +22 -0
- package/licenses/powerfmt-0.2.1/LICENSE-Apache +202 -0
- package/licenses/powerfmt-0.2.1/LICENSE-MIT +19 -0
- package/licenses/proc-macro2-1.0.107/LICENSE-APACHE +176 -0
- package/licenses/proc-macro2-1.0.107/LICENSE-MIT +23 -0
- package/licenses/quote-1.0.47/LICENSE-APACHE +176 -0
- package/licenses/quote-1.0.47/LICENSE-MIT +23 -0
- package/licenses/rand-0.10.3/COPYRIGHT +12 -0
- package/licenses/rand-0.10.3/LICENSE-APACHE +176 -0
- package/licenses/rand-0.10.3/LICENSE-MIT +26 -0
- package/licenses/rand_core-0.10.1/COPYRIGHT +9 -0
- package/licenses/rand_core-0.10.1/LICENSE-APACHE +187 -0
- package/licenses/rand_core-0.10.1/LICENSE-MIT +25 -0
- package/licenses/ring-0.17.14/LICENSE +9 -0
- package/licenses/ring-0.17.14/LICENSE-BoringSSL +272 -0
- package/licenses/ring-0.17.14/LICENSE-other-bits +13 -0
- package/licenses/ring-0.17.14/src/polyfill/once_cell/LICENSE-APACHE +201 -0
- package/licenses/ring-0.17.14/src/polyfill/once_cell/LICENSE-MIT +23 -0
- package/licenses/ring-0.17.14/third_party/fiat/LICENSE +15 -0
- package/licenses/rquickjs-0.14.0/LICENSE +22 -0
- package/licenses/rquickjs-core-0.14.0/LICENSE +22 -0
- package/licenses/rquickjs-sys-0.14.0/quickjs/LICENSE +24 -0
- package/licenses/rquickjs-sys-0.14.0/vendor/wasi-libc/NOTICE.md +26 -0
- package/licenses/rustls-0.23.46/LICENSE-APACHE +201 -0
- package/licenses/rustls-0.23.46/LICENSE-ISC +15 -0
- package/licenses/rustls-0.23.46/LICENSE-MIT +25 -0
- package/licenses/rustls-pki-types-1.15.1/LICENSE-APACHE +201 -0
- package/licenses/rustls-pki-types-1.15.1/LICENSE-MIT +25 -0
- package/licenses/rustls-webpki-0.103.15/LICENSE +19 -0
- package/licenses/scopeguard-1.2.0/LICENSE-APACHE +201 -0
- package/licenses/scopeguard-1.2.0/LICENSE-MIT +25 -0
- package/licenses/serde-1.0.229/LICENSE-APACHE +176 -0
- package/licenses/serde-1.0.229/LICENSE-MIT +23 -0
- package/licenses/serde_core-1.0.229/LICENSE-APACHE +176 -0
- package/licenses/serde_core-1.0.229/LICENSE-MIT +23 -0
- package/licenses/serde_derive-1.0.229/LICENSE-APACHE +176 -0
- package/licenses/serde_derive-1.0.229/LICENSE-MIT +23 -0
- package/licenses/serde_json-1.0.151/LICENSE-APACHE +176 -0
- package/licenses/serde_json-1.0.151/LICENSE-MIT +23 -0
- package/licenses/serde_path_to_error-0.1.20/LICENSE-APACHE +176 -0
- package/licenses/serde_path_to_error-0.1.20/LICENSE-MIT +23 -0
- package/licenses/sha2-0.11.0/LICENSE-APACHE +201 -0
- package/licenses/sha2-0.11.0/LICENSE-MIT +28 -0
- package/licenses/shlex-2.0.1/LICENSE-APACHE +13 -0
- package/licenses/shlex-2.0.1/LICENSE-MIT +21 -0
- package/licenses/signal-hook-registry-1.4.8/LICENSE-APACHE +201 -0
- package/licenses/signal-hook-registry-1.4.8/LICENSE-MIT +25 -0
- package/licenses/siphasher-1.0.4/COPYING +7 -0
- package/licenses/siphasher-1.0.4/LICENSE-APACHE +202 -0
- package/licenses/siphasher-1.0.4/LICENSE-MIT +17 -0
- package/licenses/slab-0.4.12/LICENSE +25 -0
- package/licenses/smallvec-1.16.2/LICENSE-APACHE +201 -0
- package/licenses/smallvec-1.16.2/LICENSE-MIT +25 -0
- package/licenses/socket2-0.6.5/LICENSE-APACHE +201 -0
- package/licenses/socket2-0.6.5/LICENSE-MIT +25 -0
- package/licenses/spki-0.7.3/LICENSE-APACHE +201 -0
- package/licenses/spki-0.7.3/LICENSE-MIT +25 -0
- package/licenses/stringprep-0.1.5/LICENSE-APACHE +202 -0
- package/licenses/stringprep-0.1.5/LICENSE-MIT +19 -0
- package/licenses/subtle-2.6.1/LICENSE +29 -0
- package/licenses/syn-2.0.119/LICENSE-APACHE +176 -0
- package/licenses/syn-2.0.119/LICENSE-MIT +23 -0
- package/licenses/syn-3.0.6/LICENSE-APACHE +176 -0
- package/licenses/syn-3.0.6/LICENSE-MIT +23 -0
- package/licenses/sync_wrapper-1.0.2/LICENSE +177 -0
- package/licenses/time-0.3.55/LICENSE-Apache +177 -0
- package/licenses/time-0.3.55/LICENSE-MIT +19 -0
- package/licenses/time-core-0.1.9/LICENSE-Apache +177 -0
- package/licenses/time-core-0.1.9/LICENSE-MIT +19 -0
- package/licenses/time-macros-0.2.32/LICENSE-Apache +177 -0
- package/licenses/time-macros-0.2.32/LICENSE-MIT +19 -0
- package/licenses/tinyvec-1.13.3/LICENSE-APACHE.md +202 -0
- package/licenses/tinyvec-1.13.3/LICENSE-MIT.md +5 -0
- package/licenses/tinyvec-1.13.3/LICENSE-ZLIB.md +11 -0
- package/licenses/tokio-1.53.1/LICENSE +21 -0
- package/licenses/tokio-macros-2.7.2/LICENSE +22 -0
- package/licenses/tokio-postgres-0.7.18/LICENSE-APACHE +201 -0
- package/licenses/tokio-postgres-0.7.18/LICENSE-MIT +22 -0
- package/licenses/tokio-postgres-rustls-0.14.0/LICENSE +21 -0
- package/licenses/tokio-rustls-0.26.6/LICENSE-APACHE +201 -0
- package/licenses/tokio-rustls-0.26.6/LICENSE-MIT +25 -0
- package/licenses/tokio-util-0.7.19/LICENSE +21 -0
- package/licenses/tower-0.5.3/LICENSE +25 -0
- package/licenses/tower-layer-0.3.3/LICENSE +25 -0
- package/licenses/tower-service-0.3.3/LICENSE +25 -0
- package/licenses/typenum-1.20.1/LICENSE +1 -0
- package/licenses/typenum-1.20.1/LICENSE-APACHE +201 -0
- package/licenses/typenum-1.20.1/LICENSE-MIT +21 -0
- package/licenses/unicode-bidi-0.3.18/COPYRIGHT +8 -0
- package/licenses/unicode-bidi-0.3.18/LICENSE-APACHE +201 -0
- package/licenses/unicode-bidi-0.3.18/LICENSE-MIT +25 -0
- package/licenses/unicode-ident-1.0.26/LICENSE-APACHE +176 -0
- package/licenses/unicode-ident-1.0.26/LICENSE-MIT +23 -0
- package/licenses/unicode-ident-1.0.26/LICENSE-UNICODE +39 -0
- package/licenses/unicode-normalization-0.1.25/COPYRIGHT +7 -0
- package/licenses/unicode-normalization-0.1.25/LICENSE-APACHE +201 -0
- package/licenses/unicode-normalization-0.1.25/LICENSE-MIT +25 -0
- package/licenses/unicode-properties-0.1.4/COPYRIGHT +7 -0
- package/licenses/unicode-properties-0.1.4/LICENSE-APACHE +201 -0
- package/licenses/unicode-properties-0.1.4/LICENSE-MIT +25 -0
- package/licenses/untrusted-0.9.0/LICENSE.txt +13 -0
- package/licenses/uuid-1.26.1/LICENSE-APACHE +201 -0
- package/licenses/uuid-1.26.1/LICENSE-MIT +26 -0
- package/licenses/webpki-roots-1.0.9/LICENSE +61 -0
- package/licenses/whoami-2.1.3/LICENSE_APACHE +176 -0
- package/licenses/whoami-2.1.3/LICENSE_BOOST +23 -0
- package/licenses/whoami-2.1.3/LICENSE_MIT +19 -0
- package/licenses/x509-cert-0.2.5/LICENSE-APACHE +201 -0
- package/licenses/x509-cert-0.2.5/LICENSE-MIT +25 -0
- package/licenses/zeroize-1.9.1/LICENSE-APACHE +202 -0
- package/licenses/zeroize-1.9.1/LICENSE-MIT +25 -0
- package/licenses/zmij-1.0.23/LICENSE-MIT +23 -0
- package/native/darwin-arm64/hulladb-bridge +0 -0
- package/native/darwin-arm64/hulladb-js +0 -0
- package/native/darwin-arm64/hulladb-service +0 -0
- package/native/linux-x64/hulladb-bridge +0 -0
- package/native/linux-x64/hulladb-js +0 -0
- package/native/linux-x64/hulladb-service +0 -0
- package/package.json +90 -4
package/dist/http.js
ADDED
|
@@ -0,0 +1,911 @@
|
|
|
1
|
+
import { batchNotifications, notifyObserver } from "./notifications.js";
|
|
2
|
+
import { DatabaseError, isApplicationError } from "./error.js";
|
|
3
|
+
import { operationKey, parseError, parseSession, parseHead, parseReceipt, parseSnapshot, parsePage, record, sequence, uuid, } from "./http/protocol.js";
|
|
4
|
+
import { OptimisticResults } from "./optimistic.js";
|
|
5
|
+
import { sseEvents } from "./http/sse.js";
|
|
6
|
+
import { authState, isAuthPromise, sameAuth } from "./auth.js";
|
|
7
|
+
const statuses = { unauthorized: 401, forbidden: 403, invalid_request: 400, execution_limit: 422, execution_failed: 422, row_expectation_failed: 422, quota_exceeded: 422, ticket_expired: 410, not_found: 404, conflict: 409, request_id_reused: 409, receipt_expired: 410, capacity: 429, unavailable: 503, reset_required: 409, outcome_unknown: 503 };
|
|
8
|
+
class TransportFailure extends Error {
|
|
9
|
+
constructor(cause) { super("Database transport interrupted", { cause }); }
|
|
10
|
+
}
|
|
11
|
+
function transient(error) { return !(error instanceof DatabaseError) || (!isApplicationError(error) && ["unavailable", "capacity", "outcome_unknown"].includes(error.code)); }
|
|
12
|
+
function copy(value) { return structuredClone(value); }
|
|
13
|
+
function budget(value, fallback) {
|
|
14
|
+
value ??= fallback;
|
|
15
|
+
if (!Number.isSafeInteger(value) || value < 1 || value > 2_147_483_647)
|
|
16
|
+
throw new TypeError("Invalid runtime budget");
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
function pause(ms, signal) {
|
|
20
|
+
return new Promise((resolve, reject) => {
|
|
21
|
+
signal.throwIfAborted();
|
|
22
|
+
const aborted = () => { clearTimeout(timer); reject(signal.reason); };
|
|
23
|
+
const timer = setTimeout(() => { signal.removeEventListener("abort", aborted); resolve(); }, ms);
|
|
24
|
+
signal.addEventListener("abort", aborted, { once: true });
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
function abortable(promise, signal) {
|
|
28
|
+
if (!signal)
|
|
29
|
+
return promise;
|
|
30
|
+
return new Promise((resolve, reject) => {
|
|
31
|
+
const abort = () => reject(signal.reason);
|
|
32
|
+
if (signal.aborted) {
|
|
33
|
+
void promise.catch(() => { });
|
|
34
|
+
reject(signal.reason);
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
38
|
+
void promise.then(value => { signal.removeEventListener("abort", abort); resolve(value); }, error => { signal.removeEventListener("abort", abort); reject(error); });
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
/** Generated function runtime. One owner coordinates in-memory exact-query subscriptions and receipt confirmation. */
|
|
42
|
+
export class HttpRuntime {
|
|
43
|
+
#baseUrl;
|
|
44
|
+
#options;
|
|
45
|
+
#fetch;
|
|
46
|
+
#timeout;
|
|
47
|
+
#queryTimeout;
|
|
48
|
+
#idleTimeout;
|
|
49
|
+
#maxBytes;
|
|
50
|
+
#reconnect;
|
|
51
|
+
#confirmationTimeout;
|
|
52
|
+
#optimism;
|
|
53
|
+
#auth = null;
|
|
54
|
+
#authPending = false;
|
|
55
|
+
#authFailure;
|
|
56
|
+
#authUpdate = 0;
|
|
57
|
+
#authTimer;
|
|
58
|
+
#disposed = false;
|
|
59
|
+
#epoch = 0;
|
|
60
|
+
#lifetime = new AbortController();
|
|
61
|
+
#source;
|
|
62
|
+
#handshake;
|
|
63
|
+
#session;
|
|
64
|
+
#renewTimer;
|
|
65
|
+
#pending = new Map();
|
|
66
|
+
#watches = new Map();
|
|
67
|
+
#results = new Map();
|
|
68
|
+
#calls = new Set();
|
|
69
|
+
#idleResults = new Map();
|
|
70
|
+
#cacheTimer;
|
|
71
|
+
#streamGeneration = 0;
|
|
72
|
+
#liveRevision = -1n;
|
|
73
|
+
#streamController;
|
|
74
|
+
#rebuildQueued = false;
|
|
75
|
+
constructor(options) {
|
|
76
|
+
const url = new URL(options.baseUrl);
|
|
77
|
+
if (url.username || url.password || url.search || url.hash || !(url.protocol === "https:" || (url.protocol === "http:" && ["127.0.0.1", "[::1]", "localhost"].includes(url.hostname))))
|
|
78
|
+
throw new TypeError("Use HTTPS or loopback HTTP without URL credentials");
|
|
79
|
+
this.#baseUrl = url.href.replace(/\/$/, "");
|
|
80
|
+
this.#options = { ...options, contracts: Object.freeze({ ...options.contracts }) };
|
|
81
|
+
this.#optimism = new OptimisticResults(query => {
|
|
82
|
+
const operation = this.#operation({ name: query.name, kind: "query", input: query.input });
|
|
83
|
+
return { key: operationKey(operation), operation };
|
|
84
|
+
}, options.maxOptimisticLayers);
|
|
85
|
+
// Browser fetch checks its receiver; calling it as a runtime method is invalid.
|
|
86
|
+
this.#fetch = (options.fetch ?? globalThis.fetch).bind(globalThis);
|
|
87
|
+
this.#timeout = budget(options.operationTimeoutMs, 10_000);
|
|
88
|
+
this.#queryTimeout = budget(options.queryTimeoutMs, 30_000);
|
|
89
|
+
this.#idleTimeout = budget(options.streamIdleTimeoutMs, 30_000);
|
|
90
|
+
this.#maxBytes = budget(options.maxResponseBytes, 16 * 1024 * 1024 + 64 * 1024);
|
|
91
|
+
this.#reconnect = budget(options.reconnectDelayMs, 250);
|
|
92
|
+
this.#confirmationTimeout = budget(options.confirmationTimeoutMs, 30_000);
|
|
93
|
+
this.setAuth(options.auth ?? null);
|
|
94
|
+
}
|
|
95
|
+
get identityEpoch() { this.#expireAuth(); return this.#epoch; }
|
|
96
|
+
get identitySignal() { this.#expireAuth(); return this.#lifetime.signal; }
|
|
97
|
+
get clientAuth() {
|
|
98
|
+
this.#expireAuth();
|
|
99
|
+
return { key: this.#auth?.key ?? null, pending: this.#authPending,
|
|
100
|
+
...(this.#authFailure ? { error: this.#authFailure } : {}) };
|
|
101
|
+
}
|
|
102
|
+
#expireAuth() {
|
|
103
|
+
if (!this.#disposed && this.#auth !== null
|
|
104
|
+
&& this.#auth.expiresAt !== undefined && this.#auth.expiresAt <= Date.now()) {
|
|
105
|
+
clearTimeout(this.#authTimer);
|
|
106
|
+
this.#authTimer = undefined;
|
|
107
|
+
this.#auth = null;
|
|
108
|
+
this.#retire(new DatabaseError({ code: "context_changed", message: "Function auth scope expired" }));
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
111
|
+
return false;
|
|
112
|
+
}
|
|
113
|
+
#scheduleAuthExpiry() {
|
|
114
|
+
clearTimeout(this.#authTimer);
|
|
115
|
+
this.#authTimer = undefined;
|
|
116
|
+
if (this.#expireAuth())
|
|
117
|
+
return;
|
|
118
|
+
if (this.#disposed || this.#auth === null || this.#auth.expiresAt === undefined)
|
|
119
|
+
return;
|
|
120
|
+
// Long deadlines must not overflow setTimeout. Recheck the wall clock when
|
|
121
|
+
// waking; access checks also fence results after a suspended browser resumes.
|
|
122
|
+
this.#authTimer = setTimeout(() => this.#scheduleAuthExpiry(), Math.min(Math.max(1, this.#auth.expiresAt - Date.now()), 2_147_483_647));
|
|
123
|
+
this.#authTimer.unref?.();
|
|
124
|
+
}
|
|
125
|
+
#check(epoch) {
|
|
126
|
+
this.#expireAuth();
|
|
127
|
+
if (this.#disposed)
|
|
128
|
+
throw new DatabaseError({ code: "disposed", message: "Function runtime disposed" });
|
|
129
|
+
if (epoch !== this.#epoch || this.#lifetime.signal.aborted)
|
|
130
|
+
throw new DatabaseError({ code: "context_changed", message: "Function auth scope retired" });
|
|
131
|
+
if (this.#authPending)
|
|
132
|
+
throw new DatabaseError({ code: "authentication_pending", message: "Authentication is still loading" });
|
|
133
|
+
if (this.#authFailure)
|
|
134
|
+
throw this.#authFailure;
|
|
135
|
+
}
|
|
136
|
+
#contract(operation) {
|
|
137
|
+
const contract = Object.hasOwn(this.#options.contracts, operation.name) ? this.#options.contracts[operation.name] : undefined;
|
|
138
|
+
if (!contract || contract.kind !== operation.kind)
|
|
139
|
+
throw new TypeError("Unknown function or execution kind");
|
|
140
|
+
return contract;
|
|
141
|
+
}
|
|
142
|
+
#operation(operation) {
|
|
143
|
+
const codecs = this.#contract(operation);
|
|
144
|
+
return { name: operation.name, kind: operation.kind, input: codecs.input.parse(operation.input), codecs, ...(operation.page ? { page: operation.page } : {}) };
|
|
145
|
+
}
|
|
146
|
+
#snapshot(value, session, source) {
|
|
147
|
+
const snapshot = parseSnapshot(value);
|
|
148
|
+
if (snapshot.scope !== session.scope || snapshot.principal !== session.principal || snapshot.authorization_scope !== session.authorizationScope)
|
|
149
|
+
throw new DatabaseError({ code: "reset_required", message: "Response identity does not match the active session" });
|
|
150
|
+
if (source && source !== snapshot.source)
|
|
151
|
+
throw new DatabaseError({ code: "reset_required", message: "reset_required" });
|
|
152
|
+
return snapshot;
|
|
153
|
+
}
|
|
154
|
+
async #headers(session, signal, accept) {
|
|
155
|
+
this.#expireAuth();
|
|
156
|
+
signal.throwIfAborted();
|
|
157
|
+
const configured = this.#options.headers;
|
|
158
|
+
const value = typeof configured === "function" ? await abortable(Promise.resolve(configured()), signal) : configured;
|
|
159
|
+
this.#expireAuth();
|
|
160
|
+
signal.throwIfAborted();
|
|
161
|
+
const headers = new Headers(value);
|
|
162
|
+
// Identity pins come exclusively from the verified server handshake.
|
|
163
|
+
for (const key of [...headers.keys()])
|
|
164
|
+
if (key.startsWith("x-hulladb-"))
|
|
165
|
+
headers.delete(key);
|
|
166
|
+
headers.set("content-type", "application/json");
|
|
167
|
+
headers.set("accept", accept);
|
|
168
|
+
headers.delete("last-event-id");
|
|
169
|
+
if (session) {
|
|
170
|
+
headers.set("x-hulladb-scope", session.scope);
|
|
171
|
+
headers.set("x-hulladb-principal", session.principal);
|
|
172
|
+
headers.set("x-hulladb-authorization-scope", session.authorizationScope);
|
|
173
|
+
}
|
|
174
|
+
return headers;
|
|
175
|
+
}
|
|
176
|
+
async #json(path, body, session, signal) {
|
|
177
|
+
const deadline = new AbortController();
|
|
178
|
+
const timer = setTimeout(() => deadline.abort(new Error("Database request timed out")), this.#timeout);
|
|
179
|
+
const combined = AbortSignal.any([signal, deadline.signal]);
|
|
180
|
+
try {
|
|
181
|
+
const headers = await this.#headers(session, combined, "application/json");
|
|
182
|
+
combined.throwIfAborted();
|
|
183
|
+
const request = this.#fetch(this.#baseUrl + path, {
|
|
184
|
+
method: body === undefined ? "GET" : "POST", redirect: "error", credentials: this.#options.credentials ?? "same-origin", signal: combined,
|
|
185
|
+
headers,
|
|
186
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
187
|
+
}).catch(error => { throw new TransportFailure(error); });
|
|
188
|
+
void request.then(response => { if (combined.aborted)
|
|
189
|
+
void response.body?.cancel().catch(() => { }); }, () => { });
|
|
190
|
+
const response = await abortable(request, combined);
|
|
191
|
+
return await this.#readResponse(response, combined);
|
|
192
|
+
}
|
|
193
|
+
catch (error) {
|
|
194
|
+
if (signal.aborted)
|
|
195
|
+
throw signal.reason;
|
|
196
|
+
if (deadline.signal.aborted)
|
|
197
|
+
throw new TransportFailure(error);
|
|
198
|
+
throw error;
|
|
199
|
+
}
|
|
200
|
+
finally {
|
|
201
|
+
clearTimeout(timer);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
async #readResponse(response, signal) {
|
|
205
|
+
if (response.headers.get("content-type")?.split(";")[0] !== "application/json" || !response.body) {
|
|
206
|
+
void response.body?.cancel().catch(() => { });
|
|
207
|
+
throw new TypeError("Invalid JSON response");
|
|
208
|
+
}
|
|
209
|
+
const reader = response.body.getReader();
|
|
210
|
+
let bytes = 0;
|
|
211
|
+
const chunks = [];
|
|
212
|
+
try {
|
|
213
|
+
while (true) {
|
|
214
|
+
const chunk = await abortable(reader.read().catch(error => { throw new TransportFailure(error); }), signal);
|
|
215
|
+
if (chunk.done)
|
|
216
|
+
break;
|
|
217
|
+
bytes += chunk.value.byteLength;
|
|
218
|
+
if (bytes > this.#maxBytes)
|
|
219
|
+
throw new TypeError("Response exceeds budget");
|
|
220
|
+
chunks.push(chunk.value);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
finally {
|
|
224
|
+
void reader.cancel().catch(() => { });
|
|
225
|
+
reader.releaseLock();
|
|
226
|
+
}
|
|
227
|
+
const joined = new Uint8Array(bytes);
|
|
228
|
+
let offset = 0;
|
|
229
|
+
for (const chunk of chunks) {
|
|
230
|
+
joined.set(chunk, offset);
|
|
231
|
+
offset += chunk.length;
|
|
232
|
+
}
|
|
233
|
+
const parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(joined));
|
|
234
|
+
if (!response.ok) {
|
|
235
|
+
const error = parseError(parsed);
|
|
236
|
+
if ((isApplicationError(error) ? 422 : statuses[error.code]) !== response.status && !(!isApplicationError(error) && error.code === "invalid_request" && [413, 415, 422].includes(response.status)))
|
|
237
|
+
throw new TypeError("Error status does not match its contract");
|
|
238
|
+
throw error;
|
|
239
|
+
}
|
|
240
|
+
return parsed;
|
|
241
|
+
}
|
|
242
|
+
async #ensure(epoch) {
|
|
243
|
+
this.#check(epoch);
|
|
244
|
+
if (this.#session && this.#session.expiresAt > Date.now()) {
|
|
245
|
+
this.#scheduleRenewal(epoch);
|
|
246
|
+
return this.#session;
|
|
247
|
+
}
|
|
248
|
+
const session = await this.#renew(epoch);
|
|
249
|
+
this.#scheduleRenewal(epoch);
|
|
250
|
+
return session;
|
|
251
|
+
}
|
|
252
|
+
#scheduleRenewal(epoch) {
|
|
253
|
+
clearTimeout(this.#renewTimer);
|
|
254
|
+
if (!this.#session)
|
|
255
|
+
return;
|
|
256
|
+
this.#renewTimer = setTimeout(() => {
|
|
257
|
+
this.#renewTimer = undefined;
|
|
258
|
+
void this.#renew(epoch).then(() => {
|
|
259
|
+
if (epoch === this.#epoch && (this.#calls.size || this.#watches.size))
|
|
260
|
+
this.#scheduleRenewal(epoch);
|
|
261
|
+
}).catch(error => {
|
|
262
|
+
if (error instanceof DatabaseError && !isApplicationError(error) && ["unauthorized", "forbidden", "reset_required"].includes(error.code))
|
|
263
|
+
void this.#invalidate(error, epoch);
|
|
264
|
+
});
|
|
265
|
+
}, Math.min(Math.max(1, this.#session.renewAfter - Date.now()), 2_147_483_647));
|
|
266
|
+
this.#renewTimer.unref?.();
|
|
267
|
+
}
|
|
268
|
+
async #renew(epoch) {
|
|
269
|
+
this.#check(epoch);
|
|
270
|
+
if (!this.#handshake) {
|
|
271
|
+
const previous = this.#session;
|
|
272
|
+
// Measure validity conservatively from request start, including network time.
|
|
273
|
+
const started = Date.now();
|
|
274
|
+
this.#handshake = (async () => {
|
|
275
|
+
const head = parseSession(await this.#json("/functions/session", undefined, previous, this.#lifetime.signal));
|
|
276
|
+
this.#check(epoch);
|
|
277
|
+
if ((this.#source && this.#source !== head.source) || (previous && (previous.scope !== head.scope
|
|
278
|
+
|| previous.principal !== head.principal || previous.authorizationScope !== head.authorization_scope)))
|
|
279
|
+
throw new DatabaseError({ code: "reset_required", message: "Session renewal changed the verified scope" });
|
|
280
|
+
const session = { source: head.source, scope: head.scope, principal: head.principal, authorizationScope: head.authorization_scope,
|
|
281
|
+
ticket: head.ticket.id, expiresAt: started + head.ticket.expires_in_ms, renewAfter: started + head.ticket.renew_after_ms };
|
|
282
|
+
if (session.expiresAt <= Date.now())
|
|
283
|
+
throw new DatabaseError({ code: "unavailable", message: "Session ticket expired during setup" });
|
|
284
|
+
this.#source = head.source;
|
|
285
|
+
this.#session = session;
|
|
286
|
+
return session;
|
|
287
|
+
})().finally(() => { if (epoch === this.#epoch)
|
|
288
|
+
this.#handshake = undefined; });
|
|
289
|
+
}
|
|
290
|
+
const session = await this.#handshake;
|
|
291
|
+
return session;
|
|
292
|
+
}
|
|
293
|
+
#publish(watch, state) {
|
|
294
|
+
if (state.status === "success") {
|
|
295
|
+
const rendered = this.#optimism.view(operationKey(watch.operation));
|
|
296
|
+
state = { ...state, ...(rendered ?? { isOptimistic: false }) };
|
|
297
|
+
}
|
|
298
|
+
watch.state = state;
|
|
299
|
+
for (const observer of [...watch.observers]) {
|
|
300
|
+
if (watch.state !== state)
|
|
301
|
+
break;
|
|
302
|
+
// An observer exception cannot break receipt recovery or another observer.
|
|
303
|
+
notifyObserver(observer, () => {
|
|
304
|
+
if (watch.state !== state || !watch.observers.has(observer))
|
|
305
|
+
return;
|
|
306
|
+
try {
|
|
307
|
+
observer(state.status === "success" ? { ...state, data: copy(state.data) } : state);
|
|
308
|
+
}
|
|
309
|
+
catch { /* application observer */ }
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
#refreshPredictions() {
|
|
314
|
+
batchNotifications(() => { for (const watch of this.#watches.values())
|
|
315
|
+
if (watch.state.status === "success")
|
|
316
|
+
this.#publish(watch, watch.state); });
|
|
317
|
+
}
|
|
318
|
+
async #correlate(snapshot, session, epoch, signal) {
|
|
319
|
+
// A frame can arrive before its acknowledgement. Receipt lookup after the
|
|
320
|
+
// snapshot either proves absence or supplies the fence for safe rebasing.
|
|
321
|
+
for (const prediction of this.#optimism.unconfirmed()) {
|
|
322
|
+
const pending = this.#pending.get(prediction.requestId);
|
|
323
|
+
if (!pending)
|
|
324
|
+
continue;
|
|
325
|
+
let receipt = pending.receipt;
|
|
326
|
+
if (!receipt) {
|
|
327
|
+
try {
|
|
328
|
+
const raw = await this.#json(`/functions/receipts/${pending.requestId}?source=${pending.source}&ticket=${pending.ticket}`, undefined, session, signal);
|
|
329
|
+
this.#check(epoch);
|
|
330
|
+
receipt = pending.receipt ?? (raw === null ? undefined : parseReceipt(raw, pending.requestId, session, snapshot.source));
|
|
331
|
+
}
|
|
332
|
+
catch (error) {
|
|
333
|
+
this.#check(epoch);
|
|
334
|
+
// ACK can compact the remote payload while this lookup is in flight.
|
|
335
|
+
// The delivered local receipt remains sufficient for its optimistic fence.
|
|
336
|
+
if (pending.receipt && error instanceof DatabaseError && !isApplicationError(error) && error.code === "receipt_expired")
|
|
337
|
+
receipt = pending.receipt;
|
|
338
|
+
else if (error instanceof DatabaseError && !isApplicationError(error) && ["execution_failed", "quota_exceeded", "ticket_expired", "receipt_expired"].includes(error.code)) {
|
|
339
|
+
this.#optimism.reject(pending.requestId);
|
|
340
|
+
continue;
|
|
341
|
+
}
|
|
342
|
+
else
|
|
343
|
+
throw error;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
if (!receipt)
|
|
347
|
+
continue;
|
|
348
|
+
this.#contract({ name: pending.name, kind: "mutation" }).result.decode(receipt.result);
|
|
349
|
+
this.#optimism.commit(pending.requestId, receipt.source, receipt.revision);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
// Only inactive results consume this disposable cache. Active round members
|
|
353
|
+
// have their own admission/frame limits and must never be partially evicted.
|
|
354
|
+
#remember(key, snapshot) {
|
|
355
|
+
this.#results.set(key, { source: snapshot.source, revision: snapshot.revision,
|
|
356
|
+
bytes: new TextEncoder().encode(key + JSON.stringify(snapshot)).byteLength });
|
|
357
|
+
}
|
|
358
|
+
#retainIdle(key) {
|
|
359
|
+
const snapshot = this.#results.get(key);
|
|
360
|
+
if (snapshot && !this.#watches.has(key)) {
|
|
361
|
+
this.#idleResults.delete(key);
|
|
362
|
+
this.#idleResults.set(key, { expiresAt: Date.now() + 5 * 60_000, bytes: snapshot.bytes });
|
|
363
|
+
}
|
|
364
|
+
this.#pruneCache();
|
|
365
|
+
}
|
|
366
|
+
#pruneCache() {
|
|
367
|
+
clearTimeout(this.#cacheTimer);
|
|
368
|
+
this.#cacheTimer = undefined;
|
|
369
|
+
let bytes = [...this.#idleResults.values()].reduce((sum, entry) => sum + entry.bytes, 0);
|
|
370
|
+
for (const [key, entry] of this.#idleResults) {
|
|
371
|
+
if (entry.expiresAt > Date.now() && this.#idleResults.size <= 128 && bytes <= 16 * 1024 * 1024)
|
|
372
|
+
break;
|
|
373
|
+
this.#idleResults.delete(key);
|
|
374
|
+
bytes -= entry.bytes;
|
|
375
|
+
this.#results.delete(key);
|
|
376
|
+
this.#optimism.removeResult(key);
|
|
377
|
+
}
|
|
378
|
+
const first = this.#idleResults.values().next().value;
|
|
379
|
+
if (first) {
|
|
380
|
+
this.#cacheTimer = setTimeout(() => this.#pruneCache(), Math.max(1, first.expiresAt - Date.now()));
|
|
381
|
+
this.#cacheTimer.unref?.();
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
#cache(key, snapshot, operation) {
|
|
385
|
+
const previous = this.#results.get(key);
|
|
386
|
+
if (previous && previous.source === snapshot.source && BigInt(previous.revision) > BigInt(snapshot.revision))
|
|
387
|
+
return;
|
|
388
|
+
this.#remember(key, snapshot);
|
|
389
|
+
this.#optimism.confirm(key, operation, operation.codecs.result.decode(snapshot.result), snapshot.source, snapshot.revision);
|
|
390
|
+
this.#retainIdle(key);
|
|
391
|
+
this.#refreshPredictions();
|
|
392
|
+
}
|
|
393
|
+
#retire(error) {
|
|
394
|
+
this.#epoch++;
|
|
395
|
+
this.#liveRevision = -1n;
|
|
396
|
+
this.#streamGeneration++;
|
|
397
|
+
this.#streamController?.abort();
|
|
398
|
+
const lifetime = this.#lifetime;
|
|
399
|
+
this.#lifetime = new AbortController();
|
|
400
|
+
clearTimeout(this.#renewTimer);
|
|
401
|
+
this.#renewTimer = undefined;
|
|
402
|
+
this.#session = undefined;
|
|
403
|
+
this.#pending.clear();
|
|
404
|
+
this.#handshake = undefined;
|
|
405
|
+
this.#source = undefined;
|
|
406
|
+
const watches = [...this.#watches.values()];
|
|
407
|
+
this.#watches.clear();
|
|
408
|
+
this.#results.clear();
|
|
409
|
+
this.#optimism.clear();
|
|
410
|
+
this.#idleResults.clear();
|
|
411
|
+
clearTimeout(this.#cacheTimer);
|
|
412
|
+
this.#cacheTimer = undefined;
|
|
413
|
+
lifetime.abort(error);
|
|
414
|
+
// Clear shared state before notifying: an observer may install a new auth scope.
|
|
415
|
+
for (const watch of watches) {
|
|
416
|
+
watch.controller.abort(error);
|
|
417
|
+
this.#publish(watch, { status: "error", error });
|
|
418
|
+
for (const stop of [...watch.cleanups])
|
|
419
|
+
stop();
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
async #invalidate(error, epoch) {
|
|
423
|
+
if (epoch !== this.#epoch)
|
|
424
|
+
return;
|
|
425
|
+
this.#retire(error instanceof DatabaseError ? error : new DatabaseError({ code: "context_changed", message: "Function auth scope retired" }));
|
|
426
|
+
}
|
|
427
|
+
#track(call) {
|
|
428
|
+
this.#calls.add(call);
|
|
429
|
+
void call.then(() => this.#calls.delete(call), () => this.#calls.delete(call));
|
|
430
|
+
return call;
|
|
431
|
+
}
|
|
432
|
+
call(raw, options = {}, onStatus) {
|
|
433
|
+
if (this.#calls.size >= 128)
|
|
434
|
+
return Promise.reject(new DatabaseError({ code: "capacity", message: "Too many concurrent function calls" }));
|
|
435
|
+
return this.#track(this.#call(raw, options, onStatus));
|
|
436
|
+
}
|
|
437
|
+
async #call(raw, options, onStatus) {
|
|
438
|
+
options.signal?.throwIfAborted();
|
|
439
|
+
const operation = this.#operation(raw), epoch = this.#epoch;
|
|
440
|
+
this.#check(epoch);
|
|
441
|
+
if (operation.kind === "query" && options.optimistic !== undefined)
|
|
442
|
+
throw new TypeError("Optimistic updates apply only to mutations");
|
|
443
|
+
if (operation.kind === "mutation" && options.signal !== undefined)
|
|
444
|
+
throw new TypeError("Mutation cancellation is not supported");
|
|
445
|
+
if (operation.kind === "query")
|
|
446
|
+
return this.#query(operation, epoch, options.signal);
|
|
447
|
+
const signal = options.signal ? AbortSignal.any([options.signal, this.#lifetime.signal]) : this.#lifetime.signal;
|
|
448
|
+
let session;
|
|
449
|
+
try {
|
|
450
|
+
session = await abortable(this.#ensure(epoch), signal);
|
|
451
|
+
}
|
|
452
|
+
catch (error) {
|
|
453
|
+
if (error instanceof DatabaseError && !isApplicationError(error) && ["unauthorized", "forbidden", "reset_required"].includes(error.code))
|
|
454
|
+
await this.#invalidate(error, epoch);
|
|
455
|
+
throw error;
|
|
456
|
+
}
|
|
457
|
+
signal.throwIfAborted();
|
|
458
|
+
this.#check(epoch);
|
|
459
|
+
const source = session.source;
|
|
460
|
+
const pending = { requestId: crypto.randomUUID(), name: operation.name, input: operation.codecs.input.encode(operation.input), source, ticket: session.ticket };
|
|
461
|
+
try {
|
|
462
|
+
this.#check(epoch);
|
|
463
|
+
signal.throwIfAborted();
|
|
464
|
+
if (options.optimistic) {
|
|
465
|
+
this.#pruneCache();
|
|
466
|
+
try {
|
|
467
|
+
this.#optimism.begin(pending.requestId, operation.name, operation.input, options.optimistic);
|
|
468
|
+
}
|
|
469
|
+
catch {
|
|
470
|
+
this.#optimism.reject(pending.requestId);
|
|
471
|
+
if (typeof process !== "undefined" && process.env.NODE_ENV === "development")
|
|
472
|
+
console.warn("@hulla/db: optimistic update failed; continuing the server mutation");
|
|
473
|
+
}
|
|
474
|
+
this.#refreshPredictions();
|
|
475
|
+
this.#check(epoch);
|
|
476
|
+
signal.throwIfAborted();
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
catch (error) {
|
|
480
|
+
this.#optimism.reject(pending.requestId);
|
|
481
|
+
this.#refreshPredictions();
|
|
482
|
+
throw error;
|
|
483
|
+
}
|
|
484
|
+
this.#pending.set(pending.requestId, pending);
|
|
485
|
+
return this.#mutation(pending, operation.codecs, session, epoch, signal, onStatus);
|
|
486
|
+
}
|
|
487
|
+
async #query(operation, epoch, caller) {
|
|
488
|
+
const deadline = new AbortController();
|
|
489
|
+
const timeout = new DatabaseError({ code: "query_timeout", message: "Query did not complete within its client deadline" });
|
|
490
|
+
const timer = setTimeout(() => deadline.abort(timeout), this.#queryTimeout);
|
|
491
|
+
const signal = AbortSignal.any([this.#lifetime.signal, deadline.signal, ...(caller ? [caller] : [])]);
|
|
492
|
+
let failures = 0;
|
|
493
|
+
try {
|
|
494
|
+
while (true) {
|
|
495
|
+
try {
|
|
496
|
+
signal.throwIfAborted();
|
|
497
|
+
this.#check(epoch);
|
|
498
|
+
// Session setup is shared with watches and other calls. Only this
|
|
499
|
+
// caller's wait is cancelled; its deadline never aborts that setup.
|
|
500
|
+
const session = await abortable(this.#ensure(epoch), signal);
|
|
501
|
+
signal.throwIfAborted();
|
|
502
|
+
this.#check(epoch);
|
|
503
|
+
const source = session.source;
|
|
504
|
+
const snapshot = this.#snapshot(await this.#json("/functions/query", { name: operation.name, input: operation.codecs.input.encode(operation.input), expected_source: source, ...(operation.page?.range ? { page: { range: operation.page.range } } : {}) }, session, signal), session, source);
|
|
505
|
+
this.#check(epoch);
|
|
506
|
+
const data = operation.codecs.result.decode(snapshot.result);
|
|
507
|
+
if (operation.page && snapshot.page)
|
|
508
|
+
operation.page.range = snapshot.page.range;
|
|
509
|
+
const key = operationKey(operation);
|
|
510
|
+
// One-shot reads cannot advance a member independently of its live round.
|
|
511
|
+
if (!this.#watches.has(key)) {
|
|
512
|
+
await this.#correlate(snapshot, session, epoch, signal);
|
|
513
|
+
this.#check(epoch);
|
|
514
|
+
if (!this.#watches.has(key))
|
|
515
|
+
this.#cache(key, snapshot, operation);
|
|
516
|
+
}
|
|
517
|
+
signal.throwIfAborted();
|
|
518
|
+
return data;
|
|
519
|
+
}
|
|
520
|
+
catch (error) {
|
|
521
|
+
if (signal.aborted)
|
|
522
|
+
throw signal.reason;
|
|
523
|
+
if (error instanceof DatabaseError && !isApplicationError(error) && ["unauthorized", "forbidden", "reset_required"].includes(error.code))
|
|
524
|
+
await this.#invalidate(error, epoch);
|
|
525
|
+
if (!(error instanceof TransportFailure))
|
|
526
|
+
throw error;
|
|
527
|
+
await pause(Math.min(this.#reconnect * 2 ** Math.min(failures++, 5), 30_000), signal);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
finally {
|
|
532
|
+
clearTimeout(timer);
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
async #mutation(pending, codecs, session, epoch, lifetime, onStatus) {
|
|
536
|
+
const timeout = new DatabaseError({ code: "confirmation_timeout", message: "Mutation confirmation timed out; the write may have committed", details: { requestId: pending.requestId } });
|
|
537
|
+
const deadline = new AbortController();
|
|
538
|
+
const timer = setTimeout(() => deadline.abort(timeout), this.#confirmationTimeout);
|
|
539
|
+
const signal = AbortSignal.any([lifetime, deadline.signal]);
|
|
540
|
+
let recovering = false, committed = false, failures = 0;
|
|
541
|
+
try {
|
|
542
|
+
while (true) {
|
|
543
|
+
try {
|
|
544
|
+
this.#check(epoch);
|
|
545
|
+
signal.throwIfAborted();
|
|
546
|
+
// Exactly one submission. Missing receipts are nonterminal and never
|
|
547
|
+
// authorize replay of the original payload or a replacement invocation.
|
|
548
|
+
const raw = recovering
|
|
549
|
+
? await this.#json(`/functions/receipts/${pending.requestId}?source=${pending.source}&ticket=${pending.ticket}`, undefined, session, signal)
|
|
550
|
+
: await this.#json("/functions/mutate", { request_id: pending.requestId, ticket: pending.ticket, name: pending.name, input: pending.input, expected_source: pending.source }, session, signal);
|
|
551
|
+
this.#check(epoch);
|
|
552
|
+
signal.throwIfAborted();
|
|
553
|
+
if (raw !== null || !recovering) {
|
|
554
|
+
const receipt = parseReceipt(raw, pending.requestId, session, pending.source);
|
|
555
|
+
committed = true;
|
|
556
|
+
let result;
|
|
557
|
+
try {
|
|
558
|
+
result = codecs.result.decode(receipt.result);
|
|
559
|
+
}
|
|
560
|
+
catch {
|
|
561
|
+
throw new DatabaseError({ code: "invalid_result", message: "The mutation committed, but its result did not match its contract", details: { requestId: pending.requestId, committed: true } });
|
|
562
|
+
}
|
|
563
|
+
pending.receipt = receipt;
|
|
564
|
+
try {
|
|
565
|
+
this.#optimism.commit(pending.requestId, receipt.source, receipt.revision);
|
|
566
|
+
}
|
|
567
|
+
catch {
|
|
568
|
+
this.#optimism.reject(pending.requestId);
|
|
569
|
+
}
|
|
570
|
+
this.#refreshPredictions();
|
|
571
|
+
this.#check(epoch);
|
|
572
|
+
signal.throwIfAborted();
|
|
573
|
+
for (const query of this.#optimism.queries(pending.requestId))
|
|
574
|
+
if (!this.#watches.has(operationKey(this.#operation(query))))
|
|
575
|
+
void this.call(query).catch(() => { });
|
|
576
|
+
// Best-effort ACKs share admission accounting so a slow endpoint
|
|
577
|
+
// cannot accumulate unbounded background requests.
|
|
578
|
+
void this.#track(this.#json(`/functions/receipts/${pending.requestId}/ack`, { source: pending.source, ticket: pending.ticket }, session, lifetime)).catch(() => { });
|
|
579
|
+
return result;
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
catch (error) {
|
|
583
|
+
this.#optimism.reject(pending.requestId);
|
|
584
|
+
this.#refreshPredictions();
|
|
585
|
+
if (deadline.signal.aborted)
|
|
586
|
+
throw timeout;
|
|
587
|
+
if (epoch !== this.#epoch || lifetime.aborted) {
|
|
588
|
+
throw new DatabaseError({ code: "confirmation_interrupted", message: "Mutation confirmation ended with its session; the write may have committed", details: { requestId: pending.requestId, ...(committed ? { committed: true } : {}) } });
|
|
589
|
+
}
|
|
590
|
+
if (error instanceof DatabaseError && !isApplicationError(error) && error.code === "receipt_expired") {
|
|
591
|
+
throw new DatabaseError({ code: "receipt_expired", message: "The mutation committed, but its retained result has expired", details: { requestId: pending.requestId, committed: true } });
|
|
592
|
+
}
|
|
593
|
+
if (committed && !(error instanceof DatabaseError))
|
|
594
|
+
throw new DatabaseError({ code: "invalid_result", message: "The mutation committed, but its result could not be delivered", details: { requestId: pending.requestId, committed: true } });
|
|
595
|
+
if (error instanceof DatabaseError && !transient(error)) {
|
|
596
|
+
if (!isApplicationError(error) && ["unauthorized", "forbidden", "reset_required"].includes(error.code))
|
|
597
|
+
await this.#invalidate(error, epoch);
|
|
598
|
+
throw error;
|
|
599
|
+
}
|
|
600
|
+
if (!recovering) {
|
|
601
|
+
recovering = true;
|
|
602
|
+
// State observers must never interrupt confirmation.
|
|
603
|
+
try {
|
|
604
|
+
onStatus?.("recovering");
|
|
605
|
+
}
|
|
606
|
+
catch { /* application observer */ }
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
await pause(Math.min(this.#reconnect * 2 ** Math.min(failures++, 5), 30_000), signal);
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
catch (error) {
|
|
613
|
+
this.#optimism.reject(pending.requestId);
|
|
614
|
+
this.#refreshPredictions();
|
|
615
|
+
if (deadline.signal.aborted)
|
|
616
|
+
throw timeout;
|
|
617
|
+
if (error instanceof DatabaseError)
|
|
618
|
+
throw error;
|
|
619
|
+
if (epoch !== this.#epoch || lifetime.aborted)
|
|
620
|
+
throw new DatabaseError({ code: "confirmation_interrupted", message: "Mutation confirmation ended with its session; the write may have committed", details: { requestId: pending.requestId } });
|
|
621
|
+
throw error;
|
|
622
|
+
}
|
|
623
|
+
finally {
|
|
624
|
+
clearTimeout(timer);
|
|
625
|
+
this.#pending.delete(pending.requestId);
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
watch(raw, observer, options = {}) {
|
|
629
|
+
options.signal?.throwIfAborted();
|
|
630
|
+
if (options.optimistic !== undefined)
|
|
631
|
+
throw new TypeError("Optimistic updates are not a subscription option");
|
|
632
|
+
const operation = this.#operation(raw);
|
|
633
|
+
const epoch = this.#epoch, key = operationKey(operation);
|
|
634
|
+
this.#check(epoch);
|
|
635
|
+
this.#pruneCache();
|
|
636
|
+
let watch = this.#watches.get(key);
|
|
637
|
+
const fresh = !watch;
|
|
638
|
+
if (!watch && this.#watches.size >= 128)
|
|
639
|
+
throw new DatabaseError({ code: "capacity", message: "Live query set exceeds 128 members" });
|
|
640
|
+
if (!watch) {
|
|
641
|
+
watch = { operation, observers: new Set(), controller: new AbortController(), cleanups: new Set(), state: { status: "pending" } };
|
|
642
|
+
this.#watches.set(key, watch);
|
|
643
|
+
}
|
|
644
|
+
this.#idleResults.delete(key);
|
|
645
|
+
const entry = watch;
|
|
646
|
+
entry.observers.add(observer);
|
|
647
|
+
const stop = () => {
|
|
648
|
+
options.signal?.removeEventListener("abort", stop);
|
|
649
|
+
entry.observers.delete(observer);
|
|
650
|
+
entry.cleanups.delete(stop);
|
|
651
|
+
if (!entry.observers.size) {
|
|
652
|
+
entry.controller.abort();
|
|
653
|
+
if (this.#watches.get(key) === entry) {
|
|
654
|
+
this.#watches.delete(key);
|
|
655
|
+
this.#retainIdle(key);
|
|
656
|
+
}
|
|
657
|
+
this.#scheduleStream();
|
|
658
|
+
}
|
|
659
|
+
};
|
|
660
|
+
entry.cleanups.add(stop);
|
|
661
|
+
options.signal?.addEventListener("abort", stop, { once: true });
|
|
662
|
+
try {
|
|
663
|
+
observer(entry.state.status === "success" ? { ...entry.state, data: copy(entry.state.data) } : entry.state);
|
|
664
|
+
}
|
|
665
|
+
catch { /* observer errors are application-owned */ }
|
|
666
|
+
if (fresh && entry.observers.size && this.#watches.get(key) === entry)
|
|
667
|
+
this.#scheduleStream();
|
|
668
|
+
return stop;
|
|
669
|
+
}
|
|
670
|
+
#scheduleStream() {
|
|
671
|
+
this.#streamGeneration++;
|
|
672
|
+
this.#streamController?.abort();
|
|
673
|
+
if (this.#rebuildQueued)
|
|
674
|
+
return;
|
|
675
|
+
this.#rebuildQueued = true;
|
|
676
|
+
queueMicrotask(() => {
|
|
677
|
+
this.#rebuildQueued = false;
|
|
678
|
+
if (!this.#watches.size)
|
|
679
|
+
return;
|
|
680
|
+
const controller = new AbortController();
|
|
681
|
+
this.#streamController = controller;
|
|
682
|
+
void this.#stream([...this.#watches.entries()], this.#epoch, this.#streamGeneration, controller.signal);
|
|
683
|
+
});
|
|
684
|
+
}
|
|
685
|
+
async #stream(members, epoch, generation, membership) {
|
|
686
|
+
let failures = 0;
|
|
687
|
+
let refreshedCredentials = false;
|
|
688
|
+
const alive = () => epoch === this.identityEpoch && generation === this.#streamGeneration && !membership.aborted;
|
|
689
|
+
while (alive()) {
|
|
690
|
+
const controller = new AbortController();
|
|
691
|
+
const signal = AbortSignal.any([membership, this.#lifetime.signal, controller.signal]);
|
|
692
|
+
let timer;
|
|
693
|
+
let verified;
|
|
694
|
+
try {
|
|
695
|
+
const session = await abortable(this.#ensure(epoch), signal);
|
|
696
|
+
verified = session;
|
|
697
|
+
const source = session.source;
|
|
698
|
+
if (!alive())
|
|
699
|
+
return;
|
|
700
|
+
timer = setTimeout(() => controller.abort(new Error("Stream setup timeout")), this.#timeout);
|
|
701
|
+
const headers = await this.#headers(session, signal, "text/event-stream");
|
|
702
|
+
signal.throwIfAborted();
|
|
703
|
+
const request = this.#fetch(this.#baseUrl + "/functions/subscriptions", {
|
|
704
|
+
method: "POST", redirect: "error", credentials: this.#options.credentials ?? "same-origin", signal,
|
|
705
|
+
headers,
|
|
706
|
+
body: JSON.stringify({ expected_source: source, queries: members.map(([key, watch]) => ({ key, name: watch.operation.name, input: watch.operation.codecs.input.encode(watch.operation.input), ...(watch.operation.page?.range ? { page: { range: watch.operation.page.range } } : {}) })) }),
|
|
707
|
+
});
|
|
708
|
+
void request.then(response => { if (signal.aborted)
|
|
709
|
+
void response.body?.cancel().catch(() => { }); }, () => { });
|
|
710
|
+
const response = await abortable(request, signal);
|
|
711
|
+
if (!response.ok)
|
|
712
|
+
await this.#readResponse(response, signal);
|
|
713
|
+
clearTimeout(timer);
|
|
714
|
+
if (!response.body || response.headers.get("content-type")?.split(";")[0] !== "text/event-stream") {
|
|
715
|
+
void response.body?.cancel().catch(() => { });
|
|
716
|
+
throw new TypeError("Invalid SSE response");
|
|
717
|
+
}
|
|
718
|
+
let subscription, last = 0n;
|
|
719
|
+
const activity = () => { clearTimeout(timer); timer = setTimeout(() => controller.abort(new Error("Stream idle timeout")), this.#idleTimeout); };
|
|
720
|
+
activity();
|
|
721
|
+
for await (const event of sseEvents(response.body, this.#maxBytes, activity, signal)) {
|
|
722
|
+
if (!alive())
|
|
723
|
+
return;
|
|
724
|
+
if (event.event === "error")
|
|
725
|
+
throw parseError(JSON.parse(event.data));
|
|
726
|
+
if (event.event !== "round")
|
|
727
|
+
throw new TypeError("Unexpected SSE event");
|
|
728
|
+
const frame = record(JSON.parse(event.data), ["subscription", "sequence", "round"]);
|
|
729
|
+
const id = uuid(frame.subscription), next = BigInt(sequence(frame.sequence));
|
|
730
|
+
if (event.id !== `${id}:${next}` || (subscription && subscription !== id) || next !== last + 1n)
|
|
731
|
+
throw new TypeError("Invalid subscription cursor");
|
|
732
|
+
const { results, ...rawHead } = record(frame.round, ["source", "scope", "principal", "authorization_scope", "revision", "results"]);
|
|
733
|
+
const head = parseHead(rawHead);
|
|
734
|
+
this.#snapshot({ ...head, result: null }, session, source);
|
|
735
|
+
if (!Array.isArray(results) || results.length !== members.length)
|
|
736
|
+
throw new TypeError("Incomplete live round");
|
|
737
|
+
const remaining = new Map(members);
|
|
738
|
+
const staged = results.map(value => {
|
|
739
|
+
if (typeof value !== "object" || value === null)
|
|
740
|
+
throw new TypeError("Invalid round member");
|
|
741
|
+
const row = record(value, Object.hasOwn(value, "result") ? ["key", "result", ...(Object.hasOwn(value, "page") ? ["page"] : [])] : ["key", "error"]);
|
|
742
|
+
if (typeof row.key !== "string" || !remaining.has(row.key))
|
|
743
|
+
throw new TypeError("Unexpected live member");
|
|
744
|
+
const watch = remaining.get(row.key);
|
|
745
|
+
remaining.delete(row.key);
|
|
746
|
+
return { key: row.key, watch, ...(Object.hasOwn(row, "result")
|
|
747
|
+
? { snapshot: { ...head, result: row.result, ...(row.page === undefined ? {} : { page: parsePage(row.page) }) }, data: watch.operation.codecs.result.decode(row.result) }
|
|
748
|
+
: { error: parseError(row.error) }) };
|
|
749
|
+
});
|
|
750
|
+
for (const member of staged) {
|
|
751
|
+
if (member.snapshot && member.watch.operation.page) {
|
|
752
|
+
const range = member.snapshot.page?.range;
|
|
753
|
+
if (!range || (member.watch.operation.page.range !== undefined && member.watch.operation.page.range !== range))
|
|
754
|
+
throw new TypeError("Invalid paginated range response");
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
const discovered = staged.some(member => member.snapshot && member.watch.operation.page && !member.watch.operation.page.range);
|
|
758
|
+
const credentialFailure = staged.find(member => member.error && !isApplicationError(member.error) && ["unauthorized", "reset_required"].includes(member.error.code));
|
|
759
|
+
if (credentialFailure)
|
|
760
|
+
throw credentialFailure.error;
|
|
761
|
+
if (BigInt(head.revision) < this.#liveRevision)
|
|
762
|
+
throw new TypeError("Live round revision regressed");
|
|
763
|
+
await this.#correlate({ ...head, result: null }, session, epoch, signal);
|
|
764
|
+
if (!alive())
|
|
765
|
+
return;
|
|
766
|
+
subscription = id;
|
|
767
|
+
last = next;
|
|
768
|
+
this.#liveRevision = BigInt(head.revision);
|
|
769
|
+
batchNotifications(() => {
|
|
770
|
+
for (const member of staged) {
|
|
771
|
+
if (member.snapshot) {
|
|
772
|
+
if (member.watch.operation.page) {
|
|
773
|
+
member.watch.operation.page.range = member.snapshot.page.range;
|
|
774
|
+
}
|
|
775
|
+
this.#remember(member.key, member.snapshot);
|
|
776
|
+
}
|
|
777
|
+
else {
|
|
778
|
+
this.#results.delete(member.key);
|
|
779
|
+
this.#optimism.removeResult(member.key);
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
this.#optimism.confirmRound(staged.flatMap(member => member.snapshot ? [{ key: member.key, operation: member.watch.operation, data: member.data, source, revision: head.revision }] : []));
|
|
783
|
+
for (const member of staged) {
|
|
784
|
+
this.#publish(member.watch, member.snapshot
|
|
785
|
+
? { status: "success", data: member.data, isStale: false, isOptimistic: false }
|
|
786
|
+
: { status: "error", error: member.error });
|
|
787
|
+
}
|
|
788
|
+
});
|
|
789
|
+
if (discovered) {
|
|
790
|
+
this.#scheduleStream();
|
|
791
|
+
return;
|
|
792
|
+
}
|
|
793
|
+
failures = 0;
|
|
794
|
+
refreshedCredentials = false;
|
|
795
|
+
}
|
|
796
|
+
throw new Error("Subscription disconnected");
|
|
797
|
+
}
|
|
798
|
+
catch (error) {
|
|
799
|
+
if (!alive())
|
|
800
|
+
return;
|
|
801
|
+
// A provider may rotate a token/cookie without changing the user's cache
|
|
802
|
+
// key. Reconnect with current credentials only if the server verifies the
|
|
803
|
+
// same identity. Never refresh credentials ourselves or retry a mutation.
|
|
804
|
+
if (error instanceof DatabaseError && !isApplicationError(error) && error.code === "unauthorized" && !refreshedCredentials && verified) {
|
|
805
|
+
refreshedCredentials = true;
|
|
806
|
+
clearTimeout(timer);
|
|
807
|
+
try {
|
|
808
|
+
const head = await this.#renew(epoch);
|
|
809
|
+
this.#check(epoch);
|
|
810
|
+
if (head.source !== verified.source || head.scope !== verified.scope
|
|
811
|
+
|| head.principal !== verified.principal || head.authorizationScope !== verified.authorizationScope) {
|
|
812
|
+
throw new DatabaseError({ code: "context_changed", message: "Credential refresh changed the verified scope" });
|
|
813
|
+
}
|
|
814
|
+
if (alive())
|
|
815
|
+
continue;
|
|
816
|
+
return;
|
|
817
|
+
}
|
|
818
|
+
catch (verificationError) {
|
|
819
|
+
if (!alive())
|
|
820
|
+
return;
|
|
821
|
+
// The old stream's credentials are invalid. Failure to verify a
|
|
822
|
+
// replacement cannot authorize retaining its protected live state.
|
|
823
|
+
error = verificationError instanceof DatabaseError && !isApplicationError(verificationError) && ["unauthorized", "forbidden", "context_changed", "reset_required"].includes(verificationError.code)
|
|
824
|
+
? verificationError : new DatabaseError({ code: "unauthorized", message: "Could not verify current credentials" });
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
if (error instanceof DatabaseError && !isApplicationError(error) && ["unauthorized", "forbidden", "reset_required", "context_changed"].includes(error.code)) {
|
|
828
|
+
await this.#invalidate(error, epoch);
|
|
829
|
+
return;
|
|
830
|
+
}
|
|
831
|
+
// Keep the last complete view on transport/protocol failures; no partial
|
|
832
|
+
// member is installed, and a fresh stream can recover it.
|
|
833
|
+
batchNotifications(() => {
|
|
834
|
+
for (const [, watch] of members) {
|
|
835
|
+
if (watch.state.status === "success")
|
|
836
|
+
this.#publish(watch, { ...watch.state, isStale: true });
|
|
837
|
+
else
|
|
838
|
+
this.#publish(watch, { status: "error", error });
|
|
839
|
+
}
|
|
840
|
+
});
|
|
841
|
+
}
|
|
842
|
+
finally {
|
|
843
|
+
clearTimeout(timer);
|
|
844
|
+
controller.abort();
|
|
845
|
+
}
|
|
846
|
+
try {
|
|
847
|
+
await pause(Math.min(this.#reconnect * 2 ** Math.min(failures++, 5), 30_000), membership);
|
|
848
|
+
}
|
|
849
|
+
catch {
|
|
850
|
+
return;
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
/** Object/null updates apply immediately; promises infer loading until resolved. */
|
|
855
|
+
setAuth(state) {
|
|
856
|
+
if (this.#disposed)
|
|
857
|
+
throw new DatabaseError({ code: "disposed", message: "Function runtime disposed" });
|
|
858
|
+
if (!isAuthPromise(state)) {
|
|
859
|
+
const validated = authState(state);
|
|
860
|
+
this.#applyAuth(validated, ++this.#authUpdate);
|
|
861
|
+
return;
|
|
862
|
+
}
|
|
863
|
+
const update = ++this.#authUpdate;
|
|
864
|
+
this.#auth = null;
|
|
865
|
+
this.#authPending = true;
|
|
866
|
+
this.#authFailure = undefined;
|
|
867
|
+
clearTimeout(this.#authTimer);
|
|
868
|
+
this.#authTimer = undefined;
|
|
869
|
+
this.#retire(new DatabaseError({ code: "context_changed", message: "Function auth scope is being resolved" }));
|
|
870
|
+
const current = () => !this.#disposed && update === this.#authUpdate;
|
|
871
|
+
const resolution = Promise.resolve(state).then(value => {
|
|
872
|
+
if (current())
|
|
873
|
+
this.#applyAuth(authState(value), update);
|
|
874
|
+
}).catch(error => {
|
|
875
|
+
if (!current())
|
|
876
|
+
return;
|
|
877
|
+
this.#authPending = false;
|
|
878
|
+
this.#authFailure = new DatabaseError({ code: "authentication_failed", message: "Authentication could not be resolved" });
|
|
879
|
+
this.#retire(this.#authFailure);
|
|
880
|
+
throw error;
|
|
881
|
+
});
|
|
882
|
+
// Auth listeners may ignore the completion promise; awaiting it still reports
|
|
883
|
+
// the provider/validation failure. Calls remain blocked until a later update.
|
|
884
|
+
void resolution.catch(() => { });
|
|
885
|
+
return resolution;
|
|
886
|
+
}
|
|
887
|
+
#applyAuth(validated, update) {
|
|
888
|
+
this.#expireAuth();
|
|
889
|
+
if (this.#disposed || update !== this.#authUpdate)
|
|
890
|
+
return;
|
|
891
|
+
const next = validated !== null && validated.expiresAt !== undefined && validated.expiresAt <= Date.now() ? null : validated;
|
|
892
|
+
const changed = this.#authPending || !!this.#authFailure || !sameAuth(this.#auth, next);
|
|
893
|
+
this.#auth = next;
|
|
894
|
+
this.#authPending = false;
|
|
895
|
+
this.#authFailure = undefined;
|
|
896
|
+
// Refreshing/removing only the deadline preserves a still-valid cache scope.
|
|
897
|
+
if (changed)
|
|
898
|
+
this.#retire(new DatabaseError({ code: "context_changed", message: "Function auth scope changed" }));
|
|
899
|
+
if (update === this.#authUpdate)
|
|
900
|
+
this.#scheduleAuthExpiry();
|
|
901
|
+
}
|
|
902
|
+
async dispose() {
|
|
903
|
+
if (!this.#disposed) {
|
|
904
|
+
this.#disposed = true;
|
|
905
|
+
clearTimeout(this.#authTimer);
|
|
906
|
+
this.#authTimer = undefined;
|
|
907
|
+
this.#retire(new DatabaseError({ code: "disposed", message: "Function runtime disposed" }));
|
|
908
|
+
}
|
|
909
|
+
await Promise.allSettled([...this.#calls]);
|
|
910
|
+
}
|
|
911
|
+
}
|