fetchlet 0.1.1

Rust-hosted JavaScript functions and Fetch handlers with explicit host services
Documentation
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
use std::any::Any;
use std::future::Future;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::{Arc, Mutex, MutexGuard};
use std::thread;
use std::time::{Duration, Instant};

use tokio::sync::{mpsc, oneshot, watch};

use super::lifecycle::WorkerStatus;
use super::protocol::Command;
use super::streaming::stream_response_body;
use super::{CancelledCalls, PoolState, WorkerOptions};
use crate::app::Opened;
use crate::{App, AppBuilder, Body, Error, Response, Result};

/// The worker threads of one [`AppHandle`](super::AppHandle), each owning one
/// instance, and the queue they share.
pub(super) struct Pool {
    builder: AppBuilder,
    options: WorkerOptions,
    /// The shared queue. A worker holds the lock only while it waits for the
    /// next command, so commands go to whichever worker is free.
    receiver: tokio::sync::Mutex<mpsc::Receiver<Command>>,
    shutdown: Arc<watch::Sender<bool>>,
    status: watch::Sender<WorkerStatus>,
    state: Mutex<Workers>,
}

#[derive(Default)]
struct Workers {
    /// Worker threads alive, including those still building their instance.
    workers: usize,
    /// Workers building their first instance.
    starting: usize,
    /// Workers building the replacement of a retired instance.
    rebuilding: usize,
    /// Workers waiting for a command.
    idle: usize,
    /// Idle workers above `min` that are exiting.
    retiring: usize,
    /// The first worker panic, reported as the pool's final state.
    failure: Option<String>,
    finished: bool,
    /// Totals since the spawn, for [`PoolState`].
    builds: u64,
    failed_builds: u64,
    build_time: Duration,
    replaced: u64,
    idle_retirements: u64,
}

impl Pool {
    /// Start the pool's `min` workers and wait until each has built its
    /// instance, so that a module that fails to initialize fails the spawn.
    pub async fn start(
        builder: AppBuilder,
        options: WorkerOptions,
        receiver: mpsc::Receiver<Command>,
        shutdown: Arc<watch::Sender<bool>>,
        status: watch::Sender<WorkerStatus>,
    ) -> Result<Arc<Self>> {
        let instances = options.instances;
        if instances.min > instances.max {
            return Err(Error::Configuration(
                "worker instances: min exceeds max".into(),
            ));
        }
        if instances.max_held_connections >= instances.max.get()
            && instances.max_held_connections > 0
        {
            return Err(Error::Configuration(
                "worker instances: max_held_connections must be below max".into(),
            ));
        }
        let pool = Arc::new(Self {
            builder,
            options,
            receiver: tokio::sync::Mutex::new(receiver),
            shutdown,
            status,
            state: Mutex::new(Workers::default()),
        });
        // One build at a time: QuickJS seeds Math.random and its hash seed
        // from the time in microseconds, so contexts created at the same
        // moment on two threads would share both.
        let mut result = Ok(());
        for _ in 0..instances.min.get() {
            pool.lock_state().reserve_worker();
            let initialized = match pool.start_worker() {
                Ok(initialized) => initialized,
                Err(error) => {
                    let mut state = pool.lock_state();
                    state.starting -= 1;
                    state.workers -= 1;
                    result = Err(error);
                    break;
                }
            };
            result = match initialized.await {
                Ok(outcome) => outcome,
                // The worker panicked while it built its instance.
                Err(_) => Err(Error::WorkerClosed),
            };
            if result.is_err() {
                break;
            }
        }
        if let Err(error) = result {
            // Workers that did start stop once the handle drops the sender.
            pool.shutdown.send_replace(true);
            return Err(error);
        }
        Ok(pool)
    }

