Repository navigation
Expand file tree
/
Copy pathguide.html
More file actions
621 lines (553 loc) · 30.3 KB
/
Copy pathguide.html
File metadata and controls
621 lines (553 loc) · 30.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
<!doctype html>
<html lang="en" data-theme="light">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>moonrpc — Guide</title>
<meta name="description" content="A progressive guide to moonrpc: define messages from a .proto or as annotated structs, handle the four gRPC call kinds, run the pure client/server engines in memory or over a real socket, and compile a Thrift IDL to the same kinds of service.">
<link rel="icon" type="image/svg+xml" href="assets/favicon.svg">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600&family=Newsreader:opsz,wght@6..72,500;6..72,600&family=Caveat:wght@500;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="assets/site.css">
<script>try{var t=localStorage.getItem("moonrpc-theme");document.documentElement.setAttribute("data-theme",(t==="dark"?"dark":"light"));}catch(e){document.documentElement.setAttribute("data-theme","light");}</script>
</head>
<body>
<nav class="topnav">
<a class="brand" href="index.html">
<svg viewBox="0 0 32 32" fill="none" aria-hidden="true">
<rect x="3.5" y="3.5" width="25" height="25" style="stroke:var(--struct)" stroke-width="1.5"/>
<line x1="3.5" y1="3.5" x2="28.5" y2="28.5" style="stroke:var(--struct)" stroke-width="0.75" stroke-dasharray="2 2"/>
<line x1="28.5" y1="3.5" x2="3.5" y2="28.5" style="stroke:var(--struct)" stroke-width="0.75" stroke-dasharray="2 2"/>
<circle cx="16" cy="16" r="4" style="fill:var(--op)"/>
<circle cx="16" cy="16" r="7.5" style="stroke:var(--struct)" stroke-width="0.75"/>
<circle cx="8" cy="8" r="1.6" style="fill:var(--struct)"/>
<circle cx="24" cy="24" r="1.6" style="fill:var(--struct)"/>
<circle cx="24" cy="8" r="1.6" style="fill:var(--struct)"/>
<circle cx="8" cy="24" r="1.6" style="fill:var(--struct)"/>
</svg>
moonrpc
</a>
<div class="navlinks">
<a href="index.html">Home</a>
<a href="guide.html" class="active">Guide</a>
<a href="api.html">API</a>
<a href="showcase.html">Showcase</a>
<button class="nav-theme" data-theme-toggle aria-label="toggle theme">◐ theme</button>
<a class="gh" href="https://github.com/moonbitstack/moonrpc" rel="noopener">
<svg viewBox="0 0 16 16" aria-hidden="true" style="fill:currentColor"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.01 8.01 0 0 0 16 8c0-4.42-3.58-8-8-8z"/></svg>
GitHub
</a>
</div>
</nav>
<header class="section wrap hero">
<div class="eyebrow">guide</div>
<h1>From a message to a stream</h1>
<p class="tag">A walk through moonrpc: define a message, handle a call, run the two pure engines in memory, then put a real socket in front of them. Every snippet uses the API as it ships.</p>
<p>
<a class="btn" href="showcase.html">Try it live</a>
<a class="btn ghost" href="api.html">Full API</a>
</p>
<div class="style-bar" data-style-bar>
<span class="k">writing style</span>
<button type="button" data-style="annotation" class="on">Annotation</button>
<button type="button" data-style="functional">Functional</button>
<button type="button" data-style="class">Class</button>
</div>
<p class="note" style="margin-top:.6rem"><span class="src"></span> The switch changes the service-definition examples in §4 and §12; protocol-level snippets are the same in all three styles.</p>
</header>
<section class="section wrap">
<h2 class="h">1 · Install</h2>
<p class="lede">Add the package with the MoonBit toolchain. The root package re-exports the pure engines and every typed helper, so one import is enough.</p>
<pre><code>$ moon add moonbitstack/moonrpc
import "moonbitstack/moonrpc" // @moonrpc
// sockets, when you need them:
import "moonbitstack/moonrpc/net" // @net (native only)</code></pre>
<p class="note"><span class="src"></span> <code>@net</code> is flagged <code>supported_targets="native"</code>; everything under <code>@moonrpc</code> compiles to JS, native and Wasm.</p>
</section>
<section class="section wrap">
<h2 class="h">2 · Two pure engines</h2>
<p class="lede">A gRPC call is two state machines trading HTTP/2 frames. <code>H2Client</code> and <code>H2Server</code> are <b>pure</b>: you hand each one a frame, it returns the frames to send back. No socket, no I/O — just data in, data out. That is why the same code runs in a server and in the <a href="showcase.html">browser showcase</a>.</p>
<pre><code>let server = @moonrpc.H2Server::new()
let client = @moonrpc.H2Client::new()
// client.unary opens a stream and returns the first frames to send
let (id, frames) = client.unary("/greet.Greeter/SayHello", request_bytes)
// shuttle frames between the engines until the call finishes
while !client.is_done(id) {
for f in frames { for r in server.feed(f) { /* frames to client */ } }
// ... and back: client.feed(r) -> frames to server
}</code></pre>
<p class="note"><span class="src"></span> See the whole loop in <code>src/examples/07-unary-call</code>. The homepage shows the nine frames a single unary call produces.</p>
</section>
<section class="section wrap">
<h2 class="h">3 · Define a message</h2>
<p class="lede">A message is just bytes on the wire, packed by the protobuf codec. You can do it by hand, or let <code>#rpc.message</code> derive the codec from the struct.</p>
<h3>With <code>#rpc.message</code></h3>
<p class="lede">The annotation derives <code>@moonrpc.Message</code>.</p>
<pre><code>#rpc.message
pub struct HelloRequest {
#rpc.field(number="1")
name : String
}
#rpc.message
pub struct HelloReply {
#rpc.field(number="1")
name : String
}
#rpc.enum
pub enum Mood { Calm = 0; Glad = 1 } // MOOD_CALM = 0, MOOD_GLAD = 1
#rpc.message
pub struct Profile {
mood : Mood // an enum field
scores : Map[String, Int64] // map<string, int64>
nickname : String? // proto3 optional
}</code></pre>
<h3>By hand</h3>
<pre><code>fn encode_request(name : String) -> Bytes {
let w = @moonrpc.PbWriter::new()
w.string_(1, name) // field 1, wire type LengthDelimited
w.to_bytes()
}
fn decode_name(msg : Bytes) -> String {
let r = @moonrpc.PbReader::new(msg)
let _ = r.read_tag() // consume the tag for field 1
r.read_string()
}</code></pre>
<p class="note"><span class="src"></span> <code>#rpc.field(number="…")</code> pins the protobuf tag. Omitted fields get consecutive numbers; <code>#rpc.skip</code> leaves a field out of the wire form. An enum's values take MoonBit's own tags, or count up from 0.</p>
</section>
<section class="section wrap">
<h2 class="h">4 · Handle a unary call</h2>
<p class="lede">Register a path and a function from request bytes to reply bytes. For typed messages, <code>@moonrpc.unary</code> decodes the input and encodes the output for you.</p>
<pre><code>let server = @moonrpc.H2Server::new()
// hand-rolled: request bytes -> reply bytes
server.register("/greet.Greeter/SayHello", req => {
let name = decode_name(req)
let w = @moonrpc.PbWriter::new()
w.string_(1, "hello, " + name)
w.to_bytes()
})
// typed: works once HelloRequest / HelloReply are #rpc.message
server.register_handler(
"/greet.Greeter/SayHello",
@moonrpc.unary(fn (_ctx : @moonrpc.RpcContext, req : HelloRequest) -> HelloReply {
{ name : "hello, " + req.name }
}),
)</code></pre>
<p class="lede" style="margin-top:1.2rem">Or describe the whole service once and let <code>#rpc</code> wire it up:</p>
<pre><code>#rpc.service(name="greet.Greeter")
pub struct Greeter {}
#rpc.method
pub fn Greeter::say_hello(
self : Greeter, _ctx : @moonrpc.RpcContext, req : HelloRequest,
) -> HelloReply {
{ name : "hello, " + req.name }
}
// later:
let greeter = Greeter::{}
greeter.register(server) // generated by #rpc.service</code></pre>
<p class="lede" style="margin-top:1.2rem">The same service in the other two forms — switch the writing style at the top of the page:</p>
<!-- BEGIN guide-styles -->
<div class="styles" data-style-group data-active="annotation">
<div class="variant" data-style="annotation"><div class="vhead">Annotation</div><pre><code>///|
/// The guide's annotation variant: a message, a service and its method, all
/// declared with `#rpc`. `cmd/rpc` writes `service.g.mbt` from this file.
#rpc.message
pub struct HelloRequest {
name : String
}
///|
#rpc.message
pub struct HelloReply {
message : String
}
///|
#rpc.service(name="greet.Greeter")
pub struct Greeter {}
///|
#rpc.method
fn Greeter::say_hello(self : Greeter, req : HelloRequest) -> HelloReply {
ignore(self)
{ message: "Hello, " + req.name, }
}</code></pre><pre class="out"><code>Hello, Ada</code></pre></div>
<div class="variant" data-style="functional"><div class="vhead">Functional</div><pre><code>///|
/// Run the same greeter registered as functions on the server.
///
/// moon run src/examples/guide/functional
fn encode_request(name : String) -> Bytes {
let w = @moonrpc.PbWriter::new()
w.string_(1, name)
w.to_bytes()
}
///|
fn decode_name(msg : Bytes) -> String {
try {
let r = @moonrpc.PbReader::new(msg)
let _ = r.read_tag()
r.read_string()
} catch {
_ => ""
}
}
///|
fn encode_reply(message : String) -> Bytes {
let w = @moonrpc.PbWriter::new()
w.string_(1, message)
w.to_bytes()
}
///|
fn decode_reply(msg : Bytes) -> String {
try {
let r = @moonrpc.PbReader::new(msg)
let _ = r.read_tag()
r.read_string()
} catch {
_ => ""
}
}
///|
fn main {
let reply = @harness.round_trip(
server => {
server.register_unary("/greet.Greeter/SayHello", (_ctx, req) => {
encode_reply("Hello, " + decode_name(req))
})
},
"/greet.Greeter/SayHello",
encode_request("Ada"),
) catch {
_ => abort("the call failed")
}
println(decode_reply(reply))
}</code></pre><pre class="out"><code>Hello, Ada</code></pre></div>
<div class="variant" data-style="class"><div class="vhead">Class</div><pre><code>///|
/// Run the same greeter written as a struct with methods.
///
/// moon run src/examples/guide/class
struct Greeter {
prefix : String
}
///|
fn encode_request(name : String) -> Bytes {
let w = @moonrpc.PbWriter::new()
w.string_(1, name)
w.to_bytes()
}
///|
fn decode_name(msg : Bytes) -> String {
try {
let r = @moonrpc.PbReader::new(msg)
let _ = r.read_tag()
r.read_string()
} catch {
_ => ""
}
}
///|
fn encode_reply(message : String) -> Bytes {
let w = @moonrpc.PbWriter::new()
w.string_(1, message)
w.to_bytes()
}
///|
fn decode_reply(msg : Bytes) -> String {
try {
let r = @moonrpc.PbReader::new(msg)
let _ = r.read_tag()
r.read_string()
} catch {
_ => ""
}
}
///|
fn Greeter::say_hello(self : Greeter, req : Bytes) -> Bytes {
encode_reply(self.prefix + ", " + decode_name(req))
}
///|
fn Greeter::register(self : Greeter, server : @moonrpc.H2Server) -> Unit {
server.register_unary("/greet.Greeter/SayHello", (_ctx, req) => {
self.say_hello(req)
})
}
///|
fn main {
let reply = @harness.round_trip(
server => Greeter::{ prefix: "Hello", }.register(server),
"/greet.Greeter/SayHello",
encode_request("Ada"),
) catch {
_ => abort("the call failed")
}
println(decode_reply(reply))
}</code></pre><pre class="out"><code>Hello, Ada</code></pre></div>
</div>
<!-- END guide-styles -->
<p class="note"><span class="src"></span> The method's type decides the call kind: a plain reply is unary, an <code>Array[…]</code> reply is server-streaming, an <code>Array[…]</code> request is client-streaming, and both is bidi.</p>
</section>
<section class="section wrap">
<h2 class="h">5 · Run it in memory</h2>
<p class="lede">Because the engines are pure, a full call needs no socket — only the frame shuttle. This is the exact shape the showcase runs in your browser.</p>
<pre><code>let server = @moonrpc.H2Server::new()
server.register("/greet.Greeter/SayHello", req => /* … */)
let client = @moonrpc.H2Client::new()
let (id, to_server) = client.unary("/greet.Greeter/SayHello", encode_request("heke"))
let mut to_client : Array[@http2.Frame] = []
let mut steps = 0
while !client.is_done(id) && steps < 100000 {
steps = steps + 1
for f in to_server { for r in server.feed(f) { to_client.push(r) } }
to_server = []
for r in to_client { for f in client.feed(r) { to_server.push(f) } }
to_client = []
}
let reply = client.reply(id)
println("grpc-status \{reply.grpc_status}")
println("reply: \{decode_name(reply.messages[0])}")</code></pre>
</section>
<section class="section wrap">
<h2 class="h">6 · Serve it for real</h2>
<p class="lede">To actually accept TCP connections you add the native socket layer. <code>@net.GrpcServer</code> wraps an engine and listens on a port — native only, because MoonBit's async runtime has no JS/Wasm sockets.</p>
<pre><code>let greeter = Greeter::{}
let server = @net.GrpcServer::new()
greeter.register(server) // the #rpc-generated registrar
server.serve() // listens on :12000 (native target)
// elsewhere, the client #rpc.service generates alongside:
let client = GreeterClient::new(@net.Channel::connect("127.0.0.1", @net.port))
let reply = client.say_hello({ name: "heke" }) // a HelloReply, or a StatusError</code></pre>
<p class="note"><span class="src"></span> Build with <code>moon build --target native</code>. The engines you tested in memory are the same ones serving here.</p>
</section>
<section class="section wrap">
<h2 class="h">7 · The four call kinds</h2>
<p class="lede">All four are the same frame machinery; only the number of messages each side sends differs. Each has a typed wrapper under <code>@moonrpc</code>.</p>
<table class="fieldtbl">
<thead><tr><th>Kind</th><th>Request</th><th>Reply</th><th>Typed wrapper</th></tr></thead>
<tbody>
<tr><td class="mono">Unary</td><td>one</td><td>one</td><td class="mono">@moonrpc.unary</td></tr>
<tr><td class="mono">Server streaming</td><td>one</td><td>many</td><td class="mono">@moonrpc.server_streaming</td></tr>
<tr><td class="mono">Client streaming</td><td>many</td><td>one</td><td class="mono">@moonrpc.client_streaming</td></tr>
<tr><td class="mono">Bidi streaming</td><td>many</td><td>many</td><td class="mono">register_bidi + BidiHandler</td></tr>
</tbody>
</table>
<pre><code>// server streaming: one request, a sequence back
server.register_handler(
"/demo.Counter/Up",
@moonrpc.server_streaming(fn (_ctx, _req : UpRequest) -> Array[UpReply] {
[{ n : 1 }, { n : 2 }, { n : 3 }]
}),
)</code></pre>
<p class="note"><span class="src"></span> Run all four live in the <a href="showcase.html">Showcase</a> — each shows the frames it produces.</p>
</section>
<section class="section wrap">
<h2 class="h">8 · Status and errors</h2>
<p class="lede">Raise a <code>StatusError</code> and the engine answers the call with that grpc-status and message in the trailers. Any other error becomes <code>UNKNOWN</code>.</p>
<pre><code>server.register_handler(
"/greet.Greeter/SayHello",
@moonrpc.unary(fn (_ctx, req : HelloRequest) -> HelloReply raise {
if req.name == "" {
raise @wire.StatusError(@wire.Status::InvalidArgument, "name required")
}
{ name : "hello, " + req.name }
}),
)
// on the client:
let reply = client.reply(id)
// reply.grpc_status -> Int32 (0 = OK)
// reply.grpc_message -> String</code></pre>
</section>
<section class="section wrap">
<h2 class="h">9 · TLS</h2>
<p class="lede">HTTP/2 over TLS is chosen by ALPN: both ends name <code>h2</code> in the handshake and check what it settled on before a frame is exchanged. <code>@net.server_tls</code> and <code>@net.client_tls</code> build the two configurations with <code>h2</code> alone, so the agreement cannot be forgotten.</p>
<pre><code>// the server: a certificate chain, leaf first, and its key
let server = @net.GrpcServer::new()
greeter.register(server)
server.serve(port=12000, tls=@net.server_tls(@x509.pems(cert_text), @x509.PrivateKey::pem(key_text)))
// the client: the CA that signed the server, and nothing else to configure
let chan = @net.Channel::connect("api.example.com", 12000, tls=@net.client_tls(ca_roots))
let reply = chan.unary("/greet.Greeter/SayHello", request)</code></pre>
<p class="note"><span class="src"></span> <code>MuxChannel::connect</code>, <code>ManagedChannel::connect</code> and <code>dns_connect</code> take the same <code>tls</code>. A peer that offers no <code>h2</code> is closed rather than spoken to in a version it did not agree to, and a handshake failure on <code>serve</code> is a refused client, not a broken server.</p>
</section>
<section class="section wrap">
<h2 class="h">10 · Interceptors</h2>
<p class="lede">One interceptor shape covers all four call kinds, on both ends: a call is the request messages it carries and the replies they produce.</p>
<pre><code>// server: (info, ctx, requests, next) -> replies
server_engine.add_interceptor((info, ctx, requests, next) => {
let started = @async.now()
let replies = next(requests) // or answer here and never call it
println("\{info.path} took \{@async.now() - started} ms")
replies
})
// client: (invocation, next) -> reply
chan.add_interceptor((invocation, next) => {
let metadata = invocation.metadata.copy()
metadata.push({ name: b"authorization", value: b"Bearer ..." })
next({ ..invocation, metadata })
})</code></pre>
<p class="note"><span class="src"></span> An interceptor sees <code>CallInfo</code> — the path and which sides stream — so passing unary calls through untouched and handling only those is one <code>if</code>. The client chain wraps a call once, outside the retry loop: a retry is one invocation to an interceptor.</p>
</section>
<section class="section wrap">
<h2 class="h">11 · Compression</h2>
<p class="lede">gRPC names three encodings — <code>identity</code>, <code>gzip</code> and <code>deflate</code> — and negotiates them with <code>grpc-encoding</code> and <code>grpc-accept-encoding</code>. Set one and messages go compressed; a peer that did not ask for it still gets identity.</p>
<pre><code>// the server answers in gzip to a caller that accepts it
let server = @net.GrpcServer::new()
server.set_encoding(@moonrpc.Encoding::Gzip)
greeter.register(server)
// the client compresses its own requests, and decodes whatever comes back
let chan = @net.Channel::connect("127.0.0.1", 12000, encoding=@moonrpc.Encoding::Gzip)
let reply = chan.unary("/greet.Greeter/SayHello", request)</code></pre>
<p class="note"><span class="src"></span> A message whose compression flag is set under <code>identity</code> — compressed and not compressed at once — is refused rather than read as plaintext, and a body that will not inflate fails the call with <code>INTERNAL</code>.</p>
</section>
<section class="section wrap">
<h2 class="h">12 · Three ways to write the same service</h2>
<p class="lede">moonrpc accepts the same service three ways. The annotations come first: they generate the protobuf codec, the registration and the descriptor reflection serves. The functional form registers handlers directly on the server; the class form keeps state on a struct and registers its methods. All three answer the same request with the same bytes.</p>
<p class="note"><span class="src"></span> The three variants are the same service as §4; switch them with the bar at the top of the page, where the choice is remembered. Protocol-level sections — frames, HPACK, TLS, compression — are identical in all three styles, so they are shown once.</p>
</section>
<section class="section wrap">
<h2 class="h">13 · From a .proto file</h2>
<p class="lede">A service usually arrives as a <code>.proto</code> file. Nothing is generated from that file here: it is the schema the other side of the connection compiles, and the declarations the generator reads are the same schema written out in MoonBit. Two descriptions of one service are safe only while something holds them together, so the file compiles at run time as well, and what it says is checked against what the declarations say.</p>
<pre><code>// notice.proto
syntax = "proto3";
package notice.v1;
enum Level {
LEVEL_UNSPECIFIED = 0;
LEVEL_QUIET = 1;
LEVEL_LOUD = 5;
}
message Notice {
string title = 1;
repeated string tags = 4;
optional string body = 5;
Level level = 6;
map<string, int64> counts = 7;
}</code></pre>
<pre><code>// notice.mbt — the same schema as declarations
#rpc.enum
pub enum Level { Unspecified = 0; Quiet = 1; Loud = 5 }
#rpc.message
pub struct Notice {
title : String
#rpc.field(number="4")
tags : Array[String]
body : String? // optional
level : Level // Level level
counts : Map[String, Int64] // map<string, int64>
}</code></pre>
<p class="note"><span class="src"></span> Fields are numbered in declaration order from 1, so only a field that skips a number carries one; moving a field in the struct moves its tag. Enum values are numbered by their MoonBit tags and named after the enum and themselves, which is why <code>Quiet</code> is <code>LEVEL_QUIET</code>. A file is named after the declaration file it is written from — <code>notice.mbt</code> describes <code>notice.proto</code> — and the package is the part of the service's name before the service.</p>
<p class="lede">From those declarations <code>cmd/rpc</code> writes the codec of every message, the registration of the service, a typed client, and the descriptor reflection serves. The service declarations are the same ones §4 shows; what the generator adds is the wire form each message already carries a tag for.</p>
<pre><code>// what cmd/rpc writes for greet.mbt — greet.g.mbt, generated, never edited by hand
pub fn[R : @moonrpc.Registrar] Greeter::register(self : Greeter, server : R) -> Unit {
server.register_handler(
"/greet.v1.Greeter/SayHello",
@moonrpc.unary((ctx, req : HelloRequest) => Greeter::say_hello(self, ctx, req)),
)
// CountTo with server_streaming, Sum with client_streaming, Echo with bidi
}
pub struct GreeterClient[C] { channel : C }
pub async fn[C : @moonrpc.Caller] GreeterClient::say_hello(
self : GreeterClient[C],
req : HelloRequest,
metadata? : Array[@moonrpc.Header],
timeout_millis? : Int32,
retry? : @moonrpc.Retry,
) -> HelloReply {
self.channel.invoke(
"/greet.v1.Greeter/SayHello",
[@moonrpc.Message::encode(req)],
metadata.unwrap_or([]),
timeout_millis,
retry,
).reply()
}
pub fn descriptor() -> @moonrpc.FileDescriptor // the file reflection serves</code></pre>
<p class="note"><span class="src"></span> The declarations decide the call kind, so there is one handler shape per RPC and a client method that returns what the reply is: a message, an array of them, or an array folded from a client stream. <code>oneof</code>, <code>import</code> and custom options are not expressible as annotations yet — a file using them needs those messages written by hand, and the descriptor model does carry oneofs when they are.</p>
<pre><code>// the file, compiled at run time: the descriptor and the JSON mapping in one value
let schema = @moonrpc.Schema::compile([("notice.proto", text)])
// a message the generated codec wrote, read back by the schema the .proto compiled to
let json = schema.to_json(".notice.v1.Notice", bytes)
let same = schema.to_bytes(".notice.v1.Notice", json) == bytes</code></pre>
<p class="note"><span class="src"></span> <code>src/examples/30-proto-source</code> runs that in full and fails loudly when the two drift: the descriptor the file produces against the one the declarations produce, the octets of each, the JSON spelling — lowerCamelCase names, enums by name, <code>int64</code> as a string — and one call on the generated service. The descriptor is also what reflection serves, so a peer can ask the running server for the shape of the file.</p>
</section>
<section class="section wrap">
<h2 class="h">14 · Thrift beside gRPC</h2>
<p class="lede">The same module also speaks Apache Thrift: <code>TBinaryProtocol</code> and <code>TCompactProtocol</code> over <code>TFramedTransport</code>, written against one <code>Protocol</code> trait, so the processor, the client request and <code>skip</code> exist once. A Thrift peer is a different conversation from a gRPC one — nothing here goes through HTTP/2.</p>
<pre><code>// serve it on 9090; a Compact here would be the other protocol, same service
let processor = @thrift.Processor::new()
processor.add("ping", proto => {
ignore(proto.read_field_begin()) // field 1: the argument
let text = proto.read_string()
ignore(proto.read_field_begin()) // STOP
proto.write_field_begin(@thrift.type_string, 0) // field 0: the result
proto.write_string("pong:" + text)
})
@net.serve_thrift(
host="127.0.0.1", port=9090, processor, () => @thrift.Binary::new(b""),
)
// the client, over the same protocol object
let proto : &@thrift.Protocol = @thrift.Compact::new(b"")
let client = @net.ThriftClient::connect("127.0.0.1", 9090, proto)
let pong = @thrift.call(client, proto, "ping", 1, proto => {
proto.write_field_begin(@thrift.type_string, 1)
proto.write_string("moonrpc")
}, proto => proto.read_string())</code></pre>
<p class="note"><span class="src"></span> A call is one framed round trip. The flag picks the bytes, not the service: the two protocols differ in how a field is numbered and how a double is ordered, and the trait is what keeps that difference in one place.</p>
<p class="lede">Writing those bytes by hand gets old, so <code>cmd/thriftc</code> compiles the IDL instead: types with their codecs, each service's registration and client, and the constants.</p>
<pre><code>// greet.thrift — the shapes the compiler reads
typedef map<string, i32> Scores
exception Missing {
1: string message
}
union Contact {
1: string email
2: i64 phone
}
struct Person {
1: required string name
2: optional i32 age
3: Scores scores
}
const i32 MAX_AGE = 130
service Greeter {
string find(1: string key) throws (1: Missing missing)
}</code></pre>
<pre><code>// what thriftc writes
pub(all) struct Person { name : String, age : Option[Int32], scores : Map[String, Int32] }
pub(all) enum Contact { Email(String); Phone(Int64) }
pub(all) enum GreeterFindError { Missing(Missing) }
pub let maxAge : Int32 = 130
// a method that declares throws answers a Result, on both ends
find : (String) -> Result[String, GreeterFindError]
let found = greeter_find(transport, proto, "ada") // Result[String, GreeterFindError]</code></pre>
<p class="note"><span class="src"></span> <code>include</code> folds another file's types in under a prefix (<code>shared.Person</code> becomes <code>SharedPerson</code>) and <code>service Child extends Base</code> carries the base's methods into the child's registration. A <code>typedef</code> is substituted where it is used, so no alias reaches the generated code; a <code>union</code> becomes an enum that carries exactly one field. CI compiles the example with <code>--check</code>, so the generated file and the IDL cannot drift.</p>
<p class="lede">The type set is Thrift's rather than a convenient subset: <code>uuid</code> as sixteen raw bytes with no length in front, <code>set</code> with a field type of its own, structs nested inside structs, maps of maps. Two failures and one silence complete it — a handler that raises answers a <code>TApplicationException</code> instead of dropping the connection, and a method the IDL declares <code>oneway</code> runs without a reply.</p>
<pre><code>// a handler that fails answers an application exception, not silence
processor.add("find", proto => {
ignore(proto.read_field_begin())
let key = proto.read_string()
ignore(proto.read_field_begin())
if key == "ada" {
proto.write_field_begin(@thrift.type_string, 0)
proto.write_string("found")
} else {
raise @thrift.Application("no such key")
}
})
// a oneway method runs and answers nothing; the flag belongs to the method,
// because a client may send it as an ordinary CALL and never read a reply
processor.add_oneway("notify", proto => {
ignore(proto.read_field_begin())
ignore(proto.read_string())
})</code></pre>
<p class="note"><span class="src"></span> Apache Thrift's own cross test runs against this stack in both directions: their Go client calls the service served here, and the client here calls their Go server, in the binary and in the compact protocol. All 23 methods of <code>ThriftTest</code> — structs nested two deep, maps of maps, sets, a uuid, a <code>oneway</code> method, a value in field 0, a declared exception in its own field, and the application exception a failing handler produces — pass both ways. <code>src/cmd/thriftcrosstest</code> is this side of it, and <a href="https://github.com/moonbitstack/moonrpc#conformance">Conformance</a> lists what the suite covers and what it does not.</p>
</section>
<section class="section wrap">
<h2 class="h">Where to next</h2>
<p class="lede">The <a href="api.html">API reference</a> lists every public item by package. The <a href="showcase.html">Showcase</a> runs the real engine in your browser. The repository's <code>src/examples/*</code> cover HTTP/2 frames, HPACK, flow control, health, reflection, deadlines, retries, a <code>.proto</code> transcribed to declarations and checked against itself, the Thrift protocols and the IDL compiler.</p>
<p><a class="btn" href="index.html">Back to home</a></p>
</section>
<footer>
<div class="wrap">
<p><b>moonrpc</b> · MoonBit gRPC library · <a href="https://github.com/moonbitstack/moonrpc" rel="noopener">github.com/moonbitstack/moonrpc</a></p>
<p class="note">Snippets follow the shipped API; the engines they call are the same ones compiled into the showcase.</p>
</div>
</footer>
<script src="assets/site.js"></script>
</body>
</html>