@shivaedev/contract 0.30.1 → 0.31.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 (72) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +30 -30
  3. package/dist/automaticLive.d.ts +2 -1
  4. package/dist/automaticLive.d.ts.map +1 -1
  5. package/dist/automaticLive.js +2 -2
  6. package/dist/automaticLive.js.map +1 -1
  7. package/dist/bind.d.ts +5 -5
  8. package/dist/bind.d.ts.map +1 -1
  9. package/dist/bind.js +5 -4
  10. package/dist/bind.js.map +1 -1
  11. package/dist/clientOptions.d.ts +3 -0
  12. package/dist/clientOptions.d.ts.map +1 -1
  13. package/dist/internal/automaticQuery.d.ts.map +1 -1
  14. package/dist/internal/automaticQuery.js +6 -1
  15. package/dist/internal/automaticQuery.js.map +1 -1
  16. package/dist/internal/changesSuccess.d.ts +2 -1
  17. package/dist/internal/changesSuccess.d.ts.map +1 -1
  18. package/dist/internal/changesSuccess.js +2 -0
  19. package/dist/internal/changesSuccess.js.map +1 -1
  20. package/dist/internal/clientOperations.d.ts +14 -14
  21. package/dist/internal/clientOperations.d.ts.map +1 -1
  22. package/dist/internal/clientOperations.js +18 -5
  23. package/dist/internal/clientOperations.js.map +1 -1
  24. package/dist/internal/declarationError.d.ts.map +1 -1
  25. package/dist/internal/declarationError.js +3 -0
  26. package/dist/internal/declarationError.js.map +1 -1
  27. package/dist/internal/liveAttempt.d.ts +13 -0
  28. package/dist/internal/liveAttempt.d.ts.map +1 -0
  29. package/dist/internal/liveAttempt.js +28 -0
  30. package/dist/internal/liveAttempt.js.map +1 -0
  31. package/dist/internal/queryDelivery.d.ts +2 -20
  32. package/dist/internal/queryDelivery.d.ts.map +1 -1
  33. package/dist/internal/queryDelivery.js.map +1 -1
  34. package/dist/internal/queryHints.d.ts +3 -2
  35. package/dist/internal/queryHints.d.ts.map +1 -1
  36. package/dist/internal/queryHints.js +1 -1
  37. package/dist/internal/queryHints.js.map +1 -1
  38. package/dist/live.d.ts +5 -3
  39. package/dist/live.d.ts.map +1 -1
  40. package/dist/live.js +16 -24
  41. package/dist/live.js.map +1 -1
  42. package/dist/makeLiveServer.d.ts +2 -2
  43. package/dist/makeLiveServer.d.ts.map +1 -1
  44. package/dist/makeLiveServer.js +4 -3
  45. package/dist/makeLiveServer.js.map +1 -1
  46. package/dist/publicConfig.d.ts +1 -1
  47. package/dist/publicConfig.d.ts.map +1 -1
  48. package/dist/querySubscription.d.ts +2 -1
  49. package/dist/querySubscription.d.ts.map +1 -1
  50. package/dist/querySubscription.js +4 -1
  51. package/dist/querySubscription.js.map +1 -1
  52. package/dist/queryUpdate.d.ts +3 -1
  53. package/dist/queryUpdate.d.ts.map +1 -1
  54. package/dist/testing.d.ts +4 -40
  55. package/dist/testing.d.ts.map +1 -1
  56. package/dist/testing.js.map +1 -1
  57. package/package.json +11 -11
  58. package/src/automaticLive.ts +3 -1
  59. package/src/bind.ts +14 -12
  60. package/src/clientOptions.ts +3 -0
  61. package/src/internal/automaticQuery.ts +6 -1
  62. package/src/internal/changesSuccess.ts +3 -1
  63. package/src/internal/clientOperations.ts +26 -4
  64. package/src/internal/declarationError.ts +3 -0
  65. package/src/internal/liveAttempt.ts +44 -0
  66. package/src/internal/queryDelivery.ts +2 -3
  67. package/src/internal/queryHints.ts +3 -2
  68. package/src/live.ts +20 -27
  69. package/src/makeLiveServer.ts +11 -5
  70. package/src/querySubscription.ts +5 -1
  71. package/src/queryUpdate.ts +3 -1
  72. package/src/testing.ts +5 -5
