@shivaedev/contract 0.43.5 → 0.44.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/CHANGELOG.md +37 -0
- package/README.md +262 -44
- package/dist/adapters/servedHandlers.d.ts +8 -0
- package/dist/adapters/servedHandlers.d.ts.map +1 -0
- package/dist/adapters/servedHandlers.js +51 -0
- package/dist/adapters/servedHandlers.js.map +1 -0
- package/dist/automaticQuery.js +1 -1
- package/dist/automaticQuery.js.map +1 -1
- package/dist/clientActivity.d.ts +0 -2
- package/dist/clientActivity.d.ts.map +1 -1
- package/dist/clientActivity.js +1 -1
- package/dist/clientActivity.js.map +1 -1
- package/dist/clientContract.d.ts +51 -0
- package/dist/clientContract.d.ts.map +1 -0
- package/dist/clientContract.js +32 -0
- package/dist/clientContract.js.map +1 -0
- package/dist/clientMatchesModule.d.ts +18 -0
- package/dist/clientMatchesModule.d.ts.map +1 -0
- package/dist/clientMatchesModule.js +2 -0
- package/dist/clientMatchesModule.js.map +1 -0
- package/dist/contract.d.ts +23 -1
- package/dist/contract.d.ts.map +1 -1
- package/dist/contract.js +9 -6
- package/dist/contract.js.map +1 -1
- package/dist/declarationError.d.ts +1 -2
- package/dist/declarationError.d.ts.map +1 -1
- package/dist/declarationError.js +3 -1
- package/dist/declarationError.js.map +1 -1
- package/dist/defineModule.d.ts +41 -0
- package/dist/defineModule.d.ts.map +1 -0
- package/dist/defineModule.js +17 -0
- package/dist/defineModule.js.map +1 -0
- package/dist/live-server/subscribe.d.ts.map +1 -1
- package/dist/live-server/subscribe.js +64 -6
- package/dist/live-server/subscribe.js.map +1 -1
- package/dist/live.d.ts +1 -0
- package/dist/live.d.ts.map +1 -1
- package/dist/live.js +5 -0
- package/dist/live.js.map +1 -1
- package/dist/liveAnswers.d.ts +9 -0
- package/dist/liveAnswers.d.ts.map +1 -0
- package/dist/liveAnswers.js +12 -0
- package/dist/liveAnswers.js.map +1 -0
- package/dist/moduleHandlers.d.ts +15 -0
- package/dist/moduleHandlers.d.ts.map +1 -0
- package/dist/moduleHandlers.js +5 -0
- package/dist/moduleHandlers.js.map +1 -0
- package/dist/moduleProof.d.ts +79 -0
- package/dist/moduleProof.d.ts.map +1 -0
- package/dist/moduleProof.js +2 -0
- package/dist/moduleProof.js.map +1 -0
- package/dist/operation.d.ts +14 -12
- package/dist/operation.d.ts.map +1 -1
- package/dist/operation.js +10 -4
- package/dist/operation.js.map +1 -1
- package/dist/operationDeclaration.d.ts +9 -1
- package/dist/operationDeclaration.d.ts.map +1 -1
- package/dist/operationDeclaration.js.map +1 -1
- package/dist/queryDelivery.js +1 -1
- package/dist/queryDelivery.js.map +1 -1
- package/dist/querySubscription.d.ts +1 -1
- package/dist/querySubscription.d.ts.map +1 -1
- package/dist/querySubscription.js +6 -4
- package/dist/querySubscription.js.map +1 -1
- package/dist/readPolicy.d.ts +2 -1
- package/dist/readPolicy.d.ts.map +1 -1
- package/dist/readPolicy.js +9 -5
- package/dist/readPolicy.js.map +1 -1
- package/dist/retainQuery.d.ts +1 -0
- package/dist/retainQuery.d.ts.map +1 -1
- package/dist/retainQuery.js +5 -0
- package/dist/retainQuery.js.map +1 -1
- package/dist/runProof.d.ts +69 -0
- package/dist/runProof.d.ts.map +1 -0
- package/dist/runProof.js +2 -0
- package/dist/runProof.js.map +1 -0
- package/dist/servedOperation.d.ts +72 -0
- package/dist/servedOperation.d.ts.map +1 -0
- package/dist/servedOperation.js +11 -0
- package/dist/servedOperation.js.map +1 -0
- package/dist/servedReadPolicy.d.ts +11 -0
- package/dist/servedReadPolicy.d.ts.map +1 -0
- package/dist/servedReadPolicy.js +9 -0
- package/dist/servedReadPolicy.js.map +1 -0
- package/dist/serverMetadata.d.ts +1 -4
- package/dist/serverMetadata.d.ts.map +1 -1
- package/dist/serverMetadata.js +3 -6
- package/dist/serverMetadata.js.map +1 -1
- package/dist/successProof.d.ts +51 -0
- package/dist/successProof.d.ts.map +1 -0
- package/dist/successProof.js +2 -0
- package/dist/successProof.js.map +1 -0
- package/dist/wire.d.ts +25 -0
- package/dist/wire.d.ts.map +1 -0
- package/dist/wire.js +13 -0
- package/dist/wire.js.map +1 -0
- package/package.json +16 -16
- package/src/adapters/servedHandlers.ts +69 -0
- package/src/automaticQuery.ts +1 -1
- package/src/clientActivity.ts +1 -1
- package/src/clientContract.ts +128 -0
- package/src/clientMatchesModule.ts +24 -0
- package/src/contract.ts +24 -17
- package/src/declarationError.ts +5 -2
- package/src/defineModule.ts +112 -0
- package/src/live-server/subscribe.ts +74 -6
- package/src/live.ts +7 -0
- package/src/liveAnswers.ts +13 -0
- package/src/moduleHandlers.ts +23 -0
- package/src/moduleProof.ts +101 -0
- package/src/operation.ts +47 -33
- package/src/operationDeclaration.ts +19 -1
- package/src/queryDelivery.ts +1 -1
- package/src/querySubscription.ts +6 -4
- package/src/readPolicy.ts +15 -5
- package/src/retainQuery.ts +7 -0
- package/src/runProof.ts +96 -0
- package/src/servedOperation.ts +145 -0
- package/src/servedReadPolicy.ts +19 -0
- package/src/serverMetadata.ts +3 -6
- package/src/successProof.ts +120 -0
- package/src/wire.ts +45 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { Effect, Layer, type Schema } from "effect";
|
|
2
|
+
import { Rpc, RpcGroup, RpcSchema } from "effect/rpc";
|
|
3
|
+
import { ReadRecorder } from "@shivaedev/changes/readRecorder.ts";
|
|
4
|
+
import { rpcBoundary } from "@shivaedev/errors/boundary.ts";
|
|
5
|
+
import { InternalServerError } from "@shivaedev/errors/taxonomy.ts";
|
|
6
|
+
import type { Declared } from "#contract.ts";
|
|
7
|
+
import type { CommandShape, QueryShape, StreamShape } from "#operation.ts";
|
|
8
|
+
import { CurrentViewer, checkPolicy, type QueryReadPolicy } from "#readPolicy.ts";
|
|
9
|
+
import { ServedReadPolicy } from "#servedReadPolicy.ts";
|
|
10
|
+
|
|
11
|
+
type Runnable = (payload: unknown) => Effect.Effect<unknown, unknown, unknown>;
|
|
12
|
+
|
|
13
|
+
function runOf(operation: QueryShape | CommandShape): Runnable | undefined {
|
|
14
|
+
const run: unknown = Reflect.get(operation, "run");
|
|
15
|
+
return typeof run === "function" ? (payload) => Reflect.apply(run, operation, [payload]) : undefined;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function spanOwner(name: string) {
|
|
19
|
+
return `${name.charAt(0).toUpperCase()}${name.slice(1)}`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function guarded(rpc: Rpc.AnyWithProps) {
|
|
23
|
+
return rpcBoundary(rpc.errorSchema, { unexpected: (message) => new InternalServerError({ message }) });
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function served(rpc: Rpc.AnyWithProps, operation: QueryShape | CommandShape, run: Runnable, span: string) {
|
|
27
|
+
const boundary = guarded(rpc);
|
|
28
|
+
return (payload: unknown) =>
|
|
29
|
+
Effect.gen(function* () {
|
|
30
|
+
if (operation.kind === "query") {
|
|
31
|
+
yield* checkPolicy(operation, operation.readPolicy, payload, yield* CurrentViewer).pipe(
|
|
32
|
+
Effect.provideService(ReadRecorder, ReadRecorder.defaultValue()),
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
return yield* run(payload);
|
|
36
|
+
}).pipe(Effect.withSpan(span), boundary);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Live subscriptions check the policy outside the handler, so the policy carries the handler's failure mapping.
|
|
40
|
+
function servedPolicy(rpc: Rpc.AnyWithProps, policy: QueryReadPolicy<unknown, unknown, unknown>): QueryReadPolicy<unknown, unknown, unknown> {
|
|
41
|
+
const boundary = guarded(rpc);
|
|
42
|
+
return (payload, viewer) => boundary(Effect.suspend(() => policy(payload, viewer)));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
type EffectRpc = Rpc.Rpc<string, Schema.Top, Schema.Top, Schema.Top>;
|
|
46
|
+
|
|
47
|
+
// An erased Rpc's `any` success schema selects the stream branch of Rpc.ResultFrom, which an Effect handler cannot satisfy.
|
|
48
|
+
function isEffectRpc(rpc: Rpc.Any | undefined): rpc is EffectRpc {
|
|
49
|
+
return Rpc.isRpc(rpc) && !RpcSchema.isStreamSchema(rpc.successSchema);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function servedHandlers(
|
|
53
|
+
application: { readonly requests: ReadonlyMap<string, Rpc.Any> },
|
|
54
|
+
declaration: Declared<string, readonly QueryShape[], readonly CommandShape[], readonly StreamShape[], "session" | undefined>,
|
|
55
|
+
): Layer.Layer<Rpc.Handler<string>, never, unknown> {
|
|
56
|
+
const layers = [...declaration.queries, ...declaration.commands].map((operation): Layer.Layer<Rpc.Handler<string>, never, unknown> => {
|
|
57
|
+
const tag = `${declaration.name}.${operation.name}`;
|
|
58
|
+
const rpc = application.requests.get(tag);
|
|
59
|
+
const run = runOf(operation);
|
|
60
|
+
if (!isEffectRpc(rpc) || run === undefined) {
|
|
61
|
+
return Layer.effectContext(Effect.die(new Error(`Module ${declaration.name} cannot serve ${tag}: it has no RPC or no run`)));
|
|
62
|
+
}
|
|
63
|
+
const handler = RpcGroup.make(rpc).toLayerHandler(tag, served(rpc, operation, run, `${spanOwner(declaration.name)}.${operation.name}`));
|
|
64
|
+
return operation.kind === "query" && operation.readPolicy !== undefined
|
|
65
|
+
? handler.pipe(Layer.provide(Layer.succeed(ServedReadPolicy, { check: servedPolicy(rpc, operation.readPolicy) })))
|
|
66
|
+
: handler;
|
|
67
|
+
});
|
|
68
|
+
return Layer.mergeAll(Layer.empty, ...layers);
|
|
69
|
+
}
|
package/src/automaticQuery.ts
CHANGED
package/src/clientActivity.ts
CHANGED
|
@@ -37,7 +37,7 @@ export function isClientSettled(state: ClientActivityState): boolean {
|
|
|
37
37
|
|
|
38
38
|
export function activityScreenSignal(activity: ClientActivity, settled = isClientSettled) {
|
|
39
39
|
function screenState(state: ClientActivityState) {
|
|
40
|
-
return { connectionStatus: state.connectionStatus,
|
|
40
|
+
return { connectionStatus: state.connectionStatus, pending: !settled(state) };
|
|
41
41
|
}
|
|
42
42
|
return Object.assign(Stream.map(activity, screenState), { current: Effect.map(activity.current, screenState) });
|
|
43
43
|
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import type { Option, Schema } from "effect";
|
|
2
|
+
import type { RpcMiddleware } from "effect/rpc";
|
|
3
|
+
import type { Key } from "@shivaedev/changes/keys.ts";
|
|
4
|
+
import { declaredGroup } from "#contract.ts";
|
|
5
|
+
import type { ModuleContract } from "#defineModule.ts";
|
|
6
|
+
import type { Command, Operation, PayloadSchema } from "#operation.ts";
|
|
7
|
+
import { operation } from "#operationDeclaration.ts";
|
|
8
|
+
import type { Viewer } from "#readPolicy.ts";
|
|
9
|
+
import type { RejectionSpecs } from "#rejection.ts";
|
|
10
|
+
import type { SpecsOf } from "#runProof.ts";
|
|
11
|
+
import type { SubjectDeclaration } from "#subject.ts";
|
|
12
|
+
import { type Wire, type WireEntry, wireRejections } from "#wire.ts";
|
|
13
|
+
|
|
14
|
+
export interface ClientQuery<TName extends string, TPayload extends Schema.Top, TSuccess extends Schema.Top, TSpecs extends RejectionSpecs>
|
|
15
|
+
extends Operation<TName, TPayload, TSuccess, TSpecs> {
|
|
16
|
+
readonly kind: "query";
|
|
17
|
+
reads: (payload: TPayload["Type"], viewer: Option.Option<Viewer>) => readonly Key[];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
type Payloads<TWire> = { readonly [TOperation in keyof TWire]?: Schema.Top | Schema.Struct.Fields };
|
|
21
|
+
type PayloadOf<TPayloads, TOperation> = PayloadSchema<TOperation extends keyof TPayloads ? NonNullable<TPayloads[TOperation]> : Schema.Void>;
|
|
22
|
+
type EntryOf<TWire, TOperation> = TOperation extends keyof TWire ? (TWire[TOperation] extends WireEntry ? TWire[TOperation] : never) : never;
|
|
23
|
+
|
|
24
|
+
interface QueryKeys<TPayload> {
|
|
25
|
+
readonly reads: (payload: TPayload, viewer: Option.Option<Viewer>) => readonly Key[];
|
|
26
|
+
readonly readsCollections?: readonly { readonly name: string }[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
interface CommandKeys<TPayload, TResult> {
|
|
30
|
+
readonly invalidates?: (payload: TPayload, result: TResult, viewer?: Option.Option<Viewer>) => readonly Key[];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
type ClientQueries<TWire, TPayloads, TQueries extends string> = {
|
|
34
|
+
readonly [TOperation in TQueries]: ClientQuery<
|
|
35
|
+
TOperation,
|
|
36
|
+
PayloadOf<TPayloads, TOperation>,
|
|
37
|
+
EntryOf<TWire, TOperation>["success"],
|
|
38
|
+
SpecsOf<EntryOf<TWire, TOperation>["rejections"]>
|
|
39
|
+
>;
|
|
40
|
+
}[TQueries];
|
|
41
|
+
|
|
42
|
+
type ClientCommands<TWire, TPayloads, TCommands extends string> = {
|
|
43
|
+
readonly [TOperation in TCommands]: Command<
|
|
44
|
+
TOperation,
|
|
45
|
+
PayloadOf<TPayloads, TOperation>,
|
|
46
|
+
EntryOf<TWire, TOperation>["success"],
|
|
47
|
+
SpecsOf<EntryOf<TWire, TOperation>["rejections"]>
|
|
48
|
+
>;
|
|
49
|
+
}[TCommands];
|
|
50
|
+
|
|
51
|
+
export interface ClientContractDefinition<
|
|
52
|
+
TName extends string,
|
|
53
|
+
TWire extends Wire,
|
|
54
|
+
TPayloads extends Payloads<TWire>,
|
|
55
|
+
TQueries extends keyof TWire & string,
|
|
56
|
+
TCommands extends keyof TWire & string,
|
|
57
|
+
TMiddleware extends RpcMiddleware.AnyService,
|
|
58
|
+
TSubject extends SubjectDeclaration | undefined,
|
|
59
|
+
TScope extends "session" | undefined,
|
|
60
|
+
> {
|
|
61
|
+
readonly commands?: {
|
|
62
|
+
readonly [TOperation in TCommands]: CommandKeys<PayloadOf<TPayloads, TOperation>["Type"], EntryOf<TWire, TOperation>["success"]["Type"]>;
|
|
63
|
+
};
|
|
64
|
+
readonly keyScope?: TScope;
|
|
65
|
+
readonly middleware?: TMiddleware;
|
|
66
|
+
readonly name: TName;
|
|
67
|
+
readonly payloads?: TPayloads;
|
|
68
|
+
readonly queries?: { readonly [TOperation in TQueries]: QueryKeys<PayloadOf<TPayloads, TOperation>["Type"]> };
|
|
69
|
+
readonly subject?: TSubject;
|
|
70
|
+
readonly wire: TWire;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Written by the generator: what the browser needs of a module as values, without its run, read policy or services.
|
|
74
|
+
export function clientContract<
|
|
75
|
+
const TName extends string,
|
|
76
|
+
const TWire extends Wire,
|
|
77
|
+
const TPayloads extends Payloads<TWire> = Record<never, never>,
|
|
78
|
+
TQueries extends keyof TWire & string = never,
|
|
79
|
+
TCommands extends keyof TWire & string = never,
|
|
80
|
+
TMiddleware extends RpcMiddleware.AnyService = never,
|
|
81
|
+
const TSubject extends SubjectDeclaration | undefined = undefined,
|
|
82
|
+
const TScope extends "session" | undefined = undefined,
|
|
83
|
+
>(
|
|
84
|
+
definition: ClientContractDefinition<TName, TWire, TPayloads, TQueries, TCommands, TMiddleware, TSubject, TScope>,
|
|
85
|
+
): ModuleContract<
|
|
86
|
+
TName,
|
|
87
|
+
readonly (ClientQueries<TWire, TPayloads, TQueries> | ClientCommands<TWire, TPayloads, TCommands>)[],
|
|
88
|
+
TMiddleware,
|
|
89
|
+
TSubject,
|
|
90
|
+
TScope
|
|
91
|
+
>;
|
|
92
|
+
export function clientContract(definition: {
|
|
93
|
+
readonly commands?: { readonly [operation: string]: CommandKeys<unknown, unknown> };
|
|
94
|
+
readonly keyScope?: "session";
|
|
95
|
+
readonly middleware?: RpcMiddleware.AnyService;
|
|
96
|
+
readonly name: string;
|
|
97
|
+
readonly payloads?: { readonly [operation: string]: Schema.Top | Schema.Struct.Fields | undefined };
|
|
98
|
+
readonly queries?: { readonly [operation: string]: QueryKeys<unknown> };
|
|
99
|
+
readonly subject?: SubjectDeclaration;
|
|
100
|
+
readonly wire: Wire;
|
|
101
|
+
}): unknown {
|
|
102
|
+
function declared(name: string) {
|
|
103
|
+
const entry = definition.wire[name];
|
|
104
|
+
const payload = definition.payloads?.[name];
|
|
105
|
+
return {
|
|
106
|
+
...(payload === undefined ? {} : { payload }),
|
|
107
|
+
...(entry === undefined ? {} : { rejections: wireRejections(entry.rejections), success: entry.success }),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
const queries = Object.entries(definition.queries ?? {}).map(([name, { reads, readsCollections = [] }]) => {
|
|
111
|
+
const collections: readonly Key[] = readsCollections.map((collection) => ({ _tag: "List", collection: collection.name }));
|
|
112
|
+
return {
|
|
113
|
+
...operation("query", name, declared(name)),
|
|
114
|
+
reads: (payload: unknown, viewer: Option.Option<Viewer>) => [...reads(payload, viewer), ...collections],
|
|
115
|
+
};
|
|
116
|
+
});
|
|
117
|
+
const commands = Object.entries(definition.commands ?? {}).map(([name, { invalidates }]) => ({
|
|
118
|
+
...operation("command", name, declared(name)),
|
|
119
|
+
invalidates: invalidates ?? (() => []),
|
|
120
|
+
}));
|
|
121
|
+
const group = declaredGroup(definition.name, {
|
|
122
|
+
commands,
|
|
123
|
+
queries,
|
|
124
|
+
...(definition.keyScope === undefined ? {} : { keyScope: definition.keyScope }),
|
|
125
|
+
...(definition.subject === undefined ? {} : { subject: definition.subject }),
|
|
126
|
+
});
|
|
127
|
+
return definition.middleware?.key === undefined ? group : group.middleware(definition.middleware);
|
|
128
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { RpcGroup } from "effect/rpc";
|
|
2
|
+
|
|
3
|
+
type Rpcs<TGroup> = TGroup extends RpcGroup.RpcGroup<infer TRpcs> ? TRpcs : never;
|
|
4
|
+
type Same<TLeft, TRight> = [TLeft] extends [TRight] ? ([TRight] extends [TLeft] ? true : false) : false;
|
|
5
|
+
type OperationOf<TTag> = TTag extends `${string}.${infer TOperation}` ? TOperation : TTag;
|
|
6
|
+
|
|
7
|
+
type Differing<TClient, TModule> = {
|
|
8
|
+
readonly [TTag in Rpcs<TClient>["_tag"] | Rpcs<TModule>["_tag"]]: Same<
|
|
9
|
+
Extract<Rpcs<TClient>, { readonly _tag: TTag }>,
|
|
10
|
+
Extract<Rpcs<TModule>, { readonly _tag: TTag }>
|
|
11
|
+
> extends true
|
|
12
|
+
? never
|
|
13
|
+
: OperationOf<TTag>;
|
|
14
|
+
}[Rpcs<TClient>["_tag"] | Rpcs<TModule>["_tag"]];
|
|
15
|
+
|
|
16
|
+
export interface ClientDiffersFromModule<TOperations, TFix extends string> {
|
|
17
|
+
readonly fix: TFix;
|
|
18
|
+
readonly operations: TOperations;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// A generated file ends with `export const matches: ClientMatchesModule<typeof Client, typeof Module> = true;`.
|
|
22
|
+
export type ClientMatchesModule<TClient, TModule> = [Differing<TClient, TModule>] extends [never]
|
|
23
|
+
? true
|
|
24
|
+
: ClientDiffersFromModule<Differing<TClient, TModule>, "the generated file is stale; run pnpm generate">;
|
package/src/contract.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { Schema } from "effect";
|
|
1
|
+
import { Context, Schema } from "effect";
|
|
2
2
|
import { Rpc, RpcGroup, type RpcMiddleware } from "effect/rpc";
|
|
3
3
|
import { DeclarationError, declarationError, type Unique } from "#declarationError.ts";
|
|
4
4
|
import type { CommandShape, QueryShape, StreamShape } from "#operation.ts";
|
|
5
5
|
import type { OperationRpc } from "#operationRpc.ts";
|
|
6
6
|
import { ReadPolicyGuard } from "#ReadPolicyGuard.ts";
|
|
7
7
|
import { QueryReadDenied } from "#readPolicyErrors.ts";
|
|
8
|
-
import { changesRpc,
|
|
8
|
+
import { changesRpc, operationAnnotations } from "#serverMetadata.ts";
|
|
9
9
|
import type { SubjectDeclaration, WithSubject } from "#subject.ts";
|
|
10
10
|
import { subjectMiddleware } from "#subjectMiddleware.ts";
|
|
11
11
|
|
|
@@ -67,9 +67,12 @@ function withDeclaration(group: Group, application: Group, declaration: AnyDecla
|
|
|
67
67
|
});
|
|
68
68
|
}
|
|
69
69
|
|
|
70
|
+
// A host refuses a query without a read policy, so a contract written for the host requires one; only the browser's contract has none.
|
|
71
|
+
type PolicedQuery = QueryShape & { readonly readPolicy: NonNullable<QueryShape["readPolicy"]> };
|
|
72
|
+
|
|
70
73
|
export function contract<
|
|
71
74
|
const TName extends string,
|
|
72
|
-
const TQueries extends readonly
|
|
75
|
+
const TQueries extends readonly PolicedQuery[] = readonly [],
|
|
73
76
|
const TCommands extends readonly CommandShape[] = readonly [],
|
|
74
77
|
const TStreams extends readonly StreamShape[] = readonly [],
|
|
75
78
|
const TScope extends "session" | undefined = undefined,
|
|
@@ -95,17 +98,21 @@ export function contract<
|
|
|
95
98
|
TStreams,
|
|
96
99
|
TScope
|
|
97
100
|
>;
|
|
98
|
-
export function contract(
|
|
99
|
-
name
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
101
|
+
export function contract(name: string, operations: Operations): DeclaredGroup {
|
|
102
|
+
return declaredGroup(name, operations);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
interface Operations {
|
|
106
|
+
readonly annotations?: Context.Context<never>;
|
|
107
|
+
readonly commands?: readonly CommandShape[];
|
|
108
|
+
readonly keyScope?: "session";
|
|
109
|
+
readonly queries?: readonly QueryShape[];
|
|
110
|
+
readonly streams?: readonly StreamShape[];
|
|
111
|
+
readonly subject?: SubjectDeclaration;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function declaredGroup(name: string, operations: Operations): DeclaredGroup {
|
|
115
|
+
const { queries = [], commands = [], streams = [], keyScope, annotations = Context.empty() } = operations;
|
|
109
116
|
const error = assertValid(name, [...queries, ...commands, ...streams]);
|
|
110
117
|
const rpcs = [...queries, ...commands, ...streams].map((operation) => {
|
|
111
118
|
const rpc = Rpc.make(`${name}.${operation.name}`, {
|
|
@@ -113,14 +120,14 @@ export function contract(
|
|
|
113
120
|
payload: operation.payload,
|
|
114
121
|
stream: operation.kind === "stream",
|
|
115
122
|
success: operation.success,
|
|
116
|
-
}).annotateMerge(operationAnnotations(operation,
|
|
123
|
+
}).annotateMerge(Context.merge(operationAnnotations(operation), annotations));
|
|
117
124
|
const guarded = operation.kind === "query" ? rpc.middleware(ReadPolicyGuard) : rpc;
|
|
118
125
|
return operations.subject === undefined ? guarded : guarded.middleware(subjectMiddleware(`${name}.${operation.name}`, operations.subject));
|
|
119
126
|
});
|
|
120
127
|
const application = RpcGroup.make(...rpcs);
|
|
121
|
-
const changes = changesRpc(name, queries).middleware(ReadPolicyGuard);
|
|
128
|
+
const changes = changesRpc(name, queries).annotateMerge(annotations).middleware(ReadPolicyGuard);
|
|
122
129
|
const subjectChanges = operations.subject === undefined ? changes : changes.middleware(subjectMiddleware(`${name}.$changes`, operations.subject));
|
|
123
|
-
const built = application.add(
|
|
130
|
+
const built = application.add(subjectChanges);
|
|
124
131
|
const group = error === undefined ? built : built.annotate(DeclarationError, error);
|
|
125
132
|
return withDeclaration(group, application, {
|
|
126
133
|
commands,
|
package/src/declarationError.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { isPermissionReadPolicy } from "#permissionReadPolicy.ts";
|
|
|
4
4
|
|
|
5
5
|
export const DeclarationError = Context.Reference<string | undefined>("@shivaedev/contract/DeclarationError", { defaultValue: () => undefined });
|
|
6
6
|
|
|
7
|
-
type Duplicated<TOperations extends readonly OperationShape[], TSeen extends string = never> = TOperations extends readonly [
|
|
7
|
+
export type Duplicated<TOperations extends readonly OperationShape[], TSeen extends string = never> = TOperations extends readonly [
|
|
8
8
|
infer THead extends OperationShape,
|
|
9
9
|
...infer TTail extends readonly OperationShape[],
|
|
10
10
|
]
|
|
@@ -24,7 +24,10 @@ export function declarationError(contractName: string, operations: readonly (Que
|
|
|
24
24
|
return `Operation names must be unique; duplicated: ${[...new Set(duplicated)].join(", ")}`;
|
|
25
25
|
}
|
|
26
26
|
const member = operations.find(
|
|
27
|
-
(operation) =>
|
|
27
|
+
(operation) =>
|
|
28
|
+
operation.kind === "query"
|
|
29
|
+
&& operation.readsCollections !== undefined
|
|
30
|
+
&& (operation.readPolicy === undefined || !isPermissionReadPolicy(operation.readPolicy)),
|
|
28
31
|
);
|
|
29
32
|
return member === undefined
|
|
30
33
|
? undefined
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { Context, type Effect } from "effect";
|
|
2
|
+
import type { Rpc, RpcMiddleware } from "effect/rpc";
|
|
3
|
+
import type { RequirementRecord } from "@shivaedev/service/ServiceRequirements.ts";
|
|
4
|
+
import { type Contract, declaredGroup } from "#contract.ts";
|
|
5
|
+
import type { Allowed, NameProof } from "#moduleProof.ts";
|
|
6
|
+
import type { CommandShape, QueryShape } from "#operation.ts";
|
|
7
|
+
import type { OperationRpc } from "#operationRpc.ts";
|
|
8
|
+
import type { ReadPolicyGuard } from "#ReadPolicyGuard.ts";
|
|
9
|
+
import type { changesRpc } from "#serverMetadata.ts";
|
|
10
|
+
import type { SubjectDeclaration, WithSubject } from "#subject.ts";
|
|
11
|
+
import { type Wire, type WiredAll, wired } from "#wire.ts";
|
|
12
|
+
|
|
13
|
+
export class DefinedModule extends Context.Service<DefinedModule, string>()("@shivaedev/contract/DefinedModule") {}
|
|
14
|
+
|
|
15
|
+
export type ModuleOperation = (QueryShape | CommandShape) & { readonly run: (payload: never) => Effect.Effect<unknown, unknown, unknown> };
|
|
16
|
+
|
|
17
|
+
type QueriesOf<TOperations extends readonly (QueryShape | CommandShape)[]> = readonly Extract<TOperations[number], { readonly kind: "query" }>[];
|
|
18
|
+
type CommandsOf<TOperations extends readonly (QueryShape | CommandShape)[]> = readonly Extract<TOperations[number], { readonly kind: "command" }>[];
|
|
19
|
+
|
|
20
|
+
// The module's handlers provide every service its operations use, read policies included, so its RPCs require none.
|
|
21
|
+
type Served<TRpc> =
|
|
22
|
+
TRpc extends Rpc.Rpc<infer TTag, infer TPayload, infer TSuccess, infer TError, infer TMiddleware, infer _TRequires>
|
|
23
|
+
? Rpc.Rpc<TTag, TPayload, TSuccess, TError, TMiddleware, never>
|
|
24
|
+
: never;
|
|
25
|
+
|
|
26
|
+
type WithMiddleware<TRpcs extends Rpc.Any, TMiddleware extends RpcMiddleware.AnyService> = [TMiddleware] extends [never]
|
|
27
|
+
? TRpcs
|
|
28
|
+
: Rpc.AddMiddleware<TRpcs, TMiddleware>;
|
|
29
|
+
|
|
30
|
+
export type ModuleContract<
|
|
31
|
+
TName extends string,
|
|
32
|
+
TOperations extends readonly (QueryShape | CommandShape)[],
|
|
33
|
+
TMiddleware extends RpcMiddleware.AnyService = never,
|
|
34
|
+
TSubject extends SubjectDeclaration | undefined = undefined,
|
|
35
|
+
TScope extends "session" | undefined = undefined,
|
|
36
|
+
> = Contract<
|
|
37
|
+
TName,
|
|
38
|
+
QueriesOf<TOperations>,
|
|
39
|
+
CommandsOf<TOperations>,
|
|
40
|
+
WithMiddleware<
|
|
41
|
+
WithSubject<
|
|
42
|
+
Served<
|
|
43
|
+
| OperationRpc<TName, TOperations[number]>
|
|
44
|
+
| Rpc.AddMiddleware<ReturnType<typeof changesRpc<TName, QueriesOf<TOperations>>>, typeof ReadPolicyGuard>
|
|
45
|
+
>,
|
|
46
|
+
TSubject
|
|
47
|
+
>,
|
|
48
|
+
TMiddleware
|
|
49
|
+
>,
|
|
50
|
+
readonly [],
|
|
51
|
+
TScope
|
|
52
|
+
>;
|
|
53
|
+
|
|
54
|
+
export type Module<
|
|
55
|
+
TName extends string,
|
|
56
|
+
TOperations extends readonly ModuleOperation[],
|
|
57
|
+
TRequirements extends RequirementRecord,
|
|
58
|
+
TMiddleware extends RpcMiddleware.AnyService = never,
|
|
59
|
+
TSubject extends SubjectDeclaration | undefined = undefined,
|
|
60
|
+
TScope extends "session" | undefined = undefined,
|
|
61
|
+
> = ModuleContract<TName, TOperations, TMiddleware, TSubject, TScope> & {
|
|
62
|
+
// The compiler checks the list and nothing reads it at run time, so, like Rpc's ~requires, it exists only in the type.
|
|
63
|
+
readonly "~requires": TRequirements;
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
export interface ModuleDefinition<
|
|
67
|
+
TName extends string,
|
|
68
|
+
TOperations extends readonly ModuleOperation[],
|
|
69
|
+
TRequirements extends RequirementRecord,
|
|
70
|
+
TMiddleware extends RpcMiddleware.AnyService,
|
|
71
|
+
TSubject extends SubjectDeclaration | undefined,
|
|
72
|
+
TScope extends "session" | undefined,
|
|
73
|
+
TWire extends Wire,
|
|
74
|
+
> {
|
|
75
|
+
readonly keyScope?: TScope;
|
|
76
|
+
readonly middleware?: TMiddleware;
|
|
77
|
+
readonly name: TName & NoInfer<NameProof<TOperations, TWire, Allowed<TRequirements, TMiddleware, TSubject>>>;
|
|
78
|
+
readonly operations: TOperations;
|
|
79
|
+
readonly requires: TRequirements;
|
|
80
|
+
readonly subject?: TSubject;
|
|
81
|
+
readonly wire?: TWire;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function defineModule<
|
|
85
|
+
const TName extends string,
|
|
86
|
+
const TOperations extends readonly ModuleOperation[],
|
|
87
|
+
const TRequirements extends RequirementRecord,
|
|
88
|
+
TMiddleware extends RpcMiddleware.AnyService = never,
|
|
89
|
+
const TSubject extends SubjectDeclaration | undefined = undefined,
|
|
90
|
+
const TScope extends "session" | undefined = undefined,
|
|
91
|
+
const TWire extends Wire = Record<never, never>,
|
|
92
|
+
>(
|
|
93
|
+
definition: ModuleDefinition<TName, TOperations, TRequirements, TMiddleware, TSubject, TScope, TWire>,
|
|
94
|
+
): Module<TName, WiredAll<TOperations, TWire> & readonly ModuleOperation[], TRequirements, TMiddleware, TSubject, TScope>;
|
|
95
|
+
export function defineModule(definition: {
|
|
96
|
+
readonly keyScope?: "session";
|
|
97
|
+
readonly middleware?: RpcMiddleware.AnyService;
|
|
98
|
+
readonly name: string;
|
|
99
|
+
readonly operations: readonly ModuleOperation[];
|
|
100
|
+
readonly subject?: SubjectDeclaration;
|
|
101
|
+
readonly wire?: Wire;
|
|
102
|
+
}): unknown {
|
|
103
|
+
const operations = definition.operations.map((operation) => wired(operation, definition.wire?.[operation.name]));
|
|
104
|
+
const group = declaredGroup(definition.name, {
|
|
105
|
+
annotations: Context.make(DefinedModule, definition.name),
|
|
106
|
+
commands: operations.filter((operation) => operation.kind === "command"),
|
|
107
|
+
queries: operations.filter((operation) => operation.kind === "query"),
|
|
108
|
+
...(definition.keyScope === undefined ? {} : { keyScope: definition.keyScope }),
|
|
109
|
+
...(definition.subject === undefined ? {} : { subject: definition.subject }),
|
|
110
|
+
});
|
|
111
|
+
return definition.middleware?.key === undefined ? group : group.middleware(definition.middleware);
|
|
112
|
+
}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { Effect, Stream } from "effect";
|
|
2
|
+
import type { Key } from "@shivaedev/changes/keys.ts";
|
|
3
|
+
import { ReadRecorder, type RecordReadOptions } from "@shivaedev/changes/readRecorder.ts";
|
|
2
4
|
import { refreshSubscription } from "#adapters/refreshSubscription.ts";
|
|
3
5
|
import { compareQueries } from "#compareQueries.ts";
|
|
4
6
|
import type { LiveHint } from "#live.ts";
|
|
@@ -6,6 +8,72 @@ import { LiveServer } from "#live-server/service.ts";
|
|
|
6
8
|
import type { QueryRerun, QuerySubscription } from "#querySubscription.ts";
|
|
7
9
|
import type { QueryUpdate } from "#queryUpdate.ts";
|
|
8
10
|
import { QueryReadDenied } from "#readPolicyErrors.ts";
|
|
11
|
+
import type { QueryRequest } from "#serverMetadata.ts";
|
|
12
|
+
|
|
13
|
+
// Matching compares serialized keys, so the same serialization identifies a registered key.
|
|
14
|
+
function identity(key: Key) {
|
|
15
|
+
return JSON.stringify(key);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function subscriptionKeys<E, R>(subscription: QuerySubscription<E, R>, read: QueryRerun<E, R>, replaceKeys: (keys: readonly Key[]) => void) {
|
|
19
|
+
let scopes = subscription.scopes;
|
|
20
|
+
const recorded = subscription.queries.map((): readonly Key[] => []);
|
|
21
|
+
const recording = subscription.queries.map(() => new Map<string, Key>());
|
|
22
|
+
function merged() {
|
|
23
|
+
return scopes.map((declared, index) => [...declared, ...(recorded[index] ?? [])]);
|
|
24
|
+
}
|
|
25
|
+
let registered = new Set(merged().flat().map(identity));
|
|
26
|
+
function register() {
|
|
27
|
+
const current = new Map([...merged().flat(), ...recording.flatMap((run) => [...run.values()])].map((key) => [identity(key), key]));
|
|
28
|
+
if (current.size === registered.size && [...current.keys()].every((key) => registered.has(key))) {
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
registered = new Set(current.keys());
|
|
32
|
+
replaceKeys([...current.values()]);
|
|
33
|
+
}
|
|
34
|
+
function recordInto(run: Map<string, Key>, declared: boolean) {
|
|
35
|
+
return (keys: readonly Key[], { inferred = false }: RecordReadOptions) =>
|
|
36
|
+
Effect.sync(() => {
|
|
37
|
+
if (inferred && declared) {
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
let unregistered = false;
|
|
41
|
+
for (const key of keys) {
|
|
42
|
+
const id = identity(key);
|
|
43
|
+
run.set(id, key);
|
|
44
|
+
unregistered ||= !registered.has(id);
|
|
45
|
+
}
|
|
46
|
+
if (unregistered) {
|
|
47
|
+
register();
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
function keep(request: QueryRequest, index: number, run: ReadonlyMap<string, Key>) {
|
|
52
|
+
return Effect.suspend(() => {
|
|
53
|
+
recorded[index] = [...run.values()];
|
|
54
|
+
recording[index] = new Map();
|
|
55
|
+
// A handler may read nothing for some payloads, so an unheard query is reported, never failed.
|
|
56
|
+
return request.query.undeclaredReads === true && run.size === 0
|
|
57
|
+
? Effect.logWarning(
|
|
58
|
+
`Live query ${request.query.name} declares no reads and recorded no key, so no write reruns it. Mark its raw SQL reads with their keys or declare reads; reads: () => [] states that it reads nothing.`,
|
|
59
|
+
)
|
|
60
|
+
: Effect.void;
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
function recordingRead(request: QueryRequest) {
|
|
64
|
+
const index = subscription.queries.indexOf(request);
|
|
65
|
+
const run = new Map<string, Key>();
|
|
66
|
+
recording[index] = run;
|
|
67
|
+
return read(request).pipe(
|
|
68
|
+
Effect.provideService(ReadRecorder, recordInto(run, request.query.undeclaredReads !== true)),
|
|
69
|
+
Effect.tap(() => keep(request, index, run)),
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
function replaceScopes(next: readonly (readonly Key[])[]) {
|
|
73
|
+
scopes = next;
|
|
74
|
+
}
|
|
75
|
+
return { merged, recordingRead, register, replaceScopes };
|
|
76
|
+
}
|
|
9
77
|
|
|
10
78
|
function subscribeQueries<E, R>(
|
|
11
79
|
subscription: QuerySubscription<E, R>,
|
|
@@ -17,18 +85,18 @@ function subscribeQueries<E, R>(subscription: QuerySubscription<E, R>, read: Que
|
|
|
17
85
|
const hints = yield* server.register(subscription.keys);
|
|
18
86
|
return hints.pipe(
|
|
19
87
|
Stream.flatMap((registration) => {
|
|
20
|
-
|
|
21
|
-
let compare = compareQueries(subscription,
|
|
88
|
+
const keys = subscriptionKeys(subscription, read, registration.replaceKeys);
|
|
89
|
+
let compare = compareQueries(subscription, keys.recordingRead);
|
|
22
90
|
const next = Effect.fnUntraced(function* (hint: LiveHint) {
|
|
23
91
|
if (!(yield* subscription.authorized)) {
|
|
24
|
-
compare = compareQueries(subscription,
|
|
92
|
+
compare = compareQueries(subscription, keys.recordingRead, false);
|
|
25
93
|
return [new QueryReadDenied({ message: "Read no longer allowed for subscribed queries" })];
|
|
26
94
|
}
|
|
27
|
-
const updates = yield* compare(hint,
|
|
95
|
+
const updates = yield* compare(hint, keys.merged());
|
|
28
96
|
if (subscription.readScopes !== undefined) {
|
|
29
|
-
|
|
30
|
-
registration.replaceKeys(scopes.flat());
|
|
97
|
+
keys.replaceScopes(yield* subscription.readScopes);
|
|
31
98
|
}
|
|
99
|
+
keys.register();
|
|
32
100
|
return updates;
|
|
33
101
|
});
|
|
34
102
|
return registration.stream.pipe(
|
package/src/live.ts
CHANGED
|
@@ -27,6 +27,12 @@ export interface LiveOptions<E, R> {
|
|
|
27
27
|
readonly stream: Stream.Stream<SubscriptionEvent, E, R>;
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
+
const connections = new WeakSet<Atom.Atom<unknown>>();
|
|
31
|
+
|
|
32
|
+
export function isLiveConnection(atom: Atom.Atom<unknown>): boolean {
|
|
33
|
+
return connections.has(atom);
|
|
34
|
+
}
|
|
35
|
+
|
|
30
36
|
export function live<R, E, TRuntimeError>(runtime: Atom.AtomRuntime<R, TRuntimeError>, options: LiveOptions<E, R>) {
|
|
31
37
|
const paused = Atom.make(false);
|
|
32
38
|
const status = Atom.make<LiveStatus<E>>({ connection: "connecting", failure: Option.none(), needsResync: true, pending: 0 });
|
|
@@ -69,5 +75,6 @@ export function live<R, E, TRuntimeError>(runtime: Atom.AtomRuntime<R, TRuntimeE
|
|
|
69
75
|
}),
|
|
70
76
|
)
|
|
71
77
|
.pipe(Atom.setIdleTTL(0));
|
|
78
|
+
connections.add(connection);
|
|
72
79
|
return { connection, paused, status };
|
|
73
80
|
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { Effect, Stream } from "effect";
|
|
2
|
+
import type * as Atom from "effect/reactivity/Atom";
|
|
3
|
+
import * as AtomRegistry from "effect/reactivity/AtomRegistry";
|
|
4
|
+
import { querySignals } from "#querySignals.ts";
|
|
5
|
+
|
|
6
|
+
export function liveAnswers(registry: AtomRegistry.AtomRegistry, name: string, query: Atom.Atom<unknown>) {
|
|
7
|
+
const signals = querySignals(query);
|
|
8
|
+
return {
|
|
9
|
+
answered: Stream.map(AtomRegistry.toStream(registry, signals), (state) => state.completed),
|
|
10
|
+
current: Effect.sync(() => registry.get(signals).completed),
|
|
11
|
+
name,
|
|
12
|
+
};
|
|
13
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { Layer } from "effect";
|
|
2
|
+
import type { Rpc, RpcGroup } from "effect/rpc";
|
|
3
|
+
import type { RequirementRecord, RequirementsOf } from "@shivaedev/service/ServiceRequirements.ts";
|
|
4
|
+
import { servedHandlers } from "#adapters/servedHandlers.ts";
|
|
5
|
+
import type { Declared } from "#contract.ts";
|
|
6
|
+
import type { CommandShape, QueryShape, StreamShape } from "#operation.ts";
|
|
7
|
+
|
|
8
|
+
export interface AnyModule {
|
|
9
|
+
readonly "~requires": RequirementRecord;
|
|
10
|
+
readonly application: { readonly requests: ReadonlyMap<string, Rpc.Any> };
|
|
11
|
+
readonly declaration: Declared<string, readonly QueryShape[], readonly CommandShape[], readonly StreamShape[], "session" | undefined>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export type ModuleHandlers<TModule extends AnyModule> = Layer.Layer<
|
|
15
|
+
Rpc.ToHandler<RpcGroup.Rpcs<TModule["application"]>>,
|
|
16
|
+
never,
|
|
17
|
+
RequirementsOf<TModule["~requires"]>
|
|
18
|
+
>;
|
|
19
|
+
|
|
20
|
+
export function moduleHandlers<TModule extends AnyModule>(module: TModule): ModuleHandlers<TModule>;
|
|
21
|
+
export function moduleHandlers(module: AnyModule): Layer.Layer<Rpc.Handler<string>, never, unknown> {
|
|
22
|
+
return servedHandlers(module.application, module.declaration);
|
|
23
|
+
}
|