fetchlet 0.1.0

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
use std::rc::Rc;

use anyhow::{Result, anyhow};
use boa_engine::builtins::promise::{OperationType, Promise, PromiseState};
use boa_engine::context::HostHooks;
use boa_engine::error::RuntimeLimitError;
use boa_engine::job::JobCallback;
use boa_engine::object::JsObject;
use boa_engine::object::builtins::JsFunction;
use boa_engine::object::builtins::JsPromise;
use boa_engine::object::builtins::{JsArrayBuffer, JsUint8Array};
use boa_engine::{
    Context, JsArgs, JsData, JsError, JsNativeError, JsResult, JsString, JsValue, NativeFunction,
    Source, js_string,
};
use boa_gc::{Finalize, Trace};
use serde_json::Value;

use super::{BoaOptions, array_buffer, stack_trace};
use crate::Instance;
use crate::backend::Startup;
use crate::bridge::GuestLink;
use crate::execution::{
    FLUSH_REJECTIONS, HOST_BOOTSTRAP, Interrupt, Interrupted, LOOP_STEP, LoopState, PRELUDE,
    SEAL_HOST, STACK_TRACE, WakeSignal, invocation, observed,
};

pub struct Boa {
    context: Context,
    interrupt: Interrupt,
    poisoned: bool,
    wake: WakeSignal,
}

/// The link to the host and the instance's interrupt, which Boa's natives
/// and hooks reach through the context.
struct BoaHost(GuestLink, Interrupt);

impl Boa {
    pub fn new(source: &str) -> Result<Self> {
        Self::with_host(
            &Startup::unchecked(source),
            GuestLink::default(),
            BoaOptions::default(),
        )
    }

    pub(crate) fn with_host(
        startup: &Startup<'_>,
        host: GuestLink,
        options: BoaOptions,
    ) -> Result<Self> {
        let mut context = Context::builder()
            .host_hooks(Rc::new(EngineHooks))
            .build()
            .map_err(|error| anyhow!("{error}"))?;
        options.apply(&mut context);
        // Host-defined data contains no JS values and stays with its Context.
        let wake = host.wake_signal();
        let interrupt = startup.interrupt();
        context.insert_data(BoaHost(host, interrupt.clone()));
        interrupt.arm_startup(startup.deadline());
        let loaded = load(&mut context, startup);
        interrupt.disarm();
        if let Err(error) = loaded {
            return Err(match interrupt.stopped() {
                Some(reason) => Interrupted(reason).into(),
                None => error,
            });
        }
        Ok(Self {
            context,
            interrupt,
            poisoned: false,
            wake,
        })
    }
}

/// Install the host's natives and evaluate the scripts and the module.
fn load(context: &mut Context, startup: &Startup<'_>) -> Result<()> {
    array_buffer::install(context).map_err(|error| anyhow!("{error}"))?;
    stack_trace::install(context).map_err(|error| anyhow!("{error}"))?;
    context
        .register_global_callable(
            js_string!("__fetchletHost"),
            2,
            NativeFunction::from_fn_ptr(|_, args, ctx| {
                check_interrupt(ctx)?;
                let operation = args
                    .get_or_undefined(0)
                    .to_string(ctx)?
                    .to_std_string_escaped();
                let input = args
                    .get_or_undefined(1)
                    .to_string(ctx)?
                    .to_std_string_escaped();
                let host = ctx.get_data::<BoaHost>().expect("host installed");
                Ok(JsString::from(host.0.dispatch(operation, input)).into())
            }),
        )
        .map_err(|error| anyhow!("{error}"))?;
    context
        .register_global_callable(
            js_string!("__fetchletTakeBytes"),
            1,
            NativeFunction::from_fn_ptr(take_bytes),
        )
        .map_err(|error| anyhow!("{error}"))?;
    context
        .register_global_callable(
            js_string!("__fetchletPutBytes"),
            1,
            NativeFunction::from_fn_ptr(put_bytes),
        )
        .map_err(|error| anyhow!("{error}"))?;
    context
        .eval(Source::from_bytes(ASYNC_CONTEXT_SLOT))
        .map_err(|error| anyhow!("{error}"))?;
    context
        .eval(Source::from_bytes(STACK_TRACE))
        .map_err(|error| anyhow!("{error}"))?;
    context
        .eval(Source::from_bytes(PRELUDE))
        .map_err(|error| anyhow!("{error}"))?;
    context
        .eval(Source::from_bytes(HOST_BOOTSTRAP))
        .map_err(|error| anyhow!("{error}"))?;
    let report = match startup.check().probe() {
        Some(probe) => Some(
            context
                .eval(Source::from_bytes(probe))
                .and_then(|value| value.to_string(context))
                .map_err(|error| anyhow!("{error}"))?
                .to_std_string_escaped(),
        ),
        None => None,
    };
    startup.check().admit(report.as_deref())?;
    context
        .eval(Source::from_bytes(startup.source()))
        .map_err(|error| anyhow!("{error}"))?;
    context
        .eval(Source::from_bytes(SEAL_HOST))
        .map_err(|error| anyhow!("{error}"))?;
    Ok(())
}

