alpha2-host 0.10.0

Native project-rendering sidecar and batch CLI for alpha2.
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
//! Stopping a running request, by a `cancel` line or a request to terminate the process.
//!
//! A cancel stops the export at its next wait; the normal abort path removes the partial output,
//! the request is answered `CANCELLED`, and the host serves the next. A cancel for a request not
//! yet read or started is kept until that request arrives.
//!
//! `SIGTERM`, `SIGINT`, `SIGHUP`, a console control event, or the exit of the process that started
//! `serve` cancels the running export the same way, and the process then exits with the signal's
//! status. Ending in place would run no destructors: the partial output would stay on disk,
//! decoder surfaces and encoder sessions would leak, and the caller would get no answer. A second
//! signal of the same kind, or `SIGKILL`, still ends the process immediately.

use std::collections::VecDeque;
use std::io::Write;
use std::sync::{Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant};

use alpha2_media::CancelToken;
use alpha2_os::Termination;

pub(crate) struct Terminations {
    state: Mutex<State>,
    /// Called when a termination was requested and the last request being handled is answered.
    on_idle: fn(Termination),
    /// Called when a termination's grace runs out, whatever still runs.
    on_deadline: fn(Termination),
    deadline_started: std::sync::atomic::AtomicBool,
}

struct State {
    requested: Option<Termination>,
    /// Requests from their frame being read until answered.
    busy: usize,
    /// Export cancel tokens and the request each belongs to, if known.
    running: Vec<(u64, Option<u64>, CancelToken)>,
    next: u64,
    /// Requests being handled, from [`Terminations::begin_request`] until answered.
    active: Vec<Active>,
    /// Set once the host retires: every export starts cancelled.
    retiring: Option<&'static str>,
    /// Ids cancelled before they were read or started, oldest first. A cancel for a request that
    /// already ended stays until newer ones push it out.
    pending: VecDeque<String>,
}

const MAX_PENDING_CANCELS: usize = 1024;

struct Active {
    sequence: u64,
    id: String,
    stop: Option<Stop>,
}

/// Why a request being handled was stopped.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Stop {
    /// A `cancel` line named it.
    Client,
    /// The host retires for this drain reason ([`Terminations::retire`]).
    Retiring(&'static str),
    /// Its cause is recorded as the export's failure ([`Terminations::stop_for_recorded_cause`]).
    Recorded,
}

thread_local! {
    /// The request this thread handles, set by [`Terminations::begin_request`].
    static CURRENT: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
}

impl Terminations {
    pub(crate) const fn new(on_idle: fn(Termination), on_deadline: fn(Termination)) -> Self {
        Self {
            state: Mutex::new(State {
                requested: None,
                busy: 0,
                running: Vec::new(),
                next: 0,
                active: Vec::new(),
                retiring: None,
                pending: VecDeque::new(),
            }),
            on_idle,
            on_deadline,
            deadline_started: std::sync::atomic::AtomicBool::new(false),
        }
    }

    /// Once per process: calls `on_deadline` after `grace` on a thread of its own, so a request
    /// that cannot stop, or an output nobody reads, cannot keep the process alive.
    pub(crate) fn start_deadline(&'static self, termination: Termination, grace: Duration) {
        if self
            .deadline_started
            .swap(true, std::sync::atomic::Ordering::AcqRel)
        {
            return;
        }
        let spawned = std::thread::Builder::new()
            .name("alpha2-termination-deadline".to_owned())
            .spawn(move || {
                std::thread::sleep(grace);
                (self.on_deadline)(termination);
            });
        if spawned.is_err() {
            self.deadline_started
                .store(false, std::sync::atomic::Ordering::Release);
        }
    }

    fn lock(&self) -> MutexGuard<'_, State> {
        self.state.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// Cancels every running export. Returns whether the process is idle and can exit now.
    pub(crate) fn request(&self, termination: Termination) -> bool {
        let mut state = self.lock();
        state.requested.get_or_insert(termination);
        for (_, _, token) in &state.running {
            token.cancel();
        }
        state.busy == 0
    }