@@ -1,4 +1,5 @@
1
1
  import { type Duration, Effect, type Schema, Stream } from "effect";
2
+ import type { Headers } from "effect/http";
2
3
  import type * as AsyncResult from "effect/reactivity/AsyncResult";
3
4
  import * as Atom from "effect/reactivity/Atom";
4
5
  import type * as AtomRpc from "effect/reactivity/AtomRpc";
@@ -71,6 +72,7 @@ export function automaticLive(
71
72
  keys: readonly Key[],
72
73
  equivalent: (left: A, right: A) => boolean,
73
74
  decode?: (value: unknown) => A,
75
+ headers?: Headers.Input,
74
76
  ) {
75
77
  if (!enabled) {
76
78
  return atom;
@@ -84,7 +86,7 @@ export function automaticLive(
84
86
  resume: signal,
85
87
  resyncKeys: decode === undefined ? localQueryKeys(keys) : [],
86
88
  retryKeys: keys,
87
- stream: Stream.unwrap(service.use((client) => Effect.succeed(client(`${name}.$changes`, { queries: [reference] })))).pipe(
89
+ stream: Stream.unwrap(service.use((client) => Effect.succeed(client(`${name}.$changes`, { queries: [reference] }, { headers })))).pipe(
88
90
  delivery.stream,
89
91
  Stream.map((hint) => queryHint(hint, [{ keys }])),
90
92
  ),
package/src/bind.ts CHANGED
@@ -11,20 +11,17 @@ import { automaticLive, type LiveBound, LiveConnection } from "#automaticLive.ts
11
11
  import type { ClientOptions, MadeClient } from "#clientOptions.ts";
12
12
  import type { Contract, Declared, Tag } from "#contract.ts";
13
13
  import { bindingOwner } from "#internal/bindingOwner.ts";
14
- import { boundCommand, boundQuery, boundStream } from "#internal/clientOperations.ts";
14
+ import { clientOperations } from "#internal/clientOperations.ts";
15
15
  import { type RpcSource, rpcClient } from "#internal/rpcClient.ts";
16
16
  import type { CommandShape, QueryShape, StreamShape } from "#operation.ts";
17
17
  import type { ResumeSource, ResumeWindow } from "#resume.ts";
18
18
 
19
19
  export type Failure<R extends Rpc.Any> =
20
20
  R extends Rpc.Rpc<infer _Tag, infer _Payload, infer _Success, infer _Error, infer TMiddleware, infer _Requires>
21
- ? Rpc.ErrorExit<R> | TMiddleware["error"]["Type"] | RpcClientError
21
+ ? Rpc.ErrorExit<R> | TMiddleware["error"]["Type"] | TMiddleware["~ClientError"] | RpcClientError
22
22
  : never;
23
23
 
24
- export type RunFailure<R extends Rpc.Any> =
25
- R extends Rpc.Rpc<infer _Tag, infer _Payload, infer _Success, infer _Error, infer TMiddleware, infer _Requires>
26
- ? Failure<R> | TMiddleware["~ClientError"]
27
- : never;
24
+ export type RunFailure<R extends Rpc.Any> = Failure<R>;
28
25
 
29
26
  export interface QueryOptions {
30
27
  readonly headers?: Headers.Input;
@@ -32,8 +29,8 @@ export interface QueryOptions {
32
29
  readonly timeToLive?: Duration.Input;
33
30
  }
34
31
 
35
- export interface BoundQuery<R extends Rpc.Any, TSelf> {
36
- readonly query: (payload: Rpc.Payload<R>, options?: QueryOptions) => Atom.Atom<AsyncResult.AsyncResult<Rpc.Success<R>, Failure<R>>>;
32
+ export interface BoundQuery<R extends Rpc.Any, TSelf, TSubscription extends Rpc.Any = never> {
33
+ readonly query: (payload: Rpc.Payload<R>, options?: QueryOptions) => Atom.Atom<AsyncResult.AsyncResult<Rpc.Success<R>, Failure<R | TSubscription>>>;
37
34
  readonly run: (payload: Rpc.Payload<R>) => Effect.Effect<Rpc.Success<R>, RunFailure<R>, TSelf>;
38
35
  }
39
36
 
@@ -53,7 +50,11 @@ export type Bound<
53
50
  TSelf,
54
51
  TStreams extends readonly StreamShape[] = readonly [],
55
52
  > = {
56
- readonly [TQuery in TQueries[number] as TQuery["name"]]: BoundQuery<Rpc.ExtractTag<TRpcs, Tag<TName, TQuery["name"]>>, TSelf>;
53
+ readonly [TQuery in TQueries[number] as TQuery["name"]]: BoundQuery<
54
+ Rpc.ExtractTag<TRpcs, Tag<TName, TQuery["name"]>>,
55
+ TSelf,
56
+ Rpc.ExtractTag<TRpcs, Tag<TName, "$changes">>
57
+ >;
57
58
  } & {
58
59
  readonly [TCommand in TCommands[number] as TCommand["name"]]: BoundCommand<Rpc.ExtractTag<TRpcs, Tag<TName, TCommand["name"]>>, TSelf>;
59
60
  } & {
@@ -104,11 +105,12 @@ function bindApi(
104
105
  const { name, queries, commands, streams, keyScope } = contract.declaration;
105
106
  const owner = bindingOwner(keyScope, options?.registry);
106
107
  const automatic = automaticLive(service, name, owner, options?.resume, options?.live, options?.resumeWindow);
108
+ const operations = clientOperations(service, automatic, owner);
107
109
  return Object.assign(
108
110
  Object.fromEntries([
109
- ...queries.map((query) => [query.name, boundQuery(service, `${name}.${query.name}`, query, automatic, owner)] as const),
110
- ...commands.map((command) => [command.name, boundCommand(service, `${name}.${command.name}`, command, owner)] as const),
111
- ...streams.map((stream) => [stream.name, boundStream(service, `${name}.${stream.name}`)] as const),
111
+ ...queries.map((query) => [query.name, operations.query(`${name}.${query.name}`, query)] as const),
112
+ ...commands.map((command) => [command.name, operations.command(`${name}.${command.name}`, command)] as const),
113
+ ...streams.map((stream) => [stream.name, operations.stream(`${name}.${stream.name}`)] as const),
112
114
  ]),
113
115
  { [LiveConnection]: automatic.subscription },
114
116
  );
@@ -8,12 +8,15 @@ import type { LiveBound } from "#automaticLive.ts";
8
8
  import type { Bound } from "#bind.ts";
9
9
  import type { ActiveClient } from "#clientActivity.ts";
10
10
  import type { CommandShape, QueryShape, StreamShape } from "#operation.ts";
11
+ import type { ResumeSource, ResumeWindow } from "#resume.ts";
11
12
 
12
13
  export interface ClientOptions {
13
14
  readonly bearerToken?: string;
14
15
  readonly headers?: Readonly<Record<string, string>>;
15
16
  readonly live?: boolean;
16
17
  readonly protocol?: Layer.Layer<RpcClient.Protocol> | ((identity: string | undefined) => Layer.Layer<RpcClient.Protocol>);
18
+ readonly resume?: ResumeSource;
19
+ readonly resumeWindow?: ResumeWindow;
17
20
  readonly url: string;
18
21
  readonly webSocketConstructor?: Layer.Layer<Socket.WebSocketConstructor>;
19
22
  }
@@ -127,7 +127,12 @@ export function automaticQuery<A, E>({
127
127
  }
128
128
  return AsyncResult.initial();
129
129
  },
130
- (refresh) => (pushed ? refresh(subscription.connection) : refresh(atom)),
130
+ (refresh) => {
131
+ if (!pushed) {
132
+ refresh(atom);
133
+ }
134
+ refresh(subscription.connection);
135
+ },
131
136
  ).pipe(Atom.setIdleTTL(0));
132
137
  return gated;
133
138
  }
@@ -1,6 +1,7 @@
1
1
  import { Schema } from "effect";
2
2
  import { LiveHint } from "#live.ts";
3
3
  import type { QueryShape } from "#operation.ts";
4
+ import { QueryReadDenied } from "#readPolicyErrors.ts";
4
5
 
5
6
  type Rerun<TQuery extends QueryShape> = TQuery extends QueryShape ? ("rerun-and-compare" extends TQuery["live"] ? TQuery : never) : never;
6
7
  type ResultSchema<TQuery extends QueryShape> = TQuery extends QueryShape
@@ -14,10 +15,11 @@ type ResultSchema<TQuery extends QueryShape> = TQuery extends QueryShape
14
15
 
15
16
  export function changesSuccess<const TQueries extends readonly QueryShape[]>(
16
17
  queries: TQueries,
17
- ): Schema.Union<readonly [typeof LiveHint, ...ResultSchema<Rerun<TQueries[number]>>[]]>;
18
+ ): Schema.Union<readonly [typeof LiveHint, typeof QueryReadDenied, ...ResultSchema<Rerun<TQueries[number]>>[]]>;
18
19
  export function changesSuccess(queries: readonly QueryShape[]) {
19
20
  return Schema.Union([
20
21
  LiveHint,
22
+ QueryReadDenied,
21
23
  ...queries
22
24
  .filter((query) => query.live === "rerun-and-compare")
23
25
  .map((query) =>
@@ -1,4 +1,5 @@
1
1
  import { Effect, Option, Schema, Stream } from "effect";
2
+ import * as Atom from "effect/reactivity/Atom";
2
3
  import * as AtomRegistry from "effect/reactivity/AtomRegistry";
3
4
  import type * as AtomRpc from "effect/reactivity/AtomRpc";
4
5
  import * as Reactivity from "effect/reactivity/Reactivity";
@@ -23,7 +24,7 @@ function run<A, E>(service: ErasedClient, effect: Effect.Effect<A, E, unknown>,
23
24
  return owner === undefined ? effect : Effect.suspend(() => AtomRegistry.getResult(owner.registry, service.runtime.atom(effect)));
24
25
  }
25
26
 
26
- export function boundQuery(service: ErasedClient, tag: string, query: QueryShape, automatic: ReturnType<typeof automaticLive>, owner?: BindingOwner) {
27
+ function boundQuery(service: ErasedClient, tag: string, query: QueryShape, automatic: ReturnType<typeof automaticLive>, owner?: BindingOwner) {
27
28
  const reactive = queryReactivity(service.runtime, clientActivities.get(service)?.queued);
28
29
  const cached = new WeakMap<ReturnType<typeof service.query>, ReturnType<typeof service.query>>();
29
30
  return {
@@ -44,6 +45,7 @@ export function boundQuery(service: ErasedClient, tag: string, query: QueryShape
44
45
  keys,
45
46
  Schema.toEquivalence(query.success),
46
47
  query.live === "rerun-and-compare" ? Schema.decodeUnknownSync(Schema.toType(query.success)) : undefined,
48
+ options.headers,
47
49
  );
48
50
  const tracked = clientActivities.get(service)?.watch(result) ?? result;
49
51
  cached.set(atom, tracked);
@@ -58,7 +60,7 @@ export function boundQuery(service: ErasedClient, tag: string, query: QueryShape
58
60
  };
59
61
  }
60
62
 
61
- export function boundCommand(service: ErasedClient, tag: string, command: CommandShape, owner?: BindingOwner) {
63
+ function boundCommand(service: ErasedClient, tag: string, command: CommandShape, owner?: BindingOwner) {
62
64
  function invalidate(payload: unknown, result: unknown) {
63
65
  const keys: readonly Key[] = [
64
66
  ...command.invalidates(payload, result),
@@ -72,8 +74,28 @@ export function boundCommand(service: ErasedClient, tag: string, command: Comman
72
74
  };
73
75
  }
74
76
 
75
- export function boundStream(service: ErasedStreamingClient, tag: string) {
77
+ function boundStream(service: ErasedStreamingClient, tag: string, owner?: BindingOwner) {
76
78
  return {
77
- run: (payload: unknown) => Stream.unwrap(service.use((client) => Effect.succeed(client(tag, payload)))),
79
+ run: (payload: unknown) => {
80
+ const stream = Stream.unwrap(service.use((client) => Effect.succeed(client(tag, payload))));
81
+ return owner === undefined
82
+ ? stream
83
+ : Stream.callback<unknown, unknown>(
84
+ (queue) => AtomRegistry.getResult(owner.registry, service.runtime.atom(Stream.runIntoQueue(stream, queue)).pipe(Atom.setIdleTTL(0))),
85
+ { bufferSize: 1 },
86
+ );
87
+ },
88
+ };
89
+ }
90
+
91
+ export function clientOperations(
92
+ service: AtomRpc.AtomRpcClient<unknown, string, Rpc.Any>,
93
+ automatic: ReturnType<typeof automaticLive>,
94
+ owner?: BindingOwner,
95
+ ) {
96
+ return {
97
+ command: (tag: string, command: CommandShape) => boundCommand(service, tag, command, owner),
98
+ query: (tag: string, query: QueryShape) => boundQuery(service, tag, query, automatic, owner),
99
+ stream: (tag: string) => boundStream(service, tag, owner),
78
100
  };
79
101
  }
@@ -2,6 +2,9 @@ import type { CommandShape, QueryShape, StreamShape } from "#operation.ts";
2
2
  import { isPermissionReadPolicy } from "#permissionReadPolicy.ts";
3
3
 
4
4
  export function declarationError(contractName: string, operations: readonly (QueryShape | CommandShape | StreamShape)[]): string | undefined {
5
+ if (operations.some(({ name }) => name === "$changes")) {
6
+ return `Operation name $changes is reserved for the built-in changes stream on contract ${contractName}`;
7
+ }
5
8
  const duplicated = operations.map(({ name }) => name).filter((name, index, names) => names.indexOf(name) !== index);
6
9
  if (duplicated.length > 0) {
7
10
  return `Operation names must be unique; duplicated: ${[...new Set(duplicated)].join(", ")}`;
@@ -0,0 +1,44 @@
1
+ import { Effect, Stream } from "effect";
2
+ import type { Key } from "@shivaedev/changes/keys.ts";
3
+ import type { SubscriptionHint } from "#queryUpdate.ts";
4
+ import type { QueryReadDenied } from "#readPolicyErrors.ts";
5
+
6
+ export function liveAttempt<E, R>(
7
+ stream: Stream.Stream<SubscriptionHint, E, R>,
8
+ observe: {
9
+ readonly changed: (keys: readonly Key[]) => void;
10
+ readonly denied: (denial: QueryReadDenied) => void;
11
+ readonly live: () => void;
12
+ readonly paused: () => boolean;
13
+ readonly queued: () => void;
14
+ readonly reconcile: (connected: boolean) => void;
15
+ },
16
+ ) {
17
+ let connected = false;
18
+ return Effect.suspend(() => {
19
+ let first = true;
20
+ return stream.pipe(
21
+ Stream.runForEach((hint) =>
22
+ Effect.sync(() => {
23
+ if (hint._tag === "QueryReadDenied") {
24
+ observe.denied(hint);
25
+ connected = true;
26
+ first = true;
27
+ return;
28
+ }
29
+ observe.live();
30
+ if (observe.paused()) {
31
+ observe.queued();
32
+ } else if (first || hint._tag === "Resync") {
33
+ observe.reconcile(connected);
34
+ } else {
35
+ observe.changed(hint.keys);
36
+ }
37
+ connected = true;
38
+ first = false;
39
+ }),
40
+ ),
41
+ Effect.scoped,
42
+ );
43
+ });
44
+ }
@@ -2,8 +2,7 @@ import { Effect, Stream } from "effect";
2
2
  import * as AsyncResult from "effect/reactivity/AsyncResult";
3
3
  import * as Atom from "effect/reactivity/Atom";
4
4
  import * as AtomRegistry from "effect/reactivity/AtomRegistry";
5
- import type { LiveHint } from "#live.ts";
6
- import type { QueryUpdate } from "#queryUpdate.ts";
5
+ import type { QueryUpdate, SubscriptionHint } from "#queryUpdate.ts";
7
6
 
8
7
  export function queryDelivery<A, E>(
9
8
  atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
@@ -11,7 +10,7 @@ export function queryDelivery<A, E>(
11
10
  paused: Atom.Atom<boolean>,
12
11
  ) {
13
12
  const pushed = Atom.make<AsyncResult.AsyncResult<A, E>>(AsyncResult.initial());
14
- const deliver = Effect.fnUntraced(function* (update: QueryUpdate): Effect.fn.Return<LiveHint, never, AtomRegistry.AtomRegistry> {
13
+ const deliver = Effect.fnUntraced(function* (update: QueryUpdate): Effect.fn.Return<SubscriptionHint, never, AtomRegistry.AtomRegistry> {
15
14
  if (update._tag !== "Result") {
16
15
  return update;
17
16
  }
@@ -1,12 +1,13 @@
1
1
  import { invalidationKeys, type Key, readKeys } from "@shivaedev/changes/keys.ts";
2
2
  import type { LiveHint } from "#live.ts";
3
+ import type { SubscriptionHint } from "#queryUpdate.ts";
3
4
 
4
5
  export function localQueryKeys(keys: readonly Key[]) {
5
6
  return keys.filter((key) => key.collection.startsWith("@query/"));
6
7
  }
7
8
 
8
- export function queryHint(hint: LiveHint, tracked: readonly { readonly keys: readonly Key[] }[]): LiveHint {
9
- if (hint._tag === "Resync") {
9
+ export function queryHint(hint: SubscriptionHint, tracked: readonly { readonly keys: readonly Key[] }[]): SubscriptionHint {
10
+ if (hint._tag !== "Changed") {
10
11
  return hint;
11
12
  }
12
13
  const invalidated = invalidationKeys(hint.keys);
package/src/live.ts CHANGED
@@ -1,12 +1,15 @@
1
- import { type Cause, Duration, Effect, Option, Schema, Stream } from "effect";
1
+ import { Cause, Duration, Effect, Option, Schema, type Stream } from "effect";
2
2
  import * as Atom from "effect/reactivity/Atom";
3
3
  import type * as AtomRegistry from "effect/reactivity/AtomRegistry";
4
4
  import * as Reactivity from "effect/reactivity/Reactivity";
5
5
  import { invalidationKeys, Key, type KeyContext, readKeys } from "@shivaedev/changes/keys.ts";
6
+ import { liveAttempt } from "#internal/liveAttempt.ts";
6
7
  import { invalidateLive } from "#internal/liveInvalidation.ts";
7
8
  import { livePending } from "#internal/livePending.ts";
8
9
  import { liveRetry } from "#internal/liveRetry.ts";
9
10
  import { retryOnChange } from "#internal/retryOnChange.ts";
11
+ import type { SubscriptionHint } from "#queryUpdate.ts";
12
+ import type { QueryReadDenied } from "#readPolicyErrors.ts";
10
13
 
11
14
  export const LiveHint = Schema.Union([
12
15
  Schema.Struct({ _tag: Schema.Literal("Changed"), keys: Schema.Array(Key), queryIndexes: Schema.optional(Schema.Array(Schema.Number)) }),
@@ -15,7 +18,7 @@ export const LiveHint = Schema.Union([
15
18
  export type LiveHint = typeof LiveHint.Type;
16
19
  export interface LiveStatus<E> {
17
20
  readonly connection: "connecting" | "live" | "reconnecting" | "failed";
18
- readonly failure: Option.Option<Cause.Cause<E>>;
21
+ readonly failure: Option.Option<Cause.Cause<E | QueryReadDenied>>;
19
22
  readonly needsResync: boolean;
20
23
  readonly pending: number;
21
24
  }
@@ -27,7 +30,7 @@ export interface LiveOptions<E, R> {
27
30
  readonly resyncKeys: readonly Key[] | ((registry: AtomRegistry.AtomRegistry) => readonly Key[]);
28
31
  readonly retryDelay?: Duration.Input;
29
32
  readonly retryKeys?: readonly Key[];
30
- readonly stream: Stream.Stream<LiveHint, E, R>;
33
+ readonly stream: Stream.Stream<SubscriptionHint, E, R>;
31
34
  }
32
35
 
33
36
  const MAX_PENDING = 256;
@@ -102,32 +105,22 @@ export function live<R, E, TRuntimeError>(runtime: Atom.AtomRuntime<R, TRuntimeE
102
105
  get.once(options.resume);
103
106
  get.subscribe(options.resume, resync);
104
107
  }
105
- let connected = false;
106
- function reconcile() {
107
- if (connected || options.initialResync !== false) {
108
- resync();
109
- } else {
110
- update({ needsResync: false });
111
- }
112
- }
113
- const attempt = Effect.suspend(() => {
114
- let isFirst = true;
115
- function observe(hint: LiveHint) {
116
- update({ connection: "live", failure: Option.none() });
117
- if (get.once(paused)) {
118
- update({ needsResync: true, pending: Math.min(MAX_PENDING, get.once(status).pending + 1) });
119
- } else if (isFirst || hint._tag === "Resync") {
120
- reconcile();
108
+ const attempt = liveAttempt(options.stream, {
109
+ changed,
110
+ denied: (denial) => {
111
+ pending.clear();
112
+ update({ connection: "failed", failure: Option.some(Cause.fail(denial)), needsResync: true, pending: 0 });
113
+ },
114
+ live: () => update({ connection: "live", failure: Option.none() }),
115
+ paused: () => get.once(paused),
116
+ queued: () => update({ needsResync: true, pending: Math.min(MAX_PENDING, get.once(status).pending + 1) }),
117
+ reconcile: (connected) => {
118
+ if (connected || options.initialResync !== false) {
119
+ resync();
121
120
  } else {
122
- changed(hint.keys);
121
+ update({ needsResync: false });
123
122
  }
124
- connected = true;
125
- isFirst = false;
126
- }
127
- return options.stream.pipe(
128
- Stream.runForEach((hint) => Effect.sync(() => observe(hint))),
129
- Effect.scoped,
130
- );
123
+ },
131
124
  });
132
125
  yield* liveRetry(
133
126
  attempt,
@@ -5,7 +5,7 @@ import { compareQueries } from "#internal/compareQueries.ts";
5
5
  import { liveHintQueue } from "#internal/liveHintQueue.ts";
6
6
  import type { LiveHint } from "#live.ts";
7
7
  import type { QueryRerun, QuerySubscription } from "#querySubscription.ts";
8
- import type { QueryUpdate } from "#queryUpdate.ts";
8
+ import type { QueryUpdate, SubscriptionHint } from "#queryUpdate.ts";
9
9
  import { QueryReadDenied } from "#readPolicyErrors.ts";
10
10
 
11
11
  export const makeLiveServer = Effect.gen(function* () {
@@ -68,7 +68,7 @@ export const makeLiveServer = Effect.gen(function* () {
68
68
  reactivity.invalidateUnsafe([resyncKey]);
69
69
  return openStreams;
70
70
  });
71
- function subscribe<E, R>(subscription: QuerySubscription<E, R>, context?: KeyContext): Stream.Stream<LiveHint, E | QueryReadDenied, R>;
71
+ function subscribe<E, R>(subscription: QuerySubscription<E, R>, context?: KeyContext): Stream.Stream<SubscriptionHint, E | QueryReadDenied, R>;
72
72
  function subscribe<E, R>(
73
73
  subscription: QuerySubscription<E, R>,
74
74
  context: KeyContext | undefined,
@@ -77,14 +77,20 @@ export const makeLiveServer = Effect.gen(function* () {
77
77
  function subscribe<E, R>(subscription: QuerySubscription<E, R>, context?: KeyContext, read?: QueryRerun<E, R>) {
78
78
  return Stream.unwrap(
79
79
  Effect.sync(() => {
80
- const compare = compareQueries(subscription, read);
80
+ let compare = compareQueries(subscription, read);
81
81
  const next = Effect.fnUntraced(function* (hint: LiveHint) {
82
82
  if (!(yield* subscription.authorized)) {
83
- return yield* new QueryReadDenied({ message: "Read no longer allowed for subscribed queries" });
83
+ compare = compareQueries(subscription, read);
84
+ return [new QueryReadDenied({ message: "Read no longer allowed for subscribed queries" })];
84
85
  }
85
86
  return yield* compare(hint);
86
87
  });
87
- return open(subscription.keys, context, subscription.globalKeys).pipe(Stream.mapEffect(next), Stream.flatMap(Stream.fromIterable));
88
+ return open(subscription.keys, context, subscription.globalKeys).pipe(
89
+ Stream.mapEffect((hint) =>
90
+ Effect.flatMap(subscription.refresh ?? Effect.context<never>(), (current) => Effect.provideContext(next(hint), current)),
91
+ ),
92
+ Stream.flatMap(Stream.fromIterable),
93
+ );
88
94
  }),
89
95
  );
90
96
  }
@@ -14,6 +14,7 @@ export interface QuerySubscription<E = never, R = never> {
14
14
  readonly globalKeys?: readonly Key[];
15
15
  readonly keys: readonly Key[];
16
16
  readonly queries?: readonly QueryRequest[];
17
+ readonly refresh?: Effect.Effect<Context.Context<never>, E, R>;
17
18
  readonly scopes: readonly (readonly Key[])[];
18
19
  }
19
20
 
@@ -37,7 +38,10 @@ export function querySubscription(rpc: Rpc.Any, references: readonly QueryRefere
37
38
  return {
38
39
  check: Effect.provideContext(checkQuery(query, payload, viewer), context),
39
40
  keys: queryReadKeys(query, payload, viewer).pipe(Effect.provideContext(context)),
40
- permitted: Effect.suspend(() => query.readPolicy?.(payload, viewer) ?? Effect.succeed(false)).pipe(Effect.provideContext(context)),
41
+ permitted: Effect.gen(function* () {
42
+ const current = yield* policyContext(Rpc.make(`${prefix}${query.name}`));
43
+ return yield* Effect.suspend(() => query.readPolicy?.(payload, viewer) ?? Effect.succeed(false)).pipe(Effect.provideContext(current));
44
+ }),
41
45
  };
42
46
  }),
43
47
  );
@@ -1,4 +1,5 @@
1
1
  import type { LiveHint } from "#live.ts";
2
+ import type { QueryReadDenied } from "#readPolicyErrors.ts";
2
3
 
3
4
  export interface QueryResult {
4
5
  readonly _tag: "Result";
@@ -6,4 +7,5 @@ export interface QueryResult {
6
7
  readonly queryIndex: number;
7
8
  readonly value: unknown;
8
9
  }
9
- export type QueryUpdate = LiveHint | QueryResult;
10
+ export type SubscriptionHint = LiveHint | QueryReadDenied;
11
+ export type QueryUpdate = SubscriptionHint | QueryResult;
package/src/testing.ts CHANGED
@@ -1,15 +1,15 @@
1
1
  import { Deferred, type Duration, Effect, Fiber, Layer, Queue, Stream, SubscriptionRef } from "effect";
2
2
  import { type Rpc, RpcClient, type RpcGroup, type RpcMessage, RpcSerialization, RpcServer } from "effect/rpc";
3
3
  import type { Key } from "@shivaedev/changes/keys.ts";
4
- import type { LiveHint } from "#live.ts";
4
+ import type { SubscriptionHint } from "#queryUpdate.ts";
5
5
 
6
6
  export interface HintViewer<E> {
7
7
  readonly finished: Effect.Effect<void, E>;
8
- readonly hints: SubscriptionRef.SubscriptionRef<readonly LiveHint[]>;
8
+ readonly hints: SubscriptionRef.SubscriptionRef<readonly SubscriptionHint[]>;
9
9
  }
10
10
 
11
- export const watchHints = Effect.fn("Live.watchHints")(function* <E, R>(stream: Stream.Stream<LiveHint, E, R>) {
12
- const hints = yield* SubscriptionRef.make<readonly LiveHint[]>([]);
11
+ export const watchHints = Effect.fn("Live.watchHints")(function* <E, R>(stream: Stream.Stream<SubscriptionHint, E, R>) {
12
+ const hints = yield* SubscriptionRef.make<readonly SubscriptionHint[]>([]);
13
13
  const ready = yield* Deferred.make<void>();
14
14
  const fiber = yield* stream.pipe(
15
15
  Stream.runForEach((hint) =>
@@ -37,7 +37,7 @@ export const heard = Effect.fn("Live.heard")(function* <E>(
37
37
  );
38
38
  });
39
39
 
40
- function namesKeys(hint: LiveHint, keys: readonly Key[]): boolean {
40
+ function namesKeys(hint: SubscriptionHint, keys: readonly Key[]): boolean {
41
41
  return hint._tag === "Changed" && keys.every((key) => hint.keys.some((actual) => JSON.stringify(actual) === JSON.stringify(key)));
42
42
  }
43
43