@shivaedev/contract 0.27.0 → 0.29.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.
Files changed (115) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/README.md +170 -21
  3. package/dist/LiveServer.d.ts +30 -0
  4. package/dist/LiveServer.d.ts.map +1 -0
  5. package/dist/LiveServer.js +16 -0
  6. package/dist/LiveServer.js.map +1 -0
  7. package/dist/QueryServerReads.d.ts +5 -0
  8. package/dist/QueryServerReads.d.ts.map +1 -0
  9. package/dist/QueryServerReads.js +2 -0
  10. package/dist/QueryServerReads.js.map +1 -0
  11. package/dist/WebSocketRequired.d.ts +8 -0
  12. package/dist/WebSocketRequired.d.ts.map +1 -0
  13. package/dist/WebSocketRequired.js +4 -0
  14. package/dist/WebSocketRequired.js.map +1 -0
  15. package/dist/automaticLive.js +1 -1
  16. package/dist/automaticLive.js.map +1 -1
  17. package/dist/bind.d.ts +1 -2
  18. package/dist/bind.d.ts.map +1 -1
  19. package/dist/bind.js.map +1 -1
  20. package/dist/clientOptions.d.ts +1 -0
  21. package/dist/clientOptions.d.ts.map +1 -1
  22. package/dist/internal/automaticQuery.d.ts +1 -1
  23. package/dist/internal/automaticQuery.d.ts.map +1 -1
  24. package/dist/internal/automaticQuery.js +21 -4
  25. package/dist/internal/automaticQuery.js.map +1 -1
  26. package/dist/internal/clientOperations.d.ts.map +1 -1
  27. package/dist/internal/clientOperations.js +0 -4
  28. package/dist/internal/clientOperations.js.map +1 -1
  29. package/dist/internal/operationDeclaration.d.ts +6 -1
  30. package/dist/internal/operationDeclaration.d.ts.map +1 -1
  31. package/dist/internal/operationDeclaration.js.map +1 -1
  32. package/dist/internal/policyContext.d.ts +4 -0
  33. package/dist/internal/policyContext.d.ts.map +1 -0
  34. package/dist/internal/policyContext.js +7 -0
  35. package/dist/internal/policyContext.js.map +1 -0
  36. package/dist/internal/queryReactivity.d.ts.map +1 -1
  37. package/dist/internal/queryReactivity.js +10 -5
  38. package/dist/internal/queryReactivity.js.map +1 -1
  39. package/dist/internal/queryReadKeys.d.ts +5 -0
  40. package/dist/internal/queryReadKeys.d.ts.map +1 -0
  41. package/dist/internal/queryReadKeys.js +6 -0
  42. package/dist/internal/queryReadKeys.js.map +1 -0
  43. package/dist/internal/resolveQueries.d.ts +8 -0
  44. package/dist/internal/resolveQueries.d.ts.map +1 -0
  45. package/dist/internal/resolveQueries.js +8 -0
  46. package/dist/internal/resolveQueries.js.map +1 -0
  47. package/dist/internal/retryOnChange.d.ts.map +1 -1
  48. package/dist/internal/retryOnChange.js +8 -3
  49. package/dist/internal/retryOnChange.js.map +1 -1
  50. package/dist/internal/rpcClient.d.ts.map +1 -1
  51. package/dist/internal/rpcClient.js +11 -1
  52. package/dist/internal/rpcClient.js.map +1 -1
  53. package/dist/operation.d.ts +9 -9
  54. package/dist/operation.d.ts.map +1 -1
  55. package/dist/operation.js +2 -1
  56. package/dist/operation.js.map +1 -1
  57. package/dist/publicConfig.d.ts +1 -1
  58. package/dist/publicConfig.d.ts.map +1 -1
  59. package/dist/queryKeys.d.ts +9 -0
  60. package/dist/queryKeys.d.ts.map +1 -0
  61. package/dist/queryKeys.js +13 -0
  62. package/dist/queryKeys.js.map +1 -0
  63. package/dist/querySubscription.d.ts +1 -1
  64. package/dist/querySubscription.d.ts.map +1 -1
  65. package/dist/querySubscription.js +15 -3
  66. package/dist/querySubscription.js.map +1 -1
  67. package/dist/readPolicy.d.ts +1 -0
  68. package/dist/readPolicy.d.ts.map +1 -1
  69. package/dist/readPolicy.js +6 -3
  70. package/dist/readPolicy.js.map +1 -1
  71. package/dist/readPolicyErrors.d.ts +6 -0
  72. package/dist/readPolicyErrors.d.ts.map +1 -1
  73. package/dist/readPolicyErrors.js +5 -0
  74. package/dist/readPolicyErrors.js.map +1 -1
  75. package/dist/serverMetadata.d.ts +4 -5
  76. package/dist/serverMetadata.d.ts.map +1 -1
  77. package/dist/serverMetadata.js +5 -13
  78. package/dist/serverMetadata.js.map +1 -1
  79. package/dist/socketAuthentication.d.ts +18 -0
  80. package/dist/socketAuthentication.d.ts.map +1 -0
  81. package/dist/socketAuthentication.js +27 -0
  82. package/dist/socketAuthentication.js.map +1 -0
  83. package/dist/testing.d.ts +4 -2
  84. package/dist/testing.d.ts.map +1 -1
  85. package/dist/testing.js +35 -1
  86. package/dist/testing.js.map +1 -1
  87. package/dist/validateReadPolicies.d.ts +5 -0
  88. package/dist/validateReadPolicies.d.ts.map +1 -0
  89. package/dist/validateReadPolicies.js +25 -0
  90. package/dist/validateReadPolicies.js.map +1 -0
  91. package/package.json +7 -3
  92. package/src/LiveServer.ts +20 -0
  93. package/src/QueryServerReads.ts +8 -0
  94. package/src/WebSocketRequired.ts +3 -0
  95. package/src/automaticLive.ts +1 -1
  96. package/src/bind.ts +1 -5
  97. package/src/clientOptions.ts +1 -0
  98. package/src/internal/automaticQuery.ts +21 -5
  99. package/src/internal/clientOperations.ts +0 -6
  100. package/src/internal/operationDeclaration.ts +7 -1
  101. package/src/internal/policyContext.ts +8 -0
  102. package/src/internal/queryReactivity.ts +14 -5
  103. package/src/internal/queryReadKeys.ts +8 -0
  104. package/src/internal/resolveQueries.ts +10 -0
  105. package/src/internal/retryOnChange.ts +10 -3
  106. package/src/internal/rpcClient.ts +14 -5
  107. package/src/operation.ts +13 -13
  108. package/src/queryKeys.ts +23 -0
  109. package/src/querySubscription.ts +18 -4
  110. package/src/readPolicy.ts +7 -3
  111. package/src/readPolicyErrors.ts +5 -0
  112. package/src/serverMetadata.ts +7 -22
  113. package/src/socketAuthentication.ts +28 -0
  114. package/src/testing.ts +42 -2
  115. package/src/validateReadPolicies.ts +26 -0