    pub(crate) fn requested(&self) -> Option<Termination> {
        self.lock().requested
    }

    /// Held until the guard drops, on the thread that handles the request. A cancel that named
    /// `id` earlier is taken now ([`RequestGuard::cancelled_before_start`]).
    pub(crate) fn begin_request(&'static self, id: &str) -> RequestGuard {
        let mut state = self.lock();
        state.busy += 1;
        let cancelled = take_pending(&mut state.pending, id);
        let sequence = state.next;
        state.next += 1;
        state.active.push(Active {
            sequence,
            id: id.to_owned(),
            stop: cancelled.then_some(Stop::Client),
        });
        drop(state);
        CURRENT.with(|current| current.set(Some(sequence)));
        RequestGuard {
            owner: self,
            sequence,
            cancelled_before_start: cancelled,
        }
    }

    pub(crate) fn take_pending_cancel(&self, id: &str) -> bool {
        take_pending(&mut self.lock().pending, id)
    }

    /// `running` when a request with id `target` is being handled (a request with nothing to
    /// cancel finishes); otherwise `pending`, kept for a later request with that id.
    pub(crate) fn cancel_request(&self, target: &str) -> &'static str {
        let mut state = self.lock();
        let State {
            active, running, ..
        } = &mut *state;
        let mut found = false;
        for request in active.iter_mut().filter(|request| request.id == target) {
            request.stop.get_or_insert(Stop::Client);
            found = true;
            cancel_tokens_of(running, Some(request.sequence));
        }
        if found {
            return "running";
        }
        if state.pending.len() >= MAX_PENDING_CANCELS {
            state.pending.pop_front();
        }
        state.pending.push_back(target.to_owned());
        "pending"
    }

    /// Stops `request` for a cause the caller recorded as its failure (the Linux memory watchdog),
    /// so the export reports that cause, not a cancel: its running exports are cancelled and
    /// those it starts later begin cancelled. Cancels every running export when `request` is
    /// unknown.
    pub(crate) fn stop_for_recorded_cause(&self, request: Option<u64>) {
        let mut state = self.lock();
        let State {
            active, running, ..
        } = &mut *state;
        match request {
            Some(_) => {
                for entry in active
                    .iter_mut()
                    .filter(|entry| Some(entry.sequence) == request)
                {
                    entry.stop.get_or_insert(Stop::Recorded);
                }
                cancel_tokens_of(running, request);
            }
            None => {
                for (_, _, token) in running.iter() {
                    token.cancel();
                }
            }
        }
    }

    /// Stops every request being handled and makes every later export start cancelled, for a host
    /// that cannot take another request. Unlike [`Self::request`] it leaves the exit status alone.
    pub(crate) fn retire(&self, reason: &'static str) {
        let mut state = self.lock();
        state.retiring.get_or_insert(reason);
        for request in &mut state.active {
            request.stop.get_or_insert(Stop::Retiring(reason));
        }
        for (_, _, token) in &state.running {
            token.cancel();
        }
    }

    /// The drain reason, when the host stopped request `sequence` because it retires.
    fn retired(&self, sequence: u64) -> Option<&'static str> {
        match stop_of(&self.lock(), Some(sequence)) {
            Some(Stop::Retiring(reason)) => Some(reason),
            _ => None,
        }
    }

    /// For a process that answers a single request and then exits through `main`.
    pub(crate) fn hold_busy(&self) {
        self.lock().busy += 1;
    }

    /// Belongs to the request this thread handles. Already cancelled when a termination was asked
    /// for or a cancel named the request.
    pub(crate) fn export_cancel(&'static self) -> ExportCancel {
        let token = CancelToken::default();
        let request = current_request();
        let mut state = self.lock();
        let stopped = stop_of(&state, request).is_some();
        if state.requested.is_some() || state.retiring.is_some() || stopped {
            token.cancel();
        }
        let id = state.next;
        state.next += 1;
        state.running.push((id, request, token.clone()));
        ExportCancel {
            token,
            id,
            owner: self,
        }
    }

    fn wait_idle(&self, limit: Duration) {
        let started = Instant::now();
        while self.lock().busy != 0 && started.elapsed() < limit {
            std::thread::sleep(Duration::from_millis(20));
        }
    }
}