    /// Start another worker when the queue holds more commands than idle and
    /// starting workers can take and the pool is below `max`.
    pub fn grow(self: &Arc<Self>, queued: usize) {
        let mut state = self.lock_state();
        if state.finished
            || *self.shutdown.borrow()
            || state.workers - state.retiring >= self.options.instances.max.get()
            || queued <= state.idle + state.starting
        {
            return;
        }
        state.reserve_worker();
        drop(state);
        // A worker that fails to build exits; the queue keeps its commands
        // for the others.
        if self.start_worker().is_err() {
            let mut state = self.lock_state();
            state.starting -= 1;
            state.workers -= 1;
        }
    }

    fn lock_state(&self) -> MutexGuard<'_, Workers> {
        self.state.lock().unwrap_or_else(|error| error.into_inner())
    }

    /// The instance counts and totals of [`PoolState`]; the handle adds the
    /// queue and held connections.
    pub fn state(&self) -> PoolState {
        let state = self.lock_state();
        let instances = self.options.instances;
        let building = state.starting + state.rebuilding;
        PoolState {
            building,
            idle: state.idle,
            // A worker between two counts, such as one exiting after a
            // failed build, reads as busy for that moment.
            busy: state
                .workers
                .saturating_sub(building + state.idle + state.retiring),
            retiring: state.retiring,
            min: instances.min.get(),
            max: instances.max.get(),
            queue_capacity: self.options.queue_capacity.get(),
            max_held_connections: instances.max_held_connections,
            builds: state.builds,
            failed_builds: state.failed_builds,
            build_time: state.build_time,
            replaced: state.replaced,
            idle_retirements: state.idle_retirements,
            ..PoolState::default()
        }
    }

    /// Build an instance, counting it in the totals.
    fn build(&self) -> Result<App> {
        let started = Instant::now();
        let built = self.builder.clone().build();
        let mut state = self.lock_state();
        state.build_time += started.elapsed();
        match built {
            Ok(_) => state.builds += 1,
            Err(_) => state.failed_builds += 1,
        }
        built
    }

    /// Build the replacement of a retired instance while counted as
    /// rebuilding.
    fn rebuild(&self) -> Result<App> {
        self.lock_state().rebuilding += 1;
        let built = self.build();
        self.lock_state().rebuilding -= 1;
        built
    }

    /// Spawn a worker counted by [`Workers::reserve_worker`].
    fn start_worker(self: &Arc<Self>) -> Result<oneshot::Receiver<Result<()>>> {
        let (initialized, ready) = oneshot::channel();
        let mut thread = thread::Builder::new().name("fetchlet-app".into());
        if let Some(size) = self.options.stack_size_bytes {
            thread = thread.stack_size(size.get());
        }
        let pool = self.clone();
        thread
            .spawn(move || {
                let result = catch_unwind(AssertUnwindSafe(|| pool.run_worker(initialized)));
                let retired = match result {
                    Ok(retired) => retired,
                    Err(payload) => {
                        pool.fail(panic_message(payload));
                        false
                    }
                };
                pool.exit_worker(retired);
            })
            .map_err(|error| Error::WorkerFailed(error.to_string()))?;
        Ok(ready)
    }

    /// Returns whether the worker retired as idle.
    fn run_worker(self: &Arc<Self>, initialized: oneshot::Sender<Result<()>>) -> bool {
        let executor = match tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
        {
            Ok(executor) => executor,
            Err(error) => {
                self.lock_state().starting -= 1;
                let _ = initialized.send(Err(Error::WorkerFailed(error.to_string())));
                return false;
            }
        };
        let _entered = executor.enter();
        let built = self.build();
        self.lock_state().starting -= 1;
        let app = match built {
            Ok(app) => app,
            Err(error) => {
                let _ = initialized.send(Err(error));
                return false;
            }
        };
        let _ = initialized.send(Ok(()));
        executor.block_on(self.serve(app))
    }

    /// Take commands from the shared queue until it closes, or until this
    /// worker retires as idle, which it returns.
    async fn serve(self: &Arc<Self>, app: App) -> bool {
        let execution = Execution {
            response_body_queue: self.options.response_body_queue.get(),
            cancelled_calls: self.options.cancelled_calls,
        };
        let idle_timeout = self.options.instances.idle_timeout;
        let mut stopping = self.shutdown.subscribe();
        let mut draining = *stopping.borrow();
        if draining {
            // Shutdown began before this worker started: close the queue
            // itself, since it will not see the request as an event. A worker
            // holding the queue while it waits sees the request and lets go.
            self.receiver.lock().await.close();
        }
        let mut app = Some(app);
        loop {
            self.lock_state().idle += 1;
            let next = tokio::select! {
                command = async { self.receiver.lock().await.recv().await } => Next::Command(command),
                _ = stopping.wait_for(|requested| *requested), if !draining => Next::Shutdown,
                () = sleep(idle_timeout), if idle_timeout.is_some() => Next::Idle,
            };
            self.lock_state().idle -= 1;
            let command = match next {
                Next::Shutdown => {
                    // Accepted commands still run; no new ones arrive.
                    self.receiver.lock().await.close();
                    draining = true;
                    continue;
                }
                Next::Idle => {
                    if self.retire_idle() {
                        return true;
                    }
                    continue;
                }
                Next::Command(None) => return false,
                Next::Command(Some(command)) => command,
            };
            if command.is_cancelled() {
                continue;
            }
            let instance = match app.as_mut() {
                Some(instance) => instance,
                None => match self.rebuild() {
                    Ok(instance) => app.insert(instance),
                    Err(error) => {
                        command.reject(error);
                        continue;
                    }
                },
            };
            command.execute(instance, execution, stopping.clone()).await;
            // Background work runs after the reply, before the next command.
            let _ = instance.finish_background().await;
            // A retired instance is replaced now, while other workers serve
            // the queue, rather than when the next command arrives. A build
            // that fails is retried, and reported, by the next command.
            if !instance.is_reusable() {
                self.lock_state().replaced += 1;
                app = self.rebuild().ok();
            }
        }
    }

    /// Whether an idle worker above `min` may exit, reserving its exit so
    /// that workers timing out together leave `min` running.
    fn retire_idle(&self) -> bool {
        let mut state = self.lock_state();
        if state.workers - state.starting - state.retiring > self.options.instances.min.get() {
            state.retiring += 1;
            state.idle_retirements += 1;
            return true;
        }
        false
    }

    fn fail(&self, message: String) {
        self.lock_state().failure.get_or_insert(message);
        // The other workers finish what was accepted, then stop.
        self.shutdown.send_replace(true);
    }

    /// Count an exiting worker out. The last one closes the queue, so that
    /// commands left in it fail instead of waiting, and reports the final state.
    fn exit_worker(&self, retired: bool) {
        let mut state = self.lock_state();
        state.workers -= 1;
        if retired {
            state.retiring -= 1;
        }
        if state.workers > 0 || state.finished {
            return;
        }
        state.finished = true;
        let outcome = match state.failure.clone() {
            Some(message) => Err(message),
            None => Ok(()),
        };
        drop(state);
        if let Ok(mut receiver) = self.receiver.try_lock() {
            receiver.close();
            while receiver.try_recv().is_ok() {}
        }
        self.status.send_replace(WorkerStatus::Finished(outcome));
    }
}

