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
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
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::task::Poll;

use bytes::Bytes;
use serde::Deserialize;
use serde_json::{Value, json};

use super::body_source::{BodyRead, BodySource};
use super::channels::{GuestClose, GuestMessage, GuestPause, GuestWrite};
use super::clock::Clock;
use super::functions::{self, CallMessage, PendingCalls, Resources};
use super::handles::{Handles, Resource};
use super::upload::{UploadWrite, Uploads};
use crate::config::check_limit;
use crate::execution::WakeSignal;
use crate::host::{GuestEnd, Method, Redirect, TransportFuture, pair};
use crate::reentry;
use crate::wire::{BodyTransfer, BridgeBytes, ByteStore, WireBytes, WireRequest, WireResponse};
use crate::{
    Body, ChannelEnd, ChannelRequest, CloseFrame, ConsoleLevel, Context, Error, FunctionRequest,
    HostServices, Limits, Response, Result, SecureTransport, SocketAddress,
};

struct PendingFetch {
    future: TransportFuture,
}

/// A read of a body source, of its next chunk or of all the rest.
struct PendingRead {
    id: u64,
    whole: Option<Whole>,
}

/// How a whole-body read hands the body to JavaScript.
#[derive(Clone, Copy)]
pub(super) enum Whole {
    /// One buffer in the byte store.
    Bytes,
    /// A string, decoded as Fetch's `text()` decodes: UTF-8 without a
    /// leading byte order mark, with U+FFFD for invalid sequences.
    Text,
}

struct InvocationState {
    generation: u64,
    next_ticket: u64,
    started_fetches: usize,
    /// `channel.open` attempts, which `Limits::open_channels` bounds.
    opened_channels: usize,
    /// Calls of `Functions` methods, which `Limits::function_calls` bounds.
    function_calls: usize,
    limits: Limits,
    pending_fetches: BTreeMap<String, PendingFetch>,
    /// Async calls of `Functions` methods not yet finished.
    pending_calls: PendingCalls,
    bytes: ByteStore,
    /// What JavaScript reaches by handle: Rust bodies it reads on demand and
    /// channels it holds, such as an accepted WebSocket.
    handles: Handles,
    /// Outstanding `body.read` and `body.readAll` tickets.
    pending_reads: BTreeMap<String, PendingRead>,
    /// Request bodies JavaScript streams to outbound fetches.
    uploads: Uploads,
    /// `fetchlet.waitUntil` registrations, and those not yet settled.
    background_registered: usize,
    background_pending: usize,
    /// Trusted values attached to each host fetch of this invocation.
    context: Option<Context>,
    /// Set when the client of this Fetch invocation went away; JavaScript
    /// aborts the request's signal when it sees it.
    disconnect: Option<Disconnect>,
    /// Web API state, such as open compression streams.
    #[cfg(fetchlet_web)]
    web: fetchlet_web::WebState,
    /// Whether this Fetch invocation may accept a WebSocket upgrade.
    upgrade: Upgrade,
}

/// The WebSocket upgrade of a Fetch invocation.
enum Upgrade {
    /// The request did not ask for one, or the host cannot hold it.
    Unavailable,
    Available,
    /// JavaScript accepted it; Rust's end waits for the response.
    Accepted {
        id: u64,
        end: Option<ChannelEnd>,
    },
}

/// Tells a running Fetch invocation that its client went away.
///
/// The worker signals it while it lets a cancelled call finish
/// ([`CancelledCalls::Finish`](crate::CancelledCalls::Finish)); the engine
/// wakes, and JavaScript aborts the request's signal at its next host step.
#[derive(Clone)]
pub(crate) struct Disconnect {
    gone: Arc<AtomicBool>,
    wake: WakeSignal,
}

impl Disconnect {
    #[cfg_attr(
        not(any(feature = "boa", feature = "quickjs", feature = "v8")),
        allow(dead_code)
    )]
    pub fn signal(&self) {
        self.gone.store(true, Ordering::Release);
        self.wake.notify();
    }

    fn is_signalled(&self) -> bool {
        self.gone.load(Ordering::Acquire)
    }
}

impl InvocationState {
    fn next_ticket(&mut self) -> Result<String> {
        self.next_ticket = self
            .next_ticket
            .checked_add(1)
            .ok_or(Error::LimitExceeded("host operation tickets"))?;
        Ok(format!("{}:{}", self.generation, self.next_ticket))
    }

    fn bridge_bytes(&mut self) -> InvocationBytes<'_> {
        InvocationBytes {
            bytes: &mut self.bytes,
            handles: &mut self.handles,
        }
    }
}

/// How bytes cross the bridge within the locked state of an invocation:
/// through its byte store, and its handle table for streamed bodies.
struct InvocationBytes<'a> {
    bytes: &'a mut ByteStore,
    handles: &'a mut Handles,
}

impl BridgeBytes for InvocationBytes<'_> {
    fn send(&mut self, bytes: Bytes) -> Result<WireBytes> {
        self.bytes.put(bytes).map(WireBytes::Handle)
    }

    fn receive(&mut self, bytes: WireBytes) -> Result<Bytes> {
        match bytes {
            WireBytes::Handle(handle) => self.bytes.take(handle),
            WireBytes::Inline(bytes) => Ok(bytes.into()),
        }
    }

    fn stream(
        &mut self,
        body: Body,
        limit: Option<usize>,
        resource: &'static str,
    ) -> Result<BodyTransfer> {
        if body.is_buffered() {
            return Ok(BodyTransfer::Collect(body));
        }
        // A declared length over the budget fails before JavaScript reads it.
        check_limit(limit, body.declared_len(), resource)?;
        self.handles
            .insert(Resource::Body(BodySource::new(body, limit, resource)))
            .map(BodyTransfer::Stream)
    }
}