impl Instance for Boa {
    fn is_reusable(&self) -> bool {
        !self.poisoned
    }

    async fn call_json(&mut self, export: &str, args: &[Value]) -> Result<Value> {
        self.evaluate_until(invocation(export, args)?, None).await
    }
}

impl Boa {
    /// Evaluate an invocation expression and drive its Promise to completion,
    /// stopping JavaScript at its next promise job or host call once
    /// `deadline` or the busy timeout passes, with [`Interrupted`]. Boa has
    /// no interrupt inside its interpreter, so JavaScript that neither
    /// queues jobs nor calls the host runs on. A stopped instance is not
    /// reusable.
    pub(crate) async fn evaluate_until(
        &mut self,
        expression: String,
        deadline: Option<std::time::Instant>,
    ) -> Result<Value> {
        self.interrupt.arm(deadline);
        let result = self.evaluate(expression).await;
        self.interrupt.disarm();
        match self.interrupt.stopped() {
            Some(reason) => {
                self.poisoned = true;
                Err(Interrupted(reason).into())
            }
            None => result,
        }
    }

    /// Evaluate an invocation expression and drive its Promise to completion.
    /// The invocation script owns timer and response-body cleanup.
    async fn evaluate(&mut self, expression: String) -> Result<Value> {
        if self.poisoned {
            anyhow::bail!("Instance cannot be reused after an interrupted call");
        }
        self.poisoned = true;
        // The busy clock runs from each entry into JavaScript, the first
        // evaluation or a return from the loop's wait, until the next wait.
        self.interrupt.enter();
        let result = self
            .context
            .eval(Source::from_bytes(&observed(&expression)))
            .map_err(|error| anyhow!("{error}"))?;
        let promise = result
            .as_promise()
            .ok_or_else(|| anyhow!("Invocation did not return a Promise"))?;
        loop {
            self.context
                .run_jobs()
                .map_err(|error| anyhow!("{error}"))?;
            let state = promise.state();
            if !matches!(state, PromiseState::Pending) {
                self.flush_rejections();
            }
            match state {
                PromiseState::Fulfilled(value) => {
                    self.poisoned = false;
                    let json = value
                        .as_string()
                        .ok_or_else(|| anyhow!("Invocation did not return JSON"))?
                        .to_std_string_escaped();
                    return Ok(serde_json::from_str(&json)?);
                }
                PromiseState::Rejected(value) => {
                    self.poisoned = false;
                    return Err(anyhow!(
                        "{}",
                        value
                            .to_string(&mut self.context)
                            .map_err(|error| anyhow!("{error}"))?
                            .to_std_string_escaped()
                    ));
                }
                PromiseState::Pending => {}
            }
            let state = self
                .context
                .eval(Source::from_bytes(LOOP_STEP))
                .map_err(|error| anyhow!("{error}"))?;
            let state = state
                .to_string(&mut self.context)
                .map_err(|error| anyhow!("{error}"))?
                .to_std_string_escaped();
            let state: LoopState = serde_json::from_str(&state)?;

            self.interrupt.leave();
            if state.progress {
                tokio::task::yield_now().await;
            } else {
                self.wake.wait(state.timer_delay()).await;
            }
            self.interrupt.enter();
        }
    }
}

impl Boa {
    /// Notify unhandled rejections once an invocation settles, and run the
    /// jobs their listeners queue.
    fn flush_rejections(&mut self) {
        let _ = self.context.eval(Source::from_bytes(FLUSH_REJECTIONS));
        let _ = self.context.run_jobs();
    }
}

/// The host hooks: rejection tracking for the profile's global events, and
/// the async context slot carried through promise jobs.
struct EngineHooks;

/// The async context slot. The current mapping lives on an object that the
/// global object holds, where the garbage collector traces it; the hooks
/// read and write it there.
const ASYNC_CONTEXT_SLOT: &str = r#"(() => {
  const slot = {
    mapping: undefined,
  };
  Object.defineProperty(globalThis, "__fetchletAsyncContextSlot", {
    value: slot,
  });
  globalThis.__fetchletAsyncContext = {
    get: () => slot.mapping,
    set: (mapping) => {
      slot.mapping = mapping;
    },
  };
})();"#;

/// The mapping current when a promise reaction was registered.
#[derive(Trace, Finalize, JsData)]
struct CapturedContext(JsValue);

fn async_context_slot(context: &mut Context) -> Option<JsObject> {
    context
        .global_object()
        .get(js_string!("__fetchletAsyncContextSlot"), context)
        .ok()?
        .as_object()
}