impl Workers {
    fn reserve_worker(&mut self) {
        self.workers += 1;
        self.starting += 1;
    }
}

enum Next {
    Command(Option<Command>),
    Shutdown,
    Idle,
}

async fn sleep(duration: Option<std::time::Duration>) {
    match duration {
        Some(duration) => tokio::time::sleep(duration).await,
        None => std::future::pending().await,
    }
}

/// How the worker runs each command.
#[derive(Clone, Copy)]
pub struct Execution {
    /// See [`WorkerOptions::response_body_queue`].
    pub response_body_queue: usize,
    pub cancelled_calls: CancelledCalls,
}

impl Command {
    pub fn is_cancelled(&self) -> bool {
        match self {
            Self::Call { reply, .. } => reply.is_closed(),
            Self::Fetch { reply, .. } => reply.is_closed(),
        }
    }

    pub fn reject(self, error: Error) {
        match self {
            Self::Call { reply, .. } => {
                let _ = reply.send(Err(error));
            }
            Self::Fetch { reply, .. } => {
                let _ = reply.send(Err(error));
            }
        }
    }

    /// Execute on the worker. A streaming Fetch response keeps the worker,
    /// and with it the instance, until its body finishes or is dropped; an
    /// accepted connection keeps them until it closes, or `stopping` asks
    /// it to close.
    pub async fn execute(
        self,
        app: &mut App,
        execution: Execution,
        stopping: watch::Receiver<bool>,
    ) {
        let finish = execution.cancelled_calls == CancelledCalls::Finish;
        match self {
            Self::Call { call, reply } => {
                complete(reply, app.call_with(call), finish).await;
            }
            Self::Fetch {
                request,
                context,
                mut reply,
            } => {
                let disconnect = app.disconnect();
                let head = if finish {
                    // The handler sees its request's signal abort when the
                    // caller leaves, and the closed reply fails the send
                    // below, which cancels an open body.
                    let head = app.fetch_head(*request, context, Some(disconnect.clone()), true);
                    tokio::pin!(head);
                    tokio::select! {
                        head = &mut head => head,
                        () = reply.closed() => {
                            disconnect.signal();
                            head.await
                        }
                    }
                } else {
                    tokio::select! {
                        head = app.fetch_head(*request, context, None, true) => head,
                        () = reply.closed() => return,
                    }
                };
                let (response, open) = match head {
                    Ok(head) => head,
                    Err(error) => {
                        let _ = reply.send(Err(error));
                        return;
                    }
                };
                let open = match open {
                    None => {
                        let _ = reply.send(Ok(response));
                        return;
                    }
                    Some(Opened::Body(open)) => open,
                    Some(Opened::Connection(open)) => {
                        // A caller that left drops the response and with it
                        // Rust's end, which closes the connection at once.
                        let _ = reply.send(Ok(response));
                        app.hold_connection(open, shutdown_requested(stopping))
                            .await;
                        return;
                    }
                };
                let (parts, body) = response.into_parts();
                let prefix = match body.collect_within(None, "response body bytes").await {
                    Ok(prefix) => prefix,
                    Err(error) => {
                        app.cancel_response_body(open).await;
                        let _ = reply.send(Err(error));
                        return;
                    }
                };
                let (sender, body) = Body::channel(prefix, execution.response_body_queue);
                if reply.send(Ok(Response::from_parts(parts, body))).is_err() {
                    app.cancel_response_body(open).await;
                    return;
                }
                stream_response_body(app, open, sender, finish.then_some(disconnect)).await;
            }
        }
    }
}

/// Completes once shutdown is requested.
async fn shutdown_requested(mut stopping: watch::Receiver<bool>) {
    if stopping.wait_for(|requested| *requested).await.is_err() {
        // The pool keeps the sender while any worker runs.
        std::future::pending::<()>().await;
    }
}

async fn complete<T>(
    mut reply: oneshot::Sender<Result<T>>,
    execution: impl Future<Output = Result<T>>,
    finish: bool,
) {
    if finish {
        let _ = reply.send(execution.await);
        return;
    }
    tokio::select! {
        result = execution => {
            let _ = reply.send(result);
        }
        () = reply.closed() => {}
    }
}

fn panic_message(payload: Box<dyn Any + Send>) -> String {
    if let Some(message) = payload.downcast_ref::<String>() {
        return message.clone();
    }
    if let Some(message) = payload.downcast_ref::<&str>() {
        return (*message).to_owned();
    }
    "Rust worker panicked".into()
}