#[derive(Default)]
struct BridgeState {
    generation: u64,
    invocation: Option<InvocationState>,
    /// The handle table between invocations, every entry released. Its
    /// generations carry over, so an earlier invocation's handles stay stale.
    handles: Handles,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct FetchStartRequest {
    request: WireRequest,
    #[serde(default)]
    redirect: Redirect,
    service: Option<String>,
    /// JavaScript streams the body with `fetch.upload` instead of sending
    /// it in `request`.
    #[serde(default)]
    upload: bool,
}

struct Completion {
    id: String,
    result: Value,
}

impl Completion {
    /// Moves the result into the message; a whole body read as text can be
    /// megabytes long.
    fn into_value(self) -> Value {
        json!({ "id": self.id, "result": self.result })
    }
}

/// Native callbacks retain this handle rather than request-scoped JS globals.
#[derive(Clone)]
pub(crate) struct HostBridge {
    services: HostServices,
    state: Arc<Mutex<BridgeState>>,
    limits: Limits,
    wake: WakeSignal,
    clock: Clock,
    /// The application identity used to refuse reentrant calls.
    key: u64,
    /// The runtime whose context host futures are polled in, if not the
    /// instance's own ([`AppBuilder::host_runtime`](crate::AppBuilder::host_runtime)).
    runtime: Option<tokio::runtime::Handle>,
}

impl Default for HostBridge {
    fn default() -> Self {
        Self::new(HostServices::default())
    }
}

impl HostBridge {
    pub fn new(services: HostServices) -> Self {
        Self::with_limits(services, Limits::default())
    }

    pub fn with_limits(services: HostServices, limits: Limits) -> Self {
        Self {
            services,
            state: Arc::new(Mutex::new(BridgeState::default())),
            limits,
            wake: WakeSignal::default(),
            clock: Clock::default(),
            key: reentry::new_key(),
            runtime: None,
        }
    }