impl HostHooks for EngineHooks {
    /// HostMakeJobCallback: Boa calls it whenever a promise reaction is
    /// registered (`then`, `await` and thenable jobs), so the reaction
    /// captures the current mapping, as V8 does with its embedder data.
    fn make_job_callback(&self, callback: JsFunction, context: &mut Context) -> JobCallback {
        let mapping = async_context_slot(context)
            .and_then(|slot| slot.get(js_string!("mapping"), context).ok())
            .unwrap_or_default();
        JobCallback::new(callback, CapturedContext(mapping))
    }

    /// HostCallJobCallback: runs the reaction with its captured mapping
    /// current and restores the previous one afterwards.
    fn call_job_callback(
        &self,
        job: &JobCallback,
        this: &JsValue,
        args: &[JsValue],
        context: &mut Context,
    ) -> JsResult<JsValue> {
        check_interrupt(context)?;
        let Some(slot) = async_context_slot(context) else {
            return job.callback().call(this, args, context);
        };
        let captured = job
            .host_defined()
            .downcast_ref::<CapturedContext>()
            .map(|captured| captured.0.clone())
            .unwrap_or_default();
        let previous = slot.get(js_string!("mapping"), context)?;
        slot.set(js_string!("mapping"), captured, false, context)?;
        let result = job.callback().call(this, args, context);
        slot.set(js_string!("mapping"), previous, false, context)?;
        result
    }

    /// HostPromiseRejectionTracker: hands each rejection without a handler,
    /// and each handler added after one, to the profile's tracking hook.
    fn promise_rejection_tracker(
        &self,
        promise: &JsObject<Promise>,
        operation: OperationType,
        context: &mut Context,
    ) {
        let global = context.global_object();
        let Ok(hook) = global.get(js_string!("__fetchletPromiseRejection"), context) else {
            return;
        };
        let Some(hook) = hook.as_callable() else {
            return;
        };
        let promise = promise.clone().upcast();
        let reason = match JsPromise::from_object(promise.clone()).map(|promise| promise.state()) {
            Ok(PromiseState::Rejected(reason)) => reason,
            _ => JsValue::undefined(),
        };
        let handled = JsValue::from(operation == OperationType::Handle);
        let _ = hook.call(
            &JsValue::undefined(),
            &[promise.into(), reason, handled],
            context,
        );
    }
}

fn host(context: &Context) -> GuestLink {
    context
        .get_data::<BoaHost>()
        .expect("host installed")
        .0
        .clone()
}

/// Stop JavaScript with an error it cannot catch once the instance's
/// interrupt expires. Boa checks at promise jobs and host calls, the points
/// where it hands control to fetchlet.
fn check_interrupt(context: &Context) -> JsResult<()> {
    let expired = context
        .get_data::<BoaHost>()
        .is_some_and(|host| host.1.expired());
    if expired {
        // Boa reports runtime limits as engine errors, which `try`/`catch`
        // and promise handlers do not see. The evaluation is classified by
        // the interrupt's recorded reason, not by this error's text.
        return Err(RuntimeLimitError::LoopIteration.into());
    }
    Ok(())
}

fn type_error(message: &str) -> JsError {
    JsNativeError::typ().with_message(message.to_owned()).into()
}

/// `__fetchletTakeBytes(handle)`: a Uint8Array with bytes Rust stored.
fn take_bytes(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    check_interrupt(context)?;
    let handle = args.get_or_undefined(0).to_number(context)?;
    let bytes = host(context)
        .take_guest_bytes(handle)
        .map_err(|error| type_error(error.guest_message()))?;
    Ok(JsUint8Array::from_iter(bytes.iter().copied(), context)?.into())
}

/// `__fetchletPutBytes(view)`: copy a Uint8Array into the store; returns its handle.
fn put_bytes(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    check_interrupt(context)?;
    let view = args
        .get_or_undefined(0)
        .as_object()
        .and_then(|object| JsUint8Array::from_object(object.clone()).ok())
        .ok_or_else(|| type_error("expected a Uint8Array"))?;
    let offset = view.byte_offset(context)?;
    let length = view.length(context)?;
    let buffer = view
        .buffer(context)?
        .as_object()
        .and_then(|object| JsArrayBuffer::from_object(object.clone()).ok())
        .ok_or_else(|| type_error("expected an ArrayBuffer-backed Uint8Array"))?;
    let host = host(context);
    let data = buffer
        .data()
        .ok_or_else(|| type_error("detached byte array"))?;
    let bytes = offset
        .checked_add(length)
        .and_then(|end| data.get(offset..end))
        .ok_or_else(|| type_error("byte array is out of bounds"))?;
    let handle = host
        .put_guest_bytes(bytes)
        .map_err(|error| type_error(error.guest_message()))?;
    Ok(JsValue::from(handle as f64))
}