Diffinery

homeflare/celldpublic

celld/examples/rpc/index.js
136 lines · 4.6 KBRaw History
1// JS RPC: https://developers.cloudflare.com/workers/runtime-apis/rpc/
2//
3// Calling a method on a binding runs it in the other object. Arguments and
4// return values are structured-cloned. Values that cannot be cloned — a class
5// instance, a function — travel as *stubs*: the receiver gets a handle, and
6// calling it runs the code back where it came from. Stubs are what make
7// callbacks and pipelining work.
8//
9// One celld limit worth knowing, because it decides how you shape an API: a
10// stub cannot cross an isolate boundary yet. A Durable Object is its own
11// isolate, so a DO method takes and returns cloneable values. Named
12// entrypoints reached through `ctx.exports` share this isolate, so they get
13// the whole surface. Passing a function into a DO method throws rather than
14// failing quietly.
15import { DurableObject, RpcTarget, WorkerEntrypoint } from "cloudflare:workers";
16
17// An RpcTarget may travel as a live object rather than a copy. A plain class
18// cannot be sent over RPC at all.
19class Receipt extends RpcTarget {
20 constructor(id, balance) {
21 super();
22 this.id = id;
23 this.balance = balance;
24 }
25 describe() {
26 return `${this.id} holds ${this.balance}`;
27 }
28}
29
30// A Durable Object exposes RPC methods directly: no fetch(), no URL, no
31// Request. `super(state, env)` is what makes the methods reachable.
32export class Account extends DurableObject {
33 constructor(state, env) {
34 super(state, env);
35 this.state = state;
36 }
37
38 async deposit(amount) {
39 const balance = ((await this.state.storage.get("balance")) ?? 0) + amount;
40 await this.state.storage.put("balance", balance);
41 return balance;
42 }
43
44 async balance() {
45 return (await this.state.storage.get("balance")) ?? 0;
46 }
47
48 // Cloneable in, cloneable out — the shape a cross-isolate call needs.
49 async depositMany(amounts) {
50 const running = [];
51 for (const amount of amounts) running.push(await this.deposit(amount));
52 return { total: running.at(-1), running };
53 }
54}
55
56// A named entrypoint is a second, separately addressable interface on the
57// same Worker. `ctx.exports` reaches it in-process; a service binding in
58// another project reaches it by name.
59export class Ledger extends WorkerEntrypoint {
60 add(left, right) {
61 return left + right;
62 }
63
64 // A returned function becomes a stub, so this is a callback factory.
65 adder(left) {
66 return (right) => left + right;
67 }
68
69 // A function argument arrives as a stub, so the callee calls back into the
70 // caller while the call is still in flight.
71 async tally(values, onEach) {
72 let total = 0;
73 for (const value of values) {
74 total += value;
75 await onEach(value, total);
76 }
77 return total;
78 }
79
80 // Returning an RpcTarget lets the caller pipeline: it can call a method on
81 // the result before the result exists.
82 open(id, balance) {
83 return new Receipt(id, balance);
84 }
85}
86
87export default {
88 async fetch(request, env, ctx) {
89 const url = new URL(request.url);
90 const account = env.ACCOUNT.getByName("acct-1");
91
92 switch (url.pathname) {
93 // Durable Object RPC: a method call on the stub.
94 case "/deposit":
95 return Response.json({ balance: await account.deposit(10) });
96
97 // Still cross-isolate, so the argument and the result are cloneable.
98 case "/deposit-many":
99 return Response.json(await account.depositMany([1, 2, 3]));
100
101 // ctx.exports reaches a named entrypoint in this same Worker.
102 case "/entrypoint":
103 return Response.json({ sum: await ctx.exports.Ledger.add(20, 22) });
104
105 // The returned function is a stub; calling it runs in the entrypoint.
106 case "/adder": {
107 using addFive = await ctx.exports.Ledger.adder(5);
108 return Response.json({ sum: await addFive(37) });
109 }
110
111 // The function argument is a stub the entrypoint calls back.
112 case "/callback": {
113 const steps = [];
114 const total = await ctx.exports.Ledger.tally([1, 2, 3], (v, running) => {
115 steps.push({ v, running });
116 });
117 return Response.json({ total, steps });
118 }
119
120 // An RpcTarget crosses as a live object, and `using` disposes the stub.
121 case "/receipt": {
122 using receipt = await ctx.exports.Ledger.open("acct-1", 100);
123 return Response.json({ describe: await receipt.describe() });
124 }
125
126 // Promise pipelining: no await on open(), so both hops leave together.
127 case "/pipeline": {
128 const describe = await ctx.exports.Ledger.open("acct-9", 7).describe();
129 return Response.json({ describe });
130 }
131
132 default:
133 return Response.json({ balance: await account.balance() });
134 }
135 },
136};