@supalive/core 1.20.1 → 1.21.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/dist/ephemeral-BVeIVuYw.js +276 -0
- package/dist/ephemeral-BVeIVuYw.js.map +1 -0
- package/dist/ephemeral-CkidSG9y.js +295 -0
- package/dist/ephemeral-CkidSG9y.js.map +1 -0
- package/dist/index-CzW0TkpK.d.ts +2729 -0
- package/dist/index-CzW0TkpK.d.ts.map +1 -0
- package/dist/index-DB7_pv9P.d.ts +2746 -0
- package/dist/index-DB7_pv9P.d.ts.map +1 -0
- package/dist/logger-BJNCJkFh.js +463 -0
- package/dist/logger-BJNCJkFh.js.map +1 -0
- package/dist/logger-By9Pw-X2.js +454 -0
- package/dist/logger-By9Pw-X2.js.map +1 -0
- package/dist/mysql-Bvc_iWUy.d.ts +114 -0
- package/dist/mysql-Bvc_iWUy.d.ts.map +1 -0
- package/dist/mysql-CcIuIAt0.js +622 -0
- package/dist/mysql-CcIuIAt0.js.map +1 -0
- package/dist/mysql-DTK2f5oU.d.ts +114 -0
- package/dist/mysql-DTK2f5oU.d.ts.map +1 -0
- package/dist/one-shot-query-BNYLU19W.js +573 -0
- package/dist/one-shot-query-BNYLU19W.js.map +1 -0
- package/dist/one-shot-query-BSK7adwG.js +573 -0
- package/dist/one-shot-query-BSK7adwG.js.map +1 -0
- package/dist/one-shot-query-DAAHGTcI.js +573 -0
- package/dist/one-shot-query-DAAHGTcI.js.map +1 -0
- package/dist/overlap-checker-DseE1Lvh.js +300 -0
- package/dist/overlap-checker-DseE1Lvh.js.map +1 -0
- package/dist/postgres-Bp7SMb9D.d.ts +118 -0
- package/dist/postgres-Bp7SMb9D.d.ts.map +1 -0
- package/dist/postgres-C5CbPBcp.d.ts +118 -0
- package/dist/postgres-C5CbPBcp.d.ts.map +1 -0
- package/dist/postgres-CLhoKn_R.js +867 -0
- package/dist/postgres-CLhoKn_R.js.map +1 -0
- package/dist/realtime_db-CTGOrFuV.js +463 -0
- package/dist/realtime_db-CTGOrFuV.js.map +1 -0
- package/dist/src/client/index.d.ts +2 -2
- package/dist/src/client/index.js +6 -5
- package/dist/src/client/index.js.map +1 -1
- package/dist/src/exports/mysql.d.ts +1 -1
- package/dist/src/exports/mysql.js +1 -1
- package/dist/src/exports/postgres.d.ts +1 -1
- package/dist/src/exports/postgres.js +1 -1
- package/dist/src/exports/procedure.d.ts +2 -2
- package/dist/src/exports/procedure.d.ts.map +1 -1
- package/dist/src/exports/procedure.js +2 -1
- package/dist/src/exports/procedure.js.map +1 -1
- package/dist/src/exports/schema-sql.d.ts +1 -1
- package/dist/src/exports/server.d.ts +56 -5
- package/dist/src/exports/server.d.ts.map +1 -1
- package/dist/src/exports/server.js +168 -10
- package/dist/src/exports/server.js.map +1 -1
- package/dist/src/exports/sub-manager-worker-entry.js +1 -1
- package/dist/src/exports/types.d.ts +2 -2
- package/dist/src/exports/types.js +2 -2
- package/dist/sub-worker-dispatch-C20KTMfg.js +925 -0
- package/dist/sub-worker-dispatch-C20KTMfg.js.map +1 -0
- package/dist/sub-worker-dispatch-CQCuwZPm.js +925 -0
- package/dist/sub-worker-dispatch-CQCuwZPm.js.map +1 -0
- package/dist/sub-worker-dispatch-Dwrp3c40.js +925 -0
- package/dist/sub-worker-dispatch-Dwrp3c40.js.map +1 -0
- package/dist/types_client_rpc-CqUVHTwT.js +163 -0
- package/dist/types_client_rpc-CqUVHTwT.js.map +1 -0
- package/dist/types_db-DPMeNETt.js +173 -0
- package/dist/types_db-DPMeNETt.js.map +1 -0
- package/dist/types_server-hiwqDm4G.d.ts +737 -0
- package/dist/types_server-hiwqDm4G.d.ts.map +1 -0
- package/dist/types_server-xHmZ6baD.d.ts +737 -0
- package/dist/types_server-xHmZ6baD.d.ts.map +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"realtime_db-CTGOrFuV.js","names":["z","uuidv4"],"sources":["../src/db/context.ts","../src/logger.ts","../src/db/realtime_db.ts"],"sourcesContent":["import { z, ZodRawShape } from \"zod\";\nimport { Database } from \"./db\";\nimport { ReadEntry, WriteEntry, } from \"./types_db\";\n\nimport { ColumnCodec, InferSchema, InsertData, Model, SchemaDefinition } from \"./schema\";\nimport { normalizeCodec, unwrapZodType } from \"./codec\";\nimport { QueryBuilder } from \"./query\";\nimport {\n createBufferedEphemeralWriter,\n createTrackedEphemeralReader,\n type EphemeralReader,\n type EphemeralStore,\n type EphemeralWriter,\n type PendingEphemeralWrite,\n} from \"./ephemeral\";\n\n/**\n * Materialize a schema's runtime {@link Model}: column-name mapping, per-column\n * coarse type tags, and the codec used to (de)serialize each column.\n *\n * Codecs are resolved via {@link normalizeCodec}, which supplies a sensible\n * default per Zod type (e.g. a {@link dateCodec} for `z.date()`, so `Date`\n * columns round-trip automatically) while letting a user-supplied codec in\n * `schema.columnsOptions.codecs` override it — partially or fully.\n */\nexport function buildModel(schema: SchemaDefinition<string, ZodRawShape>): Model {\n const shape = schema.schema.shape;\n const customColumns = (schema as any).columns;\n const columns: Record<string, string> = {};\n const types: Record<string, string> = {};\n const codecs: Record<string, ColumnCodec<any, any>> = {};\n const schemaCodecs = schema.columnsOptions.codecs ?? {};\n\n for (const key of Object.keys(shape)) {\n columns[key] = customColumns?.[key] ?? key;\n const field = shape[key];\n const baseField = unwrapZodType(field);\n if (baseField instanceof z.ZodNumber) {\n types[key] = \"integer\";\n } else if (baseField instanceof z.ZodString) {\n types[key] = \"string\";\n } else if (baseField instanceof z.ZodBoolean) {\n types[key] = \"boolean\";\n } else if (baseField instanceof z.ZodDate) {\n types[key] = \"date\";\n } else if (baseField instanceof z.ZodArray) {\n types[key] = \"array\";\n } else {\n types[key] = \"json\";\n }\n codecs[key] = normalizeCodec(schemaCodecs[key], baseField);\n }\n\n return {\n table: schema.table,\n tableId: schema.tableId,\n columns,\n reverseColumns: Object.fromEntries(Object.entries(columns).map(([k, v]) => [v, k])),\n types,\n codecs,\n };\n}\n\nexport class TxContext {\n // Not `readonly`: a query's read connection can be rebound (primary↔replica)\n // via {@link useConnection} before the first read — see the replica routing in\n // realtime_db.ts / one-shot-query.ts. Mutations never rebind.\n beginTs: bigint;\n db: Database;\n protected readSet: ReadEntry[] = [];\n protected writeSet: WriteEntry[] = [];\n /**\n * Ephemeral keys read by this context, in first-read order and de-duplicated.\n * Kept separate from {@link readSet} on purpose: an ephemeral key has no\n * snapshot ts and no commit log, so letting it into the read set would feed\n * the OCC validator and the commit-log freshness scan a dependency neither\n * can reason about.\n *\n * `null` until the first ephemeral read. The vast majority of queries never\n * touch the store, and this context is constructed once per query execution —\n * so the array is allocated on demand rather than on every read path.\n */\n protected ephemeralKeys: string[] | null = null;\n /** `set`/`delete` calls awaiting a commit — see {@link DbWriter.ephemeral}.\n * Lazily allocated, like {@link ephemeralKeys}. */\n protected ephemeralWrites: PendingEphemeralWrite[] | null = null;\n /** Backing store for `ctx.db.ephemeral`. */\n protected readonly ephemeralStore: EphemeralStore;\n private models: Map<string, Model> = new Map();\n\n protected getOrCreateModel(schema: SchemaDefinition<string, ZodRawShape>): Model {\n const existing = this.models.get(schema.table);\n if (existing) return existing;\n\n const model = buildModel(schema);\n this.models.set(schema.table, model);\n return model;\n }\n\n constructor(db: Database, beginTs: bigint, ephemeralStore: EphemeralStore) {\n this.db = db;\n this.beginTs = beginTs;\n this.ephemeralStore = ephemeralStore;\n }\n\n /**\n * Record a live-query dependency on `key` (idempotent within a context).\n * @internal — called by the wrappers in db/ephemeral.ts.\n */\n internalTrackEphemeralRead(key: string): void {\n if (this.ephemeralKeys === null) {\n this.ephemeralKeys = [key];\n return;\n }\n if (!this.ephemeralKeys.includes(key)) this.ephemeralKeys.push(key);\n }\n\n /**\n * Queue an ephemeral write for the post-commit flush, replacing any earlier\n * write to the same key so the last write in an attempt wins.\n * @internal — called by the wrapper in db/ephemeral.ts.\n */\n internalBufferEphemeralWrite(write: PendingEphemeralWrite): void {\n if (this.ephemeralWrites === null) {\n this.ephemeralWrites = [write];\n return;\n }\n const existing = this.ephemeralWrites.findIndex((w) => w.key === write.key);\n if (existing >= 0) this.ephemeralWrites[existing] = write;\n else this.ephemeralWrites.push(write);\n }\n\n /**\n * Rebind the read connection (and its snapshot ts). Used by the replica\n * router when a query handler calls `ctx.usePrimaryConn()`/`useReplicaConn()`.\n * Must be called BEFORE any read — the readSet/beginTs would otherwise mix\n * snapshots — so this throws if a read or write has already happened.\n */\n useConnection(db: Database, beginTs: bigint): void {\n if (this.readSet.length > 0 || this.writeSet.length > 0) {\n throw new Error(\n \"useConnection()/usePrimaryConn()/useReplicaConn() must be called before any read or write in the handler\",\n );\n }\n this.db = db;\n this.beginTs = beginTs;\n }\n\n internalGetReadSet(): ReadEntry[] { return this.readSet; }\n internalGetWriteSet(): WriteEntry[] { return this.writeSet; }\n /** Null when this context read no ephemeral state — see {@link ephemeralKeys}. */\n internalGetEphemeralKeys(): string[] | null { return this.ephemeralKeys; }\n /** Null when this context buffered no ephemeral writes. */\n internalGetEphemeralWrites(): PendingEphemeralWrite[] | null { return this.ephemeralWrites; }\n\n /**\n * Merge a parent procedure's reads into this context's readSet. Used when a\n * `runMutation` sub-transaction inherits the reads of the procedure that\n * invoked it, so the sub-tx's OCC validation also fences on those rows.\n * Entries are shallow-cloned so the two readSets don't alias.\n */\n appendInternalReadSet(parentEntries: ReadEntry[]) {\n this.readSet.push(...parentEntries.map((e) => ({ ...e })));\n }\n\n /**\n * Merge ephemeral dependencies recorded elsewhere into this context. The\n * counterpart of {@link appendInternalReadSet}: used when a nested query is\n * served from cache, so the parent still depends on the keys the cached\n * computation read and re-runs when any of them change.\n */\n appendInternalEphemeralKeys(keys: string[]) {\n for (const key of keys) this.internalTrackEphemeralRead(key);\n }\n\n protected findPendingWrite(table: string, id: string): WriteEntry | undefined {\n return this.writeSet.find(w => w.table === table && w.id === id);\n }\n\n protected findPendingInsert(table: string, id: string): WriteEntry | undefined {\n return this.writeSet.find(w => w.table === table && w.id === id && w.op === \"insert\");\n }\n\n protected encodeWithCodec(model: Model, property: string, value: unknown): unknown {\n const codec = model.codecs[property];\n if (!codec?.encode || value === undefined || value === null) return value;\n return codec.encode(value);\n }\n}\n\nexport class DbReader extends TxContext {\n private ephemeralApi?: EphemeralReader;\n\n query<S extends SchemaDefinition<string, ZodRawShape>>(schema: S): QueryBuilder<S> {\n const model = this.getOrCreateModel(schema);\n return new QueryBuilder<S>(this, model);\n }\n\n /**\n * Read ephemeral state — values that drive live queries but are never stored\n * in the database (a device's latest GPS fix, a presence flag).\n *\n * Every read here records a dependency on the key, so a subscribed query\n * re-runs and pushes automatically when an action or mutation writes it. The\n * dependency is on the KEY, not the value: reading a key that is currently\n * absent still subscribes you to it being set later.\n *\n * Built on first access — a query that never reaches for ephemeral state\n * allocates neither the wrapper nor its key list.\n */\n get ephemeral(): EphemeralReader {\n return (this.ephemeralApi ??= createTrackedEphemeralReader(this, this.ephemeralStore));\n }\n}\n\nexport class DbWriter extends DbReader {\n private ephemeralWriteApi?: EphemeralWriter;\n\n /**\n * Read AND write ephemeral state. Reads behave exactly as on a\n * {@link DbReader}; writes are BUFFERED and applied only once the surrounding\n * mutation commits (see `SupaliveDb.mutation` and\n * {@link createBufferedEphemeralWriter} for why).\n */\n override get ephemeral(): EphemeralWriter {\n return (this.ephemeralWriteApi ??= createBufferedEphemeralWriter(this, this.ephemeralStore));\n }\n\n async insert<S extends SchemaDefinition<string, ZodRawShape>, ID extends string>(\n schema: S,\n id: ID,\n data: InsertData<S>\n ): Promise<void> {\n const model = this.getOrCreateModel(schema);\n const mappedData: Record<string, unknown> = { id };\n const shape = schema.schema.shape;\n\n for (const key of Object.keys(shape)) {\n let value = data[key];\n\n if (value === undefined) {\n const field = shape[key];\n if (field instanceof z.ZodDefault) {\n const defaultVal = field.def.defaultValue;\n value = (typeof defaultVal === \"function\" ? defaultVal() : defaultVal)\n\n if (value !== undefined) {\n const columnName = model.columns[key] ?? key;\n mappedData[columnName] = this.encodeWithCodec(model, key, value);\n }\n }\n } else {\n const columnName = model.columns[key] ?? key;\n mappedData[columnName] = this.encodeWithCodec(model, key, value);\n }\n }\n // ensure id same\n mappedData[\"id\"] = id;\n\n // Check for existing pending write for the same ID\n const existing = this.findPendingWrite(schema.table, id);\n if (existing) {\n if (existing.op === \"delete\") {\n // If there's a pending delete, change it to an update with the new data\n existing.op = \"update\";\n existing.data = mappedData;\n } else {\n // If there's a pending update or same insert with the same ID , merge the new data\n existing.data = { ...existing.data, ...mappedData };\n }\n } else {\n this.writeSet.push({ table: schema.table, tableId: schema.tableId, id: id, op: \"insert\", data: mappedData });\n }\n }\n\n async update<S extends SchemaDefinition<string, ZodRawShape>, ID extends string>(\n schema: S,\n id: ID,\n data: Partial<Omit<InferSchema<S>, \"id\" | \"commitTs\">>,\n ): Promise<void> {\n const model = this.getOrCreateModel(schema);\n const mappedData: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(data)) {\n const columnName = model.columns[key] ?? key;\n mappedData[columnName] = this.encodeWithCodec(model, key, value);\n }\n\n const existing = this.findPendingWrite(schema.table, id);\n if (existing) {\n existing.op = existing.op === \"insert\" ? \"insert\" : \"update\";\n existing.data = { ...existing.data, ...mappedData };\n } else {\n // expectedTs will be filled by the committer via batch fetch if not known yet\n this.writeSet.push({ table: schema.table, tableId: schema.tableId, id, op: \"update\", data: mappedData });\n }\n }\n\n async delete<S extends SchemaDefinition<string, ZodRawShape>, ID extends string>(\n schema: S,\n id: ID,\n ): Promise<void> {\n // If there's a pending insert for the same ID, remove it instead of adding a delete\n const existingInsert = this.findPendingInsert(schema.table, id);\n if (existingInsert) {\n this.writeSet = this.writeSet.filter(w => w !== existingInsert);\n return;\n }\n\n // expectedTs will be filled by the committer via batch fetch if not known yet\n this.writeSet.push({ table: schema.table, tableId: schema.tableId, id, op: \"delete\" });\n }\n}\n","import pino, { Level } from \"pino\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport pinoPretty from \"pino-pretty\";\nconst _ = pinoPretty; // Prevents tree shaking of pino-pretty\n\nexport const appInstanceId = `instance-${uuidv4().slice(0, 8)}`;\nexport const isProduction = process.env.NODE_ENV === \"production\";\nexport const logger = pino({\n level: process.env.LOG_LEVEL || \"info\",\n timestamp: pino.stdTimeFunctions.isoTime,\n redact: { paths: [\"user.password\"] },\n transport: isProduction ? undefined : {\n target: 'pino-pretty',\n options: {\n colorize: true\n },\n },\n serializers: {\n \"columnsTypes\": (map) => {\n if (map instanceof Map) return serializeMapValue(map);\n return map;\n },\n },\n base: {\n \"srv\": appInstanceId,\n },\n});\n\nexport function logLevelOf(name: string): Level {\n const defaultLogLevel = process.env.DEFAULT_LOG_LEVEL || \"info\";\n return (process.env[name]?.toLowerCase() || defaultLogLevel) as Level;\n}\n\nexport function serializeMapValue<K extends string | number | symbol, V>(map: Map<K, V>): Record<K, V> {\n const obj: Record<K, any> = {} as Record<K, any>;\n for (const [k, v] of map.entries()) {\n obj[k] = {} as V;\n if (v instanceof Map) {\n for (const [innerK, innerV] of v.entries()) {\n obj[k][innerK] = innerV;\n }\n } else {\n obj[k] = v;\n }\n }\n\n return obj as Record<K, V>;\n}","import { Database, LazyCommitTsParam, TxDatabase } from \"./db\";\nimport {\n OccConflictError, WriteEntry, CommitTs, LiveResult, MutationResult\n} from \"./types_db\";\nimport { DbReader, DbWriter } from \"./context\";\nimport { traceDbCall } from \"./db-trace\";\nimport { ExponentialBackoff, handleWhen, retry, RetryPolicy } from \"cockatiel\";\nimport {\n EMPTY_EPHEMERAL_KEYS,\n EphemeralFlushError,\n type EphemeralStore,\n type PendingEphemeralWrite,\n} from \"./ephemeral\";\nimport { logger } from \"../logger\";\n\nexport const occRetryPolicy = retry(\n handleWhen((err) => OccConflictError.isOccConflictError(err)),\n {\n maxAttempts: 15,\n backoff: new ExponentialBackoff({\n initialDelay: 10,\n maxDelay: 7000,\n exponent: 2,\n }),\n },\n);\n\nexport const getDbclientRetryPolicy = retry(\n handleWhen((err) => err.message.includes('timeout exceeded')),\n {\n maxAttempts: 3,\n backoff: new ExponentialBackoff({\n initialDelay: 500,\n maxDelay: 2000,\n exponent: 2,\n }),\n },\n);\n\nexport class SupaliveDb {\n /**\n * @param impl the PRIMARY (writer) connection — all mutations, the OCC\n * commit-ts source, and cache-freshness commit-log scans run here.\n * @param ephemeral Redis-backed store behind `ctx.db.ephemeral` (db/ephemeral.ts).\n * Required: it is reachable from every handler context, so a\n * db that could be missing one would push the failure out to\n * request time. A replica SHARES the primary's store —\n * ephemeral state lives in Redis rather than in either\n * connection, so read routing must not change what it sees.\n * @param replica optional read replica for query/action reads (see the\n * routing in one-shot-query.ts). Undefined → reads use primary.\n */\n constructor(\n readonly impl: Database,\n readonly ephemeral: EphemeralStore,\n readonly replica?: SupaliveDb,\n ) { }\n\n static create(config: {\n db: Database;\n /** See the constructor: shared with the replica, never per-connection. */\n ephemeral: EphemeralStore;\n replica?: Database;\n }): SupaliveDb {\n return new SupaliveDb(\n config.db,\n config.ephemeral,\n config.replica ? new SupaliveDb(config.replica, config.ephemeral) : undefined,\n );\n }\n\n /** True when a distinct read replica is configured. */\n get hasReplica(): boolean {\n return this.replica !== undefined;\n }\n\n /**\n * Register a hook fired after every batch of ephemeral writes lands in Redis.\n * The ephemeral twin of {@link setOnAfterCommit}: the server uses it to drive\n * subscription invalidation for writes from any source — an action, a job, or\n * a mutation's post-commit flush.\n */\n setOnAfterEphemeralWrite(cb: (keys: string[], version: string) => void): void {\n this.ephemeral.onAfterWrite = cb;\n }\n\n protected onAfterCommit?: (writeSet: WriteEntry[], commitTs: CommitTs) => void;\n\n /**\n * Register a hook fired once after every successful `mutation()` commit\n * (never on an OCC conflict/rollback), with the committed writeSet and its\n * commitTs. The server uses this to drive subscription invalidation for ALL\n * mutation sources — client WS calls, actions, jobs, and the internal caller —\n * so a server-side write pushes live updates just like a client write does.\n * Non-server consumers (migration tooling, tests) leave it unset (no-op).\n */\n setOnAfterCommit(cb: (writeSet: WriteEntry[], commitTs: CommitTs) => void): void {\n this.onAfterCommit = cb;\n }\n\n // ── Read-only query ──────────────────────────────────────────────\n\n /**\n * One-shot read against an EXPLICIT connection + snapshot ts (rather than this\n * db's own latest). Used by the replica router: the caller pre-resolves the\n * default read connection (replica for queries) and hands the handler a\n * `DbReader` it can rebind via `useConnection` (ctx.usePrimaryConn/…). The\n * returned `ts` is the FINAL bound connection's snapshot, so the cache entry is\n * stamped with the ts actually read at.\n */\n async queryInternalOn<T>(\n read: { impl: Database; beginTs: bigint },\n fn: (ctx: DbReader) => Promise<T>,\n ): Promise<LiveResult<T>> {\n const ctx = new DbReader(read.impl, read.beginTs, this.ephemeral);\n const data = await fn(ctx);\n return {\n ts: ctx.beginTs,\n data,\n readSet: ctx.internalGetReadSet(),\n ephemeralKeys: ctx.internalGetEphemeralKeys() ?? EMPTY_EPHEMERAL_KEYS,\n };\n }\n\n async query<T>(fn: (ctx: DbReader) => Promise<T>): Promise<T> {\n const beginTs = await this.impl.getLatestSnapshotTimestamp();\n const ctx = new DbReader(this.impl, beginTs, this.ephemeral);\n return await fn(ctx);\n }\n\n /**\n * Compute a query once at the latest snapshot, returning the result together\n * with the snapshot `ts` and the tracked `readSet`. This is a plain one-shot\n * evaluation — it registers NO live subscription; the `readSet`/`ts` are\n * returned purely so the caller (e.g. the one-shot query cache) can store\n * freshness metadata. Use this for cached one-shot query calls (WS `call`,\n * HTTP RPC). `liveQuery` is the same computation under the subscription path's\n * name and simply delegates here.\n */\n async queryInternal<T>(fn: (ctx: DbReader) => Promise<T>): Promise<LiveResult<T>> {\n const beginTs = await this.impl.getLatestSnapshotTimestamp();\n const ctx = new DbReader(this.impl, beginTs, this.ephemeral);\n const data = await fn(ctx);\n\n return {\n ts: beginTs,\n data: data,\n readSet: ctx.internalGetReadSet(),\n ephemeralKeys: ctx.internalGetEphemeralKeys() ?? EMPTY_EPHEMERAL_KEYS,\n };\n }\n\n async liveQuery<T>(fn: (ctx: DbReader) => Promise<T>): Promise<LiveResult<T>> {\n return this.queryInternal(fn);\n }\n\n // ── Mutation ───────────────────────────────────────────────────────\n\n async mutation<T>(\n fn: (ctx: DbWriter) => Promise<T>,\n retryPolicy: RetryPolicy = occRetryPolicy,\n ): Promise<MutationResult<T>> {\n // Ephemeral writes buffered by the attempt that COMMITTED. Captured here,\n // outside the retry loop, because they must be applied after the loop has\n // finished — see the flush below.\n let committedEphemeralWrites: PendingEphemeralWrite[] | null = null;\n\n const mutationResult = await retryPolicy.execute(async (p) => {\n let db: TxDatabase | undefined;\n try {\n // Step1: Get latest snapshot timestamp as beginTs\n const beginTs = await this.impl.getLatestSnapshotTimestamp() + 1n;\n\n const ctx = new DbWriter(this.impl, beginTs, this.ephemeral);\n const result = await fn(ctx);\n\n const readSet = ctx.internalGetReadSet();\n const writeSet = ctx.internalGetWriteSet();\n const commitTsLazy = new LazyCommitTsParam(undefined);\n\n // Step2: Capture prevData + expectedCommitTs per write. prevData\n // is consumed by the invalidator (range subs need it to detect\n // result-set transitions). expectedCommitTs becomes the CAS fence\n // for the apply step — preferring prior find()-captured ts so\n // read-then-update patterns get beginTs-level isolation.\n await this.impl.attachPrevDataToWriteSet(writeSet, readSet);\n\n // Step3: Prepare quieries before transaction\n const queries = await this.impl.prepareCommitWrites(\n readSet,\n writeSet,\n commitTsLazy,\n );\n\n // Step4: Starts new transaction\n db = await getDbclientRetryPolicy.execute(() => this.impl.getTransactionClient());\n await db.begin();\n\n // Step5: Get commitTs from DB sequence (bigger than all previous)\n const commitTs = await db.getNextTimestamp();\n commitTsLazy.value = commitTs;\n\n // Step6: Apply + validate. CAS UPDATE/DELETE catches concurrent\n // peer touches on the write set; the readSet is validated either\n // per-row (fast path, no range reads) or via commit-log scan\n // (slow path, when range reads are present so phantoms still\n // need detection).\n const commitResult = await traceDbCall(\n \"commit\",\n \"\",\n this.impl.dbType,\n () => db!.commitWrites(beginTs, queries, commitTs),\n );\n\n if (!commitResult.success) {\n throw new OccConflictError(\"Commit failed\", { commitResult });\n }\n\n await db.updateLatestSnapshotTimestamp(commitTs);\n await db.commit();\n\n // Notify after successful commit\n this.onAfterCommit?.(writeSet, commitTs);\n\n // Hand this attempt's buffered ephemeral writes to the post-loop flush.\n // Only an attempt that reaches this line — i.e. one that committed — ever\n // assigns, so a losing OCC attempt's buffer is discarded with its context\n // and never becomes visible.\n committedEphemeralWrites = ctx.internalGetEphemeralWrites();\n\n return { result, writeSet, commitTs };\n } catch (err) {\n await db?.rollback();\n throw err;\n } finally {\n db?.release();\n }\n });\n\n // Flush AFTER the commit, and outside the retry loop / try-catch above.\n //\n // Why not before `db.commit()`, so a Redis failure would roll the mutation\n // back? Because applying early publishes ephemeral state for a transaction\n // that may still abort, in two ways that matter:\n //\n // 1. Before `commitWrites`, every OCC conflict — the routine path under\n // contention, retried up to 15 times — would publish state from an\n // attempt that never committed. That is precisely what buffering the\n // writes exists to prevent.\n // 2. Even placed after `commitWrites` (OCC already resolved), `apply`\n // fires `onAfterWrite`, whose recompute opens a FRESH read on the\n // primary. Our transaction is not committed yet, so that read sees the\n // OLD rows next to the NEW ephemeral value — a query reading both\n // pushes a torn frame to subscribers before the commit lands.\n //\n // Publishing state for a transaction that never happened is worse than\n // failing to publish state for one that did: the former is silent and\n // permanent, the latter is logged, TTL-bounded, and healed by the next\n // write. Ephemeral state is expendable by design — silent TTL expiry is\n // already its contract.\n //\n // A failure here is therefore NOT a mutation failure and is not thrown: the\n // rows are durable and their invalidation has already gone out, so rejecting\n // would report a successful mutation as failed and tempt a caller into a\n // retry that re-applies the row writes. It is logged instead — the operator,\n // not the caller, is who can act on \"Redis is unreachable\".\n if (committedEphemeralWrites) {\n const writes: PendingEphemeralWrite[] = committedEphemeralWrites;\n try {\n await this.ephemeral.apply(writes);\n } catch (cause) {\n logger.error(\n new EphemeralFlushError(writes.map((w) => w.key), { cause }),\n \"ephemeral flush failed after commit\",\n );\n }\n }\n\n return mutationResult;\n }\n}\n\nexport const sleep = (ms: number) => new Promise<void>((res) => setTimeout(res, ms));\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,WAAW,QAAsD;CAC/E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mBAAmB;IACvC,MAAM,WAAW,IAAI,oBAAoB;IACzC,MAAM,eAAe,IAAI,kBAAkB,KAAA,CAAS;IAOpD,MAAM,KAAK,KAAK,yBAAyB,UAAU,OAAO;IAG1D,MAAM,UAAU,MAAM,KAAK,KAAK,oBAC9B,SACA,UACA,YACF;IAGA,KAAK,MAAM,uBAAuB,cAAc,KAAK,KAAK,qBAAqB,CAAC;IAChF,MAAM,GAAG,MAAM;IAGf,MAAM,WAAW,MAAM,GAAG,iBAAiB;IAC3C,aAAa,QAAQ;IAOrB,MAAM,eAAe,MAAM,YACzB,UACA,IACA,KAAK,KAAK,cACJ,GAAI,aAAa,SAAS,SAAS,QAAQ,CACnD;IAEA,IAAI,CAAC,aAAa,SAChB,MAAM,IAAI,iBAAiB,iBAAiB,EAAE,aAAa,CAAC;IAG9D,MAAM,GAAG,8BAA8B,QAAQ;IAC/C,MAAM,GAAG,OAAO;IAGhB,KAAK,gBAAgB,UAAU,QAAQ;IAMvC,2BAA2B,IAAI,2BAA2B;IAE1D,OAAO;KAAE;KAAQ;KAAU;IAAS;GACtC,SAAS,KAAK;IACZ,MAAM,IAAI,SAAS;IACnB,MAAM;GACR,UAAU;IACR,IAAI,QAAQ;GACd;EACF,CAAC;EA6BD,IAAI,0BAA0B;GAC5B,MAAM,SAAkC;GACxC,IAAI;IACF,MAAM,KAAK,UAAU,MAAM,MAAM;GACnC,SAAS,OAAO;IACd,OAAO,MACL,IAAI,oBAAoB,OAAO,KAAK,MAAM,EAAE,GAAG,GAAG,EAAE,MAAM,CAAC,GAC3D,qCACF;GACF;EACF;EAEA,OAAO;CACT;AACF;AAEA,MAAa,SAAS,OAAe,IAAI,SAAe,QAAQ,WAAW,KAAK,EAAE,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $ as ActionProcedures, $
|
|
2
|
-
export { type ActionConfig, type ActionCtx, type ActionFn, type ActionProcedure, type ActionProcedures, AndPredicate, AndPredicateSchema, type AnyProcedure, type AnyQueryDef, type AppRouter, BigIntSchema, CachedPgMetadata, CachedPgMetadataSchema, type CallOptions, CallerClientInitConfig, CallerFromProcedures, CallerFromRouter, CallerOptions, type ClientEvent, type ClientFromProcedures, type ClientLogLevel, type ClientLogger, type ClientOptions, type ClientPublicState, type ColumnCodec, CommitLogEntry, CommitTs, CompareOperator, CompareOperatorSchema, type ComputedFieldConfig, type ContextOf, DEFAULT_RETRY, type Database, type DbQueryResult, DbReader, DbReader as ReadContext, DbWriter, DbWriter as WritableContext, type DefsToMap, type HandlerLogger, type HandlerObservability, type HeartbeatOptions, type InferSchema, type InsertData, LeafPredicate, LeafPredicateSchema, type LiveQueryHandle, type LiveQueryState, type LiveQueryStatus, LiveResult, type Model, type MutationConfig, type MutationCtx, type MutationFn, type MutationProcedure, type MutationProcedures, MutationResult, NO_RETRY, OccAbortError, OccConflictError, OrPredicate, OrPredicateSchema, type OutputOf, type ParamsOf, PointRead, PointReadSchema, type PooledClient, Predicate, PredicateSchema, type ProcedureNames, type PublicProcedures, QueryCacheEntry, QueryCacheEntrySchema, QueryCacheMetadata, QueryCacheMetadataSchema, type QueryConfig, type QueryCtx, type QueryDefinition, type QueryFn, type QueryProcedure, type QueryProcedures, QuerySpec, RPCError, RangeRead, RangeReadSchema, type RawClient, RawPointRead, RawPointReadSchema, RawRangeRead, RawRangeReadSchema, RawReadEntry, RawReadEntrySchema, ReadEntry, ReadEntrySchema, type RegisteredProcedure, type ResultOf, RetryConfig, type Router, type SchemaCodecs, type SchemaColumnsOptions, type SchemaDefinition, SupaliveDb, TxContext, type TypeOf, type WSClientMethods, type WSClientOptions, WriteEntry, WriteEntrySchema, WriteOp, WriteOpSchema, WsClientManager, _resetGlobalDefs, bytesFromJson, createActionBuilder, createCaller, createClient, createConsoleLogger, createMutationBuilder, createQueryBuilder, defineComputedField, defineQuery, defineSchema, matchesPredicate, normalizeIdToBytes, normalizeToBytes, router, sleep };
|
|
1
|
+
import { $ as ActionProcedures, $r as Predicate, $t as ResultOf, At as QueryFn, Br as CompareOperatorSchema, Ci as normalizeToBytes, Ct as MutationConfig, Dn as matchesPredicate, Dt as OutputOf, Et as MutationProcedure, Fr as CachedPgMetadata, Ft as createMutationBuilder, G as ClientLogLevel, Gr as MutationResult, Hr as LeafPredicate, Ir as CachedPgMetadataSchema, It as createQueryBuilder, J as HeartbeatOptions, Jn as SchemaColumnsOptions, Jr as OccConflictError, Jt as sleep, K as ClientLogger, Kn as SchemaCodecs, Kr as NO_RETRY, Ln as InferSchema, Lr as CommitLogEntry, Mr as AndPredicate, Mt as TypeOf, Nn as ComputedFieldConfig, Nr as AndPredicateSchema, Nt as createActionBuilder, Ot as QueryConfig, Pr as BigIntSchema, Q as createConsoleLogger, Qn as defineSchema, Qr as PointReadSchema, Qt as QueryDefinition, Rn as InsertData, Rr as CommitTs, Si as normalizeIdToBytes, Tt as MutationFn, Ur as LeafPredicateSchema, Vr as DEFAULT_RETRY, W as ClientEvent, Wr as LiveResult, X as WSClientOptions, Xr as OrPredicateSchema, Xt as DefsToMap, Y as RPCError, Yn as SchemaDefinition, Yr as OrPredicate, Yt as AnyQueryDef, Z as WsClientManager, Zn as defineComputedField, Zr as PointRead, Zt as ParamsOf, _i as WriteEntry, _t as HandlerLogger, a as createCaller, ai as QuerySpec, an as EMPTY_EPHEMERAL_KEYS, at as PublicProcedures, bi as WriteOpSchema, c as ClientOptions, ci as RawPointRead, cn as EphemeralFlushError, ct as Router, d as LiveQueryStatus, di as RawRangeReadSchema, dn as EphemeralSetOptions, dt as ActionConfig, ei as PredicateSchema, en as _resetGlobalDefs, et as AppRouter, f as WSClientMethods, fi as RawReadEntry, fn as EphemeralStore, ft as ActionCtx, gi as RetryConfig, gt as ContextOf, hi as ReadEntrySchema, ht as AnyProcedure, i as CallerOptions, ii as QueryCacheMetadataSchema, in as TxContext, ir as DbQueryResult, it as ProcedureNames, jt as QueryProcedure, kn as ColumnCodec, kt as QueryCtx, l as LiveQueryHandle, li as RawPointReadSchema, ln as EphemeralKeyNotFoundError, lr as RawClient, mi as ReadEntry, mn as createMemoryEphemeralStore, mt as ActionProcedure, n as CallerFromProcedures, ni as QueryCacheEntrySchema, nn as DbReader, o as CallOptions, oi as RangeRead, on as EPHEMERAL_DEFAULT_TTL_SECONDS, ot as QueryProcedures, p as createClient, pi as RawReadEntrySchema, pn as EphemeralWriter, pt as ActionFn, q as ClientPublicState, qr as OccAbortError, qt as SupaliveDb, r as CallerFromRouter, ri as QueryCacheMetadata, rn as DbWriter, rr as Database, rt as MutationProcedures, s as ClientFromProcedures, si as RangeReadSchema, sn as EphemeralDecodeError, sr as PooledClient, st as RegisteredProcedure, t as CallerClientInitConfig, ti as QueryCacheEntry, tn as defineQuery, u as LiveQueryState, ui as RawRangeRead, un as EphemeralReader, ut as router, vi as WriteEntrySchema, vt as HandlerObservability, wt as MutationCtx, xi as bytesFromJson, yi as WriteOp, zn as Model, zr as CompareOperator } from "../../index-DB7_pv9P.js";
|
|
2
|
+
export { type ActionConfig, type ActionCtx, type ActionFn, type ActionProcedure, type ActionProcedures, AndPredicate, AndPredicateSchema, type AnyProcedure, type AnyQueryDef, type AppRouter, BigIntSchema, CachedPgMetadata, CachedPgMetadataSchema, type CallOptions, CallerClientInitConfig, CallerFromProcedures, CallerFromRouter, CallerOptions, type ClientEvent, type ClientFromProcedures, type ClientLogLevel, type ClientLogger, type ClientOptions, type ClientPublicState, type ColumnCodec, CommitLogEntry, CommitTs, CompareOperator, CompareOperatorSchema, type ComputedFieldConfig, type ContextOf, DEFAULT_RETRY, type Database, type DbQueryResult, DbReader, DbReader as ReadContext, DbWriter, DbWriter as WritableContext, type DefsToMap, EMPTY_EPHEMERAL_KEYS, EPHEMERAL_DEFAULT_TTL_SECONDS, EphemeralDecodeError, EphemeralFlushError, EphemeralKeyNotFoundError, type EphemeralReader, type EphemeralSetOptions, EphemeralStore, type EphemeralWriter, type HandlerLogger, type HandlerObservability, type HeartbeatOptions, type InferSchema, type InsertData, LeafPredicate, LeafPredicateSchema, type LiveQueryHandle, type LiveQueryState, type LiveQueryStatus, LiveResult, type Model, type MutationConfig, type MutationCtx, type MutationFn, type MutationProcedure, type MutationProcedures, MutationResult, NO_RETRY, OccAbortError, OccConflictError, OrPredicate, OrPredicateSchema, type OutputOf, type ParamsOf, PointRead, PointReadSchema, type PooledClient, Predicate, PredicateSchema, type ProcedureNames, type PublicProcedures, QueryCacheEntry, QueryCacheEntrySchema, QueryCacheMetadata, QueryCacheMetadataSchema, type QueryConfig, type QueryCtx, type QueryDefinition, type QueryFn, type QueryProcedure, type QueryProcedures, QuerySpec, RPCError, RangeRead, RangeReadSchema, type RawClient, RawPointRead, RawPointReadSchema, RawRangeRead, RawRangeReadSchema, RawReadEntry, RawReadEntrySchema, ReadEntry, ReadEntrySchema, type RegisteredProcedure, type ResultOf, RetryConfig, type Router, type SchemaCodecs, type SchemaColumnsOptions, type SchemaDefinition, SupaliveDb, TxContext, type TypeOf, type WSClientMethods, type WSClientOptions, WriteEntry, WriteEntrySchema, WriteOp, WriteOpSchema, WsClientManager, _resetGlobalDefs, bytesFromJson, createActionBuilder, createCaller, createClient, createConsoleLogger, createMemoryEphemeralStore, createMutationBuilder, createQueryBuilder, defineComputedField, defineQuery, defineSchema, matchesPredicate, normalizeIdToBytes, normalizeToBytes, router, sleep };
|
package/dist/src/client/index.js
CHANGED
|
@@ -2,10 +2,11 @@ import { i as createActionBuilder, l as primaryOnlyConn, n as getContextRegistry
|
|
|
2
2
|
import { r as supaliveStringify } from "../../helper-zdJT5FUc.js";
|
|
3
3
|
import { o as matchesPredicate } from "../../query-LJranz0c.js";
|
|
4
4
|
import { n as defineSchema, t as defineComputedField } from "../../schema-DRtz5h5l.js";
|
|
5
|
-
import {
|
|
6
|
-
import { l as
|
|
7
|
-
import {
|
|
8
|
-
import { n as
|
|
5
|
+
import { a as EphemeralKeyNotFoundError, c as createMemoryEphemeralStore, i as EphemeralFlushError, n as EPHEMERAL_DEFAULT_TTL_SECONDS, o as EphemeralStore, r as EphemeralDecodeError, t as EMPTY_EPHEMERAL_KEYS } from "../../ephemeral-CkidSG9y.js";
|
|
6
|
+
import { C as normalizeIdToBytes, S as bytesFromJson, _ as RawRangeReadSchema, a as DEFAULT_RETRY, b as WriteEntrySchema, c as OccAbortError, d as PointReadSchema, f as PredicateSchema, g as RawPointReadSchema, h as RangeReadSchema, i as CompareOperatorSchema, l as OccConflictError, m as QueryCacheMetadataSchema, n as BigIntSchema, o as LeafPredicateSchema, p as QueryCacheEntrySchema, r as CachedPgMetadataSchema, s as NO_RETRY, t as AndPredicateSchema, u as OrPredicateSchema, v as RawReadEntrySchema, w as normalizeToBytes, x as WriteOpSchema, y as ReadEntrySchema } from "../../types_db-DPMeNETt.js";
|
|
7
|
+
import { l as ServerMessageSchema } from "../../types_client_rpc-CqUVHTwT.js";
|
|
8
|
+
import { c as DbReader, l as DbWriter, n as sleep, t as SupaliveDb, u as TxContext } from "../../realtime_db-CTGOrFuV.js";
|
|
9
|
+
import { n as runCachedQueryInParent, t as runCachedQuery } from "../../one-shot-query-DAAHGTcI.js";
|
|
9
10
|
import { sha1 } from "hash-wasm";
|
|
10
11
|
//#region src/db/query_definition.ts
|
|
11
12
|
const _globalDefs = /* @__PURE__ */ new Map();
|
|
@@ -1305,6 +1306,6 @@ function createCaller(options) {
|
|
|
1305
1306
|
} });
|
|
1306
1307
|
}
|
|
1307
1308
|
//#endregion
|
|
1308
|
-
export { AndPredicateSchema, BigIntSchema, CachedPgMetadataSchema, CompareOperatorSchema, DEFAULT_RETRY, DbReader, DbReader as ReadContext, DbWriter, DbWriter as WritableContext, LeafPredicateSchema, NO_RETRY, OccAbortError, OccConflictError, OrPredicateSchema, PointReadSchema, PredicateSchema, QueryCacheEntrySchema, QueryCacheMetadataSchema, RPCError, RangeReadSchema, RawPointReadSchema, RawRangeReadSchema, RawReadEntrySchema, ReadEntrySchema, SupaliveDb, TxContext, WriteEntrySchema, WriteOpSchema, WsClientManager, _resetGlobalDefs, bytesFromJson, createActionBuilder, createCaller, createClient, createConsoleLogger, createMutationBuilder, createQueryBuilder, defineComputedField, defineQuery, defineSchema, matchesPredicate, normalizeIdToBytes, normalizeToBytes, router, sleep };
|
|
1309
|
+
export { AndPredicateSchema, BigIntSchema, CachedPgMetadataSchema, CompareOperatorSchema, DEFAULT_RETRY, DbReader, DbReader as ReadContext, DbWriter, DbWriter as WritableContext, EMPTY_EPHEMERAL_KEYS, EPHEMERAL_DEFAULT_TTL_SECONDS, EphemeralDecodeError, EphemeralFlushError, EphemeralKeyNotFoundError, EphemeralStore, LeafPredicateSchema, NO_RETRY, OccAbortError, OccConflictError, OrPredicateSchema, PointReadSchema, PredicateSchema, QueryCacheEntrySchema, QueryCacheMetadataSchema, RPCError, RangeReadSchema, RawPointReadSchema, RawRangeReadSchema, RawReadEntrySchema, ReadEntrySchema, SupaliveDb, TxContext, WriteEntrySchema, WriteOpSchema, WsClientManager, _resetGlobalDefs, bytesFromJson, createActionBuilder, createCaller, createClient, createConsoleLogger, createMemoryEphemeralStore, createMutationBuilder, createQueryBuilder, defineComputedField, defineQuery, defineSchema, matchesPredicate, normalizeIdToBytes, normalizeToBytes, router, sleep };
|
|
1309
1310
|
|
|
1310
1311
|
//# sourceMappingURL=index.js.map
|