@kubun/plugin-rpc 0.8.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 { GetRandomValues } from '@enkaku/runtime';
2
+ import type { ProcedureHandlers } from '@enkaku/server';
3
+ import type { SigningIdentity } from '@enkaku/token';
4
+ import type { Engine, GraphInternals } from '@kubun/engine';
5
+ import type { HLC } from '@kubun/hlc';
6
+ import type { GraphProtocol } from '@kubun/protocol';
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 @@
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}from"@kubun/mutation";function i(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 o(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(s){let{allowDelegatedMutations:u,engine:l,getRandomValues:p,graph:c,defaultDID:m,hlc:d,signingIdentity:g,transactionManager:h}=s;return{"graph/deploy":async a=>await l.deployGraph({clusters:a.param.clusters,id:a.param.id,name:a.param.name,plugins:a.param.plugins}),"graph/list":async()=>await l.listGraphs(),"graph/load":async a=>await l.loadGraph({id:a.param.id}),"graph/mutate":async a=>{let{viewerDID:s}=o(a,m);if(null!=a.param.mutations){let t=a.param.mutations,e=Object.keys(t),r=e.map(a=>t[a]),{results:n}=await c.applyVerifiedMutations({tokens:r,graphID:a.param.id}),o={};for(let a=0;a<e.length;a++)o[e[a]]=n[a].document;return i(await c.execute({graphID:a.param.id,text:a.param.text,variables:a.param.variables??{},viewerDID:s,contextExtensions:{executeCreateMutation:async a=>o[a.info.path.key],executeSetMutation:async a=>o[a.info.path.key],executeUpdateMutation:async a=>o[a.info.path.key],executeRemoveMutation:async()=>{}}}))}if(!u)throw Error("Delegated mutations not enabled. Set allowDelegatedMutations: true or provide pre-signed mutations.");if(null==g)throw Error("Delegated mutations require a SigningIdentity on the engine");let y=a.param.transactionID??null;if(null==y)return i(await l.mutateGraph({id:a.param.id,text:a.param.text,variables:a.param.variables??{},viewerDID:s}));let w=async a=>{let r=t(await g.signToken(a)),n=h.getTransaction(y);if(null==n)throw Error(`Transaction not found or expired: ${y}`);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},D=n({issuer:g.id,hlc:d,getRandomValues:p,processSetMutation:async a=>await w(a),processChangeMutation:async a=>await w(a)});return i(await c.execute({graphID:a.param.id,text:a.param.text,variables:a.param.variables??{},viewerDID:s,contextExtensions:{executeCreateMutation:async a=>await D.createDocument({modelID:a.modelID,data:a.data}),executeSetMutation:async a=>await D.setDocument({modelID:a.modelID,unique:a.unique,data:a.data}),executeUpdateMutation:async a=>await D.updateDocument({docID:a.input.id,patch:r(a.input.patch)}),executeRemoveMutation:async a=>{await D.removeDocument({docID:a.id})}}}))},"graph/query":async a=>i(await l.queryGraph(o(a,m))),"graph/subscribe":async t=>{let e=await l.subscribeToGraph(o(t,m));if(t.signal.aborted)return null;if("errors"in e)return i(e);let r=t.writable.getWriter();try{await a(e,async a=>{await r.write(i(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??m;return await l.loadGraph({id:a.param.id}),{transactionID:h.beginTransaction(e,a.param.id).id}},"graph/commitTransaction":async a=>{let t=h.getTransaction(a.param.transactionID);if(null==t)throw Error(`Transaction not found or expired: ${a.param.transactionID}`);if(t.mutations.length>0){let a=t.mutations.map(a=>a.jwt);await c.applyVerifiedMutations({tokens:a,graphID:t.graphID})}return h.markCommitted(a.param.transactionID),{success:!0}},"graph/rollbackTransaction":async a=>(h.rollbackTransaction(a.param.transactionID),{success:!0})}}
package/lib/index.d.ts ADDED
@@ -0,0 +1,35 @@
1
+ import type { ServerTransportOf } from '@enkaku/protocol';
2
+ import { type Server } from '@enkaku/server';
3
+ import type { KubunPlugin, PluginFactoryParams } from '@kubun/engine';
4
+ import type { GraphProtocol } from '@kubun/protocol';
5
+ import { type TransactionManagerOptions } from './transaction-manager.js';
6
+ export type { TransactionManagerOptions };
7
+ export type ServerTransport = ServerTransportOf<GraphProtocol>;
8
+ /**
9
+ * Options for the RPC plugin.
10
+ */
11
+ export type RPCPluginOptions = {
12
+ /** Enkaku protocol access control. Default: true. */
13
+ accessControl?: false | true | Record<string, boolean | Array<string>>;
14
+ /** Allow the engine to sign mutations on behalf of clients (delegated mode). Default: false. */
15
+ allowDelegatedMutations?: boolean;
16
+ /** Configuration for the transaction manager. */
17
+ transactionConfig?: TransactionManagerOptions;
18
+ };
19
+ /**
20
+ * API provided by the RPC plugin.
21
+ */
22
+ export type RPCPluginAPI = {
23
+ serve: (transport: ServerTransport, signal?: AbortSignal) => Server<GraphProtocol>;
24
+ };
25
+ /**
26
+ * Creates the RPC plugin.
27
+ *
28
+ * The RPC plugin exposes the engine over transport. It optionally depends
29
+ * on the HTTP plugin for registering a /graphql route. Even without HTTP,
30
+ * the RPC plugin provides status tracking and a GraphQL query for server status.
31
+ *
32
+ * Creates Enkaku protocol handlers backed by the engine's Core interface
33
+ * (queryGraph/mutateGraph/subscribeToGraph via GraphInternals). Clients connect via `serve()` on any transport.
34
+ */
35
+ export declare function createRPCPlugin(options?: RPCPluginOptions): (params: PluginFactoryParams) => KubunPlugin;
package/lib/index.js ADDED
@@ -0,0 +1 @@
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 o=>{let a=[],s=t(o.identity)?o.identity:null,g=new i({getRandomID:o.runtime.getRandomID,...r?.transactionConfig}),d=n({allowDelegatedMutations:r?.allowDelegatedMutations??!1,defaultDID:o.identity.id,engine:o.engine,getRandomValues:o.runtime.getRandomValues,graph:o.graph,signingIdentity:s,hlc:o.hlc,transactionManager:g});return{name:"rpc",api:{serve:(t,n)=>{let i=r?.accessControl??!0,s=e({accessControl:i,getRandomID:o.runtime.getRandomID,handlers:d,identity:!1!==i?o.identity:void 0,logger:o.getLogger("rpc-server"),signal:n,transport:t});return a.push(s),s}},dispose:async()=>{for(let e of(g.dispose(),a))await e.dispose()}}}}
@@ -0,0 +1,32 @@
1
+ import type { DocumentMutation, DocumentNode } from '@kubun/protocol';
2
+ export type BufferedMutation = {
3
+ mutation: DocumentMutation;
4
+ jwt: string;
5
+ authorDID: string;
6
+ documentID: string;
7
+ result: DocumentNode;
8
+ };
9
+ export type TransactionStatus = 'open' | 'committing' | 'committed' | 'rolledBack';
10
+ export type TransactionContext = {
11
+ id: string;
12
+ callerDID: string;
13
+ graphID: string;
14
+ mutations: Array<BufferedMutation>;
15
+ createdAt: number;
16
+ status: TransactionStatus;
17
+ };
18
+ export type TransactionManagerOptions = {
19
+ getRandomID: () => string;
20
+ perDIDLimit?: number;
21
+ globalLimit?: number;
22
+ timeoutMS?: number;
23
+ };
24
+ export declare class TransactionManager {
25
+ #private;
26
+ constructor(options: TransactionManagerOptions);
27
+ beginTransaction(callerDID: string, graphID: string): TransactionContext;
28
+ getTransaction(transactionID: string): TransactionContext | null;
29
+ rollbackTransaction(transactionID: string): void;
30
+ markCommitted(transactionID: string): void;
31
+ dispose(): void;
32
+ }
@@ -0,0 +1 @@
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()}}
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@kubun/plugin-rpc",
3
+ "version": "0.8.0",
4
+ "license": "see LICENSE.md",
5
+ "type": "module",
6
+ "main": "lib/index.js",
7
+ "types": "lib/index.d.ts",
8
+ "exports": {
9
+ ".": "./lib/index.js"
10
+ },
11
+ "files": [
12
+ "lib/*",
13
+ "LICENSE.md"
14
+ ],
15
+ "sideEffects": false,
16
+ "dependencies": {
17
+ "@enkaku/generator": "^0.14.0",
18
+ "@enkaku/runtime": "^0.14.0",
19
+ "@enkaku/server": "^0.14.3",
20
+ "@enkaku/token": "0.14.1",
21
+ "graphql": "^16.13.2",
22
+ "@kubun/db": "^0.8.0",
23
+ "@kubun/engine": "^0.8.0",
24
+ "@kubun/graphql": "^0.8.0",
25
+ "@kubun/mutation": "^0.8.0",
26
+ "@kubun/protocol": "^0.8.0",
27
+ "@kubun/hlc": "^0.8.0"
28
+ },
29
+ "devDependencies": {
30
+ "@enkaku/transport": "0.14.0",
31
+ "@kubun/id": "^0.8.0",
32
+ "@kubun/client": "^0.8.0",
33
+ "@kubun/test-utils": "^0.8.0"
34
+ },
35
+ "scripts": {
36
+ "build:clean": "del lib",
37
+ "build:js": "swc src -d ./lib --config-file ../../swc.json --strip-leading-paths",
38
+ "build:types": "tsc --emitDeclarationOnly --skipLibCheck",
39
+ "build": "pnpm run build:clean && pnpm run build:js && pnpm run build:types",
40
+ "test:types": "tsc --noEmit -p tsconfig.test.json",
41
+ "test:unit": "vitest run",
42
+ "test": "pnpm run test:types && pnpm run test:unit"
43
+ }
44
+ }