fn stop_of(state: &State, request: Option<u64>) -> Option<Stop> {
    state
        .active
        .iter()
        .find(|active| Some(active.sequence) == request)
        .and_then(|active| active.stop)
}

/// Tokens of no known request are cancelled with any request, as they may be its.
fn cancel_tokens_of(running: &[(u64, Option<u64>, CancelToken)], request: Option<u64>) {
    for (_, owner, token) in running {
        if owner.is_none() || *owner == request {
            token.cancel();
        }
    }
}

/// The request the calling thread handles, if it handles one.
pub(crate) fn current_request() -> Option<u64> {
    CURRENT.with(std::cell::Cell::get)
}

fn take_pending(pending: &mut VecDeque<String>, id: &str) -> bool {
    match pending.iter().position(|cancelled| cancelled == id) {
        Some(at) => {
            pending.remove(at);
            true
        }
        None => false,
    }
}

pub(crate) struct RequestGuard {
    owner: &'static Terminations,
    sequence: u64,
    cancelled_before_start: bool,
}

impl RequestGuard {
    pub(crate) const fn cancelled_before_start(&self) -> bool {
        self.cancelled_before_start
    }

    pub(crate) const fn sequence(&self) -> u64 {
        self.sequence
    }

    /// The drain reason, when the host stopped this request because it retires.
    pub(crate) fn retired(&self) -> Option<&'static str> {
        self.owner.retired(self.sequence)
    }
}

impl Drop for RequestGuard {
    fn drop(&mut self) {
        CURRENT.with(|current| {
            if current.get() == Some(self.sequence) {
                current.set(None);
            }
        });
        let mut state = self.owner.lock();
        state.busy = state.busy.saturating_sub(1);
        state
            .active
            .retain(|active| active.sequence != self.sequence);
        let idle = (state.busy == 0).then_some(state.requested).flatten();
        drop(state);
        if let Some(termination) = idle {
            (self.owner.on_idle)(termination);
        }
    }
}

pub(crate) struct ExportCancel {
    token: CancelToken,
    id: u64,
    owner: &'static Terminations,
}

impl std::ops::Deref for ExportCancel {
    type Target = CancelToken;

    fn deref(&self) -> &CancelToken {
        &self.token
    }
}

impl Drop for ExportCancel {
    fn drop(&mut self) {
        self.owner
            .lock()
            .running
            .retain(|(id, _, _)| *id != self.id);
    }
}

static TERMINATIONS: Terminations = Terminations::new(exit_on_termination, exit_at_deadline);

fn exit_on_termination(termination: Termination) {
    crate::lifecycle::announce_termination();
    crate::exit_unflushed(termination.exit_code());
}

/// Writes and flushes nothing: a blocked writer may hold either stream.
fn exit_at_deadline(termination: Termination) {
    alpha2_os::exit_without_handlers(termination.exit_code());
}

/// How long a termination waits for running requests: past the stall limit the host itself calls a
/// step stuck. After the parent's exit nobody reads the answers, so only a healthy stop is awaited.
fn grace(termination: Termination) -> Duration {
    #[cfg(test)]
    if let Some(grace) = *TEST_GRACE.lock().unwrap_or_else(PoisonError::into_inner) {
        return grace;
    }
    if termination.parent_exited() {
        PARENT_EXIT_GRACE
    } else {
        stop_grace()
    }
}

fn stop_grace() -> Duration {
    #[cfg(test)]
    if let Some(grace) = *TEST_GRACE.lock().unwrap_or_else(PoisonError::into_inner) {
        return grace;
    }
    crate::config::configured_stall_timeout().saturating_add(SIGNAL_GRACE_MARGIN)
}