    /// Use the identity of an application whose worker recreates instances.
    #[cfg_attr(
        not(any(feature = "boa", feature = "quickjs", feature = "v8")),
        allow(dead_code)
    )]
    pub fn with_key(mut self, key: u64) -> Self {
        self.key = key;
        self
    }

    /// Poll host futures in the context of `runtime`.
    #[cfg_attr(
        not(any(feature = "boa", feature = "quickjs", feature = "v8")),
        allow(dead_code)
    )]
    pub fn with_runtime(mut self, runtime: tokio::runtime::Handle) -> Self {
        self.runtime = Some(runtime);
        self
    }

    #[cfg_attr(
        not(any(feature = "boa", feature = "quickjs", feature = "v8")),
        allow(dead_code)
    )]
    pub fn wake_signal(&self) -> WakeSignal {
        self.wake.clone()
    }

    /// A new disconnect token for a Fetch invocation of this bridge.
    #[cfg_attr(
        not(any(feature = "boa", feature = "quickjs", feature = "v8")),
        allow(dead_code)
    )]
    pub fn disconnect(&self) -> Disconnect {
        Disconnect {
            gone: Arc::default(),
            wake: self.wake.clone(),
        }
    }

    /// Attach `disconnect` to the current invocation.
    #[cfg_attr(
        not(any(feature = "boa", feature = "quickjs", feature = "v8")),
        allow(dead_code)
    )]
    pub fn watch_disconnect(&self, disconnect: Disconnect) -> Result<()> {
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
        invocation.disconnect = Some(disconnect);
        Ok(())
    }

    /// Let the current Fetch invocation accept a WebSocket upgrade.
    #[cfg_attr(
        not(any(feature = "boa", feature = "quickjs", feature = "v8")),
        allow(dead_code)
    )]
    pub fn allow_upgrade(&self) -> Result<()> {
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
        // An upgrade already accepted stays accepted.
        if matches!(invocation.upgrade, Upgrade::Unavailable) {
            invocation.upgrade = Upgrade::Available;
        }
        Ok(())
    }

    /// Enter a channel Rust lends to the current call in its table. It opens
    /// at the next poll, as a service's open does.
    #[cfg_attr(
        not(any(feature = "boa", feature = "quickjs", feature = "v8")),
        allow(dead_code)
    )]
    pub fn lend_channel(&self, end: GuestEnd) -> Result<u64> {
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
        let id = invocation
            .handles
            .open_requested(end, Box::pin(async { Ok(()) }))?;
        self.wake.notify();
        Ok(id)
    }

    /// Store bytes Rust passes to the current call for JavaScript to take.
    /// The caller that passes them owns their size.
    #[cfg_attr(
        not(any(feature = "boa", feature = "quickjs", feature = "v8")),
        allow(dead_code)
    )]
    pub fn put_bytes(&self, bytes: Bytes) -> Result<u64> {
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
        invocation.bytes.put(bytes)
    }

    /// Rust's end of the upgrade that the Fetch result returned as `id`.
    #[cfg_attr(
        not(any(feature = "boa", feature = "quickjs", feature = "v8")),
        allow(dead_code)
    )]
    pub fn take_upgrade(&self, id: u64) -> Result<ChannelEnd> {
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
        match &mut invocation.upgrade {
            Upgrade::Accepted { id: accepted, end } if *accepted == id => end
                .take()
                .ok_or_else(|| Error::InvalidRequest("upgrade already returned".into())),
            _ => Err(Error::InvalidRequest("unknown upgrade".into())),
        }
    }

    /// Close the current invocation's channels on the host's behalf.
    #[cfg_attr(
        not(any(feature = "boa", feature = "quickjs", feature = "v8")),
        allow(dead_code)
    )]
    pub fn close_channels(&self, frame: &CloseFrame) {
        if let Ok(mut state) = self.lock_state()
            && let Some(invocation) = state.invocation.as_mut()
        {
            invocation.handles.force_channels(frame);
        }
        self.wake.notify();
    }

    fn effective_limits(&self) -> Result<Limits> {
        let state = self.lock_state()?;
        Ok(state
            .invocation
            .as_ref()
            .map(|invocation| invocation.limits.clone())
            .unwrap_or_else(|| self.limits.clone()))
    }

    #[cfg(any(feature = "fuzzing", test))]
    pub fn begin(&self, limits: Limits) -> Result<InvocationScope> {
        self.begin_with_context(limits, None)
    }

    pub fn begin_with_context(
        &self,
        limits: Limits,
        context: Option<Context>,
    ) -> Result<InvocationScope> {
        let mut state = self.lock_state()?;
        if state.invocation.is_some() {
            return Err(Error::InstanceUnavailable);
        }

        state.generation = state
            .generation
            .checked_add(1)
            .ok_or(Error::LimitExceeded("invocation IDs"))?;

        let generation = state.generation;
        let handles = std::mem::take(&mut state.handles);
        state.invocation = Some(InvocationState {
            generation,
            next_ticket: 0,
            started_fetches: 0,
            opened_channels: 0,
            function_calls: 0,
            limits,
            pending_fetches: BTreeMap::new(),
            pending_calls: PendingCalls::default(),
            bytes: ByteStore::default(),
            handles,
            pending_reads: BTreeMap::new(),
            uploads: Uploads::default(),
            background_registered: 0,
            background_pending: 0,
            context,
            disconnect: None,
            #[cfg(fetchlet_web)]
            web: fetchlet_web::WebState::default(),
            upgrade: Upgrade::Unavailable,
        });

        Ok(InvocationScope {
            bridge: self.clone(),
            generation,
        })
    }

    pub fn dispatch(&self, operation: String, input: String) -> String {
        let reply = encode_reply(self.dispatch_operation(&operation, &input)).to_string();
        #[cfg(feature = "operation-counts")]
        crate::diagnostics::record(&operation, input.len(), reply.len());
        reply
    }

    /// Copy bytes from a JavaScript typed array into the current invocation.
    ///
    /// Each buffer is one bridge message from the guest, so
    /// `bridge_message_bytes` applies to it, as to JSON messages.
    pub fn put_guest_bytes(&self, bytes: &[u8]) -> Result<u64> {
        #[cfg(feature = "operation-counts")]
        crate::diagnostics::record("bytes.put", bytes.len(), 0);
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
        check_limit(
            invocation.limits.bridge_message_bytes,
            bytes.len(),
            "bridge message bytes",
        )?;
        invocation.bytes.put_guest(Bytes::copy_from_slice(bytes))
    }

    /// Store bytes from an isolated instance's child under the handle it
    /// picked, with the checks of `put_guest_bytes`.
    #[cfg(fetchlet_process)]
    pub fn put_guest_bytes_at(&self, handle: u64, bytes: Bytes) -> Result<()> {
        #[cfg(feature = "operation-counts")]
        crate::diagnostics::record("bytes.put", bytes.len(), 0);
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
        check_limit(
            invocation.limits.bridge_message_bytes,
            bytes.len(),
            "bridge message bytes",
        )?;
        invocation.bytes.put_guest_at(handle, bytes)
    }

    /// Whether the client of the current invocation went away, which an
    /// isolated instance's parent tells its child.
    #[cfg(fetchlet_process)]
    pub fn is_disconnected(&self) -> bool {
        matches!(self.invocation_disconnected(), Ok(Value::Bool(true)))
    }

    /// Take bytes by a handle that a JavaScript number carried.
    pub fn take_guest_bytes(&self, handle: f64) -> Result<Bytes> {
        // Handles are positive integers below 2^53, exact in a JS number.
        if !((1.0..=9_007_199_254_740_991.0).contains(&handle) && handle.fract() == 0.0) {
            return Err(Error::InvalidRequest("invalid byte handle".into()));
        }
        let bytes = self.take_bytes(handle as u64);
        #[cfg(feature = "operation-counts")]
        if let Ok(bytes) = &bytes {
            crate::diagnostics::record("bytes.take", 0, bytes.len());
        }
        bytes
    }

    /// Take bytes that the other side of the current invocation stored.
    pub fn take_bytes(&self, handle: u64) -> Result<Bytes> {
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
        invocation.bytes.take(handle)
    }

    /// Let JavaScript in the current invocation read `body` on demand.
    #[cfg(any(test, feature = "fuzzing"))]
    pub fn open_body(
        &self,
        body: Body,
        limit: Option<usize>,
        resource: &'static str,
    ) -> Result<u64> {
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
        invocation
            .handles
            .insert(Resource::Body(BodySource::new(body, limit, resource)))
    }

    fn with_bridge_bytes<T>(
        &self,
        operation: impl FnOnce(&mut InvocationBytes<'_>) -> Result<T>,
    ) -> Result<T> {
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
        operation(&mut invocation.bridge_bytes())
    }

    fn lock_state(&self) -> Result<MutexGuard<'_, BridgeState>> {
        self.state.lock().map_err(|_| Error::InstanceUnavailable)
    }

    pub(super) fn dispatch_operation(&self, operation: &str, input: &str) -> Result<Value> {
        let limits = self.effective_limits()?;
        check_limit(
            limits.bridge_message_bytes,
            input.len(),
            "bridge message bytes",
        )?;

        #[cfg(fetchlet_web)]
        if let Some(result) = self.web_operation(operation, input) {
            return result;
        }

        match operation {
            "background.register" => self.register_background(),
            "background.settle" => self.settle_background(),
            "bindings" => Ok(self.bindings()),
            "body.cancel" => self.cancel_body(input),
            "body.read" => self.read_body(input, None),
            "body.readAll" => self.read_body(input, Some(Whole::Bytes)),
            "body.readText" => self.read_body(input, Some(Whole::Text)),
            "channel.buffered" => self.channel_buffered(input),
            "channel.close" => self.close_channel(input),
            "channel.open" => self.open_channel(input),
            "channel.pause" => self.pause_channel(input),
            "channel.send" => self.send_channel(input),
            "channel.write" => self.write_channel(input),
            "clock" => Ok(self.clock.read()),
            "console.write" => self.write_console(input),
            "fetch.cancel" => self.cancel_fetch(input),
            "fetch.limits" => self.fetch_limits(),
            "fetch.start" => self.start_fetch(input),
            "fetch.upload" => self.write_upload(input),
            "function.call" => self.call_function(input, false),
            "function.start" => self.call_function(input, true),
            "host.poll" => self.poll_host(),
            "invocation.disconnected" => self.invocation_disconnected(),
            "socket.end" => self.end_socket(input),
            "socket.open" => self.open_socket(input),
            "socket.startTls" => self.start_socket_tls(input),
            "websocket.open" => self.open_websocket(input),
            "websocket.upgrade" => self.upgrade_websocket(),
            _ => Err(Error::PermissionDenied),
        }
    }

    /// A Web API operation of `fetchlet-web`, with the current invocation's
    /// state and byte store when one is active, or None for other operations.
    #[cfg(fetchlet_web)]
    fn web_operation(&self, operation: &str, input: &str) -> Option<Result<Value>> {
        let mut state = match self.lock_state() {
            Ok(state) => state,
            Err(error) => return Some(Err(error)),
        };
        match state.invocation.as_mut() {
            Some(invocation) => {
                let limits = invocation.limits.web();
                fetchlet_web::dispatch(
                    operation,
                    input,
                    &limits,
                    Some(fetchlet_web::Invocation {
                        state: &mut invocation.web,
                        bytes: &mut WebBytes(&mut invocation.bytes),
                    }),
                )
            }
            None => {
                fetchlet_web::dispatch::<WebBytes<'_>>(operation, input, &self.limits.web(), None)
            }
        }
    }

    fn bindings(&self) -> Value {
        let service_names: Vec<_> = self.services.services.keys().collect();
        let channel_names: Vec<_> = self.services.channels.keys().collect();
        let functions: serde_json::Map<String, Value> = self
            .services
            .functions
            .iter()
            .map(|(name, functions)| (name.clone(), functions.describe()))
            .collect();

        json!({
            "env": self.services.env,
            "processEnv": self.services.process_env,
            "services": service_names,
            "channels": channel_names,
            "functions": functions,
            "console": self.services.console.is_some(),
        })
    }

    fn write_console(&self, input: &str) -> Result<Value> {
        #[derive(Deserialize)]
        struct Message<'a> {
            level: &'a str,
            #[serde(borrow)]
            message: std::borrow::Cow<'a, str>,
        }
        let sink = self
            .services
            .console
            .as_ref()
            .ok_or(Error::PermissionDenied)?;
        let message: Message<'_> = serde_json::from_str(input)
            .map_err(|_| Error::InvalidRequest("invalid console message".into()))?;
        let level = ConsoleLevel::parse(message.level)
            .ok_or_else(|| Error::InvalidRequest("unknown console level".into()))?;
        sink.write(level, &message.message);
        Ok(Value::Null)
    }

    /// The budgets JavaScript applies as it reads an outbound request
    /// body, before `fetch.start` sends it.
    fn fetch_limits(&self) -> Result<Value> {
        let state = self.lock_state()?;
        let invocation = state.invocation.as_ref().ok_or(Error::InvocationClosed)?;
        Ok(fetch_limits_reply(&invocation.limits))
    }

    /// Whether the client of the current invocation went away. Outside a
    /// Fetch invocation, or between invocations, it has not.
    fn invocation_disconnected(&self) -> Result<Value> {
        let state = self.lock_state()?;
        Ok(Value::Bool(state.invocation.as_ref().is_some_and(
            |invocation| {
                invocation
                    .disconnect
                    .as_ref()
                    .is_some_and(Disconnect::is_signalled)
            },
        )))
    }

    pub(super) fn start_fetch(&self, input: &str) -> Result<Value> {
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;

        let started = invocation
            .started_fetches
            .checked_add(1)
            .ok_or(Error::LimitExceeded("subrequest counter"))?;
        check_limit(invocation.limits.subrequests, started, "subrequests")?;
        invocation.started_fetches = started;

        let start: FetchStartRequest = serde_json::from_str(input)
            .map_err(|_| Error::InvalidRequest("invalid fetch message".into()))?;
        let service = match start.service {
            Some(name) => self.services.services.get(&name),
            None => self.services.outbound.as_ref(),
        }
        .cloned()
        .ok_or(Error::PermissionDenied)?;

        let mut request = start
            .request
            .into_http(&invocation.limits, &mut invocation.bytes)?;
        if let Some(context) = &invocation.context {
            request.extensions_mut().insert(context.clone());
        }
        let upload = if start.upload {
            if matches!(*request.method(), http::Method::GET | http::Method::HEAD) {
                return Err(Error::InvalidRequest("GET/HEAD request has a body".into()));
            }
            let ticket = invocation.next_ticket()?;
            *request.body_mut() = invocation.uploads.open(ticket.clone(), self.wake.clone());
            Some(ticket)
        } else {
            None
        };
        let limits = invocation.limits.clone();
        let future =
            Box::pin(async move { service.execute(request, start.redirect, limits).await });

        let ticket = invocation.next_ticket()?;
        invocation
            .pending_fetches
            .insert(ticket.clone(), PendingFetch { future });

        Ok(json!({ "ticket": ticket, "upload": upload }))
    }

    /// Take the next chunk, the end or the failure of a request body
    /// JavaScript streams. Each chunk is one bridge message.
    fn write_upload(&self, input: &str) -> Result<Value> {
        let write: UploadWrite = serde_json::from_str(input)
            .map_err(|_| Error::InvalidRequest("invalid upload write".into()))?;
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
        let chunk = write
            .chunk
            .map(|handle| invocation.bytes.take(handle))
            .transpose()?;
        let chunks = invocation.limits.request_body_chunks;
        invocation.uploads.write(write, chunk, chunks)
    }

    /// Call a method of a `Functions` binding: a sync method at once,
    /// returning its outcome, or with `start` an async method, returning
    /// the ticket its outcome arrives with in `host.poll`.
    fn call_function(&self, input: &str, start: bool) -> Result<Value> {
        let (method, request, result_bytes) = {
            let mut state = self.lock_state()?;
            let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
            let called = invocation
                .function_calls
                .checked_add(1)
                .ok_or(Error::LimitExceeded("function call counter"))?;
            check_limit(invocation.limits.function_calls, called, "function calls")?;
            invocation.function_calls = called;

            let message: CallMessage = serde_json::from_str(input)
                .map_err(|_| Error::InvalidRequest("invalid function call".into()))?;
            let (args, bytes) =
                functions::arguments(message.args, message.bytes, &mut invocation.bytes)?;
            let method = self
                .services
                .functions
                .get(&message.binding)
                .and_then(|functions| functions.get(&message.method))
                .cloned()
                .ok_or(Error::PermissionDenied)?;
            let request = FunctionRequest::new(
                message.method,
                args,
                bytes,
                invocation.context.clone(),
                invocation.limits.clone(),
            );
            (method, request, invocation.limits.bridge_message_bytes)
        };

        // The method runs without the bridge's lock. Host code must not call
        // this application again, and what it spawns belongs to the host
        // runtime.
        let running = reentry::enter(self.key);
        let runtime = self.runtime.as_ref().map(tokio::runtime::Handle::enter);
        match (method, start) {
            (Method::Sync(method), false) => {
                let result = functions::run_sync(|| method(request));
                drop(runtime);
                drop(running);
                let mut state = self.lock_state()?;
                let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
                let mut resources = Resources {
                    bytes: &mut invocation.bytes,
                    handles: &mut invocation.handles,
                };
                let outcome = functions::outcome(result, result_bytes, &mut resources);
                // A channel in the result opens at the next poll.
                self.wake.notify();
                Ok(outcome)
            }
            (Method::Async(method), true) => {
                let future = functions::start_async(|| method(request));
                drop(runtime);
                drop(running);
                let mut state = self.lock_state()?;
                let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
                let ticket = invocation.next_ticket()?;
                invocation.pending_calls.insert(ticket.clone(), future);
                // The future is first polled at the next pump.
                self.wake.notify();
                Ok(Value::String(ticket))
            }
            _ => Err(Error::InvalidRequest("wrong kind of function call".into())),
        }
    }

    pub(super) fn poll_host(&self) -> Result<Value> {
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;

        // Engines pump host futures between microtasks and yield between pumps.
        // The futures stay in this scope; no detached tasks need to be aborted.
        let waker = self.wake.waker();
        let mut context = std::task::Context::from_waker(&waker);
        let mut completed = Vec::new();
        // Host code polled here must not call this application again.
        let _polling = reentry::enter(self.key);
        // Tasks, timers and I/O that host futures create belong to the host
        // runtime, so they progress while this instance runs JavaScript.
        let _runtime = self.runtime.as_ref().map(tokio::runtime::Handle::enter);

        let InvocationState {
            pending_fetches,
            pending_calls,
            limits,
            bytes,
            handles,
            pending_reads,
            uploads: invocation_uploads,
            ..
        } = invocation;
        let mut bridge_bytes = InvocationBytes { bytes, handles };

        for (ticket, pending) in pending_fetches.iter_mut() {
            let Poll::Ready(response) = pending.future.as_mut().poll(&mut context) else {
                continue;
            };

            let result =
                response.and_then(|response| encode_response(response, limits, &mut bridge_bytes));

            completed.push(Completion {
                id: ticket.clone(),
                result: encode_reply(result),
            });
        }

        for completion in &completed {
            pending_fetches.remove(&completion.id);
        }

        let mut finished_calls = Vec::new();
        pending_calls.poll(
            &mut context,
            limits.bridge_message_bytes,
            &mut Resources {
                bytes: &mut *bridge_bytes.bytes,
                handles: &mut *bridge_bytes.handles,
            },
            &mut finished_calls,
        );
        completed.extend(
            finished_calls
                .into_iter()
                .map(|(id, result)| Completion { id, result }),
        );

        let InvocationBytes { bytes, handles } = bridge_bytes;
        pending_reads.retain(|ticket, read| {
            let id = read.id;
            let result = match handles.body_mut(id) {
                Some(source) if let Some(whole) = read.whole => {
                    match source.poll_read_all(&mut context) {
                        Poll::Pending => return true,
                        Poll::Ready(Ok(body)) => match whole {
                            Whole::Bytes => bytes
                                .put(body)
                                .map(|handle| json!({ "chunk": handle, "done": true })),
                            Whole::Text => Ok(json!({ "text": utf8_decode(&body), "done": true })),
                        },
                        Poll::Ready(Err(error)) => Err(error),
                    }
                }
                Some(source) => match source.poll_read(&mut context) {
                    Poll::Pending => return true,
                    Poll::Ready(Ok(BodyRead::Chunk(chunk))) => bytes
                        .put(chunk)
                        .map(|handle| json!({ "chunk": handle, "done": false })),
                    Poll::Ready(Ok(BodyRead::Done)) => Ok(json!({ "chunk": null, "done": true })),
                    Poll::Ready(Err(error)) => Err(error),
                },
                None => Err(Error::InvocationClosed),
            };
            // A finished or failed body releases its producer now.
            if !matches!(result, Ok(ref value) if value["done"] == false) {
                handles.release_body(id);
            }
            completed.push(Completion {
                id: ticket.clone(),
                result: encode_reply(result),
            });
            false
        });

        let mut events: Vec<Value> = completed.into_iter().map(Completion::into_value).collect();
        // Pulls and cancels of streamed request bodies.
        invocation_uploads.poll(&mut events);
        // Messages and closes of channels, each channel's in order.
        if handles.has_channels() {
            handles.poll_channels(&mut context, bytes, &mut events)?;
        }
        Ok(Value::Array(events))
    }

    pub(super) fn cancel_fetch(&self, input: &str) -> Result<Value> {
        let ticket: String = serde_json::from_str(input)
            .map_err(|_| Error::InvalidRequest("invalid fetch ticket".into()))?;

        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;

        if invocation.pending_fetches.remove(&ticket).is_none() {
            return Err(Error::InvocationClosed);
        }

        Ok(Value::Null)
    }

    /// Accept the WebSocket upgrade of the current Fetch invocation.
    fn upgrade_websocket(&self) -> Result<Value> {
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
        match invocation.upgrade {
            Upgrade::Available => {}
            Upgrade::Accepted { .. } => {
                return Err(Error::InvalidRequest(
                    "the request is already upgraded".into(),
                ));
            }
            Upgrade::Unavailable => return Err(Error::PermissionDenied),
        }
        let (end, guest) = pair(&invocation.limits);
        let id = invocation
            .handles
            .open_connection(guest, &invocation.limits)?;
        invocation.upgrade = Upgrade::Accepted { id, end: Some(end) };
        Ok(Value::from(id))
    }

    /// Open a channel of a bound service for the current invocation. The
    /// handle is JavaScript's at once; the open settles in the host pump.
    fn open_channel(&self, input: &str) -> Result<Value> {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct Open {
            service: String,
            #[serde(default)]
            options: Value,
        }
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
        let opened = invocation
            .opened_channels
            .checked_add(1)
            .ok_or(Error::LimitExceeded("channel counter"))?;
        check_limit(invocation.limits.open_channels, opened, "open channels")?;
        invocation.opened_channels = opened;

        let open: Open = serde_json::from_str(input)
            .map_err(|_| Error::InvalidRequest("invalid channel open".into()))?;
        let service = self
            .services
            .channels
            .get(&open.service)
            .ok_or(Error::PermissionDenied)?;
        let (end, guest) = pair(&invocation.limits);
        let request = ChannelRequest {
            options: open.options,
            context: invocation.context.clone(),
            end,
        };
        // The service builds its future here; host code must not call this
        // application again, and what it spawns belongs to the host runtime.
        let opening = {
            let _opening = reentry::enter(self.key);
            let _runtime = self.runtime.as_ref().map(tokio::runtime::Handle::enter);
            service.open(request)
        };
        let id = invocation.handles.open_requested(guest, opening)?;
        // The open is polled at the next pump.
        self.wake.notify();
        Ok(Value::from(id))
    }

    /// Open a TCP connection through the socket service, as a channel of
    /// the current invocation. The policy is checked now; the connection
    /// settles in the host pump.
    fn open_socket(&self, input: &str) -> Result<Value> {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields, rename_all = "camelCase")]
        struct Open {
            hostname: String,
            port: u16,
            secure_transport: SecureTransportInput,
        }
        #[derive(Deserialize)]
        #[serde(rename_all = "lowercase")]
        enum SecureTransportInput {
            Off,
            On,
            Starttls,
        }
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
        let opened = invocation
            .opened_channels
            .checked_add(1)
            .ok_or(Error::LimitExceeded("channel counter"))?;
        check_limit(invocation.limits.open_channels, opened, "open channels")?;
        invocation.opened_channels = opened;

        let open: Open = serde_json::from_str(input)
            .map_err(|_| Error::InvalidRequest("invalid socket open".into()))?;
        let service = self
            .services
            .sockets
            .as_ref()
            .ok_or(Error::PermissionDenied)?;
        let address = SocketAddress::new(&open.hostname, open.port)?;
        let secure = match open.secure_transport {
            SecureTransportInput::Off => SecureTransport::Off,
            SecureTransportInput::On => SecureTransport::On,
            SecureTransportInput::Starttls => SecureTransport::StartTls,
        };
        let (end, guest) = pair(&invocation.limits);
        let opening = {
            let _opening = reentry::enter(self.key);
            let _runtime = self.runtime.as_ref().map(tokio::runtime::Handle::enter);
            service.open(address, secure, invocation.context.clone(), end)?
        };
        let id =
            invocation
                .handles
                .open_socket(guest, opening, secure == SecureTransport::StartTls)?;
        self.wake.notify();
        Ok(Value::from(id))
    }

    /// `new WebSocket(url, protocols)`: start the handshake through the
    /// WebSocket service. Counts against `Limits::open_channels`.
    fn open_websocket(&self, input: &str) -> Result<Value> {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct Open {
            url: String,
            protocols: Vec<String>,
        }
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
        let opened = invocation
            .opened_channels
            .checked_add(1)
            .ok_or(Error::LimitExceeded("channel counter"))?;
        check_limit(invocation.limits.open_channels, opened, "open channels")?;
        invocation.opened_channels = opened;

        let open: Open = serde_json::from_str(input)
            .map_err(|_| Error::InvalidRequest("invalid WebSocket open".into()))?;
        let service = self
            .services
            .websockets
            .as_ref()
            .ok_or(Error::PermissionDenied)?;
        let (end, guest) = pair(&invocation.limits);
        let handshake = {
            let _opening = reentry::enter(self.key);
            let _runtime = self.runtime.as_ref().map(tokio::runtime::Handle::enter);
            service.open(&open.url, open.protocols, invocation.context.clone(), end)?
        };
        let id = invocation.handles.open_websocket(guest, handshake)?;
        self.wake.notify();
        Ok(Value::from(id))
    }

    /// A socket's writable closed: Rust receives the end of its messages.
    fn end_socket(&self, input: &str) -> Result<Value> {
        let id: u64 = serde_json::from_str(input)
            .map_err(|_| Error::InvalidRequest("invalid socket id".into()))?;
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
        invocation.handles.end_socket(id)
    }

    /// `startTls()`: Rust switches the connection to TLS at this point.
    fn start_socket_tls(&self, input: &str) -> Result<Value> {
        let id: u64 = serde_json::from_str(input)
            .map_err(|_| Error::InvalidRequest("invalid socket id".into()))?;
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
        invocation.handles.start_socket_tls(id)
    }

    fn write_channel(&self, input: &str) -> Result<Value> {
        let write: GuestWrite = serde_json::from_str(input)
            .map_err(|_| Error::InvalidRequest("invalid channel write".into()))?;
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
        let result = invocation
            .handles
            .write_channel(write, &mut invocation.bytes);
        self.wake.notify();
        result
    }

    fn pause_channel(&self, input: &str) -> Result<Value> {
        let pause: GuestPause = serde_json::from_str(input)
            .map_err(|_| Error::InvalidRequest("invalid channel pause".into()))?;
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
        let result = invocation.handles.pause_channel(pause);
        // Arrivals held back while paused are delivered at the next pump.
        self.wake.notify();
        result
    }

    fn send_channel(&self, input: &str) -> Result<Value> {
        let message: GuestMessage = serde_json::from_str(input)
            .map_err(|_| Error::InvalidRequest("invalid channel message".into()))?;
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
        let result = invocation
            .handles
            .send_channel(message, &mut invocation.bytes);
        // A close the send forced reaches JavaScript at the next poll.
        self.wake.notify();
        result
    }

    fn close_channel(&self, input: &str) -> Result<Value> {
        let close: GuestClose = serde_json::from_str(input)
            .map_err(|_| Error::InvalidRequest("invalid channel close".into()))?;
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
        invocation.handles.close_channel(close)
    }

    fn channel_buffered(&self, input: &str) -> Result<Value> {
        let id: u64 = serde_json::from_str(input)
            .map_err(|_| Error::InvalidRequest("invalid channel id".into()))?;
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
        invocation.handles.channel_buffered(id)
    }

    pub(super) fn register_background(&self) -> Result<Value> {
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
        let registered = invocation
            .background_registered
            .checked_add(1)
            .ok_or(Error::LimitExceeded("background tasks"))?;
        check_limit(
            invocation.limits.background_tasks,
            registered,
            "background tasks",
        )?;
        invocation.background_registered = registered;
        invocation.background_pending += 1;
        Ok(Value::Null)
    }

    pub(super) fn settle_background(&self) -> Result<Value> {
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
        invocation.background_pending = invocation.background_pending.saturating_sub(1);
        Ok(Value::Null)
    }

    /// Read the next chunk of a body source, or with `whole` the rest of it
    /// at once, which spares JavaScript a read per chunk and, as text, its
    /// own UTF-8 decoding.
    pub(super) fn read_body(&self, input: &str, whole: Option<Whole>) -> Result<Value> {
        let id: u64 = serde_json::from_str(input)
            .map_err(|_| Error::InvalidRequest("invalid body id".into()))?;
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
        if invocation.handles.body_mut(id).is_none() {
            return Err(Error::InvalidRequest("unknown body".into()));
        }
        // One read at a time, as a ReadableStream pulls.
        if invocation
            .pending_reads
            .values()
            .any(|reading| reading.id == id)
        {
            return Err(Error::InvalidRequest("body is already being read".into()));
        }
        let ticket = invocation.next_ticket()?;
        invocation
            .pending_reads
            .insert(ticket.clone(), PendingRead { id, whole });
        Ok(Value::String(ticket))
    }

    pub(super) fn cancel_body(&self, input: &str) -> Result<Value> {
        let id: u64 = serde_json::from_str(input)
            .map_err(|_| Error::InvalidRequest("invalid body id".into()))?;
        let mut state = self.lock_state()?;
        let invocation = state.invocation.as_mut().ok_or(Error::InvocationClosed)?;
        // Dropping the body cancels its producer. Cancelling twice is harmless.
        invocation.handles.release_body(id);
        invocation
            .pending_reads
            .retain(|_, reading| reading.id != id);
        Ok(Value::Null)
    }
}

