@kubun/plugin-rpc 0.9.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 +2 -2
- package/lib/handlers.js +328 -1
- package/lib/index.js +67 -1
- package/lib/transaction-manager.js +105 -1
- package/package.json +21 -18
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 '@
|
|
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{
|
|
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
|
|
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
|
-
|
|
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.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"license": "see LICENSE.md",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|
|
@@ -14,28 +14,31 @@
|
|
|
14
14
|
],
|
|
15
15
|
"sideEffects": false,
|
|
16
16
|
"dependencies": {
|
|
17
|
-
"@
|
|
18
|
-
"@
|
|
19
|
-
"@enkaku/server": "^0.
|
|
20
|
-
"@
|
|
21
|
-
"graphql": "^16.
|
|
22
|
-
"@kubun/db": "^0.
|
|
23
|
-
"@kubun/
|
|
24
|
-
"@kubun/
|
|
25
|
-
"@kubun/
|
|
26
|
-
"@kubun/
|
|
27
|
-
"@kubun/protocol": "^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
|
-
"@
|
|
31
|
-
"@
|
|
32
|
-
"@kubun/
|
|
33
|
-
"@kubun/store-graph": "^0.
|
|
34
|
-
"@kubun/
|
|
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"
|
|
35
38
|
},
|
|
36
39
|
"scripts": {
|
|
37
40
|
"build:clean": "del lib",
|
|
38
|
-
"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",
|
|
39
42
|
"build:types": "tsc --emitDeclarationOnly --skipLibCheck",
|
|
40
43
|
"build": "pnpm run build:clean && pnpm run build:js && pnpm run build:types",
|
|
41
44
|
"test:types": "tsc --noEmit -p tsconfig.test.json",
|