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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
//! The serving half of [`crate::uds::rpc`]: a generic framed JSON-RPC server
//! over a hardened Unix socket (#6277, ADR-0032).
//!
//! Why: `uds::rpc` is the client — it dials, writes one frame, reads one back —
//! and nothing in this workspace owned the other end generically. The only
//! server-side accept loop was `webhook_relay::serve`, which is a single-purpose
//! durable-delivery contract: one method, an ack conditioned on an fsync, an
//! inbox. ADR-0032 puts every trusty-* service's own transport on UDS, so the
//! next service to migrate needed either a fourth hand-rolled accept loop or
//! this. `webhook_relay` is deliberately left untouched; its ordering rule is
//! the reason it exists and is not a thing to generalise.
//!
//! What, in the order a daemon uses them.
//! - [`RpcRouter`] is the caller's half: method names mapped to handlers over
//! the caller's own request and response types (see [`RpcRouter::typed`]).
//! A service that already has a generic `(method, params)` dispatcher
//! mounts it whole through [`RpcRouter::fallback`] instead (#6286). A method
//! that answers in many frames rather than one is registered with
//! [`RpcRouter::typed_stream`] — see the wire contract below.
//! - [`RpcServer::run`] is the whole body of a daemon — bind, serve, unlink.
//! - [`serve_until`] and [`handle_connection`] are that body's two halves,
//! public so a caller with its own bind (say
//! [`crate::uds::bind_singleton_hardened`], which takes over a stale socket
//! file where [`crate::uds::bind_hardened`] refuses) drives the loop itself.
//!
//! **The trust boundary is the socket, not the payload.** [`bind_hardened`]
//! puts the socket at `0600` inside a `0700` directory, and every accepted
//! connection runs [`ensure_peer_is_self`] before a single byte is read. No
//! CSRF, origin, or token machinery is ported from the HTTP shape those checks
//! replace — on a UDS socket it would guard nothing (#6277 design review).
//!
//! ## The wire contract, including streams (#6286)
//!
//! A request is one newline-terminated JSON-RPC frame, unchanged:
//!
//! ```text
//! {"jsonrpc":"2.0","id":7,"method":"chat","params":{…}}
//! ```
//!
//! plus ONE optional field, `"stream": true`. Absent means false, and false is
//! exactly the protocol as it stood — one request frame, one response frame,
//! connection closed. An old client and a new server therefore behave as they
//! always did, byte for byte, and so does a new client calling a method that
//! does not stream.
//!
//! A request that asks for a stream, against a method registered with
//! [`RpcRouter::typed_stream`], is answered with a SEQUENCE of frames on the
//! same connection, each newline-terminated and each carrying a `"stream"`
//! discriminant a plain response never has:
//!
//! ```text
//! {"jsonrpc":"2.0","id":7,"stream":"item","result":"Hel"}
//! {"jsonrpc":"2.0","id":7,"stream":"item","result":"lo"}
//! {"jsonrpc":"2.0","id":7,"stream":"end"}
//! ```
//!
//! **A stream terminates on a frame, never on EOF.** Exactly one terminal frame
//! is written on every path — `"stream":"end"` when the producer finishes, and
//! `"stream":"error"` carrying an [`RpcError`] when the handler fails mid-stream,
//! when it fails to open at all, or when an item does not fit the frame budget.
//! A client that reaches EOF without one reports it rather than returning what
//! it happened to receive: a truncated token stream read as a complete answer is
//! the Fail-Open branch this contract exists to close, and
//! `stream_reports_a_truncated_stream_rather_than_an_empty_success` is its
//! regression test.
//!
//! **The two mismatches both fail immediately, in the shape the caller reads.**
//! A request WITHOUT the flag against a streaming method gets one ordinary
//! response frame carrying [`CODE_STREAM_REQUIRED`]. A request WITH the flag
//! against anything that does not stream — a unary method, a fallback-served
//! name, an unknown name — gets one terminal `"stream":"error"` frame carrying
//! [`CODE_STREAM_UNSUPPORTED`], naming the methods this listener does stream.
//! Neither hangs, and neither leaves the caller decoding a frame shape it does
//! not expect.
//!
//! **The socket file is unlinked explicitly.** [`bind_hardened`] binds and
//! chmods; neither it nor `tokio::net::UnixListener`'s `Drop` removes the path,
//! so a server that just returned would leave a file the next start fails to
//! bind. [`RpcServer::run`] removes it — before dropping the listener, for the
//! reason `webhook_relay::listener` records: with the order reversed there is a
//! window where nothing answers the path but the file is still there, and a
//! successor that rebinds in that window has its fresh socket deleted by this
//! process's `remove_file`.
//!
//! Test: `tests.rs` — `dispatch_*` for the decision, `serve_*` for the socket.
use ;
use Arc;
use Duration;
use ;
use ;
use crate;
pub use ;
pub use ;
pub use ;
pub use ;
/// Everything that can stop this server, or stop one of its connections.
///
/// `#[non_exhaustive]` for the same reason [`UdsSecurityError`] carries it: the
/// list grows as the transport tightens, and no consumer matches it
/// exhaustively — they log it or convert it.
/// Per-connection budgets for [`serve_until`].
///
/// Test: `serve_rejects_an_oversized_frame`.
/// What one accepted connection turned out to be.
///
/// Why: a peer that connects and closes without writing is a liveness probe —
/// [`crate::uds::probe::socket_is_serving`] and `UdsServiceSupervisor` both do
/// exactly that. Collapsing it into the failure arm makes the one warning an
/// operator greps for fire on every successful health check.
/// Serve one accepted connection: verify the peer, read one frame, answer one.
///
/// Why: split out so a test can drive the wire behaviour against a plain
/// `UnixStream` pair without an accept loop.
/// What: refuses a peer whose uid is not our own, reads bytes up to the first
/// newline or EOF under [`RpcServeOptions::max_frame_bytes`], dispatches through
/// `router`, and writes the answer — one response frame for a unary call, or the
/// frame sequence the module docs' wire contract describes for a streaming one
/// (#6286).
///
/// # Errors
///
/// Any [`RpcServerError`] variant except `Bind`. An error here means no complete
/// answer was written and the client sees a transport failure — which is why
/// every failure the router can reason about is a frame instead. On a stream,
/// [`RpcServerError::Write`] mid-sequence is the client having gone away: the
/// producer stops when its receiver drops here, and the accept loop is
/// unaffected.
///
/// Test: `serve_round_trips_a_request_over_a_real_socket`,
/// `serve_rejects_an_oversized_frame`,
/// `handle_connection_reports_a_liveness_probe_rather_than_a_failure`,
/// `stream_round_trips_many_frames_over_a_real_socket`,
/// `stream_survives_a_client_that_disconnects_mid_stream`.
pub async
/// Accept and serve connections until `shutdown` resolves.
///
/// Why: the whole loop of a UDS daemon, so a service supplies a [`RpcRouter`]
/// and nothing else.
///
/// What: each connection is handed to `tokio::spawn` rather than served inline.
/// That is a REQUIREMENT, not a throughput preference: `uds::probe`'s
/// `SocketVerdict` docs record that on macOS a bound listener with a saturated
/// accept queue answers ECONNREFUSED, which a prober classifies as `NotServing`.
/// A server that dispatched inline would be read as dead under exactly the load
/// it was handling.
///
/// The listener is borrowed, not consumed, so a caller can unlink the socket
/// while it is still bound — see the module docs for why that order matters.
///
/// A connection that errors — or whose handler panics — is logged and dropped
/// without answering, and the loop keeps accepting.
///
/// Test: `serve_round_trips_a_request_over_a_real_socket`,
/// `serve_stops_on_shutdown`,
/// `serve_handles_concurrent_connections_without_serialising`,
/// `serve_survives_a_panicking_handler_and_answers_the_next_connection`.
pub async
/// Why a serve loop ended.
///
/// Why this is returned rather than logged: an on-demand service's caller
/// distinguishes the two — a shutdown is an operator or supervisor stopping the
/// process, an idle exit is the process reclaiming itself and is the normal end
/// of a successful lifetime. `trusty-analyze` prints a different line for each.
///
/// Test: `serve_until_idle_exits_when_the_window_elapses`,
/// `serve_stops_on_shutdown`.
/// How long an idle exit waits for a connection already in the kernel backlog.
///
/// Why (#6350): `connect(2)` against a listening socket succeeds the moment the
/// kernel queues it — the server need not have called `accept` yet. So a client
/// that dialled microseconds before the idle window elapsed is sitting in the
/// backlog, and a loop that returned straight from the idle arm would drop the
/// listener and unlink the socket with that client's connection still queued.
/// The client sees a reset, not a refusal, and only `trusty-review`'s adapter
/// retries one; `trusty-analyze deep` and `tctl`'s probe report it as a failure
/// the operator cannot act on.
///
/// What: 50ms is chosen against the cost of being wrong in each direction. A
/// queued connection is already in the backlog, so it is accepted on the first
/// poll and the window is never actually spent; the only case that spends it is
/// a genuinely idle service, which pays 50ms once in its whole lifetime.
const IDLE_EXIT_DRAIN: Duration = from_millis;
/// The future [`serve_until_idle`] races against `accept`.
///
/// Why a named function rather than an inline `async` block: two `async` blocks
/// have two different anonymous types, and the loop re-arms this one in place
/// after a drain. `Pin::set` needs the replacement to be the SAME type, which
/// only one `impl Future` origin gives.
///
/// What: [`IdleTracker::expired`] when a policy is configured. With none it
/// never resolves, so the arm is inert and the loop behaves as [`serve_until`]
/// always has.
async
/// What [`drain_backlog`] found in the backlog.
/// Which arm of [`serve_until_idle`]'s `select!` won.
///
/// Why an enum rather than the drain running inside the arm: the drain re-arms
/// the pinned idle future afterwards, and `Pin::set` cannot run while the
/// `select!` still holds the `&mut` borrow of it. Naming the winner ends that
/// borrow at the `select!`'s closing brace.
/// Serve one connection queued before the idle window elapsed, if any.
///
/// Why: see [`IDLE_EXIT_DRAIN`]. Resolving the race in the CLIENT's favour is
/// the only safe direction — serving one extra request costs a round trip,
/// while resetting a connection the client believes it made costs that client a
/// failure it has no way to distinguish from a broken service.
///
/// 🔴 Why only an ANSWERED connection cancels the exit: a bare connect-and-close
/// is what [`crate::uds::socket_is_serving`] does on a poll loop, and a drain
/// that treated one as activity would hand the poller exactly the power
/// [`IdleGuard`] exists to deny it — an observed livelock, not a hypothetical.
/// A probe caught in the drain is served and the exit proceeds.
///
/// Why the connection is served INLINE rather than spawned: this is the last
/// thing that happens before the caller unlinks the socket and drops the
/// listener, and a spawned task would race the process exit. Awaiting it is what
/// guarantees the client has its answer first. One connection, once per
/// lifetime.
///
/// Test: `a_client_queued_when_the_idle_window_elapses_is_served_not_reset`,
/// `serve_until_idle_ignores_liveness_probes`.
async
/// How often [`drain_shutdown`] re-reads the in-flight count.
///
/// Five milliseconds: the drain ends the moment the last handler releases its
/// guard, so this bounds how long a clean shutdown lingers past that release.
const DRAIN_POLL_INTERVAL: Duration = from_millis;
/// Let in-flight connections finish before the caller unlinks the socket
/// (#6601).
///
/// Why: the shutdown arm used to return the instant the signal resolved. Every
/// accepted connection holds an `Arc<RpcRouter>` clone — and through it whatever
/// the service's handlers own, a redb `Database` in `trusty-analyze`'s case — so
/// returning under an open connection unlinked the socket while those handles
/// were still live. The unlink is what tells a client to spawn a successor, and
/// the successor then died opening a store this process had not let go of
/// (#6595). Draining HERE gives that guarantee to every service behind this
/// loop rather than to the one caller that noticed.
///
/// What, while the count is above zero and the budget has not expired:
/// - the accept loop is over, so nothing new is served; and
/// - a client that dials anyway is accepted and IMMEDIATELY closed, which
/// reaches it as `UdsRpcError::NoResponse` on the next poll. Leaving it in
/// the backlog instead would hold it open until the listener dropped and
/// then reset it — a failure the client cannot tell from a broken service.
///
/// A budget that expires warns and returns: the process is exiting on a signal
/// either way, and holding the path open longer trades one hazard for a socket
/// file nobody unlinks.
///
/// Connections queued in the kernel backlog but never accepted are NOT counted —
/// `connect(2)` succeeds before this server sees anything. Those are refused by
/// the loop above when a drain is running, and reset by the listener drop when
/// there was nothing to drain.
///
/// Test: `shutdown_drains_an_in_flight_connection_before_it_returns`,
/// `shutdown_refuses_a_connection_dialled_after_the_signal`,
/// `shutdown_returns_when_the_drain_budget_expires`.
async
/// [`serve_until`], plus an optional idle-exit policy (#6350).
///
/// Why: ADR-0032 makes `trusty-analyze` an on-demand service — clients spawn it
/// and nothing supervises it — so the accept loop is the only place that knows
/// enough to end the process. It has to be here rather than in a timer the
/// service arms itself, because "idle" means no connection is OPEN and none has
/// answered recently, and only this loop observes both.
///
/// What: identical to [`serve_until`] with `idle` as `None`. With a tracker, the
/// loop additionally races [`IdleTracker::expired`] against `accept` and returns
/// [`ServeExit::Idle`] when it wins. Each accepted connection holds an
/// [`IdleGuard`] for its lifetime, so the window can never elapse under an open
/// connection; the guard is marked answered only for a connection that produced
/// a response, which is what keeps a liveness-probe poll loop from pinning the
/// process alive.
///
/// #6621: a response to a method registered with [`RpcRouter::mark_liveness`]
/// does not mark the guard either. A monitor that dials a health METHOD instead
/// of connecting and closing was otherwise indistinguishable from a client doing
/// work, and pinned an on-demand `trusty-analyze` process resident for 46 hours.
///
/// #6350: an expired window does not exit immediately. [`drain_backlog`] first
/// gives the kernel backlog [`IDLE_EXIT_DRAIN`] to yield a connection that was
/// queued before the window elapsed; one that appears is served like any other
/// and the loop continues, so the exit only stands when nobody was waiting.
///
/// #6601: the shutdown arm drains too. Every accepted connection is counted —
/// with an idle policy or without one — and the signal runs [`drain_shutdown`]
/// before [`ServeExit::Shutdown`] is returned, so the caller's unlink never
/// lands on top of a handler that is still holding the router.
///
/// Test: `serve_until_idle_exits_when_the_window_elapses`,
/// `serve_until_idle_is_reset_by_an_answered_request`,
/// `serve_until_idle_ignores_liveness_probes`,
/// `serve_until_idle_ignores_a_registered_liveness_method`,
/// `serve_until_idle_is_held_open_by_a_non_liveness_call`,
/// `a_client_queued_when_the_idle_window_elapses_is_served_not_reset`,
/// `shutdown_drains_an_in_flight_connection_before_it_returns`,
/// `shutdown_refuses_a_connection_dialled_after_the_signal`,
/// `shutdown_returns_when_the_drain_budget_expires`.
pub async
/// A framed JSON-RPC server bound to one hardened socket.
///
/// Why: the shape a daemon's `serve` command wants — one value carrying the
/// path, the methods and the budgets, with [`run`] as its whole body.
/// What: [`RpcServer::run`] binds through [`bind_hardened`], serves until the
/// caller's shutdown future resolves, then unlinks the socket file.
/// Test: `server_round_trips_and_removes_its_socket_on_shutdown`.
///
/// [`run`]: RpcServer::run