const PARENT_EXIT_GRACE: Duration = Duration::from_secs(5);
const SIGNAL_GRACE_MARGIN: Duration = Duration::from_secs(5);

/// A short grace for the serve children of the tests.
#[cfg(test)]
pub(crate) static TEST_GRACE: Mutex<Option<Duration>> = Mutex::new(None);

pub(crate) fn terminations() -> &'static Terminations {
    &TERMINATIONS
}

pub(crate) fn requested() -> Option<Termination> {
    TERMINATIONS.requested()
}

pub(crate) fn export_cancel() -> ExportCancel {
    TERMINATIONS.export_cancel()
}

/// Once the request was cancelled or a termination asked for, the failure is reported as the
/// cancel, whatever the export stopped at.
pub(crate) fn cancelled_by_request_or_termination(message: String) -> String {
    let request = current_request();
    let state = TERMINATIONS.lock();
    let stop = stop_of(&state, request);
    if let Some(Stop::Retiring(reason)) = stop {
        return crate::protocol::cancelled(retiring_message(reason));
    }
    if crate::protocol::is_cancelled(&message) {
        return message;
    }
    if let Some(termination) = state.requested {
        return crate::protocol::cancelled(format!(
            "native export was cancelled: the host was asked to terminate ({})",
            termination.name()
        ));
    }
    match (stop, request) {
        (Some(Stop::Client), Some(request)) => {
            let id = state
                .active
                .iter()
                .find(|active| active.sequence == request)
                .map_or("", |active| active.id.as_str());
            crate::protocol::cancelled(format!(
                "native export was cancelled: the client cancelled request {id}"
            ))
        }
        _ => message,
    }
}

/// The answer of a request the host stopped because it retires for `reason`.
pub(crate) fn retiring_message(reason: &str) -> String {
    format!("the host is retiring ({reason}); the request was stopped and left no output")
}

/// How long a retiring host waits for the requests it stopped: as long as a termination does.
pub(crate) fn retire_grace() -> Duration {
    stop_grace()
}