@@ -7,7 +7,6 @@ import { invalidationKeys, type Key, readKeys } from "@shivaedev/changes/keys.ts
7
7
  import type { automaticLive } from "#automaticLive.ts";
8
8
  import type { QueryOptions } from "#bind.ts";
9
9
  import type { CommandShape, QueryShape } from "#operation.ts";
10
- import { MissingReadPolicy } from "#readPolicyErrors.ts";
11
10
  import type { BindingOwner } from "./bindingOwner.ts";
12
11
  import { clientActivities } from "./clientActivity.ts";
13
12
  import { queryReactivity } from "./queryReactivity.ts";
@@ -29,11 +28,6 @@ export function boundQuery(service: ErasedClient, tag: string, query: QueryShape
29
28
  const cached = new WeakMap<ReturnType<typeof service.query>, ReturnType<typeof service.query>>();
30
29
  return {
31
30
  query: (payload: unknown, options: QueryOptions = {}) => {
32
- if (query.readPolicy === undefined) {
33
- return service.runtime.atom(
34
- Effect.fail(new MissingReadPolicy({ message: `Declare a readPolicy on query ${query.name} before running it live or subscribing` })),
35
- );
36
- }
37
31
  const atom = service.query(tag, payload, options);
38
32
  const existing = cached.get(atom);
39
33
  if (existing !== undefined) {
@@ -1,6 +1,12 @@
1
1
  import { Schema } from "effect";
2
2
  import type { OperationShape } from "#operation.ts";
3
- import { type RejectionSpecs, rejectionSet } from "#rejection.ts";
3
+ import { type MatchingTags, type RejectionSpecs, rejectionSet } from "#rejection.ts";
4
+
5
+ export interface Declaration<TPayload extends Schema.Top | Schema.Struct.Fields, TSuccess extends Schema.Top, TSpecs extends RejectionSpecs> {
6
+ readonly payload?: TPayload;
7
+ readonly rejections?: TSpecs & MatchingTags<TSpecs>;
8
+ readonly success?: TSuccess;
9
+ }
4
10
 
5
11
  export interface Loose {
6
12
  readonly payload?: Schema.Top | Schema.Struct.Fields;
@@ -0,0 +1,8 @@
1
+ import { Context, Effect, Option } from "effect";
2
+ import type { Rpc } from "effect/rpc";
3
+
4
+ export const policyContext = Effect.fnUntraced(function* (rpc: Rpc.Any) {
5
+ const request = yield* Effect.context<unknown>();
6
+ const handler = Context.getOption(request, Context.Service<Rpc.Handler<string>>(rpc.key));
7
+ return Option.isSome(handler) ? Context.merge(handler.value.context, request) : request;
8
+ });
@@ -1,4 +1,4 @@
1
- import { Duration, Effect } from "effect";
1
+ import { Cause, Duration, Effect, Option, Predicate } from "effect";
2
2
  import * as AsyncResult from "effect/reactivity/AsyncResult";
3
3
  import * as Atom from "effect/reactivity/Atom";
4
4
  import type * as AtomRegistry from "effect/reactivity/AtomRegistry";
@@ -55,6 +55,15 @@ export function queryReactivity<R, E>(runtime: Atom.AtomRuntime<R, E>, queue?: (
55
55
  pending = undefined;
56
56
  dequeue();
57
57
  }
58
+ function reread() {
59
+ if (
60
+ !Option.exists(AsyncResult.cause(get.once(source)), (cause) =>
61
+ Option.exists(Cause.findErrorOption(cause), Predicate.isTagged("QueryReadDenied")),
62
+ )
63
+ ) {
64
+ get.refresh(source);
65
+ }
66
+ }
58
67
  function refresh(active: () => boolean) {
59
68
  if (!active()) {
60
69
  dequeue();
@@ -64,7 +73,7 @@ export function queryReactivity<R, E>(runtime: Atom.AtomRuntime<R, E>, queue?: (
64
73
  pending = active;
65
74
  } else {
66
75
  pending = undefined;
67
- get.refresh(source);
76
+ reread();
68
77
  dequeue();
69
78
  }
70
79
  }
@@ -77,7 +86,7 @@ export function queryReactivity<R, E>(runtime: Atom.AtomRuntime<R, E>, queue?: (
77
86
  const delay = Duration.toMillis(Duration.fromInputUnsafe(get.once(queryCoalesceWindow(wrapped)) ?? batch.window ?? 0));
78
87
  if (delay === 0) {
79
88
  clear();
80
- get.refresh(source);
89
+ reread();
81
90
  } else if (!scheduled) {
82
91
  queued ??= queue?.();
83
92
  scheduled = true;
@@ -90,7 +99,7 @@ export function queryReactivity<R, E>(runtime: Atom.AtomRuntime<R, E>, queue?: (
90
99
  reactivity.registerUnsafe(keys, () => {
91
100
  if (!liveBatches.has(reactivity)) {
92
101
  clear();
93
- get.refresh(source);
102
+ reread();
94
103
  }
95
104
  }),
96
105
  );
@@ -100,7 +109,7 @@ export function queryReactivity<R, E>(runtime: Atom.AtomRuntime<R, E>, queue?: (
100
109
  const active = pending;
101
110
  pending = undefined;
102
111
  if (active()) {
103
- get.refresh(source);
112
+ reread();
104
113
  }
105
114
  dequeue();
106
115
  }
@@ -0,0 +1,8 @@
1
+ import { Effect, type Option } from "effect";
2
+ import type { QueryShape } from "#operation.ts";
3
+ import type { Viewer } from "#readPolicy.ts";
4
+
5
+ export const queryReadKeys = Effect.fnUntraced(function* <E, R>(query: QueryShape<E, R>, payload: unknown, viewer: Option.Option<Viewer>) {
6
+ const derived = query.serverReads === undefined ? [] : yield* query.serverReads(payload, viewer);
7
+ return [...query.reads(payload, viewer), ...derived];
8
+ });
@@ -0,0 +1,10 @@
1
+ import { Effect } from "effect";
2
+ import type { QueryShape } from "#operation.ts";
3
+ import type { QueryReference } from "#serverMetadata.ts";
4
+
5
+ export function resolveQueries(queries: readonly QueryShape[], requested: readonly QueryReference[]) {
6
+ return Effect.forEach(requested, (reference) => {
7
+ const query = queries.find((candidate) => candidate.name === reference.query);
8
+ return query === undefined ? Effect.die(new Error(`Unknown query: ${reference.query}`)) : Effect.succeed({ payload: reference.payload, query });
9
+ });
10
+ }
@@ -1,4 +1,4 @@
1
- import { Effect } from "effect";
1
+ import { Cause, Effect, Option, Predicate } from "effect";
2
2
  import type * as Atom from "effect/reactivity/Atom";
3
3
  import * as AtomRegistry from "effect/reactivity/AtomRegistry";
4
4
  import * as Reactivity from "effect/reactivity/Reactivity";
@@ -9,13 +9,20 @@ export const retryOnChange = Effect.fnUntraced(function* <E>(status: Atom.Atom<L
9
9
  const registry = yield* AtomRegistry.AtomRegistry;
10
10
  const dispatcher = registry.schedulerAsync.makeDispatcher();
11
11
  let active = true;
12
+ function canRetry() {
13
+ const current = registry.get(status);
14
+ return (
15
+ current.connection === "failed"
16
+ && !Option.exists(current.failure, (cause) => Option.exists(Cause.findErrorOption(cause), Predicate.isTagged("QueryReadDenied")))
17
+ );
18
+ }
12
19
  function retry() {
13
- if (active && registry.get(status).connection === "failed") {
20
+ if (active && canRetry()) {
14
21
  restart();
15
22
  }
16
23
  }
17
24
  function changed() {
18
- if (registry.get(status).connection === "failed") {
25
+ if (canRetry()) {
19
26
  dispatcher.scheduleTask(retry, 0);
20
27
  }
21
28
  }
@@ -5,6 +5,7 @@ import { type Rpc, RpcClient, RpcGroup, RpcSerialization } from "effect/rpc";
5
5
  import * as Socket from "effect/socket/Socket";
6
6
  import { Activity } from "#clientActivity.ts";
7
7
  import type { ClientOptions } from "#clientOptions.ts";
8
+ import { authenticateSocket } from "#socketAuthentication.ts";
8
9
  import { clientActivities, makeActivity } from "./clientActivity.ts";
9
10
 
10
11
  export interface RpcSource {
@@ -17,6 +18,7 @@ export function rpcClient(name: string, source: RpcSource, options: ClientOption
17
18
  const group = RpcGroup.make(...source.requests.values()).annotateMerge(source.annotations);
18
19
  function sharedProtocol(identity?: string) {
19
20
  return socketProtocol({
21
+ bearerToken: options.bearerToken,
20
22
  headers: options.headers,
21
23
  identity,
22
24
  url: options.url.replace(/^http/u, "ws"),
@@ -64,19 +66,26 @@ export const socketIdentity = Atom.make<string | undefined>(undefined);
64
66
  const socketMemoMap = Layer.makeMemoMapUnsafe();
65
67
  const socketProtocol = Atom.family(
66
68
  (options: {
69
+ readonly bearerToken: ClientOptions["bearerToken"];
67
70
  readonly url: string;
68
71
  readonly headers: ClientOptions["headers"];
69
72
  readonly identity: string | undefined;
70
73
  readonly webSocketConstructor: ClientOptions["webSocketConstructor"];
71
74
  }) => {
75
+ let url = options.url;
76
+ if (options.bearerToken !== undefined) {
77
+ const address = new URL(url);
78
+ address.searchParams.set("auth", "frame");
79
+ url = address.toString();
80
+ }
81
+ const raw = Socket.layerWebSocket(url, { headers: options.headers });
82
+ const socket = (
83
+ options.bearerToken === undefined ? raw : Layer.effect(Socket.Socket, authenticateSocket(options.bearerToken)).pipe(Layer.provide(raw))
84
+ ).pipe(Layer.provide(options.webSocketConstructor ?? Socket.layerWebSocketConstructorGlobal));
72
85
  const protocol = RpcClient.layerProtocolSocket({
73
86
  retryPolicy: Schedule.jittered(Schedule.min([Schedule.exponential(500, 1.5), Schedule.spaced(5000)])),
74
87
  }).pipe(
75
- Layer.provide(
76
- Socket.layerWebSocket(options.url, { headers: options.headers }).pipe(
77
- Layer.provide(options.webSocketConstructor ?? Socket.layerWebSocketConstructorGlobal),
78
- ),
79
- ),
88
+ Layer.provide(socket),
80
89
  Layer.provide(RpcSerialization.layerNdjson),
81
90
  // Socket deadlines follow network time even when application time is simulated.
82
91
  Layer.provide(Layer.succeed(Clock.Clock, Clock.Clock.defaultValue())),
package/src/operation.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  import type { Option, Schema } from "effect";
2
2
  import type { Key } from "@shivaedev/changes/keys.ts";
3
3
  import type { Bivariant } from "@shivaedev/types/Bivariant.ts";
4
- import { type Loose, operation } from "#internal/operationDeclaration.ts";
4
+ import { type Declaration, type Loose, operation } from "#internal/operationDeclaration.ts";
5
+ import type { QueryServerReads } from "#QueryServerReads.ts";
5
6
  import type { QueryReadPolicy, Viewer } from "#readPolicy.ts";
6
- import type { MatchingTags, Reject, RejectedBy, RejectionSpecs, Rejections, RejectionUnion } from "#rejection.ts";
7
+ import type { Reject, RejectedBy, RejectionSpecs, Rejections, RejectionUnion } from "#rejection.ts";
7
8
 
8
9
  export type PayloadSchema<TPayload extends Schema.Top | Schema.Struct.Fields> = TPayload extends Schema.Struct.Fields
9
10
  ? Schema.Struct<TPayload>
@@ -25,8 +26,9 @@ export interface OperationShape {
25
26
  export interface QueryShape<E = unknown, R = unknown> extends OperationShape {
26
27
  readonly kind: "query";
27
28
  readonly live?: "rerun-and-compare" | undefined;
28
- readonly readPolicy?: Bivariant<QueryReadPolicy<unknown, E, R>>;
29
+ readonly readPolicy: Bivariant<QueryReadPolicy<unknown, E, R>>;
29
30
  reads: Bivariant<(payload: unknown, viewer: Option.Option<Viewer>) => readonly Key[]>;
31
+ readonly serverReads?: Bivariant<QueryServerReads<unknown, E, R>>;
30
32
  }
31
33
 
32
34
  export interface StreamShape extends OperationShape {
@@ -60,8 +62,9 @@ export interface Query<
60
62
  > extends Operation<TName, TPayload, TSuccess, TSpecs> {
61
63
  readonly kind: "query";
62
64
  readonly live?: TLive;
63
- readonly readPolicy?: QueryReadPolicy<TPayload["Type"], RejectedBy<TSpecs>, R>;
65
+ readonly readPolicy: QueryReadPolicy<TPayload["Type"], RejectedBy<TSpecs>, R>;
64
66
  reads: (payload: TPayload["Type"], viewer: Option.Option<Viewer>) => readonly Key[];
67
+ readonly serverReads?: QueryServerReads<TPayload["Type"], RejectedBy<TSpecs>, R>;
65
68
  }
66
69
 
67
70
  export interface Streaming<TName extends string, TPayload extends Schema.Top, TSuccess extends Schema.Top, TSpecs extends RejectionSpecs>
@@ -76,12 +79,6 @@ export interface Command<TName extends string, TPayload extends Schema.Top, TSuc
76
79
  readonly kind: "command";
77
80
  }
78
81
 
79
- interface Declaration<TPayload extends Schema.Top | Schema.Struct.Fields, TSuccess extends Schema.Top, TSpecs extends RejectionSpecs> {
80
- readonly payload?: TPayload;
81
- readonly rejections?: TSpecs & MatchingTags<TSpecs>;
82
- readonly success?: TSuccess;
83
- }
84
-
85
82
  export function query<
86
83
  const TName extends string,
87
84
  TPayload extends Schema.Top | Schema.Struct.Fields = Schema.Void,
@@ -94,7 +91,8 @@ export function query<
94
91
  declaration: Declaration<TPayload, TSuccess, TSpecs> & {
95
92
  readonly live?: TLive;
96
93
  readonly reads: (payload: PayloadSchema<TPayload>["Type"], viewer: Option.Option<Viewer>) => readonly Key[];
97
- readonly readPolicy?: QueryReadPolicy<PayloadSchema<TPayload>["Type"], NoInfer<RejectedBy<TSpecs>>, R>;
94
+ readonly readPolicy: QueryReadPolicy<PayloadSchema<TPayload>["Type"], NoInfer<RejectedBy<TSpecs>>, R>;
95
+ readonly serverReads?: QueryServerReads<PayloadSchema<TPayload>["Type"], NoInfer<RejectedBy<TSpecs>>, R>;
98
96
  },
99
97
  ): NoInfer<Query<TName, PayloadSchema<TPayload>, TSuccess, TSpecs, R, TLive>>;
100
98
  export function query(
@@ -102,14 +100,16 @@ export function query(
102
100
  declaration: Loose & {
103
101
  readonly live?: "rerun-and-compare" | undefined;
104
102
  readonly reads: (payload: unknown, viewer: Option.Option<Viewer>) => readonly Key[];
105
- readonly readPolicy?: QueryReadPolicy<unknown, unknown, unknown>;
103
+ readonly readPolicy: QueryReadPolicy<unknown, unknown, unknown>;
104
+ readonly serverReads?: QueryServerReads<unknown, unknown, unknown>;
106
105
  },
107
106
  ): QueryShape {
108
107
  return {
109
108
  ...operation("query", name, declaration),
110
109
  live: declaration.live,
110
+ readPolicy: declaration.readPolicy,
111
111
  reads: declaration.reads,
112
- ...(declaration.readPolicy === undefined ? {} : { readPolicy: declaration.readPolicy }),
112
+ ...(declaration.serverReads === undefined ? {} : { serverReads: declaration.serverReads }),
113
113
  };
114
114
  }
115
115
 
@@ -0,0 +1,23 @@
1
+ import { Effect, Option } from "effect";
2
+ import type { Key } from "@shivaedev/changes/keys.ts";
3
+ import type { QueryServices } from "#contract.ts";
4
+ import { queryReadKeys } from "#internal/queryReadKeys.ts";
5
+ import { resolveQueries } from "#internal/resolveQueries.ts";
6
+ import type { QueryShape } from "#operation.ts";
7
+ import { checkQuery, type Viewer } from "#readPolicy.ts";
8
+ import type { MissingReadPolicy, QueryReadDenied } from "#readPolicyErrors.ts";
9
+ import type { QueryReference } from "#serverMetadata.ts";
10
+
11
+ export function queryKeys<const TQueries extends readonly QueryShape[]>(
12
+ queries: TQueries,
13
+ requested: readonly QueryReference[],
14
+ viewer?: Option.Option<Viewer>,
15
+ ): Effect.Effect<readonly Key[], TQueries[number]["error"]["Type"] | MissingReadPolicy | QueryReadDenied, QueryServices<TQueries[number]>>;
16
+ export function queryKeys(queries: readonly QueryShape[], requested: readonly QueryReference[], viewer: Option.Option<Viewer> = Option.none()) {
17
+ return Effect.fnUntraced(function* () {
18
+ const resolved = yield* resolveQueries(queries, requested);
19
+ yield* Effect.forEach(resolved, ({ query, payload }) => checkQuery(query, payload, viewer));
20
+ const scopes = yield* Effect.forEach(resolved, ({ query, payload }) => queryReadKeys(query, payload, viewer));
21
+ return scopes.flat();
22
+ })();
23
+ }
@@ -1,6 +1,8 @@
1
1
  import { Context, Effect, type Option } from "effect";
2
- import type { Rpc } from "effect/rpc";
2
+ import { Rpc } from "effect/rpc";
3
3
  import type { Key } from "@shivaedev/changes/keys.ts";
4
+ import { policyContext } from "#internal/policyContext.ts";
5
+ import { queryReadKeys } from "#internal/queryReadKeys.ts";
4
6
  import { checkQuery, type PolicyChannels, type Viewer } from "#readPolicy.ts";
5
7
  import type { MissingReadPolicy, QueryReadDenied } from "#readPolicyErrors.ts";
6
8
  import { ChangesQueries, type QueryReference, type QueryRequest } from "#serverMetadata.ts";
@@ -26,10 +28,22 @@ export function querySubscription<TRpc extends Rpc.Any>(
26
28
  export function querySubscription(rpc: Rpc.Any, references: readonly QueryReference[], viewer: Option.Option<Viewer>) {
27
29
  return Effect.fnUntraced(function* () {
28
30
  const queries = yield* Context.getUnsafe(rpc.annotations, ChangesQueries).resolve(references);
29
- yield* Effect.forEach(queries, ({ query, payload }) => checkQuery(query, payload, viewer));
30
- const scopes = queries.map(({ query, payload }) => query.reads(payload, viewer));
31
+ const prefix = rpc._tag.slice(0, -"$changes".length);
32
+ const policies = yield* Effect.forEach(
33
+ queries,
34
+ Effect.fnUntraced(function* ({ query, payload }) {
35
+ const context = yield* policyContext(Rpc.make(`${prefix}${query.name}`));
36
+ return {
37
+ check: Effect.provideContext(checkQuery(query, payload, viewer), context),
38
+ keys: queryReadKeys(query, payload, viewer).pipe(Effect.provideContext(context)),
39
+ permitted: Effect.suspend(() => query.readPolicy?.(payload, viewer) ?? Effect.succeed(false)).pipe(Effect.provideContext(context)),
40
+ };
41
+ }),
42
+ );
43
+ yield* Effect.forEach(policies, ({ check }) => check);
44
+ const scopes = yield* Effect.forEach(policies, ({ keys }) => keys);
31
45
  const authorized = Effect.map(
32
- Effect.forEach(queries, ({ query, payload }) => query.readPolicy?.(payload, viewer) ?? Effect.succeed(false)),
46
+ Effect.forEach(policies, ({ permitted }) => permitted),
33
47
  (permissions) => permissions.every(Boolean),
34
48
  );
35
49
  return { authorized, keys: scopes.flat(), queries, scopes } satisfies QuerySubscription<unknown, unknown>;
package/src/readPolicy.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Context, Effect, Option, type Stream, type Types } from "effect";
2
2
  import type { Rpc } from "effect/rpc";
3
+ import { policyContext } from "#internal/policyContext.ts";
3
4
  import type { QueryShape } from "#operation.ts";
4
5
  import { MissingReadPolicy, QueryReadDenied } from "#readPolicyErrors.ts";
5
6
  import { QueryDefinition } from "#serverMetadata.ts";
@@ -10,9 +11,11 @@ export interface Viewer {
10
11
  export type QueryReadPolicy<TPayload, E = never, R = never> = (payload: TPayload, viewer: Option.Option<Viewer>) => Effect.Effect<boolean, E, R>;
11
12
 
12
13
  export const CurrentViewer = Context.Reference<Option.Option<Viewer>>("@shivaedev/contract/CurrentViewer", { defaultValue: Option.none });
14
+ export const signedIn: QueryReadPolicy<unknown> = (_payload, viewer) => Effect.succeed(Option.isSome(viewer));
15
+
13
16
  export const checkQuery = Effect.fnUntraced(function* <E, R>(query: QueryShape<E, R>, payload: unknown, viewer: Option.Option<Viewer>) {
14
17
  if (query.readPolicy === undefined) {
15
- return yield* new MissingReadPolicy({ message: `Declare a readPolicy on query ${query.name} before running it live or subscribing` });
18
+ return yield* new MissingReadPolicy({ message: `Declare a readPolicy on query ${query.name} before reading it or subscribing` });
16
19
  }
17
20
  if (!(yield* query.readPolicy(payload, viewer))) {
18
21
  return yield* new QueryReadDenied({ message: `Read not allowed for query ${query.name}` });
@@ -41,8 +44,9 @@ export function authorizeReads(
41
44
  ) {
42
45
  return Effect.fnUntraced(function* () {
43
46
  const definition = Context.getOption(request.rpc.annotations, QueryDefinition);
44
- if (Option.isSome(definition) && definition.value.definition.readPolicy !== undefined) {
45
- yield* checkQuery(definition.value.definition, request.payload, viewer);
47
+ if (Option.isSome(definition)) {
48
+ const context = yield* policyContext(request.rpc);
49
+ yield* checkQuery(definition.value.definition, request.payload, viewer).pipe(Effect.provideContext(context));
46
50
  }
47
51
  return yield* Effect.provideService(effect, CurrentViewer, viewer);
48
52
  })();
@@ -2,3 +2,8 @@ import { Schema } from "effect";
2
2
 
3
3
  export class MissingReadPolicy extends Schema.TaggedError<MissingReadPolicy>()("MissingReadPolicy", { message: Schema.String }) {}
4
4
  export class QueryReadDenied extends Schema.TaggedError<QueryReadDenied>()("QueryReadDenied", { message: Schema.String }) {}
5
+
6
+ export class MissingReadPolicies extends Schema.TaggedError<MissingReadPolicies>()("MissingReadPolicies", {
7
+ message: Schema.String,
8
+ queries: Schema.Array(Schema.String),
9
+ }) {}
@@ -1,11 +1,11 @@
1
- import { Context, Effect, Option, Schema } from "effect";
1
+ import { Context, type Effect, Schema } from "effect";
2
2
  import { Rpc, type RpcSchema } from "effect/rpc";
3
- import type { Key } from "@shivaedev/changes/keys.ts";
4
3
  import type { QueryServices } from "#contract.ts";
5
4
  import { changesSuccess } from "#internal/changesSuccess.ts";
5
+ import { resolveQueries } from "#internal/resolveQueries.ts";
6
6
  import type { CommandShape, QueryShape, StreamShape } from "#operation.ts";
7
- import type { Viewer } from "#readPolicy.ts";
8
7
  import { MissingReadPolicy, QueryReadDenied } from "#readPolicyErrors.ts";
8
+ import { WebSocketRequired } from "#WebSocketRequired.ts";
9
9
 
10
10
  export class QueryDefinition extends Context.Service<QueryDefinition, { readonly definition: QueryShape }>()("@shivaedev/contract/QueryDefinition") {}
11
11
  export interface QueryRequest<E = unknown, R = unknown> {
@@ -15,6 +15,7 @@ export interface QueryRequest<E = unknown, R = unknown> {
15
15
  export class ChangesQueries extends Context.Service<
16
16
  ChangesQueries,
17
17
  {
18
+ readonly queries: readonly QueryShape[];
18
19
  readonly resolve: (references: readonly QueryReference[]) => Effect.Effect<readonly QueryRequest[]>;
19
20
  }
20
21
  >()("@shivaedev/contract/ChangesQueries") {}
@@ -34,22 +35,6 @@ type ReferenceSchema<TQuery extends QueryShape> = TQuery extends QueryShape
34
35
  ? Schema.Struct<{ query: Schema.Literal<TQuery["name"]>; payload: TQuery["payload"] }>
35
36
  : never;
36
37
 
37
- function resolveQueries(queries: readonly QueryShape[], requested: readonly QueryReference[]) {
38
- return Effect.forEach(requested, (reference) => {
39
- const query = queries.find((candidate) => candidate.name === reference.query);
40
- return query === undefined ? Effect.die(new Error(`Unknown query: ${reference.query}`)) : Effect.succeed({ payload: reference.payload, query });
41
- });
42
- }
43
-
44
- export const queryKeys = Effect.fnUntraced(function* (
45
- queries: readonly QueryShape[],
46
- requested: readonly QueryReference[],
47
- viewer: Option.Option<Viewer> = Option.none(),
48
- ): Effect.fn.Return<readonly Key[]> {
49
- const resolved = yield* resolveQueries(queries, requested);
50
- return resolved.flatMap(({ query, payload }) => query.reads(payload, viewer));
51
- });
52
-
53
38
  function referenceSchemas<const TQueries extends readonly QueryShape[]>(
54
39
  queries: TQueries,
55
40
  ): Schema.$Array<Schema.Union<readonly ReferenceSchema<TQueries[number]>[]>>;
@@ -58,7 +43,7 @@ function referenceSchemas(queries: readonly QueryShape[]) {
58
43
  }
59
44
 
60
45
  type ChangesError<TQueries extends readonly QueryShape[]> = Schema.Union<
61
- readonly [typeof MissingReadPolicy, typeof QueryReadDenied, ...TQueries[number]["error"][]]
46
+ readonly [typeof MissingReadPolicy, typeof QueryReadDenied, typeof WebSocketRequired, ...TQueries[number]["error"][]]
62
47
  >;
63
48
 
64
49
  export function changesRpc<const TName extends string, const TQueries extends readonly QueryShape[]>(
@@ -74,11 +59,11 @@ export function changesRpc<const TName extends string, const TQueries extends re
74
59
  >;
75
60
  export function changesRpc(name: string, queries: readonly QueryShape[]) {
76
61
  return Rpc.make(`${name}.$changes`, {
77
- error: Schema.Union([MissingReadPolicy, QueryReadDenied, ...queries.map((query) => query.error)]),
62
+ error: Schema.Union([MissingReadPolicy, QueryReadDenied, WebSocketRequired, ...queries.map((query) => query.error)]),
78
63
  payload: { queries: referenceSchemas(queries) },
79
64
  stream: true,
80
65
  success: changesSuccess(queries),
81
- }).annotate(ChangesQueries, { resolve: (references) => resolveQueries(queries, references) });
66
+ }).annotate(ChangesQueries, { queries, resolve: (references) => resolveQueries(queries, references) });
82
67
  }
83
68
 
84
69
  export function operationAnnotations(operation: QueryShape | CommandShape | StreamShape, keyScope: "session" | undefined) {
@@ -0,0 +1,28 @@
1
+ import { Effect, Latch, Schema } from "effect";
2
+ import * as Socket from "effect/socket/Socket";
3
+
4
+ export const SocketAuthentication = Schema.Struct({
5
+ _tag: Schema.Literal("Authenticate"),
6
+ token: Schema.String.check(Schema.isPattern(/^[\x21-\x7e]+$/u)),
7
+ });
8
+
9
+ export const authenticateSocket = Effect.fnUntraced(function* (token: string) {
10
+ const socket = yield* Socket.Socket;
11
+ const ready = yield* Latch.make(false);
12
+ const writer = yield* Effect.map(socket.writer, (nativeWriter) => ({
13
+ write: (chunk: Parameters<typeof nativeWriter.write>[0]) => ready.await.pipe(Effect.andThen(nativeWriter.write(chunk))),
14
+ writeAll: (chunks: Parameters<typeof nativeWriter.writeAll>[0]) => ready.await.pipe(Effect.andThen(nativeWriter.writeAll(chunks))),
15
+ }));
16
+ return {
17
+ ...socket,
18
+ reader: Effect.gen(function* () {
19
+ yield* ready.close;
20
+ const reader = yield* socket.reader;
21
+ const raw = yield* socket.writer;
22
+ yield* raw.write(JSON.stringify({ _tag: "Authenticate", token }));
23
+ yield* ready.open;
24
+ return { ...reader, pull: reader.pull.pipe(Effect.onError(() => ready.close)) };
25
+ }),
26
+ writer: Effect.succeed(writer),
27
+ };
28
+ });
package/src/testing.ts CHANGED
@@ -1,6 +1,7 @@
1
- import { Deferred, type Duration, Effect, Fiber, Stream, SubscriptionRef } from "effect";
1
+ import { Deferred, type Duration, Effect, Fiber, Layer, Queue, Stream, SubscriptionRef } from "effect";
2
+ import { type Rpc, RpcClient, type RpcGroup, type RpcMessage, RpcSerialization, RpcServer } from "effect/rpc";
2
3
  import type { Key } from "@shivaedev/changes/keys.ts";
3
- import type { LiveHint } from "./live.ts";
4
+ import type { LiveHint } from "#live.ts";
4
5
 
5
6
  export interface HintViewer<E> {
6
7
  readonly finished: Effect.Effect<void, E>;
@@ -39,3 +40,42 @@ export const heard = Effect.fn("Live.heard")(function* <E>(
39
40
  function namesKeys(hint: LiveHint, keys: readonly Key[]): boolean {
40
41
  return hint._tag === "Changed" && keys.every((key) => hint.keys.some((actual) => JSON.stringify(actual) === JSON.stringify(key)));
41
42
  }
43
+
44
+ export function layerMemoryProtocol<TRpcs extends Rpc.Any>(group: RpcGroup.RpcGroup<TRpcs>) {
45
+ return Layer.effect(
46
+ RpcClient.Protocol,
47
+ Effect.gen(function* () {
48
+ const requests = yield* Queue.unbounded<readonly [number, RpcMessage.FromClientEncoded]>();
49
+ const disconnects = yield* Queue.unbounded<number>();
50
+ const { codecFor } = yield* RpcSerialization.RpcSerialization;
51
+ const protocol = yield* RpcClient.Protocol.make((send, clientIds) =>
52
+ Effect.gen(function* () {
53
+ const server = RpcServer.Protocol.of({
54
+ clientIds: Effect.sync(() => clientIds),
55
+ codecFor,
56
+ disconnects,
57
+ end: () => Effect.void,
58
+ initialMessage: Effect.succeedNone,
59
+ run: (receive) => Effect.forever(Effect.flatMap(Queue.take(requests), ([id, message]) => receive(id, message))),
60
+ send,
61
+ supportsAck: true,
62
+ supportsNotifications: true,
63
+ supportsSpanPropagation: true,
64
+ supportsTransferables: false,
65
+ });
66
+ yield* RpcServer.make(group).pipe(Effect.provideService(RpcServer.Protocol, server), Effect.forkScoped);
67
+ return {
68
+ codecFor,
69
+ send: (clientId, request) => Queue.offer(requests, [clientId, request]).pipe(Effect.asVoid),
70
+ supportsAck: true,
71
+ supportsTransferables: false,
72
+ };
73
+ }),
74
+ );
75
+ return {
76
+ ...protocol,
77
+ run: (clientId, receive) => protocol.run(clientId, receive).pipe(Effect.ensuring(Queue.offer(disconnects, clientId))),
78
+ } satisfies RpcClient.Protocol["Service"];
79
+ }),
80
+ ).pipe(Layer.provide(RpcSerialization.layerNdjson));
81
+ }
@@ -0,0 +1,26 @@
1
+ import { Context, Effect, Option } from "effect";
2
+ import type { Rpc, RpcGroup } from "effect/rpc";
3
+ import { MissingReadPolicies } from "#readPolicyErrors.ts";
4
+ import { ChangesQueries, QueryDefinition } from "#serverMetadata.ts";
5
+
6
+ export const validateReadPolicies = Effect.fnUntraced(function* <R extends Rpc.Any>(group: RpcGroup.RpcGroup<R>) {
7
+ const missing = new Set<string>();
8
+ for (const rpc of group.requests.values()) {
9
+ const query = Context.getOption(rpc.annotations, QueryDefinition);
10
+ if (Option.isSome(query) && query.value.definition.readPolicy === undefined) {
11
+ missing.add(rpc._tag);
12
+ }
13
+ const changes = Context.getOption(rpc.annotations, ChangesQueries);
14
+ if (Option.isSome(changes)) {
15
+ for (const definition of changes.value.queries) {
16
+ if (definition.readPolicy === undefined) {
17
+ missing.add(`${rpc._tag.slice(0, -"$changes".length)}${definition.name}`);
18
+ }
19
+ }
20
+ }
21
+ }
22
+ if (missing.size > 0) {
23
+ const queries = [...missing].sort((left, right) => left.localeCompare(right));
24
+ return yield* new MissingReadPolicies({ message: `Declare a readPolicy on queries: ${queries.join(", ")}`, queries });
25
+ }
26
+ });