@prisma-next/mongo-runtime 0.5.0-dev.8 → 0.5.0-dev.81
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/README.md +76 -5
- package/dist/index.d.mts +140 -13
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +226 -62
- package/dist/index.mjs.map +1 -1
- package/package.json +22 -19
- package/src/codecs/decoding.ts +170 -0
- package/src/content-hash.ts +53 -0
- package/src/exports/index.ts +17 -0
- package/src/mongo-execution-plan.ts +28 -0
- package/src/mongo-execution-stack.ts +158 -0
- package/src/mongo-middleware.ts +22 -6
- package/src/mongo-runtime.ts +118 -73
package/README.md
CHANGED
|
@@ -2,18 +2,89 @@
|
|
|
2
2
|
|
|
3
3
|
MongoDB runtime executor for Prisma Next.
|
|
4
4
|
|
|
5
|
+
## Package Classification
|
|
6
|
+
|
|
7
|
+
- **Domain**: mongo
|
|
8
|
+
- **Layer**: runtime
|
|
9
|
+
- **Plane**: runtime
|
|
10
|
+
|
|
11
|
+
## Overview
|
|
12
|
+
|
|
13
|
+
The Mongo runtime package implements the Mongo family runtime by extending the abstract `RuntimeCore` base class from `@prisma-next/framework-components/runtime` with Mongo-specific lowering and driver dispatch. It provides the public runtime API for MongoDB, layering Mongo concerns (adapter lowering and wire-command dispatch) on top of the shared middleware lifecycle.
|
|
14
|
+
|
|
15
|
+
## Usage
|
|
16
|
+
|
|
17
|
+
The runtime takes a **`MongoExecutionContext`** built from a **`MongoExecutionStack`** (target + adapter + optional driver + extension packs). The context aggregates codec contributions from each stack component into a single registry — users do not construct or thread a `MongoCodecRegistry` themselves. This mirrors the SQL pattern (see `packages/2-sql/5-runtime/src/sql-context.ts`).
|
|
18
|
+
|
|
19
|
+
Typed reads that attach a **`resultShape`** on the query plan are decoded after the driver yields each row: scalars and scalar arrays run through their `codecId` entries; `kind: 'unknown'` subtrees are passed through unchanged; plans without `resultShape` (for example raw commands) leave rows as the driver returned them.
|
|
20
|
+
|
|
21
|
+
Example:
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import mongoRuntimeAdapter from '@prisma-next/adapter-mongo/runtime';
|
|
25
|
+
import { createMongoDriver } from '@prisma-next/driver-mongo';
|
|
26
|
+
import {
|
|
27
|
+
createMongoExecutionContext,
|
|
28
|
+
createMongoExecutionStack,
|
|
29
|
+
createMongoRuntime,
|
|
30
|
+
} from '@prisma-next/mongo-runtime';
|
|
31
|
+
import mongoRuntimeTarget from '@prisma-next/target-mongo/runtime';
|
|
32
|
+
|
|
33
|
+
const stack = createMongoExecutionStack({
|
|
34
|
+
target: mongoRuntimeTarget,
|
|
35
|
+
adapter: mongoRuntimeAdapter,
|
|
36
|
+
});
|
|
37
|
+
const context = createMongoExecutionContext({ contract, stack });
|
|
38
|
+
|
|
39
|
+
const runtime = createMongoRuntime({
|
|
40
|
+
context,
|
|
41
|
+
driver: await createMongoDriver(url, dbName),
|
|
42
|
+
});
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Custom or third-party codecs (encryption, vendor scalars) are contributed via an extension-pack descriptor whose `codecs` slot returns the codec descriptors; `createMongoExecutionContext` folds them into the same registry. Duplicate codec ids across contributors throw `RUNTIME.DUPLICATE_CODEC` at composition time.
|
|
46
|
+
|
|
5
47
|
## Responsibilities
|
|
6
48
|
|
|
7
|
-
- **
|
|
49
|
+
- **Stack/context composition**: `createMongoExecutionStack` and `createMongoExecutionContext` mirror SQL's `createSqlExecutionStack` / `createExecutionContext`. The context aggregates codec contributions from `[stack.target, stack.adapter, ...stack.extensionPacks]` into a single `MongoCodecRegistry`.
|
|
50
|
+
- **Runtime executor**: `createMongoRuntime({ context, driver, ... })` composes context and driver into a `MongoRuntime` with a single `execute(plan)` entry point accepting `MongoQueryPlan<Row>` from `@prisma-next/mongo-query-ast`. The adapter is reached via `context.stack.adapter` (instantiated lazily through the stack's `create(stack)` factory). Execution lowers the plan through the adapter, runs the wire command on the driver, then **optionally decodes** each row when `plan.resultShape` is present.
|
|
8
51
|
- **Unified flow**: There is no separate `execute` vs `executeCommand`; all operations use `execute(plan)`.
|
|
9
|
-
- **Lowering**: Happens in the adapter (`lower(plan)`),
|
|
10
|
-
- **
|
|
52
|
+
- **Lowering**: Happens in the adapter (`lower(plan)`), wrapped by the runtime's `lower` override into a `MongoExecutionPlan`.
|
|
53
|
+
- **Middleware lifecycle inheritance**: `MongoRuntime` extends `RuntimeCore<MongoQueryPlan, MongoExecutionPlan, MongoMiddleware>` and inherits the `beforeExecute` / `onRow` / `afterExecute` lifecycle from the framework via `runWithMiddleware`. Mongo does **not** override `runBeforeCompile` (Mongo middleware has no `beforeCompile` hook today).
|
|
54
|
+
- **Lifecycle management**: Connection lifecycle via `close()`.
|
|
11
55
|
|
|
12
56
|
## Dependencies
|
|
13
57
|
|
|
14
58
|
- **Depends on**:
|
|
59
|
+
- `@prisma-next/mongo-codec` (`MongoCodecRegistry` for decode)
|
|
15
60
|
- `@prisma-next/mongo-lowering` (`MongoAdapter`, `MongoDriver` interfaces)
|
|
16
61
|
- `@prisma-next/mongo-query-ast` (`MongoQueryPlan`, `AnyMongoCommand` — the typed plan shape)
|
|
17
|
-
- `@prisma-next/
|
|
62
|
+
- `@prisma-next/framework-components` (`RuntimeCore` base class, `runWithMiddleware` helper, `RuntimeMiddleware` SPI, `AsyncIterableResult` return type, `RuntimeAdapterDescriptor` / `ExecutionStack` for the stack composition model)
|
|
18
63
|
- **Depended on by**:
|
|
19
|
-
- Integration tests (`test/integration/test/mongo/`)
|
|
64
|
+
- Integration tests (`test/integration/test/mongo/` and `test/integration/test/cross-package/cross-family-middleware.test.ts`)
|
|
65
|
+
|
|
66
|
+
## Architecture
|
|
67
|
+
|
|
68
|
+
`MongoRuntimeImpl` extends `RuntimeCore<MongoQueryPlan, MongoExecutionPlan, MongoMiddleware>` and overrides:
|
|
69
|
+
|
|
70
|
+
- `lower(plan)` — calls the adapter's `lower(plan)` and wraps the resulting wire command into a `MongoExecutionPlan`.
|
|
71
|
+
- `runDriver(exec)` — dispatches the wire command to the Mongo driver via `driver.execute(exec.command)`.
|
|
72
|
+
- `close()` — closes the underlying driver.
|
|
73
|
+
|
|
74
|
+
`MongoRuntimeImpl` extends `RuntimeCore` but **overrides `execute`** so that after `runWithMiddleware` yields a raw driver row, the runtime can **`decodeMongoRow`** when the lowered plan carries `resultShape`, then yield the decoded row. `lower(plan)` copies `resultShape` from the query plan onto `MongoExecutionPlan`. Middleware `onRow` still sees the raw driver row (decode happens after the middleware loop for that row, before the consumer receives the value).
|
|
75
|
+
|
|
76
|
+
The execution template is: `lower` → `runWithMiddleware` (driver loop + middleware) → **per-row decode when `exec.resultShape` is set** → yield to consumer.
|
|
77
|
+
|
|
78
|
+
```mermaid
|
|
79
|
+
flowchart LR
|
|
80
|
+
Plan[MongoQueryPlan] --> Runtime[MongoRuntime]
|
|
81
|
+
Runtime -.extends.-> Core[RuntimeCore]
|
|
82
|
+
Runtime --> Adapter[MongoAdapter.lower]
|
|
83
|
+
Adapter --> Exec[MongoExecutionPlan]
|
|
84
|
+
Runtime --> Driver[MongoDriver.execute]
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## Related Subsystems
|
|
88
|
+
|
|
89
|
+
- **[Runtime & Middleware Framework](../../../../docs/architecture%20docs/subsystems/4.%20Runtime%20&%20Middleware%20Framework.md)** — Runtime execution pipeline
|
|
90
|
+
- **[Adapters & Targets](../../../../docs/architecture%20docs/subsystems/5.%20Adapters%20&%20Targets.md)** — Adapter and driver responsibilities
|
package/dist/index.d.mts
CHANGED
|
@@ -1,30 +1,157 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { RuntimeAdapterDescriptor, RuntimeAdapterInstance, RuntimeDriverDescriptor, RuntimeDriverInstance, RuntimeExtensionDescriptor, RuntimeExtensionInstance, RuntimeTargetDescriptor, RuntimeTargetInstance, RuntimeTargetInstance as RuntimeTargetInstance$1 } from "@prisma-next/framework-components/execution";
|
|
2
|
+
import { AfterExecuteResult, AsyncIterableResult, ExecutionPlan, ParamRefMutator, RuntimeExecuteOptions, RuntimeMiddleware, RuntimeMiddlewareContext } from "@prisma-next/framework-components/runtime";
|
|
3
|
+
import { MongoCodec, MongoCodecRegistry } from "@prisma-next/mongo-codec";
|
|
4
|
+
import { MongoQueryPlan, MongoResultShape } from "@prisma-next/mongo-query-ast/execution";
|
|
5
|
+
import { AnyMongoWireCommand } from "@prisma-next/mongo-wire";
|
|
3
6
|
import { MongoAdapter, MongoDriver } from "@prisma-next/mongo-lowering";
|
|
4
7
|
|
|
8
|
+
//#region src/mongo-execution-plan.d.ts
|
|
9
|
+
/**
|
|
10
|
+
* Mongo-domain execution plan: a query lowered to the wire-command shape
|
|
11
|
+
* that a Mongo driver can run.
|
|
12
|
+
*
|
|
13
|
+
* The plan carries:
|
|
14
|
+
* - `command` — the wire command (e.g. `InsertOneWireCommand`,
|
|
15
|
+
* `AggregateWireCommand`) produced by `MongoAdapter.lower(plan)`
|
|
16
|
+
* - `meta` — family-agnostic plan metadata (target, lane, hashes, ...)
|
|
17
|
+
* - `_row` — phantom row type, propagated from the originating
|
|
18
|
+
* `MongoQueryPlan`
|
|
19
|
+
*
|
|
20
|
+
* Extends the framework-level `ExecutionPlan<Row>` marker so generic SPIs
|
|
21
|
+
* (`RuntimeExecutor<MongoExecutionPlan>`,
|
|
22
|
+
* `RuntimeMiddleware<MongoExecutionPlan>`) can be parameterized over it.
|
|
23
|
+
*
|
|
24
|
+
* Lives in the runtime layer (alongside `MongoRuntime`) because the wire
|
|
25
|
+
* command shape lives in the transport layer (`@prisma-next/mongo-wire`),
|
|
26
|
+
* which the lanes layer (`mongo-query-ast`, where `MongoQueryPlan` lives)
|
|
27
|
+
* cannot depend on.
|
|
28
|
+
*/
|
|
29
|
+
interface MongoExecutionPlan<Row = unknown> extends ExecutionPlan<Row> {
|
|
30
|
+
readonly command: AnyMongoWireCommand;
|
|
31
|
+
readonly resultShape?: MongoResultShape;
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
//#region src/mongo-execution-stack.d.ts
|
|
35
|
+
/**
|
|
36
|
+
* Mongo-specific static contributions a runtime descriptor declares.
|
|
37
|
+
*
|
|
38
|
+
* Mirrors `SqlStaticContributions` in shape: a `codecs()` getter that yields a `MongoCodecRegistry` populated with this contributor's codecs. The registry is then walked by `createMongoExecutionContext` and folded into the single per-execution registry the runtime reads from at decode time.
|
|
39
|
+
*/
|
|
40
|
+
interface MongoStaticContributions {
|
|
41
|
+
readonly codecs: () => MongoCodecRegistry;
|
|
42
|
+
}
|
|
43
|
+
interface MongoRuntimeTargetDescriptor<TTargetId extends string = 'mongo', TTargetInstance extends RuntimeTargetInstance$1<'mongo', TTargetId> = RuntimeTargetInstance$1<'mongo', TTargetId>> extends RuntimeTargetDescriptor<'mongo', TTargetId, TTargetInstance>, MongoStaticContributions {}
|
|
44
|
+
interface MongoRuntimeAdapterInstance<TTargetId extends string = 'mongo'> extends RuntimeAdapterInstance<'mongo', TTargetId>, MongoAdapter {}
|
|
45
|
+
interface MongoRuntimeAdapterDescriptor<TTargetId extends string = 'mongo', TAdapterInstance extends RuntimeAdapterInstance<'mongo', TTargetId> = MongoRuntimeAdapterInstance<TTargetId>> extends RuntimeAdapterDescriptor<'mongo', TTargetId, TAdapterInstance>, MongoStaticContributions {}
|
|
46
|
+
interface MongoRuntimeExtensionInstance<TTargetId extends string = 'mongo'> extends RuntimeExtensionInstance<'mongo', TTargetId> {}
|
|
47
|
+
interface MongoRuntimeExtensionDescriptor<TTargetId extends string = 'mongo'> extends RuntimeExtensionDescriptor<'mongo', TTargetId, MongoRuntimeExtensionInstance<TTargetId>>, MongoStaticContributions {
|
|
48
|
+
create(): MongoRuntimeExtensionInstance<TTargetId>;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The Mongo execution stack: target + adapter + optional driver + extension packs. Mirrors `SqlExecutionStack`. Constructed via `createMongoExecutionStack`.
|
|
52
|
+
*/
|
|
53
|
+
interface MongoExecutionStack<TTargetId extends string = 'mongo'> {
|
|
54
|
+
readonly target: MongoRuntimeTargetDescriptor<TTargetId>;
|
|
55
|
+
readonly adapter: MongoRuntimeAdapterDescriptor<TTargetId>;
|
|
56
|
+
readonly driver: RuntimeDriverDescriptor<'mongo', TTargetId, unknown, RuntimeDriverInstance<'mongo', TTargetId>> | undefined;
|
|
57
|
+
readonly extensionPacks: readonly MongoRuntimeExtensionDescriptor<TTargetId>[];
|
|
58
|
+
}
|
|
59
|
+
declare function createMongoExecutionStack<TTargetId extends string = 'mongo'>(options: {
|
|
60
|
+
readonly target: MongoRuntimeTargetDescriptor<TTargetId>;
|
|
61
|
+
readonly adapter: MongoRuntimeAdapterDescriptor<TTargetId>;
|
|
62
|
+
readonly driver?: RuntimeDriverDescriptor<'mongo', TTargetId, unknown, RuntimeDriverInstance<'mongo', TTargetId>> | undefined;
|
|
63
|
+
readonly extensionPacks?: readonly MongoRuntimeExtensionDescriptor<TTargetId>[] | undefined;
|
|
64
|
+
}): MongoExecutionStack<TTargetId>;
|
|
65
|
+
/**
|
|
66
|
+
* Read-only view of the codec registry exposed on `MongoExecutionContext`.
|
|
67
|
+
*
|
|
68
|
+
* Hides `register()` and the iterator from public surface — users do not mutate the per-execution codec registry. Internal aggregation in `createMongoExecutionContext` keeps using the full `MongoCodecRegistry` (it needs `register()`).
|
|
69
|
+
*/
|
|
70
|
+
interface MongoCodecLookup {
|
|
71
|
+
get(id: string): MongoCodec<string> | undefined;
|
|
72
|
+
has(id: string): boolean;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Per-execution context aggregated from a `MongoExecutionStack`.
|
|
76
|
+
*
|
|
77
|
+
* Carries the user's contract, a read-only lookup over the codec registry composed from every stack contributor, and a back-reference to the stack itself so the runtime can reach the adapter without users threading it explicitly.
|
|
78
|
+
*
|
|
79
|
+
* Mirrors SQL's `ExecutionContext` in role; Mongo's flavour is leaner because there are no parameterised codecs, JSON-schema validators, or mutation-default generators in scope yet.
|
|
80
|
+
*/
|
|
81
|
+
interface MongoExecutionContext<TTargetId extends string = 'mongo'> {
|
|
82
|
+
readonly contract: unknown;
|
|
83
|
+
readonly codecs: MongoCodecLookup;
|
|
84
|
+
readonly stack: MongoExecutionStack<TTargetId>;
|
|
85
|
+
}
|
|
86
|
+
declare function createMongoExecutionContext<TTargetId extends string = 'mongo'>(options: {
|
|
87
|
+
readonly contract: unknown;
|
|
88
|
+
readonly stack: MongoExecutionStack<TTargetId>;
|
|
89
|
+
}): MongoExecutionContext<TTargetId>;
|
|
90
|
+
//#endregion
|
|
5
91
|
//#region src/mongo-middleware.d.ts
|
|
6
92
|
interface MongoMiddlewareContext extends RuntimeMiddlewareContext {}
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
93
|
+
/**
|
|
94
|
+
* Mongo-domain middleware. Extends the framework `RuntimeMiddleware`
|
|
95
|
+
* parameterized over `MongoExecutionPlan` because `runWithMiddleware`
|
|
96
|
+
* (driven by `RuntimeCore`) invokes the lifecycle hooks with the
|
|
97
|
+
* post-lowering plan.
|
|
98
|
+
*
|
|
99
|
+
* `familyId` is optional so generic cross-family middleware (e.g.
|
|
100
|
+
* telemetry) — which carry no `familyId` — remain assignable. When
|
|
101
|
+
* present, it must be `'mongo'`; the runtime rejects mismatches at
|
|
102
|
+
* construction time via `checkMiddlewareCompatibility`.
|
|
103
|
+
*/
|
|
104
|
+
interface MongoMiddleware extends RuntimeMiddleware<MongoExecutionPlan> {
|
|
105
|
+
readonly familyId?: 'mongo';
|
|
106
|
+
beforeExecute?(plan: MongoExecutionPlan, ctx: MongoMiddlewareContext, params?: ParamRefMutator): void | Promise<void>;
|
|
107
|
+
onRow?(row: Record<string, unknown>, plan: MongoExecutionPlan, ctx: MongoMiddlewareContext): Promise<void>;
|
|
108
|
+
afterExecute?(plan: MongoExecutionPlan, result: AfterExecuteResult, ctx: MongoMiddlewareContext): Promise<void>;
|
|
12
109
|
}
|
|
13
110
|
//#endregion
|
|
14
111
|
//#region src/mongo-runtime.d.ts
|
|
112
|
+
/**
|
|
113
|
+
* Mongo runtime options.
|
|
114
|
+
*
|
|
115
|
+
* The runtime takes a {@link MongoExecutionContext} (built via
|
|
116
|
+
* `createMongoExecutionContext`) and a driver. Codec resolution flows from
|
|
117
|
+
* the context — there is no `codecs` field on this options bag. The adapter
|
|
118
|
+
* is reached via `context.stack.adapter` (instantiated lazily through the
|
|
119
|
+
* stack's `create(stack)` factory). See ADR — Mongo result-shape as a
|
|
120
|
+
* structural plan field, § Codec registry: stack aggregation, not user
|
|
121
|
+
* threading.
|
|
122
|
+
*/
|
|
15
123
|
interface MongoRuntimeOptions {
|
|
16
|
-
readonly
|
|
124
|
+
readonly context: MongoExecutionContext;
|
|
17
125
|
readonly driver: MongoDriver;
|
|
18
|
-
readonly
|
|
19
|
-
readonly targetId: string;
|
|
20
|
-
readonly middleware?: readonly RuntimeMiddleware[];
|
|
126
|
+
readonly middleware?: readonly MongoMiddleware[];
|
|
21
127
|
readonly mode?: 'strict' | 'permissive';
|
|
22
128
|
}
|
|
23
129
|
interface MongoRuntime {
|
|
24
|
-
|
|
130
|
+
/**
|
|
131
|
+
* Execute a `MongoQueryPlan` and return an async iterable of rows.
|
|
132
|
+
*
|
|
133
|
+
* The optional `options.signal` is threaded through
|
|
134
|
+
* `lower → adapter.lower → resolveValue → codec.encode` so codec authors
|
|
135
|
+
* who forward the signal to their underlying SDK get true cancellation
|
|
136
|
+
* of in-flight network calls. The runtime additionally observes the
|
|
137
|
+
* signal at two boundaries:
|
|
138
|
+
*
|
|
139
|
+
* - **Already-aborted at entry** — first `next()` throws
|
|
140
|
+
* `RUNTIME.ABORTED { phase: 'stream' }` before any work is done.
|
|
141
|
+
* (Inherited from `RuntimeCore.execute`.)
|
|
142
|
+
* - **Mid-encode abort** — surfaces as
|
|
143
|
+
* `RUNTIME.ABORTED { phase: 'encode' }` from inside `resolveValue`'s
|
|
144
|
+
* per-level `Promise.all` race.
|
|
145
|
+
*
|
|
146
|
+
* Mongo's read path decodes rows via `resultShape` (per ADR 209). The
|
|
147
|
+
* same `CodecCallContext` is forwarded into each `codec.decode(wire, ctx)`
|
|
148
|
+
* call, so async decoders that respect the signal get cancellation; the
|
|
149
|
+
* runtime itself does not currently emit a `phase: 'decode'` envelope.
|
|
150
|
+
*/
|
|
151
|
+
execute<Row>(plan: MongoQueryPlan<Row>, options?: RuntimeExecuteOptions): AsyncIterableResult<Row>;
|
|
25
152
|
close(): Promise<void>;
|
|
26
153
|
}
|
|
27
154
|
declare function createMongoRuntime(options: MongoRuntimeOptions): MongoRuntime;
|
|
28
155
|
//#endregion
|
|
29
|
-
export { type MongoMiddleware, type MongoMiddlewareContext, type MongoRuntime, type MongoRuntimeOptions, createMongoRuntime };
|
|
156
|
+
export { type MongoCodecLookup, type MongoExecutionContext, type MongoExecutionPlan, type MongoExecutionStack, type MongoMiddleware, type MongoMiddlewareContext, type MongoRuntime, type MongoRuntimeAdapterDescriptor, type MongoRuntimeAdapterInstance, type MongoRuntimeExtensionDescriptor, type MongoRuntimeExtensionInstance, type MongoRuntimeOptions, type MongoRuntimeTargetDescriptor, type MongoStaticContributions, type RuntimeTargetInstance, createMongoExecutionContext, createMongoExecutionStack, createMongoRuntime };
|
|
30
157
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/mongo-
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/mongo-execution-plan.ts","../src/mongo-execution-stack.ts","../src/mongo-middleware.ts","../src/mongo-runtime.ts"],"mappings":";;;;;;;;;;;;;AAwBA;;;;;;;;;;;;;;;UAAiB,kBAAA,wBAA0C,aAAA,CAAc,GAAA;EAAA,SAC9D,OAAA,EAAS,mBAAA;EAAA,SACT,WAAA,GAAc,gBAAA;AAAA;;;;;;;AAFzB;UCFiB,wBAAA;EAAA,SACN,MAAA,QAAc,kBAAA;AAAA;AAAA,UAGR,4BAAA,6DAES,uBAAA,UAA+B,SAAA,IAAa,uBAAA,UAElE,SAAA,WAEM,uBAAA,UAAiC,SAAA,EAAW,eAAA,GAClD,wBAAA;AAAA,UAEa,2BAAA,6CACP,sBAAA,UAAgC,SAAA,GACtC,YAAA;AAAA,UAEa,6BAAA,8DAEU,sBAAA,UAEvB,SAAA,IACE,2BAAA,CAA4B,SAAA,WACxB,wBAAA,UAAkC,SAAA,EAAW,gBAAA,GACnD,wBAAA;AAAA,UAEa,6BAAA,6CACP,wBAAA,UAAkC,SAAA;AAAA,UAE3B,+BAAA,6CACP,0BAAA,UAAoC,SAAA,EAAW,6BAAA,CAA8B,SAAA,IACnF,wBAAA;EACF,MAAA,IAAU,6BAAA,CAA8B,SAAA;AAAA;;;;UAMzB,mBAAA;EAAA,SACN,MAAA,EAAQ,4BAAA,CAA6B,SAAA;EAAA,SACrC,OAAA,EAAS,6BAAA,CAA8B,SAAA;EAAA,SACvC,MAAA,EACL,uBAAA,UAEE,SAAA,WAEA,qBAAA,UAA+B,SAAA;EAAA,SAG5B,cAAA,WAAyB,+BAAA,CAAgC,SAAA;AAAA;AAAA,iBAGpD,yBAAA,oCAAA,CAA8D,OAAA;EAAA,SACnE,MAAA,EAAQ,4BAAA,CAA6B,SAAA;EAAA,SACrC,OAAA,EAAS,6BAAA,CAA8B,SAAA;EAAA,SACvC,MAAA,GACL,uBAAA,UAEE,SAAA,WAEA,qBAAA,UAA+B,SAAA;EAAA,SAG5B,cAAA,YAA0B,+BAAA,CAAgC,SAAA;AAAA,IACjE,mBAAA,CAAoB,SAAA;;;;;;UAeP,gBAAA;EACf,GAAA,CAAI,EAAA,WAAa,UAAA;EACjB,GAAA,CAAI,EAAA;AAAA;;;;;;;;UAUW,qBAAA;EAAA,SACN,QAAA;EAAA,SACA,MAAA,EAAQ,gBAAA;EAAA,SACR,KAAA,EAAO,mBAAA,CAAoB,SAAA;AAAA;AAAA,iBAGtB,2BAAA,oCAAA,CAAgE,OAAA;EAAA,SACrE,QAAA;EAAA,SACA,KAAA,EAAO,mBAAA,CAAoB,SAAA;AAAA,IAClC,qBAAA,CAAsB,SAAA;;;UClHT,sBAAA,SAA+B,wBAAA;;;;;AFgBhD;;;;;;;UEHiB,eAAA,SAAwB,iBAAA,CAAkB,kBAAA;EAAA,SAChD,QAAA;EACT,aAAA,EACE,IAAA,EAAM,kBAAA,EACN,GAAA,EAAK,sBAAA,EACL,MAAA,GAAS,eAAA,UACD,OAAA;EACV,KAAA,EACE,GAAA,EAAK,MAAA,mBACL,IAAA,EAAM,kBAAA,EACN,GAAA,EAAK,sBAAA,GACJ,OAAA;EACH,YAAA,EACE,IAAA,EAAM,kBAAA,EACN,MAAA,EAAQ,kBAAA,EACR,GAAA,EAAK,sBAAA,GACJ,OAAA;AAAA;;;;;;AFbL;;;;;;;;UGOiB,mBAAA;EAAA,SACN,OAAA,EAAS,qBAAA;EAAA,SACT,MAAA,EAAQ,WAAA;EAAA,SACR,UAAA,YAAsB,eAAA;EAAA,SACtB,IAAA;AAAA;AAAA,UAGM,YAAA;EHZQ;;;;;;ACJzB;;;;;AAIA;;;;;;;;;;EEkCE,OAAA,MACE,IAAA,EAAM,cAAA,CAAe,GAAA,GACrB,OAAA,GAAU,qBAAA,GACT,mBAAA,CAAoB,GAAA;EACvB,KAAA,IAAS,OAAA;AAAA;AAAA,iBAiGK,kBAAA,CAAmB,OAAA,EAAS,mBAAA,GAAsB,YAAA"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,77 +1,241 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { createExecutionStack } from "@prisma-next/framework-components/execution";
|
|
2
|
+
import { AsyncIterableResult, RuntimeCore, checkAborted, checkMiddlewareCompatibility, runWithMiddleware, runtimeError } from "@prisma-next/framework-components/runtime";
|
|
3
|
+
import { newMongoCodecRegistry } from "@prisma-next/mongo-codec";
|
|
4
|
+
import { ifDefined } from "@prisma-next/utils/defined";
|
|
5
|
+
import { canonicalStringify } from "@prisma-next/utils/canonical-stringify";
|
|
6
|
+
import { hashContent } from "@prisma-next/utils/hash-content";
|
|
7
|
+
//#region src/mongo-execution-stack.ts
|
|
8
|
+
function createMongoExecutionStack(options) {
|
|
9
|
+
return createExecutionStack({
|
|
10
|
+
target: options.target,
|
|
11
|
+
adapter: options.adapter,
|
|
12
|
+
driver: options.driver,
|
|
13
|
+
extensionPacks: options.extensionPacks
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
function createMongoExecutionContext(options) {
|
|
17
|
+
const registry = newMongoCodecRegistry();
|
|
18
|
+
const owners = /* @__PURE__ */ new Map();
|
|
19
|
+
const contributors = [
|
|
20
|
+
options.stack.target,
|
|
21
|
+
options.stack.adapter,
|
|
22
|
+
...options.stack.extensionPacks
|
|
23
|
+
];
|
|
24
|
+
for (const contributor of contributors) {
|
|
25
|
+
const contributed = contributor.codecs();
|
|
26
|
+
for (const codec of iterateCodecs(contributed)) {
|
|
27
|
+
const existingOwner = owners.get(codec.id);
|
|
28
|
+
if (existingOwner !== void 0) throw runtimeError("RUNTIME.DUPLICATE_CODEC", `Duplicate Mongo codec id '${codec.id}' contributed by '${contributor.id}' (already registered by '${existingOwner}').`, {
|
|
29
|
+
codecId: codec.id,
|
|
30
|
+
existingOwner,
|
|
31
|
+
incomingOwner: contributor.id
|
|
32
|
+
});
|
|
33
|
+
registry.register(codec);
|
|
34
|
+
owners.set(codec.id, contributor.id);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return Object.freeze({
|
|
38
|
+
contract: options.contract,
|
|
39
|
+
codecs: registry,
|
|
40
|
+
stack: options.stack
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
function* iterateCodecs(registry) {
|
|
44
|
+
yield* registry.values();
|
|
45
|
+
}
|
|
46
|
+
//#endregion
|
|
47
|
+
//#region src/codecs/decoding.ts
|
|
48
|
+
const WIRE_PREVIEW_LIMIT = 100;
|
|
49
|
+
function previewWireValue(wireValue) {
|
|
50
|
+
if (typeof wireValue === "string") return wireValue.length > WIRE_PREVIEW_LIMIT ? `${wireValue.substring(0, WIRE_PREVIEW_LIMIT)}...` : wireValue;
|
|
51
|
+
return String(wireValue).substring(0, WIRE_PREVIEW_LIMIT);
|
|
52
|
+
}
|
|
53
|
+
function wrapDecodeFailure(error, collection, path, codecId, wireValue) {
|
|
54
|
+
const wrapped = runtimeError("RUNTIME.DECODE_FAILED", `Failed to decode field ${path} in collection '${collection}' with codec '${codecId}': ${error instanceof Error ? error.message : String(error)}`, {
|
|
55
|
+
collection,
|
|
56
|
+
path,
|
|
57
|
+
codec: codecId,
|
|
58
|
+
wirePreview: previewWireValue(wireValue)
|
|
59
|
+
});
|
|
60
|
+
wrapped.cause = error;
|
|
61
|
+
throw wrapped;
|
|
62
|
+
}
|
|
63
|
+
async function decodeMongoRow(row, shape, registry, collection, ctx = {}) {
|
|
64
|
+
if (shape.kind === "unknown") return row;
|
|
65
|
+
if (typeof row !== "object" || row === null) return row;
|
|
66
|
+
const rowObj = row;
|
|
67
|
+
const out = {};
|
|
68
|
+
const tasks = [];
|
|
69
|
+
function scheduleLeaf(path, codecId, wire, assign) {
|
|
70
|
+
const codec = registry.get(codecId);
|
|
71
|
+
if (!codec) {
|
|
72
|
+
assign(wire);
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
tasks.push((async () => {
|
|
76
|
+
try {
|
|
77
|
+
assign(await codec.decode(wire, ctx));
|
|
78
|
+
} catch (error) {
|
|
79
|
+
wrapDecodeFailure(error, collection, path, codecId, wire);
|
|
80
|
+
}
|
|
81
|
+
})());
|
|
82
|
+
}
|
|
83
|
+
function walkField(value, fieldShape, path, assign) {
|
|
84
|
+
switch (fieldShape.kind) {
|
|
85
|
+
case "unknown":
|
|
86
|
+
assign(value);
|
|
87
|
+
return;
|
|
88
|
+
case "leaf":
|
|
89
|
+
if (value === null || value === void 0) {
|
|
90
|
+
assign(value);
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
scheduleLeaf(path, fieldShape.codecId, value, assign);
|
|
94
|
+
return;
|
|
95
|
+
case "document": {
|
|
96
|
+
if (value === null || value === void 0) {
|
|
97
|
+
assign(value);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
101
|
+
assign(value);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
const vObj = value;
|
|
105
|
+
const nested = { ...vObj };
|
|
106
|
+
assign(nested);
|
|
107
|
+
for (const [fk, fShape] of Object.entries(fieldShape.fields)) walkField(vObj[fk], fShape, `${path}.${fk}`, (v) => {
|
|
108
|
+
nested[fk] = v;
|
|
109
|
+
});
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
case "array": {
|
|
113
|
+
if (value === null || value === void 0) {
|
|
114
|
+
assign(value);
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
if (!Array.isArray(value)) {
|
|
118
|
+
assign(value);
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
const arr = [];
|
|
122
|
+
assign(arr);
|
|
123
|
+
for (let i = 0; i < value.length; i++) {
|
|
124
|
+
const el = value[i];
|
|
125
|
+
walkField(el, fieldShape.element, `${path}.${i}`, (v) => {
|
|
126
|
+
arr[i] = v;
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/* v8 ignore stop */
|
|
133
|
+
}
|
|
134
|
+
for (const [k, fShape] of Object.entries(shape.fields)) walkField(rowObj[k], fShape, k, (v) => {
|
|
135
|
+
out[k] = v;
|
|
136
|
+
});
|
|
137
|
+
for (const k of Object.keys(rowObj)) if (!Object.hasOwn(shape.fields, k)) out[k] = rowObj[k];
|
|
138
|
+
await Promise.all(tasks);
|
|
139
|
+
return out;
|
|
140
|
+
}
|
|
141
|
+
//#endregion
|
|
142
|
+
//#region src/content-hash.ts
|
|
143
|
+
/**
|
|
144
|
+
* Computes a stable content hash for a lowered Mongo execution plan.
|
|
145
|
+
*
|
|
146
|
+
* Internally builds an unambiguous canonical-stringified preimage from
|
|
147
|
+
* two components:
|
|
148
|
+
*
|
|
149
|
+
* 1. `meta.storageHash` — discriminates by schema. A migration changes the
|
|
150
|
+
* storage hash, which invalidates cached entries automatically (no
|
|
151
|
+
* per-app invalidation logic needed for schema changes).
|
|
152
|
+
* 2. `exec.command` — the wire command. `canonicalStringify` produces a
|
|
153
|
+
* deterministic serialization that is stable across object key
|
|
154
|
+
* insertion order and that distinguishes types JSON would otherwise
|
|
155
|
+
* conflate (e.g. `BigInt(1)` vs `1`, `Date` vs ISO string, `Buffer`
|
|
156
|
+
* vs number array). The spread converts the frozen wire-command
|
|
157
|
+
* class instance (`InsertOneWireCommand`, `AggregateWireCommand`, …)
|
|
158
|
+
* into a plain object exposing its own enumerable properties
|
|
159
|
+
* (`kind`, `collection`, plus the payload-specific fields like
|
|
160
|
+
* `document`/`filter`/`update`/`pipeline`/…), which is what
|
|
161
|
+
* `canonicalStringify` accepts; class instances are rejected
|
|
162
|
+
* outright to prevent silent collisions.
|
|
163
|
+
*
|
|
164
|
+
* Unlike SQL, there is no separate "rendered statement" component because
|
|
165
|
+
* a Mongo `MongoExecutionPlan.command` is the wire command itself —
|
|
166
|
+
* canonicalizing it captures both structure and parameters in one pass.
|
|
167
|
+
*
|
|
168
|
+
* The components are wrapped in an object and canonicalized as a single
|
|
169
|
+
* unit (rather than concatenated with a delimiter) so component
|
|
170
|
+
* boundaries are unambiguous and cannot collide with a different split
|
|
171
|
+
* of the same characters.
|
|
172
|
+
*
|
|
173
|
+
* The canonical string is then piped through `hashContent` to produce a
|
|
174
|
+
* bounded, opaque digest. See `@prisma-next/utils/hash-content` for the
|
|
175
|
+
* rationale.
|
|
176
|
+
*
|
|
177
|
+
* @internal
|
|
178
|
+
*/
|
|
179
|
+
function computeMongoContentHash(exec) {
|
|
180
|
+
return hashContent(canonicalStringify({
|
|
181
|
+
storageHash: exec.meta.storageHash,
|
|
182
|
+
command: { ...exec.command }
|
|
183
|
+
}));
|
|
184
|
+
}
|
|
185
|
+
//#endregion
|
|
3
186
|
//#region src/mongo-runtime.ts
|
|
4
187
|
function noop() {}
|
|
5
|
-
|
|
6
|
-
return Date.now();
|
|
7
|
-
}
|
|
8
|
-
var MongoRuntimeImpl = class {
|
|
188
|
+
var MongoRuntimeImpl = class extends RuntimeCore {
|
|
9
189
|
#adapter;
|
|
10
190
|
#driver;
|
|
11
|
-
#
|
|
12
|
-
#middlewareContext;
|
|
191
|
+
#codecs;
|
|
13
192
|
constructor(options) {
|
|
14
|
-
this.#adapter = options.adapter;
|
|
15
|
-
this.#driver = options.driver;
|
|
16
193
|
const middleware = options.middleware ? [...options.middleware] : [];
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
contract: options.contract,
|
|
194
|
+
const targetId = options.context.stack.target.targetId;
|
|
195
|
+
for (const mw of middleware) checkMiddlewareCompatibility(mw, "mongo", targetId);
|
|
196
|
+
const ctx = {
|
|
197
|
+
contract: options.context.contract,
|
|
21
198
|
mode: options.mode ?? "strict",
|
|
22
|
-
now,
|
|
199
|
+
now: () => Date.now(),
|
|
23
200
|
log: {
|
|
24
201
|
info: noop,
|
|
25
202
|
warn: noop,
|
|
26
203
|
error: noop
|
|
27
|
-
}
|
|
204
|
+
},
|
|
205
|
+
contentHash: (exec) => computeMongoContentHash(exec)
|
|
28
206
|
};
|
|
207
|
+
super({
|
|
208
|
+
middleware,
|
|
209
|
+
ctx
|
|
210
|
+
});
|
|
211
|
+
const adapterInstance = options.context.stack.adapter.create(options.context.stack);
|
|
212
|
+
this.#adapter = adapterInstance;
|
|
213
|
+
this.#driver = options.driver;
|
|
214
|
+
this.#codecs = options.context.codecs;
|
|
29
215
|
}
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
const iterator = async function* () {
|
|
36
|
-
const startedAt = ctx.now();
|
|
37
|
-
let rowCount = 0;
|
|
38
|
-
let completed = false;
|
|
39
|
-
let failed = false;
|
|
40
|
-
try {
|
|
41
|
-
for (const mw of middleware) if (mw.beforeExecute) await mw.beforeExecute(plan, ctx);
|
|
42
|
-
const wireCommand = await adapter.lower(plan);
|
|
43
|
-
for await (const row of driver.execute(wireCommand)) {
|
|
44
|
-
for (const mw of middleware) if (mw.onRow) await mw.onRow(row, plan, ctx);
|
|
45
|
-
rowCount++;
|
|
46
|
-
yield row;
|
|
47
|
-
}
|
|
48
|
-
completed = true;
|
|
49
|
-
} catch (error) {
|
|
50
|
-
failed = true;
|
|
51
|
-
throw error;
|
|
52
|
-
} finally {
|
|
53
|
-
const latencyMs = ctx.now() - startedAt;
|
|
54
|
-
for (const mw of middleware) {
|
|
55
|
-
if (!mw.afterExecute) continue;
|
|
56
|
-
if (failed) {
|
|
57
|
-
try {
|
|
58
|
-
await mw.afterExecute(plan, {
|
|
59
|
-
rowCount,
|
|
60
|
-
latencyMs,
|
|
61
|
-
completed
|
|
62
|
-
}, ctx);
|
|
63
|
-
} catch {}
|
|
64
|
-
continue;
|
|
65
|
-
}
|
|
66
|
-
await mw.afterExecute(plan, {
|
|
67
|
-
rowCount,
|
|
68
|
-
latencyMs,
|
|
69
|
-
completed
|
|
70
|
-
}, ctx);
|
|
71
|
-
}
|
|
72
|
-
}
|
|
216
|
+
async lower(plan, ctx) {
|
|
217
|
+
return {
|
|
218
|
+
command: await this.#adapter.lower(plan, ctx),
|
|
219
|
+
meta: plan.meta,
|
|
220
|
+
...ifDefined("resultShape", plan.resultShape)
|
|
73
221
|
};
|
|
74
|
-
|
|
222
|
+
}
|
|
223
|
+
runDriver(exec) {
|
|
224
|
+
return this.#driver.execute(exec.command);
|
|
225
|
+
}
|
|
226
|
+
execute(plan, options) {
|
|
227
|
+
const self = this;
|
|
228
|
+
const signal = options?.signal;
|
|
229
|
+
const codecCtx = signal === void 0 ? {} : { signal };
|
|
230
|
+
const generator = async function* () {
|
|
231
|
+
checkAborted(codecCtx, "stream");
|
|
232
|
+
const compiled = await self.runBeforeCompile(plan);
|
|
233
|
+
const exec = await self.lower(compiled, codecCtx);
|
|
234
|
+
const stream = runWithMiddleware(exec, self.middleware, self.ctx, () => self.runDriver(exec));
|
|
235
|
+
for await (const rawRow of stream) if (exec.resultShape === void 0) yield rawRow;
|
|
236
|
+
else yield await decodeMongoRow(rawRow, exec.resultShape, self.#codecs, exec.command.collection, codecCtx);
|
|
237
|
+
};
|
|
238
|
+
return new AsyncIterableResult(generator());
|
|
75
239
|
}
|
|
76
240
|
async close() {
|
|
77
241
|
await this.#driver.close();
|
|
@@ -80,7 +244,7 @@ var MongoRuntimeImpl = class {
|
|
|
80
244
|
function createMongoRuntime(options) {
|
|
81
245
|
return new MongoRuntimeImpl(options);
|
|
82
246
|
}
|
|
83
|
-
|
|
84
247
|
//#endregion
|
|
85
|
-
export { createMongoRuntime };
|
|
248
|
+
export { createMongoExecutionContext, createMongoExecutionStack, createMongoRuntime };
|
|
249
|
+
|
|
86
250
|
//# sourceMappingURL=index.mjs.map
|