@lunora/runtime 0.0.0 → 1.0.0-alpha.10

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.
@@ -0,0 +1,61 @@
1
+ const RPC_ENDPOINT = "/_lunora/rpc";
2
+ const buildIdentityHeaders = (options) => {
3
+ const headers = { "content-type": "application/json" };
4
+ if (options.userId !== void 0 && options.userId.length > 0) {
5
+ headers["x-lunora-userid"] = options.userId;
6
+ }
7
+ if (options.identity !== void 0) {
8
+ headers["x-lunora-identity"] = JSON.stringify(options.identity);
9
+ }
10
+ return headers;
11
+ };
12
+ const fanOutRelation = async (options, body, label) => {
13
+ const doFetch = options.fetch ?? globalThis.fetch;
14
+ const response = await doFetch(
15
+ new Request(`${options.origin}${RPC_ENDPOINT}`, {
16
+ body: JSON.stringify(body),
17
+ headers: buildIdentityHeaders(options),
18
+ method: "POST"
19
+ })
20
+ );
21
+ if (!response.ok) {
22
+ throw new Error(`cross-shard relation ${label} failed: worker returned ${String(response.status)}`);
23
+ }
24
+ const result = await response.json();
25
+ if (typeof result.failed === "number" && result.failed > 0) {
26
+ const reached = (typeof result.ok === "number" ? result.ok : 0) + result.failed;
27
+ throw new Error(
28
+ `cross-shard relation ${label} failed on ${String(result.failed)} of ${String(reached)} shard(s) — refusing to return a partial result`
29
+ );
30
+ }
31
+ return result.data;
32
+ };
33
+ const createCrossShardRelationCapabilities = (options) => {
34
+ const crossShardReader = async (table, args) => {
35
+ const data = await fanOutRelation(
36
+ options,
37
+ {
38
+ args: { orderBy: args?.orderBy, table, where: args?.where, with: args?.with },
39
+ fanOut: { merge: { kind: "concat" }, table },
40
+ functionPath: "__lunora_relation__:read"
41
+ },
42
+ "read"
43
+ );
44
+ return { continueCursor: null, isDone: true, page: Array.isArray(data) ? data : [] };
45
+ };
46
+ const crossShardCounter = async (table, where) => {
47
+ const data = await fanOutRelation(
48
+ options,
49
+ {
50
+ args: { table, where },
51
+ fanOut: { merge: { kind: "sum" }, table },
52
+ functionPath: "__lunora_relation__:count"
53
+ },
54
+ "count"
55
+ );
56
+ return typeof data === "number" ? data : 0;
57
+ };
58
+ return { crossShardCounter, crossShardReader };
59
+ };
60
+
61
+ export { createCrossShardRelationCapabilities };