pub(crate) struct InvocationScope {
    bridge: HostBridge,
    generation: u64,
}

impl InvocationScope {
    /// Whether `fetchlet.waitUntil` work of this invocation has not settled.
    #[cfg_attr(
        not(any(feature = "boa", feature = "quickjs", feature = "v8")),
        allow(dead_code)
    )]
    pub fn has_background(&self) -> bool {
        let Ok(state) = self.bridge.lock_state() else {
            return false;
        };

        state.invocation.as_ref().is_some_and(|invocation| {
            invocation.generation == self.generation && invocation.background_pending > 0
        })
    }

    pub fn has_pending(&self) -> bool {
        let Ok(state) = self.bridge.lock_state() else {
            return true;
        };

        state.invocation.as_ref().is_some_and(|invocation| {
            invocation.generation == self.generation
                && (!invocation.pending_fetches.is_empty() || !invocation.pending_calls.is_empty())
        })
    }
}

impl Drop for InvocationScope {
    fn drop(&mut self) {
        // Cleanup must still run after a panicking trusted transport poisoned
        // the lock. Further operations fail closed through lock_state().
        let mut state = self
            .bridge
            .state
            .lock()
            .unwrap_or_else(|error| error.into_inner());
        let owns_invocation = state
            .invocation
            .as_ref()
            .is_some_and(|invocation| invocation.generation == self.generation);

        if owns_invocation && let Some(mut invocation) = state.invocation.take() {
            // Releasing every handle drops the invocation's bodies and
            // channels, and keeps the table's generations for the next one.
            let mut handles = std::mem::take(&mut invocation.handles);
            handles.release_all();
            state.handles = handles;
        }
    }
}

