@kubun/plugin-rpc 0.10.0 → 0.11.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/lib/handlers.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import type { GetRandomValues } from '@enkaku/runtime';
2
1
  import type { ProcedureHandlers } from '@enkaku/server';
3
- import type { SigningIdentity } from '@enkaku/token';
2
+ import type { SigningIdentity } from '@kokuin/token';
4
3
  import type { Engine, GraphInternals } from '@kubun/engine';
5
4
  import type { HLC } from '@kubun/hlc';
6
5
  import type { GraphProtocol } from '@kubun/protocol';
6
+ import type { GetRandomValues } from '@sozai/runtime';
7
7
  import type { TransactionManager } from './transaction-manager.js';
8
8
  export type CreateHandlersParams = {
9
9
  allowDelegatedMutations: boolean;
package/lib/handlers.js CHANGED
@@ -1 +1,328 @@
1
- import{consume as a}from"@enkaku/generator";import{stringifyToken as t}from"@enkaku/token";import{DocumentID as e}from"@kubun/id";import{convertPatchInput as r,createMutationOperations as n,WriteAccessDeniedError as i}from"@kubun/mutation";import{GraphQLError as o}from"graphql";function s(a){let t={data:a.data};return null!=a.errors&&(t.errors=a.errors.map(a=>a.toJSON())),null!=a.extensions&&(t.extensions=a.extensions),t}function u(a,t){let e=a.message?.payload,r=e?.sub??e?.iss??t;return{id:a.param.id,text:a.param.text,variables:a.param.variables??{},viewerDID:r}}export function createGraphHandlers(c){let{allowDelegatedMutations:l,engine:p,getRandomValues:d,graph:m,defaultDID:g,hlc:h,signingIdentity:y,transactionManager:w}=c;return{"graph/deploy":async a=>await p.deployGraph({clusters:a.param.clusters,id:a.param.id,name:a.param.name,plugins:a.param.plugins}),"graph/list":async()=>await p.listGraphs(),"graph/load":async a=>await p.loadGraph({id:a.param.id}),"graph/mutate":async a=>{let{viewerDID:c}=u(a,g);if(null!=a.param.mutations){let t,e=a.param.mutations,r=Object.keys(e),n=r.map(a=>e[a]);try{t=await m.applyVerifiedMutations({tokens:n})}catch(a){if(a instanceof i)return s({data:null,errors:[new o(a.message,{extensions:{code:a.code,docID:a.docID}})]});throw a}let{results:u}=t,l={};for(let a=0;a<r.length;a++){let t=u[a].document;if(null==t)throw Error("Unexpected dropped mutation in pre-signed apply (no gate configured)");l[r[a]]=t}return s(await m.execute({graphID:a.param.id,text:a.param.text,variables:a.param.variables??{},viewerDID:c,contextExtensions:{executeCreateMutation:async a=>l[a.info.path.key],executeSetMutation:async a=>l[a.info.path.key],executeUpdateMutation:async a=>l[a.info.path.key],executeRemoveMutation:async()=>{}}}))}if(!l)throw Error("Delegated mutations not enabled. Set allowDelegatedMutations: true or provide pre-signed mutations.");if(null==y)throw Error("Delegated mutations require a SigningIdentity on the engine");let f=a.param.transactionID??null;if(null==f)return s(await p.mutateGraph({id:a.param.id,text:a.param.text,variables:a.param.variables??{},viewerDID:c}));let D=async a=>{let r=t(await y.signToken(a)),n=w.getTransaction(f);if(null==n)throw Error(`Transaction not found or expired: ${f}`);let i=e.fromString(a.sub),o="change"===a.typ,s={id:a.sub,model:i.model.toString(),owner:a.aud??a.iss,data:o?null:a.data,createdAt:new Date,updatedAt:o?new Date:null};return n.mutations.push({mutation:a,jwt:r,authorDID:a.iss,documentID:s.id,result:s}),s},x=n({issuer:y.id,hlc:h,getRandomValues:d,processSetMutation:async a=>await D(a),processChangeMutation:async a=>await D(a)});return s(await m.execute({graphID:a.param.id,text:a.param.text,variables:a.param.variables??{},viewerDID:c,contextExtensions:{executeCreateMutation:async a=>await x.createDocument({modelID:a.modelID,data:a.data}),executeSetMutation:async a=>await x.setDocument({modelID:a.modelID,unique:a.unique,data:a.data}),executeUpdateMutation:async a=>await x.updateDocument({docID:a.input.id,patch:r(a.input.patch)}),executeRemoveMutation:async a=>{await x.removeDocument({docID:a.id})}}}))},"graph/query":async a=>s(await p.queryGraph(u(a,g))),"graph/subscribe":async t=>{let e=await p.subscribeToGraph(u(t,g));if(t.signal.aborted)return null;if("errors"in e)return s(e);let r=t.writable.getWriter();try{await a(e,async a=>{await r.write(s(a))},t.signal)}catch(a){if(!t.signal.aborted)throw a}finally{try{await r.close()}catch{}}return null},"graph/beginTransaction":async a=>{let t=a.message?.payload,e=t?.iss??g;return await p.loadGraph({id:a.param.id}),{transactionID:w.beginTransaction(e,a.param.id).id}},"graph/commitTransaction":async a=>{let t=w.getTransaction(a.param.transactionID);if(null==t)throw Error(`Transaction not found or expired: ${a.param.transactionID}`);if(t.mutations.length>0){let e=t.mutations.map(a=>a.jwt);try{await m.applyVerifiedMutations({tokens:e})}catch(t){if(t instanceof i)return w.rollbackTransaction(a.param.transactionID),{success:!1,error:{code:t.code,message:t.message,docID:t.docID}};throw t}}return w.markCommitted(a.param.transactionID),{success:!0}},"graph/rollbackTransaction":async a=>(w.rollbackTransaction(a.param.transactionID),{success:!0})}}
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
+ });
60
+ },
61
+ 'graph/list': async ()=>{
62
+ return await engine.listGraphs();
63
+ },
64
+ 'graph/load': async (ctx)=>{
65
+ return await engine.loadGraph({
66
+ id: ctx.param.id
67
+ });
68
+ },
69
+ 'graph/mutate': async (ctx)=>{
70
+ const { viewerDID } = extractGraphParams(ctx, defaultDID);
71
+ if (ctx.param.mutations != null) {
72
+ // Pre-signed mode: client submitted JWT tokens keyed by GraphQL field alias
73
+ const mutations = ctx.param.mutations;
74
+ const keys = Object.keys(mutations);
75
+ const tokens = keys.map((k)=>mutations[k]);
76
+ // Apply all mutations atomically via engine primitive. A
77
+ // capability-check failure throws `WriteAccessDeniedError` from the
78
+ // apply path; translate it into a GraphQL-shaped result so the wire
79
+ // carries the `KB07` extensions code instead of the generic enkaku
80
+ // "Handler execution failed" wrapper that would otherwise hide the
81
+ // reason.
82
+ let applied;
83
+ try {
84
+ applied = await graph.applyVerifiedMutations({
85
+ tokens
86
+ });
87
+ } catch (cause) {
88
+ if (cause instanceof WriteAccessDeniedError) {
89
+ return toGraphResult({
90
+ data: null,
91
+ errors: [
92
+ new GraphQLError(cause.message, {
93
+ extensions: {
94
+ code: cause.code,
95
+ docID: cause.docID
96
+ }
97
+ })
98
+ ]
99
+ });
100
+ }
101
+ throw cause;
102
+ }
103
+ const { results } = applied;
104
+ // Build mutatedDocuments map keyed by GraphQL field path. Pre-signed
105
+ // mode does not configure an accessGate, so every result here carries
106
+ // a non-null `document`.
107
+ const mutatedDocuments = {};
108
+ for(let i = 0; i < keys.length; i++){
109
+ const doc = results[i].document;
110
+ if (doc == null) {
111
+ throw new Error('Unexpected dropped mutation in pre-signed apply (no gate configured)');
112
+ }
113
+ mutatedDocuments[keys[i]] = doc;
114
+ }
115
+ // Execute GraphQL with overridden mutation executors that return pre-applied results.
116
+ // contextExtensions overrides the engine's default executors via shallow merge.
117
+ const result = await graph.execute({
118
+ graphID: ctx.param.id,
119
+ text: ctx.param.text,
120
+ variables: ctx.param.variables ?? {},
121
+ viewerDID,
122
+ contextExtensions: {
123
+ executeCreateMutation: async (params)=>{
124
+ return mutatedDocuments[params.info.path.key];
125
+ },
126
+ executeSetMutation: async (params)=>{
127
+ return mutatedDocuments[params.info.path.key];
128
+ },
129
+ executeUpdateMutation: async (params)=>{
130
+ return mutatedDocuments[params.info.path.key];
131
+ },
132
+ executeRemoveMutation: async ()=>{
133
+ // Remove mutations don't return a document — already applied
134
+ }
135
+ }
136
+ });
137
+ return toGraphResult(result);
138
+ }
139
+ // Delegated mode: server signs mutations on behalf of the client.
140
+ // Must be explicitly enabled via allowDelegatedMutations option.
141
+ if (!allowDelegatedMutations) {
142
+ throw new Error('Delegated mutations not enabled. Set allowDelegatedMutations: true or provide pre-signed mutations.');
143
+ }
144
+ if (signingIdentity == null) {
145
+ throw new Error('Delegated mutations require a SigningIdentity on the engine');
146
+ }
147
+ const transactionID = ctx.param.transactionID ?? null;
148
+ // Non-transaction delegated: engine.mutateGraph() handles signing internally
149
+ if (transactionID == null) {
150
+ const result = await engine.mutateGraph({
151
+ id: ctx.param.id,
152
+ text: ctx.param.text,
153
+ variables: ctx.param.variables ?? {},
154
+ viewerDID,
155
+ owner: viewerDID
156
+ });
157
+ return toGraphResult(result);
158
+ }
159
+ // Transaction mode: buffer signed mutations without applying them.
160
+ // Requires custom signing context since mutateGraph() applies immediately.
161
+ const signAndBuffer = async (mutation)=>{
162
+ const signed = await signingIdentity.signToken(mutation);
163
+ const jwt = stringifyToken(signed);
164
+ const txCtx = transactionManager.getTransaction(transactionID);
165
+ if (txCtx == null) {
166
+ throw new Error(`Transaction not found or expired: ${transactionID}`);
167
+ }
168
+ const docID = DocumentID.fromString(mutation.sub);
169
+ const isChange = mutation.typ === 'change';
170
+ const result = {
171
+ id: mutation.sub,
172
+ model: docID.model.toString(),
173
+ owner: mutation.aud ?? mutation.iss,
174
+ data: isChange ? null : mutation.data,
175
+ createdAt: new Date(),
176
+ updatedAt: isChange ? new Date() : null
177
+ };
178
+ txCtx.mutations.push({
179
+ mutation,
180
+ jwt,
181
+ authorDID: mutation.iss,
182
+ documentID: result.id,
183
+ result
184
+ });
185
+ return result;
186
+ };
187
+ const ops = createMutationOperations({
188
+ issuer: signingIdentity.id,
189
+ hlc,
190
+ getRandomValues,
191
+ owner: viewerDID,
192
+ async processSetMutation (mutation) {
193
+ return await signAndBuffer(mutation);
194
+ },
195
+ async processChangeMutation (mutation) {
196
+ return await signAndBuffer(mutation);
197
+ }
198
+ });
199
+ const result = await graph.execute({
200
+ graphID: ctx.param.id,
201
+ text: ctx.param.text,
202
+ variables: ctx.param.variables ?? {},
203
+ viewerDID,
204
+ contextExtensions: {
205
+ executeCreateMutation: async (params)=>{
206
+ return await ops.createDocument({
207
+ modelID: params.modelID,
208
+ data: params.data
209
+ });
210
+ },
211
+ executeSetMutation: async (params)=>{
212
+ return await ops.setDocument({
213
+ modelID: params.modelID,
214
+ unique: params.unique,
215
+ data: params.data
216
+ });
217
+ },
218
+ executeUpdateMutation: async (params)=>{
219
+ return await ops.updateDocument({
220
+ docID: params.input.id,
221
+ patch: convertPatchInput(params.input.patch)
222
+ });
223
+ },
224
+ executeRemoveMutation: async (params)=>{
225
+ await ops.removeDocument({
226
+ docID: params.id
227
+ });
228
+ }
229
+ }
230
+ });
231
+ return toGraphResult(result);
232
+ },
233
+ 'graph/query': async (ctx)=>{
234
+ const result = await engine.queryGraph(extractGraphParams(ctx, defaultDID));
235
+ return toGraphResult(result);
236
+ },
237
+ 'graph/subscribe': async (ctx)=>{
238
+ const subscription = await engine.subscribeToGraph(extractGraphParams(ctx, defaultDID));
239
+ if (ctx.signal.aborted) {
240
+ return null;
241
+ }
242
+ // If subscribe returned errors instead of an async generator
243
+ if ('errors' in subscription) {
244
+ return toGraphResult(subscription);
245
+ }
246
+ const writer = ctx.writable.getWriter();
247
+ try {
248
+ await consume(subscription, async (value)=>{
249
+ await writer.write(toGraphResult(value));
250
+ }, ctx.signal);
251
+ } catch (reason) {
252
+ // When aborted (client disconnect, server dispose), consume() rejects
253
+ // with the abort reason. This is expected.
254
+ if (!ctx.signal.aborted) {
255
+ throw reason;
256
+ }
257
+ } finally{
258
+ // Belt-and-braces: explicitly close the source generator so its
259
+ // document:saved listener is torn down. consume() already calls
260
+ // return() on abort and normal completion; this is an idempotent
261
+ // safeguard against a future consume() that does not.
262
+ try {
263
+ await subscription.return?.(undefined);
264
+ } catch {
265
+ // Generator may already be closed during abort teardown
266
+ }
267
+ try {
268
+ await writer.close();
269
+ } catch {
270
+ // Writer may already be closed during abort teardown
271
+ }
272
+ }
273
+ return null;
274
+ },
275
+ 'graph/beginTransaction': async (ctx)=>{
276
+ const payload = ctx.message?.payload;
277
+ const callerDID = resolveViewerDID(payload, defaultDID);
278
+ // Validate that the graph exists before starting a transaction
279
+ await engine.loadGraph({
280
+ id: ctx.param.id
281
+ });
282
+ const txCtx = transactionManager.beginTransaction(callerDID, ctx.param.id);
283
+ return {
284
+ transactionID: txCtx.id
285
+ };
286
+ },
287
+ 'graph/commitTransaction': async (ctx)=>{
288
+ const txCtx = transactionManager.getTransaction(ctx.param.transactionID);
289
+ if (txCtx == null) {
290
+ throw new Error(`Transaction not found or expired: ${ctx.param.transactionID}`);
291
+ }
292
+ if (txCtx.mutations.length > 0) {
293
+ const tokens = txCtx.mutations.map((m)=>m.jwt);
294
+ try {
295
+ await graph.applyVerifiedMutations({
296
+ tokens
297
+ });
298
+ } catch (cause) {
299
+ if (cause instanceof WriteAccessDeniedError) {
300
+ // Revocation between begin and commit — surface the reason on the
301
+ // wire via the typed `error` field so callers can distinguish
302
+ // access-denied from generic commit failures.
303
+ transactionManager.rollbackTransaction(ctx.param.transactionID);
304
+ return {
305
+ success: false,
306
+ error: {
307
+ code: cause.code,
308
+ message: cause.message,
309
+ docID: cause.docID
310
+ }
311
+ };
312
+ }
313
+ throw cause;
314
+ }
315
+ }
316
+ transactionManager.markCommitted(ctx.param.transactionID);
317
+ return {
318
+ success: true
319
+ };
320
+ },
321
+ 'graph/rollbackTransaction': async (ctx)=>{
322
+ transactionManager.rollbackTransaction(ctx.param.transactionID);
323
+ return {
324
+ success: true
325
+ };
326
+ }
327
+ };
328
+ }
package/lib/index.js CHANGED
@@ -1 +1,67 @@
1
- import{serve as e}from"@enkaku/server";import{isSigningIdentity as t}from"@enkaku/token";import{createGraphHandlers as n}from"./handlers.js";import{TransactionManager as i}from"./transaction-manager.js";export function createRPCPlugin(r){return a=>{let o=[],s=t(a.identity)?a.identity:null,g=new i({getRandomID:a.runtime.getRandomID,...r?.transactionConfig}),l=n({allowDelegatedMutations:r?.allowDelegatedMutations??!1,defaultDID:a.identity.id,engine:a.engine,getRandomValues:a.runtime.getRandomValues,graph:a.graph,signingIdentity:s,hlc:a.hlc,transactionManager:g});return{name:"rpc",api:{serve:(t,n)=>{let i=r?.accessRules,s={getRandomID:a.runtime.getRandomID,handlers:l,logger:a.getLogger("rpc-server"),signal:n,transport:t},g=e(!1===i?s:{...s,identity:a.identity,accessRules:i??{}});return o.push(g),g}},dispose:async()=>{for(let e of(g.dispose(),o))await e.dispose()}}}}
1
+ import { serve } from '@enkaku/server';
2
+ import { isSigningIdentity } from '@kokuin/token';
3
+ import { createGraphHandlers } from './handlers.js';
4
+ import { TransactionManager } from './transaction-manager.js';
5
+ // ---- Plugin factory ----
6
+ /**
7
+ * Creates the RPC plugin.
8
+ *
9
+ * The RPC plugin exposes the engine over transport. It optionally depends
10
+ * on the HTTP plugin for registering a /graphql route. Even without HTTP,
11
+ * the RPC plugin provides status tracking and a GraphQL query for server status.
12
+ *
13
+ * Creates Enkaku protocol handlers backed by the engine's Core interface
14
+ * (queryGraph/mutateGraph/subscribeToGraph via GraphInternals). Clients connect via `serve()` on any transport.
15
+ */ export function createRPCPlugin(options) {
16
+ return (params)=>{
17
+ const servers = [];
18
+ const signer = isSigningIdentity(params.identity) ? params.identity : null;
19
+ const transactionManager = new TransactionManager({
20
+ getRandomID: params.runtime.getRandomID,
21
+ ...options?.transactionConfig
22
+ });
23
+ const handlers = createGraphHandlers({
24
+ allowDelegatedMutations: options?.allowDelegatedMutations ?? false,
25
+ defaultDID: params.identity.id,
26
+ engine: params.engine,
27
+ getRandomValues: params.runtime.getRandomValues,
28
+ graph: params.graph,
29
+ signingIdentity: signer,
30
+ hlc: params.hlc,
31
+ transactionManager
32
+ });
33
+ const api = {
34
+ serve: (transport, signal)=>{
35
+ const accessRules = options?.accessRules;
36
+ const baseParams = {
37
+ getRandomID: params.runtime.getRandomID,
38
+ handlers,
39
+ logger: params.getLogger('rpc-server'),
40
+ signal,
41
+ transport
42
+ };
43
+ const serveParams = accessRules === false ? {
44
+ ...baseParams,
45
+ requireAuth: false
46
+ } : {
47
+ ...baseParams,
48
+ identity: params.identity,
49
+ accessRules: accessRules ?? {}
50
+ };
51
+ const server = serve(serveParams);
52
+ servers.push(server);
53
+ return server;
54
+ }
55
+ };
56
+ return {
57
+ name: 'rpc',
58
+ api,
59
+ dispose: async ()=>{
60
+ transactionManager.dispose();
61
+ for (const server of servers){
62
+ await server.dispose();
63
+ }
64
+ }
65
+ };
66
+ };
67
+ }
@@ -1 +1,105 @@
1
- export class TransactionManager{#t;#e;#a;#i;#s=new Map;#n=null;constructor(t){this.#t=t.getRandomID,this.#e=t.globalLimit??20,this.#a=t.perDIDLimit??3,this.#i=t.timeoutMS??3e4,this.#o()}beginTransaction(t,e){if(this.#s.size>=this.#e)throw Error(`Global transaction limit reached (${this.#e}). Cannot create new transaction.`);let a=0;for(let e of this.#s.values())e.callerDID===t&&a++;if(a>=this.#a)throw Error(`Per-DID transaction limit reached (${this.#a}) for ${t}. Cannot create new transaction.`);let i={id:this.#t(),callerDID:t,graphID:e,mutations:[],createdAt:Date.now(),status:"open"};return this.#s.set(i.id,i),i}getTransaction(t){let e=this.#s.get(t);return null==e?null:Date.now()-e.createdAt>this.#i?(e.status="rolledBack",this.#s.delete(t),null):e}rollbackTransaction(t){let e=this.#s.get(t);if(null==e)throw Error(`Transaction not found: ${t}`);if("committed"===e.status)throw Error(`Cannot rollback committed transaction: ${t}`);e.status="rolledBack",this.#s.delete(t)}markCommitted(t){let e=this.#s.get(t);null!=e&&(e.status="committed",this.#s.delete(t))}dispose(){for(let[t,e]of this.#s)("open"===e.status||"committing"===e.status)&&(e.status="rolledBack");this.#s.clear(),null!=this.#n&&(clearInterval(this.#n),this.#n=null)}#o(){this.#n=setInterval(()=>{let t=Date.now();for(let[e,a]of this.#s)t-a.createdAt>this.#i&&(a.status="rolledBack",this.#s.delete(e))},Math.min(this.#i,1e4));let t=this.#n;"object"==typeof t&&"function"==typeof t.unref&&t.unref()}}
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
+ #getRandomID;
6
+ #globalLimit;
7
+ #perDIDLimit;
8
+ #timeoutMS;
9
+ #transactions = new Map();
10
+ #sweepInterval = null;
11
+ constructor(options){
12
+ this.#getRandomID = options.getRandomID;
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.#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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubun/plugin-rpc",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "license": "see LICENSE.md",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -14,30 +14,31 @@
14
14
  ],
15
15
  "sideEffects": false,
16
16
  "dependencies": {
17
- "@enkaku/generator": "^0.16.0",
18
- "@enkaku/runtime": "^0.16.0",
19
- "@enkaku/server": "^0.16.0",
20
- "@enkaku/token": "^0.16.0",
21
- "graphql": "^16.13.2",
22
- "@kubun/db": "^0.10.0",
23
- "@kubun/hlc": "^0.10.0",
24
- "@kubun/graphql": "^0.10.0",
25
- "@kubun/mutation": "^0.10.0",
26
- "@kubun/protocol": "^0.10.0",
27
- "@kubun/engine": "^0.10.0"
17
+ "@sozai/generator": "^0.1.0",
18
+ "@sozai/runtime": "^0.1.0",
19
+ "@enkaku/server": "^0.18.1",
20
+ "@kokuin/token": "^0.1.1",
21
+ "graphql": "^16.14.2",
22
+ "@kubun/db": "^0.11.0",
23
+ "@kubun/graphql": "^0.11.0",
24
+ "@kubun/engine": "^0.11.0",
25
+ "@kubun/mutation": "^0.11.0",
26
+ "@kubun/hlc": "^0.11.0",
27
+ "@kubun/protocol": "^0.11.0"
28
28
  },
29
29
  "devDependencies": {
30
- "@enkaku/capability": "^0.16.0",
31
- "@enkaku/transport": "^0.16.0",
32
- "@kubun/client": "^0.10.0",
33
- "@kubun/id": "^0.10.0",
34
- "@kubun/store-graph": "^0.10.0",
35
- "@kubun/store-p2p": "^0.10.0",
36
- "@kubun/test-utils": "^0.10.0"
30
+ "@kokuin/capability": "^0.1.0",
31
+ "@enkaku/transport": "^0.18.1",
32
+ "@kubun/client": "^0.11.0",
33
+ "@kubun/store-graph": "^0.11.0",
34
+ "@kubun/store-delegation": "^0.11.0",
35
+ "@kubun/id": "^0.11.0",
36
+ "@kubun/store-p2p": "^0.11.0",
37
+ "@kubun/test-utils": "^0.11.0"
37
38
  },
38
39
  "scripts": {
39
40
  "build:clean": "del lib",
40
- "build:js": "swc src -d ./lib --config-file ../../swc.json --strip-leading-paths",
41
+ "build:js": "swc src -d ./lib --config-file ../../node_modules/@kigu/dev/swc.json --strip-leading-paths",
41
42
  "build:types": "tsc --emitDeclarationOnly --skipLibCheck",
42
43
  "build": "pnpm run build:clean && pnpm run build:js && pnpm run build:types",
43
44
  "test:types": "tsc --noEmit -p tsconfig.test.json",