/// # Errors
/// When the operating system refuses the handler.
pub(crate) fn install() -> std::io::Result<()> {
    alpha2_os::on_termination(|termination| {
        TERMINATIONS.start_deadline(termination, grace(termination));
        // A client may have closed the pipe already, so nothing may depend on this line.
        let _ = writeln!(
            std::io::stderr(),
            "alpha2-host: {} received; cancelling the running request",
            termination.name()
        );
        if TERMINATIONS.request(termination) {
            exit_on_termination(termination);
        }
        // The system ends the process when this returns, so give the export time to stop and
        // remove its partial.
        if termination.closing() {
            TERMINATIONS.wait_idle(Duration::from_secs(4));
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    static IDLE: Mutex<Vec<&'static str>> = Mutex::new(Vec::new());

    fn record_idle(termination: Termination) {
        IDLE.lock().expect("idle").push(termination.name());
    }

    static DEADLINES: Mutex<Vec<u8>> = Mutex::new(Vec::new());

    fn record_deadline(termination: Termination) {
        DEADLINES
            .lock()
            .expect("deadlines")
            .push(termination.exit_code());
    }

    fn leaked() -> &'static Terminations {
        Box::leak(Box::new(Terminations::new(record_idle, record_deadline)))
    }

    fn sigterm() -> Termination {
        Termination::new("SIGTERM", 143, false)
    }

    #[test]
    fn a_termination_cancels_every_running_export_and_any_that_starts_after_it() {
        let terminations = leaked();
        let request = terminations.begin_request("export");
        let running = terminations.export_cancel();
        let ended = terminations.export_cancel();
        drop(ended);
        assert!(!running.is_cancelled());
        assert!(
            !terminations.request(sigterm()),
            "a process answering a request is not idle"
        );
        assert!(running.is_cancelled());
        assert_eq!(terminations.requested(), Some(sigterm()));
        assert!(terminations.export_cancel().is_cancelled());
        drop(running);
        assert!(IDLE.lock().expect("idle").is_empty());
        drop(request);
        assert_eq!(*IDLE.lock().expect("idle"), ["SIGTERM"]);
        assert!(terminations.request(sigterm()), "idle once answered");
    }

    #[test]
    fn a_cancel_stops_the_request_it_names_and_only_that_request() {
        let terminations = leaked();
        let request = terminations.begin_request("export");
        let running = terminations.export_cancel();
        assert_eq!(terminations.cancel_request("another"), "pending");
        assert!(!running.is_cancelled());
        assert_eq!(terminations.cancel_request("export"), "running");
        assert!(running.is_cancelled());
        assert!(terminations.export_cancel().is_cancelled());
        assert_eq!(terminations.requested(), None, "a cancel is no termination");
        drop(running);
        drop(request);
        let next = terminations.begin_request("next");
        assert!(!next.cancelled_before_start());
        assert!(!terminations.export_cancel().is_cancelled());
        drop(next);
        assert!(
            !terminations
                .begin_request("export")
                .cancelled_before_start()
        );
    }

    #[test]
    fn a_cancel_for_a_request_not_started_yet_is_kept_for_it() {
        let terminations = leaked();
        assert_eq!(terminations.cancel_request("later"), "pending");
        let later = terminations.begin_request("later");
        assert!(later.cancelled_before_start());
        assert!(terminations.export_cancel().is_cancelled());
        drop(later);
        assert!(!terminations.take_pending_cancel("later"), "taken once");
        for index in 0..=MAX_PENDING_CANCELS {
            terminations.cancel_request(&index.to_string());
        }
        assert!(!terminations.take_pending_cancel("0"), "the oldest goes");
        assert!(terminations.take_pending_cancel("1"));
    }

    #[test]
    fn retiring_stops_what_runs_and_every_later_export_without_a_termination() {
        let terminations = leaked();
        let first = terminations.begin_request("first");
        let running = terminations.export_cancel();
        terminations.retire("threads-abandoned");
        assert!(running.is_cancelled());
        assert_eq!(first.retired(), Some("threads-abandoned"));
        assert_eq!(terminations.requested(), None, "the exit status stays");
        let later = terminations.begin_request("later");
        assert!(terminations.export_cancel().is_cancelled());
        assert_eq!(
            later.retired(),
            None,
            "it was not running when the host retired"
        );
    }

    #[test]
    fn a_deadline_ends_a_busy_process_once_whatever_runs() {
        // Its own idle hook: the shared one is asserted on by tests that run beside it.
        fn ignore_idle(_: Termination) {}
        let terminations: &'static Terminations =
            Box::leak(Box::new(Terminations::new(ignore_idle, record_deadline)));
        let _request = terminations.begin_request("stuck");
        assert!(!terminations.request(sigterm()));
        terminations.start_deadline(sigterm(), Duration::from_millis(50));
        terminations.start_deadline(sigterm(), Duration::from_millis(50));
        let started = Instant::now();
        while DEADLINES.lock().expect("deadlines").is_empty() {
            assert!(started.elapsed() < Duration::from_secs(10), "no deadline");
            std::thread::sleep(Duration::from_millis(10));
        }
        std::thread::sleep(Duration::from_millis(200));
        assert_eq!(*DEADLINES.lock().expect("deadlines"), [143]);
    }

    #[test]
    fn the_parent_exit_takes_the_short_grace() {
        let parent = Termination::new("PARENT_EXITED", 143, false);
        assert!(parent.parent_exited());
        assert_eq!(grace(parent), PARENT_EXIT_GRACE);
        assert!(!sigterm().parent_exited());
        assert_eq!(
            grace(sigterm()),
            crate::config::configured_stall_timeout() + SIGNAL_GRACE_MARGIN
        );
    }

    #[test]
    fn an_idle_process_can_exit_at_once() {
        let terminations = leaked();
        assert!(terminations.request(sigterm()));
    }
}