/// Fetch's UTF-8 decode: a leading byte order mark is dropped, and each
/// maximal invalid subsequence becomes U+FFFD, as the Encoding Standard
/// specifies and `String::from_utf8_lossy` implements.
fn utf8_decode(bytes: &[u8]) -> std::borrow::Cow<'_, str> {
    String::from_utf8_lossy(bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes))
}

fn encode_response(
    response: Response,
    limits: &Limits,
    bytes: &mut impl BridgeBytes,
) -> Result<Value> {
    let response = WireResponse::from_http(response, limits, bytes)?;
    serde_json::to_value(response).map_err(|_| Error::Transport("invalid response encoding".into()))
}

/// The reply to `fetch.limits` under `limits`, which an isolated instance's
/// child gives from the limits its parent sent.
pub(crate) fn fetch_limits_reply(limits: &Limits) -> Value {
    json!({
        "requestBodyBytes": limits.request_body_bytes.map(|value| value.to_string()),
        "requestBodyChunks": limits.request_body_chunks.map(|value| value.to_string()),
    })
}

pub(crate) fn encode_reply(result: Result<Value>) -> Value {
    match result {
        Ok(value) => json!({
            "ok": true,
            "value": value,
        }),
        Err(error) => json!({
            "ok": false,
            "error": {
                "code": error.code(),
                "message": error.guest_message(),
            },
        }),
    }
}

/// An invocation's byte store, as `fetchlet-web` operations use it.
#[cfg(fetchlet_web)]
struct WebBytes<'a>(&'a mut ByteStore);

#[cfg(fetchlet_web)]
impl fetchlet_web::ByteHandles for WebBytes<'_> {
    type Error = Error;

    fn put(&mut self, bytes: Bytes) -> Result<u64> {
        self.0.put(bytes)
    }

    fn take(&mut self, handle: u64) -> Result<Bytes> {
        self.0.take(handle)
    }
}

/// Bytes cross through the current invocation of a bridge.
impl BridgeBytes for HostBridge {
    fn send(&mut self, bytes: Bytes) -> Result<WireBytes> {
        self.with_bridge_bytes(|bridge_bytes| bridge_bytes.send(bytes))
    }

    fn receive(&mut self, bytes: WireBytes) -> Result<Bytes> {
        self.with_bridge_bytes(|bridge_bytes| bridge_bytes.receive(bytes))
    }

    fn stream(
        &mut self,
        body: Body,
        limit: Option<usize>,
        resource: &'static str,
    ) -> Result<BodyTransfer> {
        self.with_bridge_bytes(|bridge_bytes| bridge_bytes.stream(body, limit, resource))
    }
}