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
use std::io::Read;
use std::net::{SocketAddr, TcpStream};
use std::os::fd::AsRawFd;
use std::sync::{Arc, Mutex};
use beamr::atom::Atom;
use beamr::native::native_process::{NativeContext, NativeHandler, NativeOutcome};
use beamr::process::ExitReason;
use beamr::scheduler::{Interest, ReadinessToken};
use beamr::term::Term;
use liminal::protocol::{Frame, ProtocolError, decode};
use super::apply::apply_frame;
use super::delivery::{DELIVERY_SLICE_BUDGET, service_subscriptions};
use super::outbound::{DrainOutcome, OutboundWriter};
use super::services::server_error_from_protocol;
use super::state::{ConnectionProcessState, FrameAction, ProcessStatus};
use super::supervisor::{ConnectionControl, ConnectionRuntime};
use crate::ServerError;
#[cfg(test)]
#[path = "process_teardown_tests.rs"]
mod teardown_tests;
#[cfg(test)]
#[path = "process_wake_tests.rs"]
mod wake_tests;
const READ_BUFFER_BYTES: usize = 8192;
/// Application stream id used for server-initiated push frames. Push is an
/// application-stream frame (non-zero stream id), like publish and conversation.
const PUSH_STREAM_ID: u32 = 1;
#[derive(Debug)]
pub(super) struct ConnectionProcess {
runtime: Arc<ConnectionRuntime>,
peer_addr: Option<SocketAddr>,
stream: Option<TcpStream>,
buffer: Vec<u8>,
state: ConnectionProcessState,
/// Per-connection outbound byte buffer. EVERY server-originated frame (acks,
/// errors, `Push`, `Disconnect`, `Pong`, `Deliver`, ...) is enqueued here and
/// drained cooperatively on the slice loop with partial-write tracking, so a
/// frame larger than the socket send buffer streams out across slices instead
/// of failing a `write_all` on the non-blocking socket (ledger G4).
outbound: OutboundWriter,
/// One registration for this connection's lifetime. The same token is copied
/// into the host record so external death can deregister it.
readiness_token: Option<ReadinessToken>,
}
/// Whether a connection slice's socket/inbound servicing leaves the connection
/// running or has already resolved its lifecycle.
enum SliceStep {
Continue,
Stop(ExitReason),
}
impl ConnectionProcess {
pub(super) fn from_holder(
runtime: Arc<ConnectionRuntime>,
peer_addr: Option<SocketAddr>,
holder: &Arc<Mutex<Option<TcpStream>>>,
) -> Self {
// The `NativeHandlerFactory` is `Fn + Send + Sync`, so the accepted
// `TcpStream` cannot be moved into the closure (a `Fn` captures by shared
// reference and may be invoked more than once for restart). The shared
// `Arc<Mutex<Option<TcpStream>>>` is the interior-mutability proxy that
// lets the FIRST handler build take the stream out exactly once; the
// Mutex is required by the `Sync` bound, not incidental.
//
// If the lock is poisoned the take silently yields `None`, and the
// process would later stop with a bare crash and no root cause. Log the
// poisoning clearly (with the peer address) so a missing-stream handoff
// is diagnosable instead of a mystery crash.
let stream = match holder.lock() {
Ok(mut held) => held.take(),
Err(poisoned) => {
tracing::error!(
peer_addr = ?peer_addr,
error = %poisoned,
"connection stream handoff failed: stream holder mutex was poisoned; \
the connection process will start without a stream and stop immediately"
);
None
}
};
// Build the pending-reply table from the runtime's configured ยง5 caps
// (R1(vi), ยง1.2(3b)). The default table carries the signed defaults; this
// uses the connection's actual limits.
let limits = runtime.limits();
let pending_replies = super::pending_reply::PendingReplyTable::new(
limits.max_pending_replies_per_conversation,
limits.max_pending_conversation_replies_per_connection,
super::pending_reply::DEFAULT_REPLY_TIMEOUT,
);
let state = ConnectionProcessState {
pending_replies,
..ConnectionProcessState::default()
};
Self {
runtime,
peer_addr,
stream,
buffer: Vec::new(),
state,
outbound: OutboundWriter::new(),
readiness_token: None,
}
}
/// Runs one connection scheduler slice: service inbound socket/control work,
/// then service subscriptions into the outbound buffer, then drain the
/// outbound buffer to the socket.
///
/// The ordering is load-bearing (subscriptions are pumped AFTER socket/control
/// work), and the whole slice preserves the no-sleep `Continue` discipline: a
/// slice never parks a scheduler thread, it re-queues the process to poll again.
fn handle_slice(&mut self, pid: u64, ctx: &mut NativeContext<'_>) -> NativeOutcome {
// R7 (ยง1.2(6)): count this serviced slice. The park-flip's permanent
// rule-1 quiescence assertion โ a parked connection's counter must not
// advance without an event โ reads this; under the busy loop the counter
// advances every slice, and the instrument proves it counts.
#[cfg(test)]
self.runtime.record_slice(pid);
// `spawn_native` may schedule the first slice before the spawn thread has
// inserted the host record. Do not mint an unpublishable token; yield once
// and register after the record exists.
if !self.runtime.is_registered(pid) {
return NativeOutcome::Continue;
}
match self.service_socket(pid) {
SliceStep::Stop(reason) => return NativeOutcome::Stop(reason),
SliceStep::Continue => {}
}
// R1(vi) (ยง1.2(3b)): service the pending-reply table each slice โ expire
// due deadlines (writing timeout frames) and drain/correlate any replies
// the participants produced. A fatal outbound condition here tears the
// connection down, matching the delivery path.
if let Err(error) = self.service_pending_replies() {
tracing::warn!(
connection_pid = pid,
%error,
"outbound overflow while writing conversation replies; tearing down"
);
self.release_conversations();
self.runtime
.mark_crashed(pid, ExitReason::Error, self.peer_addr);
return NativeOutcome::Stop(ExitReason::Error);
}
// Pump subscriptions into the outbound buffer. An overflow (or an encode
// fault) is fatal: a dropped or truncated delivery would desync the stream,
// so the connection is torn down rather than allowed to continue desynced.
match service_subscriptions(&mut self.state, &mut self.outbound, DELIVERY_SLICE_BUDGET) {
Ok(shed) => self.shed_subscriptions(shed),
Err(error) => {
tracing::warn!(
connection_pid = pid,
%error,
"outbound overflow while delivering; tearing down the connection"
);
self.release_conversations();
self.runtime
.mark_crashed(pid, ExitReason::Error, self.peer_addr);
return NativeOutcome::Stop(ExitReason::Error);
}
}
// Drain queued outbound bytes with partial-write tracking. A hard write
// error (or overflow surfaced here) tears the connection down.
let drain = match self.drain_outbound() {
Ok(drain) => drain,
Err(error) => {
tracing::warn!(
connection_pid = pid,
%error,
"outbound drain failed; tearing down the connection"
);
self.release_conversations();
self.runtime
.mark_crashed(pid, ExitReason::Error, self.peer_addr);
return NativeOutcome::Stop(ExitReason::Error);
}
};
if let Err(error) = self.sync_deadline_timers(pid, ctx) {
return self.fail_slice(pid, &error);
}
// A successful budget-limited write proves immediately actionable work
// remains. Do not arm a permanently-writable socket in this state.
if drain == DrainOutcome::Progress {
return NativeOutcome::Continue;
}
let interest = if drain == DrainOutcome::WouldBlockWithResidue {
Interest::both()
} else {
Interest::READABLE
};
if let Err(error) = self.arm_readiness(pid, ctx, interest) {
return self.fail_slice(pid, &error);
}
#[cfg(test)]
let barrier_staged = self.runtime.run_pre_wait_barrier();
match self.final_probe(pid) {
Ok(true) => {
#[cfg(test)]
if barrier_staged {
self.runtime.record_pre_wait_probe_hit();
}
NativeOutcome::Continue
}
Ok(false) => NativeOutcome::Wait,
Err(error) => self.fail_slice(pid, &error),
}
}
fn fail_slice(&mut self, pid: u64, error: &ServerError) -> NativeOutcome {
tracing::error!(connection_pid = pid, %error, "connection readiness contract failed");
self.release_conversations();
self.runtime
.mark_crashed(pid, ExitReason::Error, self.peer_addr);
NativeOutcome::Stop(ExitReason::Error)
}
/// Services the inbound half of a slice: reads available bytes and applies any
/// complete frames, enqueuing responses into the outbound buffer.
fn service_socket(&mut self, pid: u64) -> SliceStep {
if self.stream.is_none() {
self.release_conversations();
self.runtime
.mark_crashed(pid, ExitReason::Error, self.peer_addr);
return SliceStep::Stop(ExitReason::Error);
}
let Some(stream) = self.stream.as_mut() else {
// Unreachable: the `is_none` guard above already handled a missing
// stream. Kept as a total match so `stream` binds without an unwrap.
return SliceStep::Stop(ExitReason::Error);
};
match read_available(stream, &mut self.buffer) {
Ok(ReadStatus::Closed) => {
// Best-effort flush of anything still queued (e.g. WouldBlock residue
// from earlier slices to a half-closed peer) before we let the stream
// drop, mirroring the ForceClose drain. The buffered-writer refactor
// removed this on the EOF path; without it, queued responses are lost.
let _ = self.drain_outbound();
self.release_conversations();
self.runtime.finish(pid);
return SliceStep::Stop(ExitReason::Normal);
}
Ok(ReadStatus::WouldBlock) => {
// No bytes ready on this non-blocking socket right now. Do NOT
// sleep: that would block a beamr scheduler worker thread (the
// supervisor runs `CONNECTION_SCHEDULER_THREADS`) on every idle
// poll and starve every other connection process sharing it. The
// caller returns `NativeOutcome::Continue` (mapping to
// `SliceOutcome::Requeue`), which re-queues this pid behind every
// other runnable process (cooperative round-robin) and reschedules
// us to poll โ and, crucially, to drain any queued outbound bytes โ
// without parking. `Wait` is wrong here: it parks until a *message*
// arrives, but socket readiness does not enqueue a message, so the
// connection would hang forever.
return SliceStep::Continue;
}
Ok(ReadStatus::Read) => {}
Err(error) => {
tracing::warn!(connection_pid = pid, %error, "connection read failed");
self.release_conversations();
self.runtime
.mark_crashed(pid, ExitReason::Error, self.peer_addr);
return SliceStep::Stop(ExitReason::Error);
}
}
match process_buffer(
pid,
&self.runtime,
&mut self.state,
&mut self.buffer,
&mut self.outbound,
) {
Ok(ProcessStatus::Continue) => SliceStep::Continue,
Ok(ProcessStatus::Close) => {
// A client-initiated close (e.g. a pipelined [Ping, Disconnect] or
// [Publish, Disconnect] in one segment) may have enqueued a response
// โ the Pong/PublishAck โ into the outbound buffer just before the
// Disconnect returned Close. Drain it best-effort before finishing so
// that queued reply is not dropped, mirroring the ForceClose drain.
let _ = self.drain_outbound();
self.release_conversations();
self.runtime.finish(pid);
SliceStep::Stop(ExitReason::Normal)
}
Err(error) => {
tracing::warn!(connection_pid = pid, %error, "connection process failed");
self.release_conversations();
self.runtime
.mark_crashed(pid, ExitReason::Error, self.peer_addr);
SliceStep::Stop(ExitReason::Error)
}
}
}
/// Releases every conversation this connection opened, finalizing each so its
/// supervised actor and participant are terminated and their runtime
/// registrations dropped โ an abrupt connection teardown never leaks them.
/// Finalization is bounded, non-blocking, and does not require the
/// conversation scheduler to run a slice (or even be live): teardown runs on
/// a connection scheduler worker and inside `Drop`, where waiting on another
/// scheduler would wedge the worker or hang reap/shutdown. The interactive
/// close round trip stays exclusively on the client-requested
/// `ConversationClose` frame path. Every in-handler termination path (EOF,
/// client `Close`, `ForceClose`, and each crash route) calls this before the
/// runtime teardown; the `Drop` backstop covers the external-termination/reap
/// and scheduler-shutdown paths that never run another slice. The
/// conversation map is drained, so a second call finds nothing โ the explicit
/// paths and the backstop cannot double-finalize.
fn release_conversations(&mut self) {
// R1(vi)/ยง1.2(5): cancel every pending-reply entry BEFORE the conversation
// actors are torn down, so no entry (and no timeout write) outlives its
// connection. Finalizing each conversation below clears its reply notifier
// in the conversation core, so no marker fires after teardown.
self.state.pending_replies.cancel_all();
for (_conversation_id, conversation) in std::mem::take(&mut self.state.conversations) {
conversation.finalize();
}
}
/// R1(vi) (ยง1.2(3b)): services the pending-reply table for this slice.
///
/// 1. DEADLINE-CHECK SEAM: expire every pending entry whose deadline passed,
/// tombstoning it and enqueuing its timeout error frame. Under the busy loop
/// this runs every slice; PARK-FLIP adds a timer-driven `READY` wake at each
/// entry's deadline (contract R1(vi) as amended) so a parked connection with
/// zero other traffic still wakes to write the timeout โ that wake feeds this
/// same seam.
/// 2. Drain and correlate: for each conversation still awaiting a reply, pull
/// buffered participant replies non-blocking and match them FIFO, enqueuing
/// each correlated reply frame. A conversation gone from the map (closed) is
/// swept from the table so its entries do not linger.
///
/// # Errors
/// Returns [`OutboundError`](super::outbound::OutboundError) when a reply or
/// timeout frame cannot be enqueued (a fatal outbound condition).
fn service_pending_replies(&mut self) -> Result<(), super::outbound::OutboundError> {
let now = std::time::Instant::now();
for frame in self.state.pending_replies.expire_due(now) {
self.outbound.enqueue_frame(&frame)?;
}
for conversation_id in self.state.pending_replies.conversations_awaiting_reply() {
let Some(conversation) = self.state.conversations.get(&conversation_id) else {
// The conversation closed while entries were pending: sweep them
// (the close-sweep tombstone-reclamation trigger) rather than poll a
// conversation that no longer exists.
self.state
.pending_replies
.remove_conversation(conversation_id);
continue;
};
// Drain every buffered reply for this conversation this slice, matching
// each FIFO. `try_receive_reply` is non-blocking, so an empty queue ends
// the loop immediately (no slice is ever blocked).
while let Some(reply) = conversation.try_receive_reply() {
if let Some(frame) = self
.state
.pending_replies
.match_reply(conversation_id, reply)
{
self.outbound.enqueue_frame(&frame)?;
} else {
// The reply consumed a tombstone (or found nothing to
// correlate): discarded, never delivered late. Keep draining in
// case more replies are buffered.
}
}
}
Ok(())
}
/// Removes and releases subscriptions the delivery pump shed on inbox overflow
/// (ยง5). The pump has already enqueued each subscription's typed `SubscribeError`
/// frame; here the subscription is dropped from connection state (its
/// delivery-sequence counter and any held frame with it, so a re-subscribe that
/// reuses the id starts clean) and released through the services adapter, the
/// same teardown path an explicit `Unsubscribe` uses. A slow consumer thus sheds
/// its own subscription without growing server memory or tearing down the
/// connection's other streams.
fn shed_subscriptions(&mut self, shed: Vec<u64>) {
for subscription_id in shed {
self.state.delivery_seqs.remove(&subscription_id);
self.state.held_deliveries.remove(&subscription_id);
if let Some(subscription) = self.state.subscriptions.remove(&subscription_id) {
if let Err(error) = self.runtime.services().unsubscribe(subscription) {
tracing::warn!(
subscription_id,
%error,
"releasing a shed (inbox-overflowed) subscription failed"
);
}
}
}
}
/// Drains queued outbound bytes to the socket, if the stream is still present.
///
/// Returns the [`DrainOutcome`](super::outbound::DrainOutcome) tri-state. Under
/// the busy loop every caller ignores the distinction and re-services on the
/// next slice; the value is reported so the seam is honest.
///
/// PARK-FLIP SEAM (R2, ยง1.2(1)): when this returns
/// `Ok(DrainOutcome::WouldBlockWithResidue)` the park-flip commit arms writable
/// readiness interest for this connection's socket (and only then), so the
/// connection re-wakes when the kernel send buffer drains instead of parking
/// with unflushed residue. `Drained`/`Progress` arm nothing. A `None` budget is
/// passed so live per-slice throughput is unchanged; the park-flip supplies a
/// byte budget here.
fn drain_outbound(
&mut self,
) -> Result<super::outbound::DrainOutcome, super::outbound::OutboundError> {
let Some(stream) = self.stream.as_mut() else {
return Ok(super::outbound::DrainOutcome::Drained);
};
self.outbound.drain(stream, Some(READ_BUFFER_BYTES))
}
fn arm_readiness(
&mut self,
pid: u64,
ctx: &NativeContext<'_>,
interest: Interest,
) -> Result<(), ServerError> {
let facility = ctx
.readiness_facility()
.ok_or_else(|| ServerError::ListenerAccept {
message: "connection scheduler started without its required readiness service"
.to_owned(),
})?;
if let Some(token) = self.readiness_token {
return facility
.rearm(&token, interest)
.map_err(|error| ServerError::ListenerAccept {
message: format!("failed to rearm connection readiness: {error}"),
});
}
let stream = self
.stream
.as_ref()
.ok_or_else(|| ServerError::ListenerAccept {
message: "cannot register readiness for a missing connection stream".to_owned(),
})?;
let token = facility
.register(stream.as_raw_fd(), interest, pid, self.runtime.ready_atom())
.map_err(|error| ServerError::ListenerAccept {
message: format!("failed to register connection readiness: {error}"),
})?;
if let Err(error) = self
.runtime
.set_readiness_token_once(pid, token, stream.as_raw_fd())
{
self.runtime.deregister_unpublished_readiness(token);
return Err(error);
}
self.readiness_token = Some(token);
Ok(())
}
fn sync_deadline_timers(
&mut self,
pid: u64,
ctx: &mut NativeContext<'_>,
) -> Result<(), ServerError> {
for timer in self.state.pending_replies.take_retired_timers() {
ctx.cancel_timer(timer);
}
for (op_id, delay) in self
.state
.pending_replies
.timers_to_arm(std::time::Instant::now())
{
let timer = ctx
.send_after(delay, pid, Term::atom(self.runtime.ready_atom()))
.ok_or_else(|| ServerError::ListenerAccept {
message: "connection scheduler has no timer facility for reply deadlines"
.to_owned(),
})?;
if !self.state.pending_replies.install_timer(op_id, timer) {
ctx.cancel_timer(timer);
}
}
Ok(())
}
/// Post-arm C1/C4 barrier. Each query is nonblocking and non-consuming.
fn final_probe(&self, pid: u64) -> Result<bool, ServerError> {
let socket_ready = if let Some(stream) = self.stream.as_ref() {
let mut byte = [0_u8; 1];
match stream.peek(&mut byte) {
Ok(_) => true,
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => false,
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => true,
Err(error) => {
return Err(ServerError::ListenerAccept {
message: format!("connection readiness probe failed: {error}"),
});
}
}
} else {
true
};
let subscription_ready = !self.state.held_deliveries.is_empty()
|| self
.state
.subscriptions
.values()
.any(|subscription| subscription.is_overflowed() || subscription.has_pending());
let reply_ready = self
.state
.pending_replies
.has_due(std::time::Instant::now())
|| self
.state
.pending_replies
.conversations_awaiting_reply()
.into_iter()
.filter_map(|id| self.state.conversations.get(&id))
.any(super::conversation::ConnectionConversation::has_pending_reply);
Ok(socket_ready || subscription_ready || reply_ready || self.runtime.has_control(pid))
}
fn handle_control(&mut self, pid: u64, control: ConnectionControl) -> Option<NativeOutcome> {
match control {
ConnectionControl::NotifyShutdown => {
self.notify_shutdown(pid, true);
None
}
ConnectionControl::ForceClose => {
self.notify_shutdown(pid, false);
// Flush the enqueued `Disconnect` (and any residue) before the
// stream is dropped; best-effort, since we are stopping regardless.
let _ = self.drain_outbound();
self.release_conversations();
// Host removal ACKs readiness deregistration while both the
// process stream and record fd guard are still live.
self.runtime.finish(pid);
self.stream.take();
Some(NativeOutcome::Stop(ExitReason::Normal))
}
ConnectionControl::Push {
correlation_id,
payload,
} => {
self.write_push(pid, correlation_id, payload);
None
}
}
}
/// Enqueues a server-initiated [`Frame::Push`] into the outbound buffer.
///
/// The frame is flushed by the slice's outbound drain (this control message is
/// handled at the start of the slice, before `handle_slice` runs). A missing
/// stream, an encode failure, or an outbound overflow cancels the push slot so
/// the awaiter does not block forever on a reply that can never arrive; the
/// connection itself is left to its normal lifecycle.
fn write_push(&mut self, pid: u64, correlation_id: u64, payload: Vec<u8>) {
if self.stream.is_none() {
tracing::warn!(
connection_pid = pid,
correlation_id,
"server push skipped because connection stream is unavailable"
);
self.runtime.cancel_push(correlation_id);
return;
}
let frame = match Frame::new_push(PUSH_STREAM_ID, correlation_id, payload) {
Ok(frame) => frame,
Err(error) => {
tracing::warn!(
connection_pid = pid,
correlation_id,
%error,
"server push frame could not be constructed"
);
self.runtime.cancel_push(correlation_id);
return;
}
};
if let Err(error) = self.outbound.enqueue_frame(&frame) {
tracing::warn!(
connection_pid = pid,
correlation_id,
%error,
"server push could not be enqueued; the push reply slot is cancelled"
);
self.runtime.cancel_push(correlation_id);
}
}
fn notify_shutdown(&mut self, pid: u64, subscribers_only: bool) {
if self.state.shutdown_notification_attempted {
return;
}
if subscribers_only && self.state.subscriptions.is_empty() {
return;
}
self.state.shutdown_notification_attempted = true;
if self.stream.is_none() {
tracing::warn!(
connection_pid = pid,
peer_addr = ?self.peer_addr,
"shutdown notification skipped because connection stream is unavailable"
);
return;
}
match self.outbound.enqueue_frame(&Frame::Disconnect { flags: 0 }) {
Ok(()) => {
tracing::debug!(
connection_pid = pid,
peer_addr = ?self.peer_addr,
subscriber_count = self.state.subscriptions.len(),
"enqueued shutdown notification to connection"
);
}
Err(error) => {
tracing::warn!(
connection_pid = pid,
peer_addr = ?self.peer_addr,
%error,
"shutdown notification could not be enqueued; connection will not be retried"
);
}
}
}
fn handle_message(&mut self, pid: u64, message: Term) -> Option<NativeOutcome> {
if message == Term::atom(Atom::ERROR) {
self.release_conversations();
self.runtime
.mark_crashed(pid, ExitReason::Error, self.peer_addr);
return Some(NativeOutcome::Stop(ExitReason::Error));
}
if message.as_atom() == Some(self.runtime.control_atom()) {
while let Some(control) = self.runtime.pop_control(pid) {
if let Some(outcome) = self.handle_control(pid, control) {
return Some(outcome);
}
}
}
// R6 (ยง1.2(4)): a `READY` marker (from any wake source โ subscription
// inbox R3, reply availability R1(vi), reply-deadline expiry) is a bare
// wake with no payload. It carries no lifecycle decision: the sole action
// is that ONE full slice runs, which the caller (`handle`) does exactly
// once after draining the whole mailbox โ so N coalesced markers, or a
// duplicate marker, collapse to one slice and never double-apply work.
// Recognised explicitly (rather than falling through) so the discipline is
// legible and the park-flip inherits it unchanged. Returning `None` lets
// the drain continue and the single post-drain slice service every source.
if message.as_atom() == Some(self.runtime.ready_atom()) {
return None;
}
None
}
}
impl NativeHandler for ConnectionProcess {
fn handle(&mut self, ctx: &mut NativeContext<'_>) -> NativeOutcome {
let pid = ctx.self_pid();
// Registration is owned solely by the spawn thread (`SupervisorInner::
// spawn_connection` calls `runtime.register` before returning the
// handle), so the handler never writes the registry โ it only reads its
// record via `mark_crashed`/`finish`. This removes the previous
// double-write (spawn-thread `insert` racing a handler `or_insert`) and
// its lost-update/duplicate-record hazard.
while let Some(message) = ctx.recv() {
if let Some(outcome) = self.handle_message(pid, message) {
return outcome;
}
}
self.handle_slice(pid, ctx)
}
}
impl Drop for ConnectionProcess {
fn drop(&mut self) {
// Backstop for termination paths that never run another handler slice:
// external termination (a `reap_crashed` target killed via the scheduler)
// and scheduler shutdown drop the handler directly. On the explicit
// in-handler teardown paths the conversation map is already drained, so
// this is a no-op there.
self.release_conversations();
let timers = self.state.pending_replies.take_retired_timers();
self.runtime.cancel_deadline_timers(timers);
}
}
fn process_buffer(
pid: u64,
runtime: &ConnectionRuntime,
state: &mut ConnectionProcessState,
buffer: &mut Vec<u8>,
outbound: &mut OutboundWriter,
) -> Result<ProcessStatus, ServerError> {
loop {
let (frame, consumed) = match decode(buffer) {
Ok(decoded) => decoded,
Err(
ProtocolError::IncompleteHeader { .. } | ProtocolError::TruncatedPayload { .. },
) => {
return Ok(ProcessStatus::Continue);
}
Err(error) => return Err(server_error_from_protocol(&error)),
};
buffer.drain(..consumed);
match apply_frame(pid, runtime, state, frame) {
FrameAction::Respond(response) => {
outbound
.enqueue_frame(&response)
.map_err(|error| ServerError::ListenerAccept {
message: format!("failed to enqueue connection response: {error}"),
})?;
}
FrameAction::NoResponse => {}
FrameAction::RespondThenClose(response) => {
// Best-effort: enqueue the rejection frame (a `ConnectError` from the
// auth gate) so the slice's Close-path drain can flush it, then close
// regardless. Unlike `Respond`, a failed enqueue here is logged and
// swallowed, never propagated: a rejected connection must be torn down
// even when its rejection notice cannot be queued. The single
// best-effort drain happens on the `ProcessStatus::Close` path in
// `service_socket`, so no write is forced (or awaited) here.
if let Err(error) = outbound.enqueue_frame(&response) {
tracing::warn!(
connection_pid = pid,
%error,
"auth-rejection frame could not be enqueued; closing anyway"
);
}
return Ok(ProcessStatus::Close);
}
FrameAction::Close => return Ok(ProcessStatus::Close),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ReadStatus {
Read,
WouldBlock,
Closed,
}
fn read_available(stream: &mut TcpStream, buffer: &mut Vec<u8>) -> Result<ReadStatus, ServerError> {
let mut chunk = [0_u8; READ_BUFFER_BYTES];
match stream.read(&mut chunk) {
Ok(0) => Ok(ReadStatus::Closed),
Ok(bytes_read) => {
buffer.extend_from_slice(chunk.get(..bytes_read).unwrap_or(&[]));
Ok(ReadStatus::Read)
}
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => Ok(ReadStatus::WouldBlock),
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => Ok(ReadStatus::WouldBlock),
Err(error) => Err(ServerError::ListenerAccept {
message: format!("failed to read connection stream: {error}"),
}),
}
}