@shivaedev/contract 0.41.0 → 0.43.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 +21 -0
- package/README.md +28 -178
- package/dist/AutomaticQueryOptions.d.ts +0 -5
- package/dist/AutomaticQueryOptions.d.ts.map +1 -1
- package/dist/HostVersion.d.ts +1 -19
- package/dist/HostVersion.d.ts.map +1 -1
- package/dist/adapters/activityState.d.ts.map +1 -1
- package/dist/adapters/activityState.js +0 -1
- package/dist/adapters/activityState.js.map +1 -1
- package/dist/adapters/liveHintStream.d.ts +0 -1
- package/dist/adapters/liveHintStream.d.ts.map +1 -1
- package/dist/adapters/openLiveHints.d.ts +0 -1
- package/dist/adapters/openLiveHints.d.ts.map +1 -1
- package/dist/adapters/retainedQueries.d.ts +7 -0
- package/dist/adapters/retainedQueries.d.ts.map +1 -0
- package/dist/adapters/retainedQueries.js +45 -0
- package/dist/adapters/retainedQueries.js.map +1 -0
- package/dist/adapters/standaloneLiveServer.d.ts +1 -7
- package/dist/adapters/standaloneLiveServer.d.ts.map +1 -1
- package/dist/adapters/standaloneLiveServer.js.map +1 -1
- package/dist/automaticLive.d.ts +2 -4
- package/dist/automaticLive.d.ts.map +1 -1
- package/dist/automaticLive.js +5 -14
- package/dist/automaticLive.js.map +1 -1
- package/dist/automaticQuery.d.ts +1 -1
- package/dist/automaticQuery.d.ts.map +1 -1
- package/dist/automaticQuery.js +20 -26
- package/dist/automaticQuery.js.map +1 -1
- package/dist/bind.d.ts +1 -2
- package/dist/bind.d.ts.map +1 -1
- package/dist/bind.js +8 -12
- package/dist/bind.js.map +1 -1
- package/dist/bindOperations.d.ts +6 -0
- package/dist/bindOperations.d.ts.map +1 -0
- package/dist/bindOperations.js +10 -0
- package/dist/bindOperations.js.map +1 -0
- package/dist/changesSuccess.d.ts +2 -3
- package/dist/changesSuccess.d.ts.map +1 -1
- package/dist/changesSuccess.js +1 -3
- package/dist/changesSuccess.js.map +1 -1
- package/dist/clientActivities.d.ts +0 -2
- package/dist/clientActivities.d.ts.map +1 -1
- package/dist/clientActivities.js +0 -4
- package/dist/clientActivities.js.map +1 -1
- package/dist/clientActivity.d.ts +0 -1
- package/dist/clientActivity.d.ts.map +1 -1
- package/dist/clientActivity.js +1 -1
- package/dist/clientActivity.js.map +1 -1
- package/dist/clientOperations.d.ts +1 -1
- package/dist/clientOperations.d.ts.map +1 -1
- package/dist/clientOperations.js +53 -52
- package/dist/clientOperations.js.map +1 -1
- package/dist/compareQueries.d.ts +2 -19
- package/dist/compareQueries.d.ts.map +1 -1
- package/dist/compareQueries.js +6 -33
- package/dist/compareQueries.js.map +1 -1
- package/dist/live-server/register.d.ts +0 -1
- package/dist/live-server/register.d.ts.map +1 -1
- package/dist/live-server/service.d.ts +0 -2
- package/dist/live-server/service.d.ts.map +1 -1
- package/dist/live-server/stream.d.ts +0 -1
- package/dist/live-server/stream.d.ts.map +1 -1
- package/dist/live-server/subscribe.d.ts +2 -2
- package/dist/live-server/subscribe.d.ts.map +1 -1
- package/dist/live-server/subscribe.js.map +1 -1
- package/dist/live.d.ts +5 -12
- package/dist/live.d.ts.map +1 -1
- package/dist/live.js +15 -85
- package/dist/live.js.map +1 -1
- package/dist/liveAttempt.d.ts +3 -6
- package/dist/liveAttempt.d.ts.map +1 -1
- package/dist/liveAttempt.js +11 -30
- package/dist/liveAttempt.js.map +1 -1
- package/dist/liveHintQueue.d.ts +0 -1
- package/dist/liveHintQueue.d.ts.map +1 -1
- package/dist/liveHintQueue.js +9 -12
- package/dist/liveHintQueue.js.map +1 -1
- package/dist/makeLiveServer.d.ts +1 -5
- package/dist/makeLiveServer.d.ts.map +1 -1
- package/dist/operation.d.ts +2 -4
- package/dist/operation.d.ts.map +1 -1
- package/dist/operation.js +0 -1
- package/dist/operation.js.map +1 -1
- package/dist/operationDeclaration.d.ts +1 -2
- package/dist/operationDeclaration.d.ts.map +1 -1
- package/dist/operationDeclaration.js.map +1 -1
- package/dist/publicConfig.d.ts +6 -21
- package/dist/publicConfig.d.ts.map +1 -1
- package/dist/queryDelivery.d.ts +4 -5
- package/dist/queryDelivery.d.ts.map +1 -1
- package/dist/queryDelivery.js +4 -15
- package/dist/queryDelivery.js.map +1 -1
- package/dist/queryProgress.d.ts.map +1 -1
- package/dist/queryProgress.js +0 -3
- package/dist/queryProgress.js.map +1 -1
- package/dist/queryRetention.d.ts +8 -0
- package/dist/queryRetention.d.ts.map +1 -0
- package/dist/queryRetention.js +3 -0
- package/dist/queryRetention.js.map +1 -0
- package/dist/querySignals.d.ts +1 -0
- package/dist/querySignals.d.ts.map +1 -1
- package/dist/querySignals.js.map +1 -1
- package/dist/querySubscription.d.ts +1 -1
- package/dist/querySubscription.d.ts.map +1 -1
- package/dist/queryUpdate.d.ts +15 -4
- package/dist/queryUpdate.d.ts.map +1 -1
- package/dist/queryUpdate.js +7 -1
- package/dist/queryUpdate.js.map +1 -1
- package/dist/retainQuery.d.ts +4 -0
- package/dist/retainQuery.d.ts.map +1 -0
- package/dist/retainQuery.js +35 -0
- package/dist/retainQuery.js.map +1 -0
- package/package.json +8 -8
- package/src/AutomaticQueryOptions.ts +0 -5
- package/src/adapters/activityState.ts +0 -1
- package/src/adapters/retainedQueries.ts +47 -0
- package/src/adapters/standaloneLiveServer.ts +1 -5
- package/src/automaticLive.ts +4 -16
- package/src/automaticQuery.ts +28 -42
- package/src/bind.ts +16 -22
- package/src/bindOperations.ts +20 -0
- package/src/changesSuccess.ts +3 -5
- package/src/clientActivities.ts +1 -5
- package/src/clientActivity.ts +1 -2
- package/src/clientOperations.ts +77 -85
- package/src/compareQueries.ts +12 -38
- package/src/live-server/subscribe.ts +5 -9
- package/src/live.ts +19 -97
- package/src/liveAttempt.ts +17 -41
- package/src/liveHintQueue.ts +9 -12
- package/src/operation.ts +3 -17
- package/src/operationDeclaration.ts +0 -2
- package/src/queryDelivery.ts +6 -26
- package/src/queryProgress.ts +0 -3
- package/src/queryRetention.ts +9 -0
- package/src/querySignals.ts +1 -0
- package/src/querySubscription.ts +1 -1
- package/src/queryUpdate.ts +10 -4
- package/src/retainQuery.ts +36 -0
- package/dist/liveInvalidation.d.ts +0 -12
- package/dist/liveInvalidation.d.ts.map +0 -1
- package/dist/liveInvalidation.js +0 -14
- package/dist/liveInvalidation.js.map +0 -1
- package/dist/livePending.d.ts +0 -7
- package/dist/livePending.d.ts.map +0 -1
- package/dist/livePending.js +0 -27
- package/dist/livePending.js.map +0 -1
- package/dist/queryCoalesceWindow.d.ts +0 -4
- package/dist/queryCoalesceWindow.d.ts.map +0 -1
- package/dist/queryCoalesceWindow.js +0 -11
- package/dist/queryCoalesceWindow.js.map +0 -1
- package/dist/queryFailure.d.ts +0 -4
- package/dist/queryFailure.d.ts.map +0 -1
- package/dist/queryFailure.js +0 -12
- package/dist/queryFailure.js.map +0 -1
- package/dist/queryHints.d.ts +0 -9
- package/dist/queryHints.d.ts.map +0 -1
- package/dist/queryHints.js +0 -34
- package/dist/queryHints.js.map +0 -1
- package/dist/queryReactivity.d.ts +0 -5
- package/dist/queryReactivity.d.ts.map +0 -1
- package/dist/queryReactivity.js +0 -109
- package/dist/queryReactivity.js.map +0 -1
- package/src/liveInvalidation.ts +0 -21
- package/src/livePending.ts +0 -28
- package/src/queryCoalesceWindow.ts +0 -13
- package/src/queryFailure.ts +0 -13
- package/src/queryHints.ts +0 -39
- package/src/queryReactivity.ts +0 -127
package/src/clientOperations.ts
CHANGED
|
@@ -14,106 +14,98 @@ import { clientInvalidationKeys, clientReadKeys } from "#clientKeys.ts";
|
|
|
14
14
|
import { commandPayload } from "#commandPayload.ts";
|
|
15
15
|
import { waitForConnection } from "#connectionReadiness.ts";
|
|
16
16
|
import type { CommandShape, QueryShape } from "#operation.ts";
|
|
17
|
-
import { queryReactivity } from "#queryReactivity.ts";
|
|
18
17
|
import { shareQuerySignals } from "#querySignals.ts";
|
|
18
|
+
import { retainQuery } from "#retainQuery.ts";
|
|
19
19
|
|
|
20
20
|
type ErasedClient = AtomRpc.AtomRpcClient<unknown, string, Rpc.Rpc<string, Schema.Top, Schema.Top, Schema.Top>>;
|
|
21
|
-
|
|
22
21
|
type ErasedStreamingClient = AtomRpc.AtomRpcClient<
|
|
23
22
|
unknown,
|
|
24
23
|
string,
|
|
25
24
|
Rpc.Rpc<string, Schema.Top, RpcSchema.Stream<Schema.Top, Schema.Top>, Schema.Never>
|
|
26
25
|
>;
|
|
27
26
|
|
|
28
|
-
function
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
const
|
|
34
|
-
const
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
const existing = cached.get(atom);
|
|
39
|
-
if (existing !== undefined) {
|
|
40
|
-
return existing;
|
|
41
|
-
}
|
|
42
|
-
const local = query.reads(payload, Option.none());
|
|
43
|
-
const keys = [...local, { _tag: "List" as const, collection: `@query/${tag}/${clientId()}` }];
|
|
44
|
-
const dependencies =
|
|
45
|
-
local.length === 0 ? [...keys, { _tag: "List" as const, collection: `@query/${tag.slice(0, tag.lastIndexOf("."))}` }] : keys;
|
|
46
|
-
const reference = { payload, query: query.name };
|
|
47
|
-
const result = automatic.query(
|
|
48
|
-
atom,
|
|
49
|
-
reference,
|
|
50
|
-
keys,
|
|
51
|
-
Schema.toEquivalence(query.success),
|
|
52
|
-
Schema.decodeUnknownSync(Schema.toType(query.success)),
|
|
53
|
-
query.live === "rerun-and-compare",
|
|
54
|
-
(source) => reactive(source, clientReadKeys(dependencies, owner?.context), owner?.registry),
|
|
55
|
-
options.headers,
|
|
56
|
-
);
|
|
57
|
-
const tracked = clientActivities.get(service)?.watch(result) ?? result;
|
|
58
|
-
shareQuerySignals(tracked, result);
|
|
59
|
-
cached.set(atom, tracked);
|
|
60
|
-
return tracked;
|
|
61
|
-
},
|
|
62
|
-
run: (payload: unknown) =>
|
|
63
|
-
run(
|
|
64
|
-
service,
|
|
65
|
-
service.use((client) => client(tag, payload)),
|
|
66
|
-
owner,
|
|
67
|
-
),
|
|
68
|
-
};
|
|
69
|
-
}
|
|
27
|
+
export function clientOperations(
|
|
28
|
+
service: AtomRpc.AtomRpcClient<unknown, string, Rpc.Any>,
|
|
29
|
+
automatic: ReturnType<typeof automaticLive>,
|
|
30
|
+
owner?: BindingOwner,
|
|
31
|
+
) {
|
|
32
|
+
const ordinaryClient: ErasedClient = service;
|
|
33
|
+
const streaming: ErasedStreamingClient = service;
|
|
34
|
+
function run<A, E>(effect: Effect.Effect<A, E, unknown>) {
|
|
35
|
+
return owner === undefined ? effect : Effect.suspend(() => AtomRegistry.getResult(owner.registry, ordinaryClient.runtime.atom(effect)));
|
|
36
|
+
}
|
|
70
37
|
|
|
71
|
-
function
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
38
|
+
function boundQuery(tag: string, query: QueryShape) {
|
|
39
|
+
const cached = new WeakMap<ReturnType<typeof ordinaryClient.query>, ReturnType<typeof ordinaryClient.query>>();
|
|
40
|
+
return {
|
|
41
|
+
query: (payload: unknown, options: QueryOptions = {}) => {
|
|
42
|
+
const atom = ordinaryClient.query(tag, payload, { ...options, timeToLive: 0 });
|
|
43
|
+
const existing = cached.get(atom);
|
|
44
|
+
if (existing !== undefined) {
|
|
45
|
+
return existing;
|
|
46
|
+
}
|
|
47
|
+
const local = query.reads(payload, Option.none());
|
|
48
|
+
const keys = [...local, { _tag: "List" as const, collection: `@query/${tag}/${clientId()}` }];
|
|
49
|
+
const dependencies =
|
|
50
|
+
local.length === 0 ? [...keys, { _tag: "List" as const, collection: `@query/${tag.slice(0, tag.lastIndexOf("."))}` }] : keys;
|
|
51
|
+
const reference = { payload, query: query.name };
|
|
52
|
+
const result = automatic.query(
|
|
53
|
+
atom,
|
|
54
|
+
reference,
|
|
55
|
+
keys,
|
|
56
|
+
Schema.toEquivalence(query.success),
|
|
57
|
+
Schema.decodeUnknownSync(Schema.toType(query.success)),
|
|
58
|
+
(source) => ordinaryClient.runtime.factory.withReactivity(clientReadKeys(dependencies, owner?.context))(source),
|
|
59
|
+
options.headers,
|
|
60
|
+
);
|
|
61
|
+
const tracked = retainQuery(ordinaryClient.runtime, clientActivities.get(ordinaryClient)?.watch(result) ?? result);
|
|
62
|
+
shareQuerySignals(tracked, result);
|
|
63
|
+
cached.set(atom, tracked);
|
|
64
|
+
return tracked;
|
|
65
|
+
},
|
|
66
|
+
run: (payload: unknown) => run(ordinaryClient.use((client) => client(tag, payload))),
|
|
67
|
+
};
|
|
78
68
|
}
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
69
|
+
|
|
70
|
+
function boundCommand(tag: string, command: CommandShape) {
|
|
71
|
+
function invalidate(payload: unknown, result: unknown) {
|
|
72
|
+
const keys: readonly Key[] = [
|
|
73
|
+
...command.invalidates(payload, result),
|
|
74
|
+
{ _tag: "List", collection: `@query/${tag.slice(0, tag.lastIndexOf("."))}` },
|
|
75
|
+
];
|
|
76
|
+
return Reactivity.invalidate(clientInvalidationKeys(keys, owner?.context));
|
|
77
|
+
}
|
|
78
|
+
return {
|
|
79
|
+
run: (payload: unknown) =>
|
|
80
|
+
run(
|
|
81
|
+
ordinaryClient.use((client) =>
|
|
82
|
+
commandPayload(command, payload).pipe(
|
|
83
|
+
Effect.tap(() => waitForConnection(client)),
|
|
84
|
+
Effect.flatMap((validated) => client(tag, validated)),
|
|
85
|
+
Effect.tap((result) => invalidate(payload, result)),
|
|
86
|
+
),
|
|
88
87
|
),
|
|
89
88
|
),
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
};
|
|
93
|
-
}
|
|
89
|
+
};
|
|
90
|
+
}
|
|
94
91
|
|
|
95
|
-
function boundStream(
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
}
|
|
92
|
+
function boundStream(tag: string) {
|
|
93
|
+
return {
|
|
94
|
+
run: (payload: unknown) => {
|
|
95
|
+
const stream = Stream.unwrap(streaming.use((client) => Effect.succeed(client(tag, payload))));
|
|
96
|
+
return owner === undefined
|
|
97
|
+
? stream
|
|
98
|
+
: Stream.callback<unknown, unknown>(
|
|
99
|
+
(queue) => AtomRegistry.getResult(owner.registry, streaming.runtime.atom(Stream.runIntoQueue(stream, queue)).pipe(Atom.setIdleTTL(0))),
|
|
100
|
+
{ bufferSize: 1 },
|
|
101
|
+
);
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
}
|
|
108
105
|
|
|
109
|
-
export function clientOperations(
|
|
110
|
-
service: AtomRpc.AtomRpcClient<unknown, string, Rpc.Any>,
|
|
111
|
-
automatic: ReturnType<typeof automaticLive>,
|
|
112
|
-
owner?: BindingOwner,
|
|
113
|
-
) {
|
|
114
106
|
return {
|
|
115
|
-
command: (tag: string, command: CommandShape) => boundCommand(
|
|
116
|
-
query: (tag: string, query: QueryShape) => boundQuery(
|
|
117
|
-
stream: (tag: string) => boundStream(
|
|
107
|
+
command: (tag: string, command: CommandShape) => boundCommand(tag, command),
|
|
108
|
+
query: (tag: string, query: QueryShape) => boundQuery(tag, query),
|
|
109
|
+
stream: (tag: string) => boundStream(tag),
|
|
118
110
|
};
|
|
119
111
|
}
|
package/src/compareQueries.ts
CHANGED
|
@@ -2,45 +2,23 @@ import { Effect, Schema } from "effect";
|
|
|
2
2
|
import { Digest } from "effect/crypto";
|
|
3
3
|
import type { Key } from "@shivaedev/changes/keys.ts";
|
|
4
4
|
import type { LiveHint } from "#live.ts";
|
|
5
|
-
import { changedHint } from "#queryHints.ts";
|
|
6
5
|
import type { QueryRerun, QuerySubscription } from "#querySubscription.ts";
|
|
7
6
|
import type { QueryResult, QueryUnchanged, QueryUpdate } from "#queryUpdate.ts";
|
|
8
7
|
import type { QueryRequest } from "#serverMetadata.ts";
|
|
9
8
|
|
|
10
|
-
function
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
}
|
|
18
|
-
const scopes = subscription.scopes.map((scope, index) => (queries[index]?.query.live === "rerun-and-compare" ? [] : scope));
|
|
19
|
-
if (queries.every(({ query }) => query.live === "rerun-and-compare")) {
|
|
20
|
-
return [];
|
|
21
|
-
}
|
|
22
|
-
if (hint._tag === "Resync") {
|
|
23
|
-
return [hint];
|
|
24
|
-
}
|
|
25
|
-
const keys = new Set(scopes.flatMap((scope) => scope.map((key) => JSON.stringify(key))));
|
|
26
|
-
const visible: readonly Key[] = hint.keys.filter((key) => keys.has(JSON.stringify(key)));
|
|
27
|
-
return visible.length === 0 ? [] : [changedHint(visible, scopes)];
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
export function compareQueries<E, R>(subscription: QuerySubscription<unknown, unknown>, read?: QueryRerun<E, R>, initialRead = true) {
|
|
31
|
-
const queries = subscription.queries ?? [];
|
|
9
|
+
export function compareQueries<E, R>(
|
|
10
|
+
subscription: QuerySubscription<unknown, unknown>,
|
|
11
|
+
read: QueryRerun<E, R>,
|
|
12
|
+
initialRead?: boolean,
|
|
13
|
+
): (hint: LiveHint, scopes?: readonly (readonly Key[])[]) => Effect.Effect<readonly QueryUpdate[], E, R>;
|
|
14
|
+
export function compareQueries<E, R>(subscription: QuerySubscription<unknown, unknown>, read: QueryRerun<E, R>, initialRead = true) {
|
|
15
|
+
const queries = subscription.queries;
|
|
32
16
|
const hashes = new Map<number, string>();
|
|
33
|
-
let initial = initialRead &&
|
|
17
|
+
let initial = initialRead && queries.length > 0;
|
|
34
18
|
const resultFor = Effect.fnUntraced(function* (request: QueryRequest, index: number) {
|
|
35
|
-
if (read === undefined) {
|
|
36
|
-
return yield* Effect.die(new Error("Result subscriptions require an authorized query runner"));
|
|
37
|
-
}
|
|
38
19
|
const value = yield* read(request);
|
|
39
|
-
if (request.query.live !== "rerun-and-compare") {
|
|
40
|
-
return { _tag: "Result", query: request.query.name, queryIndex: index, value } satisfies QueryResult;
|
|
41
|
-
}
|
|
42
20
|
const encoded = yield* Schema.encodeUnknownEffect(Schema.toCodecJson(request.query.success))(value).pipe(Effect.orDie);
|
|
43
|
-
const digest = yield* Digest.Digest;
|
|
21
|
+
const digest = yield* Digest.Digest.pipe(Effect.provide(Digest.layerWebCrypto));
|
|
44
22
|
const hash = yield* digest.digestHex(Digest.sha256, new TextEncoder().encode(JSON.stringify(encoded)));
|
|
45
23
|
if (hash === hashes.get(index)) {
|
|
46
24
|
return { _tag: "Unchanged", queryIndex: index } satisfies QueryUnchanged;
|
|
@@ -50,19 +28,15 @@ export function compareQueries<E, R>(subscription: QuerySubscription<unknown, un
|
|
|
50
28
|
});
|
|
51
29
|
return Effect.fnUntraced(function* (hint: LiveHint, scopes: readonly (readonly Key[])[] = subscription.scopes) {
|
|
52
30
|
const updates: QueryUpdate[] = [];
|
|
53
|
-
const
|
|
31
|
+
const changed = new Set(hint._tag === "Changed" ? hint.keys.map((key) => JSON.stringify(key)) : []);
|
|
54
32
|
const matching = queries
|
|
55
33
|
.map((request, index) => ({ index, request }))
|
|
56
|
-
.filter(
|
|
57
|
-
({ index, request }) =>
|
|
58
|
-
initial || (request.query.live === "rerun-and-compare" && (affected?._tag !== "Changed" || affected.queryIndexes?.includes(index))),
|
|
59
|
-
);
|
|
34
|
+
.filter(({ index }) => initial || hint._tag === "Resync" || scopes[index]?.some((key) => changed.has(JSON.stringify(key))));
|
|
60
35
|
for (const { index, request } of matching) {
|
|
61
36
|
const result = yield* resultFor(request, index);
|
|
62
37
|
updates.push(result);
|
|
63
38
|
}
|
|
64
|
-
const hints = initial ? [] : hintsFor(hint, { ...subscription, scopes });
|
|
65
39
|
initial = false;
|
|
66
|
-
return
|
|
40
|
+
return updates;
|
|
67
41
|
});
|
|
68
42
|
}
|
|
@@ -3,19 +3,15 @@ import { refreshSubscription } from "#adapters/refreshSubscription.ts";
|
|
|
3
3
|
import { compareQueries } from "#compareQueries.ts";
|
|
4
4
|
import type { LiveHint } from "#live.ts";
|
|
5
5
|
import type { QueryRerun, QuerySubscription } from "#querySubscription.ts";
|
|
6
|
-
import type { QueryUpdate
|
|
6
|
+
import type { QueryUpdate } from "#queryUpdate.ts";
|
|
7
7
|
import { QueryReadDenied } from "#readPolicyErrors.ts";
|
|
8
8
|
import { LiveServer } from "./service.ts";
|
|
9
9
|
|
|
10
|
-
function subscribeQueries<E, R
|
|
10
|
+
function subscribeQueries<E, R>(
|
|
11
11
|
subscription: QuerySubscription<E, R>,
|
|
12
|
-
read
|
|
13
|
-
): Effect.Effect<
|
|
14
|
-
|
|
15
|
-
never,
|
|
16
|
-
typeof LiveServer.Identifier
|
|
17
|
-
>;
|
|
18
|
-
function subscribeQueries<E, R>(subscription: QuerySubscription<E, R>, read?: QueryRerun<E, R>) {
|
|
12
|
+
read: QueryRerun<E, R>,
|
|
13
|
+
): Effect.Effect<Stream.Stream<QueryUpdate, E | QueryReadDenied, R>, never, typeof LiveServer.Identifier>;
|
|
14
|
+
function subscribeQueries<E, R>(subscription: QuerySubscription<E, R>, read: QueryRerun<E, R>) {
|
|
19
15
|
return Effect.fnUntraced(function* () {
|
|
20
16
|
const server = yield* LiveServer;
|
|
21
17
|
const hints = yield* server.register(subscription.keys);
|
package/src/live.ts
CHANGED
|
@@ -1,19 +1,15 @@
|
|
|
1
|
-
import { Cause,
|
|
1
|
+
import { Cause, Effect, Option, Queue, Schema, type Stream } from "effect";
|
|
2
2
|
import * as Atom from "effect/reactivity/Atom";
|
|
3
|
-
import type * as AtomRegistry from "effect/reactivity/AtomRegistry";
|
|
4
|
-
import * as Reactivity from "effect/reactivity/Reactivity";
|
|
5
3
|
import { Key } from "@shivaedev/changes/keys.ts";
|
|
6
|
-
import {
|
|
4
|
+
import { clientReadKeys, type KeyContext } from "#clientKeys.ts";
|
|
7
5
|
import { liveAttempt } from "#liveAttempt.ts";
|
|
8
|
-
import { invalidateLive } from "#liveInvalidation.ts";
|
|
9
|
-
import { livePending } from "#livePending.ts";
|
|
10
6
|
import { liveRetry } from "#liveRetry.ts";
|
|
11
|
-
import type {
|
|
7
|
+
import type { SubscriptionEvent } from "#queryUpdate.ts";
|
|
12
8
|
import type { QueryReadDenied } from "#readPolicyErrors.ts";
|
|
13
9
|
import { retryOnChange } from "#retryOnChange.ts";
|
|
14
10
|
|
|
15
11
|
export const LiveHint = Schema.Union([
|
|
16
|
-
Schema.Struct({ _tag: Schema.Literal("Changed"), keys: Schema.Array(Key)
|
|
12
|
+
Schema.Struct({ _tag: Schema.Literal("Changed"), keys: Schema.Array(Key) }),
|
|
17
13
|
Schema.Struct({ _tag: Schema.Literal("Resync") }),
|
|
18
14
|
]);
|
|
19
15
|
export type LiveHint = typeof LiveHint.Type;
|
|
@@ -24,127 +20,53 @@ export interface LiveStatus<E> {
|
|
|
24
20
|
readonly pending: number;
|
|
25
21
|
}
|
|
26
22
|
export interface LiveOptions<E, R> {
|
|
27
|
-
readonly coalesceWindow?: Duration.Input;
|
|
28
|
-
readonly initialResync?: boolean;
|
|
29
23
|
readonly keyContext?: KeyContext | undefined;
|
|
30
|
-
readonly reopenOnResume?: boolean;
|
|
31
24
|
readonly resume?: Atom.Atom<unknown>;
|
|
32
|
-
readonly
|
|
33
|
-
readonly
|
|
34
|
-
readonly
|
|
35
|
-
readonly stream: Stream.Stream<SubscriptionHint, E, R>;
|
|
25
|
+
readonly retryDelay?: import("effect").Duration.Input;
|
|
26
|
+
readonly retryKeys?: readonly (typeof Key.Type)[];
|
|
27
|
+
readonly stream: Stream.Stream<SubscriptionEvent, E, R>;
|
|
36
28
|
}
|
|
37
29
|
|
|
38
|
-
const MAX_PENDING = 256;
|
|
39
|
-
|
|
40
30
|
export function live<R, E, TRuntimeError>(runtime: Atom.AtomRuntime<R, TRuntimeError>, options: LiveOptions<E, R>) {
|
|
41
|
-
const coalesceWindow = Atom.keepAlive(Atom.make<Duration.Input>(options.coalesceWindow ?? "20 millis"));
|
|
42
31
|
const paused = Atom.make(false);
|
|
43
32
|
const status = Atom.make<LiveStatus<E>>({ connection: "connecting", failure: Option.none(), needsResync: true, pending: 0 });
|
|
44
33
|
const connection = runtime
|
|
45
34
|
.atom((get) =>
|
|
46
35
|
Effect.gen(function* () {
|
|
47
36
|
get.mount(status);
|
|
37
|
+
get.mount(paused);
|
|
48
38
|
const resumed = yield* Queue.unbounded<void>();
|
|
49
|
-
|
|
50
|
-
const retryKeys = options.retryKeys ?? (typeof options.resyncKeys === "function" ? options.resyncKeys(get.registry) : options.resyncKeys);
|
|
51
|
-
yield* retryOnChange(status, clientReadKeys(retryKeys, options.keyContext), () => get.refreshSelf());
|
|
39
|
+
yield* retryOnChange(status, clientReadKeys(options.retryKeys ?? [], options.keyContext), () => get.refreshSelf());
|
|
52
40
|
function update(value: Partial<LiveStatus<E>>) {
|
|
53
41
|
get.set(status, { ...get.once(status), ...value });
|
|
54
42
|
}
|
|
55
|
-
function flush() {
|
|
56
|
-
const queued = pending.take();
|
|
57
|
-
if (!get.once(paused)) {
|
|
58
|
-
invalidateLive(reactivity, queued, () => active && !get.once(paused));
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
const timer = runtime.fn((delay: Duration.Input) => Effect.andThen(Effect.sleep(delay), Effect.sync(flush)));
|
|
62
|
-
get.mount(timer);
|
|
63
|
-
const pending = livePending(
|
|
64
|
-
(window) => get.set(timer, window),
|
|
65
|
-
() => get.set(timer, Atom.Interrupt),
|
|
66
|
-
);
|
|
67
|
-
let active = true;
|
|
68
43
|
get.addFinalizer(() => {
|
|
69
|
-
active = false;
|
|
70
|
-
pending.clear();
|
|
71
44
|
if (get.registry.getNodes().has(status)) {
|
|
72
45
|
update({ connection: "connecting", failure: Option.none(), needsResync: true, pending: 0 });
|
|
73
46
|
}
|
|
74
47
|
});
|
|
75
|
-
function changed(changedKeys: readonly Key[]) {
|
|
76
|
-
const window = get.once(coalesceWindow);
|
|
77
|
-
const keys = clientInvalidationKeys(changedKeys, options.keyContext);
|
|
78
|
-
invalidateLive(reactivity, keys, () => active && !get.once(paused), window);
|
|
79
|
-
const delay = Duration.toMillis(Duration.fromInputUnsafe(window));
|
|
80
|
-
if (delay === 0) {
|
|
81
|
-
invalidateLive(reactivity, keys, () => active && !get.once(paused));
|
|
82
|
-
return;
|
|
83
|
-
}
|
|
84
|
-
pending.add(keys, window);
|
|
85
|
-
}
|
|
86
|
-
function resync() {
|
|
87
|
-
if (get.once(status).connection === "failed") {
|
|
88
|
-
return;
|
|
89
|
-
}
|
|
90
|
-
pending.clear();
|
|
91
|
-
if (get.once(paused)) {
|
|
92
|
-
update({ needsResync: true });
|
|
93
|
-
return;
|
|
94
|
-
}
|
|
95
|
-
const keys = typeof options.resyncKeys === "function" ? options.resyncKeys(get.registry) : options.resyncKeys;
|
|
96
|
-
reactivity.invalidateUnsafe(keys.map((key) => clientReadKeys([key], options.keyContext)[0] ?? ""));
|
|
97
|
-
update({ needsResync: false, pending: 0 });
|
|
98
|
-
}
|
|
99
|
-
// A subscription alone does not build the flag, so its first read would otherwise announce a change.
|
|
100
|
-
get.once(paused);
|
|
101
|
-
get.subscribe(paused, (value) => {
|
|
102
|
-
if (!value) {
|
|
103
|
-
resync();
|
|
104
|
-
}
|
|
105
|
-
});
|
|
106
|
-
function resume() {
|
|
107
|
-
const current = get.once(status).connection;
|
|
108
|
-
if (current === "failed") {
|
|
109
|
-
return;
|
|
110
|
-
}
|
|
111
|
-
resync();
|
|
112
|
-
if (options.reopenOnResume === true || current === "reconnecting") {
|
|
113
|
-
Queue.offerUnsafe(resumed, undefined);
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
48
|
if (options.resume !== undefined) {
|
|
117
|
-
// A subscription alone does not initialize a derived signal's dependencies.
|
|
118
49
|
get.once(options.resume);
|
|
119
|
-
get.subscribe(options.resume,
|
|
50
|
+
get.subscribe(options.resume, () => {
|
|
51
|
+
if (!get.once(paused) && get.once(status).connection !== "failed") {
|
|
52
|
+
Queue.offerUnsafe(resumed, undefined);
|
|
53
|
+
}
|
|
54
|
+
});
|
|
120
55
|
}
|
|
121
56
|
const attempt = liveAttempt(options.stream, {
|
|
122
|
-
|
|
123
|
-
denied: (denial) => {
|
|
124
|
-
pending.clear();
|
|
125
|
-
update({ connection: "failed", failure: Option.some(Cause.fail(denial)), needsResync: true, pending: 0 });
|
|
126
|
-
},
|
|
127
|
-
live: () => update({ connection: "live", failure: Option.none() }),
|
|
57
|
+
delivered: () => update({ connection: "live", failure: Option.none(), needsResync: false, pending: 0 }),
|
|
58
|
+
denied: (denial) => update({ connection: "failed", failure: Option.some(Cause.fail(denial)), needsResync: true, pending: 0 }),
|
|
128
59
|
paused: () => get.once(paused),
|
|
129
|
-
queued: () => update({ needsResync: true, pending: Math.min(
|
|
130
|
-
reconcile: (connected) => {
|
|
131
|
-
if (connected || options.initialResync !== false) {
|
|
132
|
-
resync();
|
|
133
|
-
} else {
|
|
134
|
-
update({ needsResync: false });
|
|
135
|
-
}
|
|
136
|
-
},
|
|
60
|
+
queued: () => update({ connection: "live", needsResync: true, pending: Math.min(256, get.once(status).pending + 1) }),
|
|
137
61
|
});
|
|
138
62
|
yield* liveRetry(
|
|
139
63
|
attempt,
|
|
140
|
-
(failure, retry) => {
|
|
141
|
-
update({ connection: retry ? "reconnecting" : "failed", failure, needsResync: true });
|
|
142
|
-
},
|
|
64
|
+
(failure, retry) => update({ connection: retry ? "reconnecting" : "failed", failure, needsResync: true }),
|
|
143
65
|
options.retryDelay,
|
|
144
66
|
resumed,
|
|
145
67
|
);
|
|
146
68
|
}),
|
|
147
69
|
)
|
|
148
70
|
.pipe(Atom.setIdleTTL(0));
|
|
149
|
-
return {
|
|
71
|
+
return { connection, paused, status };
|
|
150
72
|
}
|
package/src/liveAttempt.ts
CHANGED
|
@@ -1,52 +1,28 @@
|
|
|
1
1
|
import { Effect, Stream } from "effect";
|
|
2
|
-
import type {
|
|
3
|
-
import type { SubscriptionHint } from "#queryUpdate.ts";
|
|
2
|
+
import type { SubscriptionEvent } from "#queryUpdate.ts";
|
|
4
3
|
import type { QueryReadDenied } from "#readPolicyErrors.ts";
|
|
5
4
|
|
|
6
|
-
function deliveredResult(hint: SubscriptionHint): boolean {
|
|
7
|
-
return hint._tag === "Changed" && hint.keys.length === 0 && hint.queryIndexes?.length === 0;
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
function needsRead(hint: SubscriptionHint, connected: boolean): boolean {
|
|
11
|
-
return connected && !deliveredResult(hint);
|
|
12
|
-
}
|
|
13
|
-
|
|
14
5
|
export function liveAttempt<E, R>(
|
|
15
|
-
stream: Stream.Stream<
|
|
6
|
+
stream: Stream.Stream<SubscriptionEvent, E, R>,
|
|
16
7
|
observe: {
|
|
17
|
-
readonly changed: (keys: readonly Key[]) => void;
|
|
18
8
|
readonly denied: (denial: QueryReadDenied) => void;
|
|
19
|
-
readonly
|
|
9
|
+
readonly delivered: () => void;
|
|
20
10
|
readonly paused: () => boolean;
|
|
21
11
|
readonly queued: () => void;
|
|
22
|
-
readonly reconcile: (connected: boolean) => void;
|
|
23
12
|
},
|
|
24
13
|
) {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
observe.queued();
|
|
40
|
-
} else if (first || hint._tag === "Resync" || deliveredResult(hint)) {
|
|
41
|
-
observe.reconcile(needsRead(hint, connected));
|
|
42
|
-
} else {
|
|
43
|
-
observe.changed(hint.keys);
|
|
44
|
-
}
|
|
45
|
-
connected = true;
|
|
46
|
-
first = false;
|
|
47
|
-
}),
|
|
48
|
-
),
|
|
49
|
-
Effect.scoped,
|
|
50
|
-
);
|
|
51
|
-
});
|
|
14
|
+
return stream.pipe(
|
|
15
|
+
Stream.runForEach((event) =>
|
|
16
|
+
Effect.sync(() => {
|
|
17
|
+
if (event._tag === "QueryReadDenied") {
|
|
18
|
+
observe.denied(event);
|
|
19
|
+
} else if (observe.paused()) {
|
|
20
|
+
observe.queued();
|
|
21
|
+
} else {
|
|
22
|
+
observe.delivered();
|
|
23
|
+
}
|
|
24
|
+
}),
|
|
25
|
+
),
|
|
26
|
+
Effect.scoped,
|
|
27
|
+
);
|
|
52
28
|
}
|
package/src/liveHintQueue.ts
CHANGED
|
@@ -2,21 +2,18 @@ import { Effect, Queue } from "effect";
|
|
|
2
2
|
import type { LiveHint } from "#live.ts";
|
|
3
3
|
|
|
4
4
|
export const liveHintQueue = Effect.gen(function* () {
|
|
5
|
-
const queue = yield* Queue.bounded<LiveHint>(
|
|
6
|
-
let
|
|
5
|
+
const queue = yield* Queue.bounded<LiveHint>(1);
|
|
6
|
+
let count = 0;
|
|
7
7
|
function offer(hint: LiveHint) {
|
|
8
|
-
|
|
8
|
+
const queued = Queue.takeUnsafe(queue);
|
|
9
|
+
const pending = queued?._tag === "Success" ? queued.value : undefined;
|
|
10
|
+
count = pending === undefined ? 1 : count + 1;
|
|
11
|
+
if (pending?._tag === "Resync" || hint._tag === "Resync" || count > 256) {
|
|
12
|
+
Queue.offerUnsafe(queue, { _tag: "Resync" });
|
|
9
13
|
return;
|
|
10
14
|
}
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
return;
|
|
14
|
-
}
|
|
15
|
-
while (Queue.takeUnsafe(queue) !== undefined) {
|
|
16
|
-
// Overflow discards targeted hints because the resync covers every subscribed read.
|
|
17
|
-
}
|
|
18
|
-
overflowed = true;
|
|
19
|
-
Queue.offerUnsafe(queue, { _tag: "Resync" });
|
|
15
|
+
const keys = new Map([...(pending?.keys ?? []), ...hint.keys].map((key) => [JSON.stringify(key), key]));
|
|
16
|
+
Queue.offerUnsafe(queue, { _tag: "Changed", keys: [...keys.values()] });
|
|
20
17
|
}
|
|
21
18
|
return { offer, queue };
|
|
22
19
|
});
|
package/src/operation.ts
CHANGED
|
@@ -25,7 +25,6 @@ export interface OperationShape {
|
|
|
25
25
|
|
|
26
26
|
export interface QueryShape<E = unknown, R = unknown> extends OperationShape {
|
|
27
27
|
readonly kind: "query";
|
|
28
|
-
readonly live?: "rerun-and-compare" | undefined;
|
|
29
28
|
readonly readPolicy: Bivariant<QueryReadPolicy<unknown, E, R>>;
|
|
30
29
|
reads: Bivariant<(payload: unknown, viewer: Option.Option<Viewer>) => readonly Key[]>;
|
|
31
30
|
readonly readsCollections?: readonly { readonly name: string }[] | undefined;
|
|
@@ -53,16 +52,9 @@ interface Operation<TName extends string, TPayload extends Schema.Top, TSuccess
|
|
|
53
52
|
readonly success: TSuccess;
|
|
54
53
|
}
|
|
55
54
|
|
|
56
|
-
export interface Query<
|
|
57
|
-
TName
|
|
58
|
-
TPayload extends Schema.Top,
|
|
59
|
-
TSuccess extends Schema.Top,
|
|
60
|
-
TSpecs extends RejectionSpecs,
|
|
61
|
-
R = never,
|
|
62
|
-
TLive extends "rerun-and-compare" | undefined = undefined,
|
|
63
|
-
> extends Operation<TName, TPayload, TSuccess, TSpecs> {
|
|
55
|
+
export interface Query<TName extends string, TPayload extends Schema.Top, TSuccess extends Schema.Top, TSpecs extends RejectionSpecs, R = never>
|
|
56
|
+
extends Operation<TName, TPayload, TSuccess, TSpecs> {
|
|
64
57
|
readonly kind: "query";
|
|
65
|
-
readonly live?: TLive;
|
|
66
58
|
readonly readPolicy: QueryReadPolicy<TPayload["Type"], RejectedBy<TSpecs>, R>;
|
|
67
59
|
reads: (payload: TPayload["Type"], viewer: Option.Option<Viewer>) => readonly Key[];
|
|
68
60
|
readonly readsCollections?: readonly { readonly name: string }[] | undefined;
|
|
@@ -87,15 +79,10 @@ export function query<
|
|
|
87
79
|
TSuccess extends Schema.Top = Schema.Void,
|
|
88
80
|
const TSpecs extends RejectionSpecs = NoRejections,
|
|
89
81
|
R = never,
|
|
90
|
-
|
|
91
|
-
>(
|
|
92
|
-
name: TName,
|
|
93
|
-
declaration: QueryDeclaration<TPayload, TSuccess, TSpecs, R, TLive>,
|
|
94
|
-
): NoInfer<Query<TName, PayloadSchema<TPayload>, TSuccess, TSpecs, R, TLive>>;
|
|
82
|
+
>(name: TName, declaration: QueryDeclaration<TPayload, TSuccess, TSpecs, R>): NoInfer<Query<TName, PayloadSchema<TPayload>, TSuccess, TSpecs, R>>;
|
|
95
83
|
export function query(
|
|
96
84
|
name: string,
|
|
97
85
|
declaration: Loose & {
|
|
98
|
-
readonly live?: "rerun-and-compare" | undefined;
|
|
99
86
|
readonly reads: (payload: unknown, viewer: Option.Option<Viewer>) => readonly Key[];
|
|
100
87
|
readonly readPolicy: QueryReadPolicy<unknown, unknown, unknown>;
|
|
101
88
|
readonly readsCollections?: readonly { readonly name: string }[];
|
|
@@ -105,7 +92,6 @@ export function query(
|
|
|
105
92
|
const collections: readonly Key[] = declaration.readsCollections?.map((collection) => ({ _tag: "List", collection: collection.name })) ?? [];
|
|
106
93
|
return {
|
|
107
94
|
...operation("query", name, declaration),
|
|
108
|
-
live: declaration.live,
|
|
109
95
|
readPolicy: declaration.readPolicy,
|
|
110
96
|
reads: (payload, viewer) => [...declaration.reads(payload, viewer), ...collections],
|
|
111
97
|
readsCollections: declaration.readsCollections,
|
|
@@ -17,10 +17,8 @@ export type QueryDeclaration<
|
|
|
17
17
|
TSuccess extends Schema.Top,
|
|
18
18
|
TSpecs extends RejectionSpecs,
|
|
19
19
|
R,
|
|
20
|
-
TLive extends "rerun-and-compare" | undefined,
|
|
21
20
|
> = Declaration<TPayload, TSuccess, TSpecs> &
|
|
22
21
|
CollectionReads<PayloadSchema<TPayload>["Type"], NoInfer<RejectedBy<TSpecs>>, R> & {
|
|
23
|
-
readonly live?: TLive;
|
|
24
22
|
readonly reads: (payload: PayloadSchema<TPayload>["Type"], viewer: Option.Option<Viewer>) => readonly Key[];
|
|
25
23
|
readonly serverReads?: QueryServerReads<PayloadSchema<TPayload>["Type"], NoInfer<RejectedBy<TSpecs>>, R>;
|
|
26
24
|
};
|