@kubun/service-graph-api 0.14.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/LICENSE.md ADDED
@@ -0,0 +1,57 @@
1
+ # The Prosperity Public License 3.0.0
2
+
3
+ Contributor: Paul Le Cam
4
+
5
+ Source Code: https://github.com/PaulLeCam/kubun
6
+
7
+ ## Purpose
8
+
9
+ This license allows you to use and share this software for noncommercial purposes for free and to try this software for commercial purposes for thirty days.
10
+
11
+ ## Agreement
12
+
13
+ In order to receive this license, you have to agree to its rules. Those rules are both obligations under that agreement and conditions to your license. Don't do anything with this software that triggers a rule you can't or won't follow.
14
+
15
+ ## Notices
16
+
17
+ Make sure everyone who gets a copy of any part of this software from you, with or without changes, also gets the text of this license and the contributor and source code lines above.
18
+
19
+ ## Commercial Trial
20
+
21
+ Limit your use of this software for commercial purposes to a thirty-day trial period. If you use this software for work, your company gets one trial period for all personnel, not one trial per person.
22
+
23
+ ## Contributions Back
24
+
25
+ Developing feedback, changes, or additions that you contribute back to the contributor on the terms of a standardized public software license such as [the Blue Oak Model License 1.0.0](https://blueoakcouncil.org/license/1.0.0), [the Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0.html), [the MIT license](https://spdx.org/licenses/MIT.html), or [the two-clause BSD license](https://spdx.org/licenses/BSD-2-Clause.html) doesn't count as use for a commercial purpose.
26
+
27
+ ## Personal Uses
28
+
29
+ Personal use for research, experiment, and testing for the benefit of public knowledge, personal study, private entertainment, hobby projects, amateur pursuits, or religious observance, without any anticipated commercial application, doesn't count as use for a commercial purpose.
30
+
31
+ ## Noncommercial Organizations
32
+
33
+ Use by any charitable organization, educational institution, public research organization, public safety or health organization, environmental protection organization, or government institution doesn't count as use for a commercial purpose regardless of the source of funding or obligations resulting from the funding.
34
+
35
+ ## Defense
36
+
37
+ Don't make any legal claim against anyone accusing this software, with or without changes, alone or with other technology, of infringing any patent.
38
+
39
+ ## Copyright
40
+
41
+ The contributor licenses you to do everything with this software that would otherwise infringe their copyright in it.
42
+
43
+ ## Patent
44
+
45
+ The contributor licenses you to do everything with this software that would otherwise infringe any patents they can license or become able to license.
46
+
47
+ ## Reliability
48
+
49
+ The contributor can't revoke this license.
50
+
51
+ ## Excuse
52
+
53
+ You're excused for unknowingly breaking [Notices](#notices) if you take all practical steps to comply within thirty days of learning you broke the rule.
54
+
55
+ ## No Liability
56
+
57
+ ***As far as the law allows, this software comes as is, without any warranty or condition, and the contributor won't be liable to anyone for any damages related to this software or this license, under any kind of legal claim.***
@@ -0,0 +1,18 @@
1
+ import type { ProcedureHandlers } from '@enkaku/server';
2
+ import type { SigningIdentity } from '@kokuin/token';
3
+ import type { Engine, GraphInternals } from '@kubun/engine';
4
+ import type { HLC } from '@kubun/hlc';
5
+ import type { GraphProtocol } from '@kubun/protocol';
6
+ import type { GetRandomValues } from '@sozai/runtime';
7
+ import type { TransactionManager } from './transaction-manager.js';
8
+ export type CreateHandlersParams = {
9
+ allowDelegatedMutations: boolean;
10
+ defaultDID: string;
11
+ engine: Engine;
12
+ getRandomValues: GetRandomValues;
13
+ graph: GraphInternals;
14
+ hlc: HLC;
15
+ signingIdentity: SigningIdentity | null;
16
+ transactionManager: TransactionManager;
17
+ };
18
+ export declare function createGraphHandlers(params: CreateHandlersParams): ProcedureHandlers<GraphProtocol>;
@@ -0,0 +1,329 @@
1
+ import { stringifyToken } from '@kokuin/token';
2
+ import { DocumentID } from '@kubun/id';
3
+ import { convertPatchInput, createMutationOperations, WriteAccessDeniedError } from '@kubun/mutation';
4
+ import { consume } from '@sozai/generator';
5
+ import { GraphQLError } from 'graphql';
6
+ function toGraphResult(result) {
7
+ const graphResult = {
8
+ data: result.data
9
+ };
10
+ if (result.errors != null) {
11
+ graphResult.errors = result.errors.map((err)=>{
12
+ const json = err.toJSON();
13
+ return json;
14
+ });
15
+ }
16
+ if (result.extensions != null) {
17
+ graphResult.extensions = result.extensions;
18
+ }
19
+ return graphResult;
20
+ }
21
+ /**
22
+ * Resolve the viewerDID for a graph operation from the signed message payload.
23
+ *
24
+ * The verified `iss` is the only trustworthy viewer: it is the DID that signed
25
+ * the request. A `sub` that differs from `iss` is a forged-subject attempt
26
+ * (running the graph as someone else), so it is rejected outright. The
27
+ * `defaultDID` fallback applies ONLY when no payload is present, which is the
28
+ * explicit `accessRules: false` local mode where authentication is disabled.
29
+ */ function resolveViewerDID(payload, defaultDID) {
30
+ if (payload == null) return defaultDID;
31
+ const iss = payload.iss;
32
+ const sub = payload.sub;
33
+ if (sub != null && sub !== iss) {
34
+ throw new Error('Access denied: signed payload subject does not match issuer');
35
+ }
36
+ return iss ?? defaultDID;
37
+ }
38
+ /**
39
+ * Extract EngineGraphParams from a handler context, resolving the viewerDID
40
+ * from the verified issuer of the signed message payload (see resolveViewerDID).
41
+ */ function extractGraphParams(ctx, defaultDID) {
42
+ const payload = ctx.message?.payload;
43
+ return {
44
+ id: ctx.param.id,
45
+ text: ctx.param.text,
46
+ variables: ctx.param.variables ?? {},
47
+ viewerDID: resolveViewerDID(payload, defaultDID)
48
+ };
49
+ }
50
+ export function createGraphHandlers(params) {
51
+ const { allowDelegatedMutations, engine, getRandomValues, graph, defaultDID, hlc, signingIdentity, transactionManager } = params;
52
+ return {
53
+ 'graph/deploy': async (ctx)=>{
54
+ return await engine.deployGraph({
55
+ clusters: ctx.param.clusters,
56
+ id: ctx.param.id,
57
+ name: ctx.param.name,
58
+ plugins: ctx.param.plugins,
59
+ search: ctx.param.search
60
+ });
61
+ },
62
+ 'graph/list': async ()=>{
63
+ return await engine.listGraphs();
64
+ },
65
+ 'graph/load': async (ctx)=>{
66
+ return await engine.loadGraph({
67
+ id: ctx.param.id
68
+ });
69
+ },
70
+ 'graph/mutate': async (ctx)=>{
71
+ const { viewerDID } = extractGraphParams(ctx, defaultDID);
72
+ if (ctx.param.mutations != null) {
73
+ // Pre-signed mode: client submitted JWT tokens keyed by GraphQL field alias
74
+ const mutations = ctx.param.mutations;
75
+ const keys = Object.keys(mutations);
76
+ const tokens = keys.map((k)=>mutations[k]);
77
+ // Apply all mutations atomically via engine primitive. A
78
+ // capability-check failure throws `WriteAccessDeniedError` from the
79
+ // apply path; translate it into a GraphQL-shaped result so the wire
80
+ // carries the `KB07` extensions code instead of the generic enkaku
81
+ // "Handler execution failed" wrapper that would otherwise hide the
82
+ // reason.
83
+ let applied;
84
+ try {
85
+ applied = await graph.applyVerifiedMutations({
86
+ tokens
87
+ });
88
+ } catch (cause) {
89
+ if (cause instanceof WriteAccessDeniedError) {
90
+ return toGraphResult({
91
+ data: null,
92
+ errors: [
93
+ new GraphQLError(cause.message, {
94
+ extensions: {
95
+ code: cause.code,
96
+ docID: cause.docID
97
+ }
98
+ })
99
+ ]
100
+ });
101
+ }
102
+ throw cause;
103
+ }
104
+ const { results } = applied;
105
+ // Build mutatedDocuments map keyed by GraphQL field path. Pre-signed
106
+ // mode does not configure an accessGate, so every result here carries
107
+ // a non-null `document`.
108
+ const mutatedDocuments = {};
109
+ for(let i = 0; i < keys.length; i++){
110
+ const doc = results[i].document;
111
+ if (doc == null) {
112
+ throw new Error('Unexpected dropped mutation in pre-signed apply (no gate configured)');
113
+ }
114
+ mutatedDocuments[keys[i]] = doc;
115
+ }
116
+ // Execute GraphQL with overridden mutation executors that return pre-applied results.
117
+ // contextExtensions overrides the engine's default executors via shallow merge.
118
+ const result = await graph.execute({
119
+ graphID: ctx.param.id,
120
+ text: ctx.param.text,
121
+ variables: ctx.param.variables ?? {},
122
+ viewerDID,
123
+ contextExtensions: {
124
+ executeCreateMutation: async (params)=>{
125
+ return mutatedDocuments[params.info.path.key];
126
+ },
127
+ executeSetMutation: async (params)=>{
128
+ return mutatedDocuments[params.info.path.key];
129
+ },
130
+ executeUpdateMutation: async (params)=>{
131
+ return mutatedDocuments[params.info.path.key];
132
+ },
133
+ executeRemoveMutation: async ()=>{
134
+ // Remove mutations don't return a document — already applied
135
+ }
136
+ }
137
+ });
138
+ return toGraphResult(result);
139
+ }
140
+ // Delegated mode: server signs mutations on behalf of the client.
141
+ // Must be explicitly enabled via allowDelegatedMutations option.
142
+ if (!allowDelegatedMutations) {
143
+ throw new Error('Delegated mutations not enabled. Set allowDelegatedMutations: true or provide pre-signed mutations.');
144
+ }
145
+ if (signingIdentity == null) {
146
+ throw new Error('Delegated mutations require a SigningIdentity on the engine');
147
+ }
148
+ const transactionID = ctx.param.transactionID ?? null;
149
+ // Non-transaction delegated: engine.mutateGraph() handles signing internally
150
+ if (transactionID == null) {
151
+ const result = await engine.mutateGraph({
152
+ id: ctx.param.id,
153
+ text: ctx.param.text,
154
+ variables: ctx.param.variables ?? {},
155
+ viewerDID,
156
+ owner: viewerDID
157
+ });
158
+ return toGraphResult(result);
159
+ }
160
+ // Transaction mode: buffer signed mutations without applying them.
161
+ // Requires custom signing context since mutateGraph() applies immediately.
162
+ const signAndBuffer = async (mutation)=>{
163
+ const signed = await signingIdentity.signToken(mutation);
164
+ const jwt = stringifyToken(signed);
165
+ const txCtx = transactionManager.getTransaction(transactionID);
166
+ if (txCtx == null) {
167
+ throw new Error(`Transaction not found or expired: ${transactionID}`);
168
+ }
169
+ const docID = DocumentID.fromString(mutation.sub);
170
+ const isChange = mutation.typ === 'change';
171
+ const result = {
172
+ id: mutation.sub,
173
+ model: docID.model.toString(),
174
+ owner: mutation.aud ?? mutation.iss,
175
+ data: isChange ? null : mutation.data,
176
+ createdAt: new Date(),
177
+ updatedAt: isChange ? new Date() : null
178
+ };
179
+ txCtx.mutations.push({
180
+ mutation,
181
+ jwt,
182
+ authorDID: mutation.iss,
183
+ documentID: result.id,
184
+ result
185
+ });
186
+ return result;
187
+ };
188
+ const ops = createMutationOperations({
189
+ issuer: signingIdentity.id,
190
+ hlc,
191
+ getRandomValues,
192
+ owner: viewerDID,
193
+ async processSetMutation (mutation) {
194
+ return await signAndBuffer(mutation);
195
+ },
196
+ async processChangeMutation (mutation) {
197
+ return await signAndBuffer(mutation);
198
+ }
199
+ });
200
+ const result = await graph.execute({
201
+ graphID: ctx.param.id,
202
+ text: ctx.param.text,
203
+ variables: ctx.param.variables ?? {},
204
+ viewerDID,
205
+ contextExtensions: {
206
+ executeCreateMutation: async (params)=>{
207
+ return await ops.createDocument({
208
+ modelID: params.modelID,
209
+ data: params.data
210
+ });
211
+ },
212
+ executeSetMutation: async (params)=>{
213
+ return await ops.setDocument({
214
+ modelID: params.modelID,
215
+ unique: params.unique,
216
+ data: params.data
217
+ });
218
+ },
219
+ executeUpdateMutation: async (params)=>{
220
+ return await ops.updateDocument({
221
+ docID: params.input.id,
222
+ patch: convertPatchInput(params.input.patch)
223
+ });
224
+ },
225
+ executeRemoveMutation: async (params)=>{
226
+ await ops.removeDocument({
227
+ docID: params.id
228
+ });
229
+ }
230
+ }
231
+ });
232
+ return toGraphResult(result);
233
+ },
234
+ 'graph/query': async (ctx)=>{
235
+ const result = await engine.queryGraph(extractGraphParams(ctx, defaultDID));
236
+ return toGraphResult(result);
237
+ },
238
+ 'graph/subscribe': async (ctx)=>{
239
+ const subscription = await engine.subscribeToGraph(extractGraphParams(ctx, defaultDID));
240
+ if (ctx.signal.aborted) {
241
+ return null;
242
+ }
243
+ // If subscribe returned errors instead of an async generator
244
+ if ('errors' in subscription) {
245
+ return toGraphResult(subscription);
246
+ }
247
+ const writer = ctx.writable.getWriter();
248
+ try {
249
+ await consume(subscription, async (value)=>{
250
+ await writer.write(toGraphResult(value));
251
+ }, ctx.signal);
252
+ } catch (reason) {
253
+ // When aborted (client disconnect, server dispose), consume() rejects
254
+ // with the abort reason. This is expected.
255
+ if (!ctx.signal.aborted) {
256
+ throw reason;
257
+ }
258
+ } finally{
259
+ // Belt-and-braces: explicitly close the source generator so its
260
+ // document:saved listener is torn down. consume() already calls
261
+ // return() on abort and normal completion; this is an idempotent
262
+ // safeguard against a future consume() that does not.
263
+ try {
264
+ await subscription.return?.(undefined);
265
+ } catch {
266
+ // Generator may already be closed during abort teardown
267
+ }
268
+ try {
269
+ await writer.close();
270
+ } catch {
271
+ // Writer may already be closed during abort teardown
272
+ }
273
+ }
274
+ return null;
275
+ },
276
+ 'graph/beginTransaction': async (ctx)=>{
277
+ const payload = ctx.message?.payload;
278
+ const callerDID = resolveViewerDID(payload, defaultDID);
279
+ // Validate that the graph exists before starting a transaction
280
+ await engine.loadGraph({
281
+ id: ctx.param.id
282
+ });
283
+ const txCtx = transactionManager.beginTransaction(callerDID, ctx.param.id);
284
+ return {
285
+ transactionID: txCtx.id
286
+ };
287
+ },
288
+ 'graph/commitTransaction': async (ctx)=>{
289
+ const txCtx = transactionManager.getTransaction(ctx.param.transactionID);
290
+ if (txCtx == null) {
291
+ throw new Error(`Transaction not found or expired: ${ctx.param.transactionID}`);
292
+ }
293
+ if (txCtx.mutations.length > 0) {
294
+ const tokens = txCtx.mutations.map((m)=>m.jwt);
295
+ try {
296
+ await graph.applyVerifiedMutations({
297
+ tokens
298
+ });
299
+ } catch (cause) {
300
+ if (cause instanceof WriteAccessDeniedError) {
301
+ // Revocation between begin and commit — surface the reason on the
302
+ // wire via the typed `error` field so callers can distinguish
303
+ // access-denied from generic commit failures.
304
+ transactionManager.rollbackTransaction(ctx.param.transactionID);
305
+ return {
306
+ success: false,
307
+ error: {
308
+ code: cause.code,
309
+ message: cause.message,
310
+ docID: cause.docID
311
+ }
312
+ };
313
+ }
314
+ throw cause;
315
+ }
316
+ }
317
+ transactionManager.markCommitted(ctx.param.transactionID);
318
+ return {
319
+ success: true
320
+ };
321
+ },
322
+ 'graph/rollbackTransaction': async (ctx)=>{
323
+ transactionManager.rollbackTransaction(ctx.param.transactionID);
324
+ return {
325
+ success: true
326
+ };
327
+ }
328
+ };
329
+ }
package/lib/index.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ import type { KubunPlugin, PluginFactoryParams } from '@kubun/engine';
2
+ import type { AccessRules } from '@kubun/plugin-service-api';
3
+ import type { TransactionManagerOptions } from './transaction-manager.js';
4
+ export type { GraphProtocol } from '@kubun/protocol';
5
+ export type { CreateHandlersParams } from './handlers.js';
6
+ export { createGraphHandlers } from './handlers.js';
7
+ export type { TransactionManagerOptions } from './transaction-manager.js';
8
+ export { TransactionManager } from './transaction-manager.js';
9
+ export type GraphServicePluginOptions = {
10
+ /** Allow the engine to sign mutations on behalf of clients (delegated mode). Default: false. */
11
+ allowDelegatedMutations?: boolean;
12
+ /** Configuration for the transaction manager. */
13
+ transactionConfig?: TransactionManagerOptions;
14
+ /** Default access rules for the registered provider. Default: `{}` (server-only). */
15
+ accessRules?: AccessRules;
16
+ };
17
+ /**
18
+ * Creates the graph service plugin.
19
+ *
20
+ * Registers the `graph/*` handlers as a `service` provider named `graph`, so the
21
+ * service host serves them over a transport. Graph auth is unchanged: each handler
22
+ * resolves its viewer from the verified signed-message `iss` itself and never
23
+ * consults the host authorizer, so the provider's default access rules are empty
24
+ * (server-only) unless a host grants procedures per serve.
25
+ */
26
+ export declare function createGraphServicePlugin(options?: GraphServicePluginOptions): (params: PluginFactoryParams) => KubunPlugin;
package/lib/index.js ADDED
@@ -0,0 +1,51 @@
1
+ // The graph service: the `graph/*` Enkaku procedures registered as a `service`
2
+ // provider so the service host can serve them over a transport, plus the handler
3
+ // and transaction-manager building blocks the RPC plugin still composes directly.
4
+ // The wire contract itself lives in `@kubun/protocol` and is re-exported here.
5
+ import { isSigningIdentity } from '@kokuin/token';
6
+ import { createGraphHandlers } from './handlers.js';
7
+ import { TransactionManager } from './transaction-manager.js';
8
+ export { createGraphHandlers } from './handlers.js';
9
+ export { TransactionManager } from './transaction-manager.js';
10
+ // The service name the provider registers under and the host toggles via `services`.
11
+ const GRAPH_SERVICE_NAME = 'graph';
12
+ /**
13
+ * Creates the graph service plugin.
14
+ *
15
+ * Registers the `graph/*` handlers as a `service` provider named `graph`, so the
16
+ * service host serves them over a transport. Graph auth is unchanged: each handler
17
+ * resolves its viewer from the verified signed-message `iss` itself and never
18
+ * consults the host authorizer, so the provider's default access rules are empty
19
+ * (server-only) unless a host grants procedures per serve.
20
+ */ export function createGraphServicePlugin(options) {
21
+ return (params)=>{
22
+ const signer = isSigningIdentity(params.identity) ? params.identity : null;
23
+ const transactionManager = new TransactionManager({
24
+ runtime: params.runtime,
25
+ ...options?.transactionConfig
26
+ });
27
+ const handlers = createGraphHandlers({
28
+ allowDelegatedMutations: options?.allowDelegatedMutations ?? false,
29
+ defaultDID: params.identity.id,
30
+ engine: params.engine,
31
+ getRandomValues: params.runtime.getRandomValues,
32
+ graph: params.graph,
33
+ hlc: params.hlc,
34
+ signingIdentity: signer,
35
+ transactionManager
36
+ });
37
+ params.registerProvider('service', {
38
+ name: GRAPH_SERVICE_NAME,
39
+ // The typed `ProcedureHandlers<GraphProtocol>` narrows to the host's
40
+ // structural `Handlers` at this one seam, mirroring the host's serve cast.
41
+ handlers: handlers,
42
+ accessRules: options?.accessRules ?? {}
43
+ });
44
+ return {
45
+ name: 'graph-service',
46
+ dispose: async ()=>{
47
+ transactionManager.dispose();
48
+ }
49
+ };
50
+ };
51
+ }
@@ -0,0 +1,34 @@
1
+ import type { DocumentMutation, DocumentNode } from '@kubun/protocol';
2
+ import type { Runtime } from '@sozai/runtime';
3
+ export type BufferedMutation = {
4
+ mutation: DocumentMutation;
5
+ jwt: string;
6
+ authorDID: string;
7
+ documentID: string;
8
+ result: DocumentNode;
9
+ };
10
+ export type TransactionStatus = 'open' | 'committing' | 'committed' | 'rolledBack';
11
+ export type TransactionContext = {
12
+ id: string;
13
+ callerDID: string;
14
+ graphID: string;
15
+ mutations: Array<BufferedMutation>;
16
+ createdAt: number;
17
+ status: TransactionStatus;
18
+ };
19
+ export type TransactionManagerOptions = {
20
+ /** Host runtime, used to mint each transaction's id. */
21
+ runtime: Runtime;
22
+ perDIDLimit?: number;
23
+ globalLimit?: number;
24
+ timeoutMS?: number;
25
+ };
26
+ export declare class TransactionManager {
27
+ #private;
28
+ constructor(options: TransactionManagerOptions);
29
+ beginTransaction(callerDID: string, graphID: string): TransactionContext;
30
+ getTransaction(transactionID: string): TransactionContext | null;
31
+ rollbackTransaction(transactionID: string): void;
32
+ markCommitted(transactionID: string): void;
33
+ dispose(): void;
34
+ }
@@ -0,0 +1,105 @@
1
+ const DEFAULT_PER_DID_LIMIT = 3;
2
+ const DEFAULT_GLOBAL_LIMIT = 20;
3
+ const DEFAULT_TIMEOUT_MS = 30_000;
4
+ export class TransactionManager {
5
+ #runtime;
6
+ #globalLimit;
7
+ #perDIDLimit;
8
+ #timeoutMS;
9
+ #transactions = new Map();
10
+ #sweepInterval = null;
11
+ constructor(options){
12
+ this.#runtime = options.runtime;
13
+ this.#globalLimit = options.globalLimit ?? DEFAULT_GLOBAL_LIMIT;
14
+ this.#perDIDLimit = options.perDIDLimit ?? DEFAULT_PER_DID_LIMIT;
15
+ this.#timeoutMS = options.timeoutMS ?? DEFAULT_TIMEOUT_MS;
16
+ this.#startTimeoutSweep();
17
+ }
18
+ beginTransaction(callerDID, graphID) {
19
+ if (this.#transactions.size >= this.#globalLimit) {
20
+ throw new Error(`Global transaction limit reached (${this.#globalLimit}). Cannot create new transaction.`);
21
+ }
22
+ let didCount = 0;
23
+ for (const ctx of this.#transactions.values()){
24
+ if (ctx.callerDID === callerDID) {
25
+ didCount++;
26
+ }
27
+ }
28
+ if (didCount >= this.#perDIDLimit) {
29
+ throw new Error(`Per-DID transaction limit reached (${this.#perDIDLimit}) for ${callerDID}. Cannot create new transaction.`);
30
+ }
31
+ const ctx = {
32
+ id: this.#runtime.getRandomID(),
33
+ callerDID,
34
+ graphID,
35
+ mutations: [],
36
+ createdAt: Date.now(),
37
+ status: 'open'
38
+ };
39
+ this.#transactions.set(ctx.id, ctx);
40
+ return ctx;
41
+ }
42
+ getTransaction(transactionID) {
43
+ const ctx = this.#transactions.get(transactionID);
44
+ if (ctx == null) {
45
+ return null;
46
+ }
47
+ // Lazy timeout check
48
+ if (Date.now() - ctx.createdAt > this.#timeoutMS) {
49
+ ctx.status = 'rolledBack';
50
+ this.#transactions.delete(transactionID);
51
+ return null;
52
+ }
53
+ return ctx;
54
+ }
55
+ rollbackTransaction(transactionID) {
56
+ const ctx = this.#transactions.get(transactionID);
57
+ if (ctx == null) {
58
+ throw new Error(`Transaction not found: ${transactionID}`);
59
+ }
60
+ if (ctx.status === 'committed') {
61
+ throw new Error(`Cannot rollback committed transaction: ${transactionID}`);
62
+ }
63
+ ctx.status = 'rolledBack';
64
+ this.#transactions.delete(transactionID);
65
+ }
66
+ markCommitted(transactionID) {
67
+ const ctx = this.#transactions.get(transactionID);
68
+ if (ctx == null) {
69
+ return;
70
+ }
71
+ ctx.status = 'committed';
72
+ this.#transactions.delete(transactionID);
73
+ }
74
+ dispose() {
75
+ // Rollback all active transactions
76
+ for (const [_id, ctx] of this.#transactions){
77
+ if (ctx.status === 'open' || ctx.status === 'committing') {
78
+ ctx.status = 'rolledBack';
79
+ }
80
+ }
81
+ this.#transactions.clear();
82
+ if (this.#sweepInterval != null) {
83
+ clearInterval(this.#sweepInterval);
84
+ this.#sweepInterval = null;
85
+ }
86
+ }
87
+ #startTimeoutSweep() {
88
+ this.#sweepInterval = setInterval(()=>{
89
+ const now = Date.now();
90
+ for (const [id, ctx] of this.#transactions){
91
+ if (now - ctx.createdAt > this.#timeoutMS) {
92
+ ctx.status = 'rolledBack';
93
+ this.#transactions.delete(id);
94
+ }
95
+ }
96
+ }, Math.min(this.#timeoutMS, 10_000));
97
+ // Allow the process to exit even if the interval is running.
98
+ // In Node.js, setInterval returns an object with unref(); in browsers it returns a number.
99
+ const interval = this.#sweepInterval;
100
+ if (typeof interval === 'object' && typeof interval.unref === 'function') {
101
+ ;
102
+ interval.unref();
103
+ }
104
+ }
105
+ }
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@kubun/service-graph-api",
3
+ "version": "0.14.0",
4
+ "keywords": [],
5
+ "license": "see LICENSE.md",
6
+ "sideEffects": false,
7
+ "type": "module",
8
+ "exports": {
9
+ ".": "./lib/index.js"
10
+ },
11
+ "main": "lib/index.js",
12
+ "types": "lib/index.d.ts",
13
+ "files": [
14
+ "lib/*",
15
+ "LICENSE.md"
16
+ ],
17
+ "dependencies": {
18
+ "@enkaku/server": "^0.21.2",
19
+ "@kokuin/token": "^0.5.0",
20
+ "@kubun/engine": "^0.14.0",
21
+ "@kubun/hlc": "^0.14.0",
22
+ "@kubun/id": "^0.14.0",
23
+ "@kubun/mutation": "^0.14.0",
24
+ "@kubun/plugin-service-api": "^0.14.0",
25
+ "@kubun/protocol": "^0.14.0",
26
+ "@sozai/generator": "^0.2.0",
27
+ "@sozai/runtime": "^0.1.0",
28
+ "graphql": "^16.14.2"
29
+ },
30
+ "devDependencies": {
31
+ "@enkaku/client": "^0.21.0",
32
+ "@enkaku/transport": "^0.21.0",
33
+ "@kokuin/capability": "^0.3.0",
34
+ "@kokuin/controller": "^0.1.0",
35
+ "@kubun/client": "^0.14.0",
36
+ "@kubun/db": "^0.14.0",
37
+ "@kubun/plugin-service-server": "^0.14.0",
38
+ "@kubun/store-controller": "^0.14.0",
39
+ "@kubun/store-delegation": "^0.14.0",
40
+ "@kubun/store-graph": "^0.14.0",
41
+ "@kubun/store-p2p": "^0.14.0",
42
+ "@kubun/test-utils": "^0.13.0"
43
+ },
44
+ "publishConfig": {
45
+ "access": "public"
46
+ },
47
+ "scripts": {
48
+ "build": "pnpm run build:clean && pnpm run build:js && pnpm run build:types",
49
+ "build:clean": "del lib",
50
+ "build:js": "swc src -d ./lib --config-file ../../node_modules/@kigu/dev/swc.json --strip-leading-paths",
51
+ "build:types": "tsc --emitDeclarationOnly --skipLibCheck",
52
+ "build:types:ci": "tsc --emitDeclarationOnly --declarationMap false",
53
+ "test": "pnpm run test:types && pnpm run test:unit",
54
+ "test:types": "tsc --noEmit -p tsconfig.test.json",
55
+ "test:unit": "vitest run"
56
+ }
57
+ }