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
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.

// False positive lint for explicit drops.
// https://github.com/rust-lang/rust-clippy/issues/6446
#![allow(clippy::await_holding_lock)]
// https://github.com/rust-lang/rust-clippy/issues/6353
#![allow(clippy::await_holding_refcell_ref)]

use deno_core::error::generic_error;
use deno_core::error::type_error;
use deno_core::error::AnyError;
use deno_core::op;
use deno_core::serde_v8;
use deno_core::v8;
use deno_core::v8::fast_api;
use deno_core::ByteString;
use deno_core::CancelFuture;
use deno_core::CancelHandle;
use deno_core::Extension;
use deno_core::OpState;
use deno_core::StringOrBuffer;
use deno_core::ZeroCopyBuf;
use deno_core::V8_WRAPPER_OBJECT_INDEX;
use deno_tls::load_certs;
use deno_tls::load_private_keys;
use http::header::HeaderName;
use http::header::CONNECTION;
use http::header::CONTENT_LENGTH;
use http::header::EXPECT;
use http::header::TRANSFER_ENCODING;
use http::HeaderValue;
use log::trace;
use mio::net::TcpListener;
use mio::Events;
use mio::Interest;
use mio::Poll;
use mio::Token;
use mio::Waker;
use serde::Deserialize;
use serde::Serialize;
use socket2::Socket;
use std::cell::RefCell;
use std::cell::UnsafeCell;
use std::collections::HashMap;
use std::ffi::c_void;
use std::future::Future;
use std::intrinsics::transmute;
use std::io::BufReader;
use std::io::Read;
use std::io::Write;
use std::marker::PhantomPinned;
use std::mem::replace;
use std::net::SocketAddr;
use std::net::ToSocketAddrs;
use std::pin::Pin;
use std::rc::Rc;
use std::sync::Arc;
use std::sync::Mutex;
use std::task::Context;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::task::JoinHandle;

mod chunked;
mod request;
#[cfg(unix)]
mod sendfile;
mod socket;

use request::InnerRequest;
use request::Request;
use socket::InnerStream;
use socket::Stream;

pub struct FlashContext {
  next_server_id: u32,
  join_handles: HashMap<u32, JoinHandle<Result<(), AnyError>>>,
  pub servers: HashMap<u32, ServerContext>,
}

impl Drop for FlashContext {
  fn drop(&mut self) {
    // Signal each server instance to shutdown.
    for (_, server) in self.servers.drain() {
      let _ = server.waker.wake();
    }
  }
}

pub struct ServerContext {
  _addr: SocketAddr,
  tx: mpsc::Sender<Request>,
  rx: Option<mpsc::Receiver<Request>>,
  requests: HashMap<u32, Request>,
  next_token: u32,
  listening_rx: Option<mpsc::Receiver<Result<u16, std::io::Error>>>,
  cancel_handle: Rc<CancelHandle>,
  waker: Arc<Waker>,
}

#[derive(Debug, Eq, PartialEq)]
pub enum ParseStatus {
  None,
  Ongoing(usize),
}

#[op]
fn op_flash_respond(
  op_state: &mut OpState,
  server_id: u32,
  token: u32,
  response: StringOrBuffer,
  shutdown: bool,
) -> u32 {
  let flash_ctx = op_state.borrow_mut::<FlashContext>();
  let ctx = match flash_ctx.servers.get_mut(&server_id) {
    Some(ctx) => ctx,
    None => return 0,
  };
  flash_respond(ctx, token, shutdown, &response)
}

#[op(fast)]
fn op_try_flash_respond_chuncked(
  op_state: &mut OpState,
  server_id: u32,
  token: u32,
  response: &[u8],
  shutdown: bool,
) -> u32 {
  let flash_ctx = op_state.borrow_mut::<FlashContext>();
  let ctx = flash_ctx.servers.get_mut(&server_id).unwrap();
  let tx = ctx.requests.get_mut(&token).unwrap();
  let sock = tx.socket();

  // TODO(@littledivy): Use writev when `UnixIoSlice` lands.
  // https://github.com/denoland/deno/pull/15629
  let h = format!("{:x}\r\n", response.len());

  let concat = [h.as_bytes(), response, b"\r\n"].concat();
  let expected = sock.try_write(&concat);
  if expected != concat.len() {
    if expected > 2 {
      return expected as u32;
    }
    return expected as u32;
  }

  if shutdown {
    // Best case: We've written everything and the stream is done too.
    let _ = ctx.requests.remove(&token).unwrap();
  }
  0
}

#[op]
async fn op_flash_respond_async(
  state: Rc<RefCell<OpState>>,
  server_id: u32,
  token: u32,
  response: StringOrBuffer,
  shutdown: bool,
) -> Result<(), AnyError> {
  trace!("op_flash_respond_async");

  let mut close = false;
  let sock = {
    let mut op_state = state.borrow_mut();
    let flash_ctx = op_state.borrow_mut::<FlashContext>();
    let ctx = match flash_ctx.servers.get_mut(&server_id) {
      Some(ctx) => ctx,
      None => return Ok(()),
    };

    match shutdown {
      true => {
        let mut tx = ctx.requests.remove(&token).unwrap();
        close = !tx.keep_alive;
        tx.socket()
      }
      // In case of a websocket upgrade or streaming response.
      false => {
        let tx = ctx.requests.get_mut(&token).unwrap();
        tx.socket()
      }
    }
  };

  sock
    .with_async_stream(|stream| {
      Box::pin(async move {
        Ok(tokio::io::AsyncWriteExt::write(stream, &response).await?)
      })
    })
    .await?;
  // server is done writing and request doesn't want to kept alive.
  if shutdown && close {
    sock.shutdown();
  }
  Ok(())
}

#[op]
async fn op_flash_respond_chuncked(
  op_state: Rc<RefCell<OpState>>,
  server_id: u32,
  token: u32,
  response: Option<ZeroCopyBuf>,
  shutdown: bool,
  nwritten: u32,
) -> Result<(), AnyError> {
  let mut op_state = op_state.borrow_mut();
  let flash_ctx = op_state.borrow_mut::<FlashContext>();
  let ctx = flash_ctx.servers.get_mut(&server_id).unwrap();
  let sock = match shutdown {
    true => {
      let mut tx = ctx.requests.remove(&token).unwrap();
      tx.socket()
    }
    // In case of a websocket upgrade or streaming response.
    false => {
      let tx = ctx.requests.get_mut(&token).unwrap();
      tx.socket()
    }
  };

  drop(op_state);
  sock
    .with_async_stream(|stream| {
      Box::pin(async move {
        use tokio::io::AsyncWriteExt;
        // TODO(@littledivy): Use writev when `UnixIoSlice` lands.
        // https://github.com/denoland/deno/pull/15629
        macro_rules! write_whats_not_written {
          ($e:expr) => {
            let e = $e;
            let n = nwritten as usize;
            if n < e.len() {
              stream.write_all(&e[n..]).await?;
            }
          };
        }
        if let Some(response) = response {
          let h = format!("{:x}\r\n", response.len());
          write_whats_not_written!(h.as_bytes());
          write_whats_not_written!(&response);
          write_whats_not_written!(b"\r\n");
        }

        // The last chunk
        if shutdown {
          write_whats_not_written!(b"0\r\n\r\n");
        }

        Ok(())
      })
    })
    .await?;
  Ok(())
}

#[op]
async fn op_flash_write_resource(
  op_state: Rc<RefCell<OpState>>,
  response: StringOrBuffer,
  server_id: u32,
  token: u32,
  resource_id: deno_core::ResourceId,
  auto_close: bool,
) -> Result<(), AnyError> {
  let (resource, sock) = {
    let op_state = &mut op_state.borrow_mut();
    let resource = if auto_close {
      op_state.resource_table.take_any(resource_id)?
    } else {
      op_state.resource_table.get_any(resource_id)?
    };
    let flash_ctx = op_state.borrow_mut::<FlashContext>();
    let ctx = flash_ctx.servers.get_mut(&server_id).unwrap();
    (resource, ctx.requests.remove(&token).unwrap().socket())
  };

  let _ = sock.write(&response);

  #[cfg(unix)]
  {
    use std::os::unix::io::AsRawFd;
    if let InnerStream::Tcp(stream_handle) = &sock.inner {
      let stream_handle = stream_handle.as_raw_fd();
      if let Some(fd) = resource.clone().backing_fd() {
        // SAFETY: all-zero byte-pattern is a valid value for libc::stat.
        let mut stat: libc::stat = unsafe { std::mem::zeroed() };
        // SAFETY: call to libc::fstat.
        if unsafe { libc::fstat(fd, &mut stat) } >= 0 {
          let _ = sock.write(
            format!("Content-Length: {}\r\n\r\n", stat.st_size).as_bytes(),
          );
          let tx = sendfile::SendFile {
            io: (fd, stream_handle),
            written: 0,
          };
          tx.await?;
          return Ok(());
        }
      }
    }
  }

  sock
    .with_async_stream(|stream| {
      Box::pin(async move {
        use tokio::io::AsyncWriteExt;
        stream
          .write_all(b"Transfer-Encoding: chunked\r\n\r\n")
          .await?;
        loop {
          let view = resource.clone().read(64 * 1024).await?; // 64KB
          if view.is_empty() {
            stream.write_all(b"0\r\n\r\n").await?;
            break;
          }
          // TODO(@littledivy): use vectored writes.
          stream
            .write_all(format!("{:x}\r\n", view.len()).as_bytes())
            .await?;
          stream.write_all(&view).await?;
          stream.write_all(b"\r\n").await?;
        }
        resource.close();
        Ok(())
      })
    })
    .await?;
  Ok(())
}

pub struct RespondFast;

impl fast_api::FastFunction for RespondFast {
  fn function(&self) -> *const c_void {
    op_flash_respond_fast as *const c_void
  }

  fn args(&self) -> &'static [fast_api::Type] {
    &[
      fast_api::Type::V8Value,
      fast_api::Type::Uint32,
      fast_api::Type::TypedArray(fast_api::CType::Uint8),
      fast_api::Type::Bool,
    ]
  }

  fn return_type(&self) -> fast_api::CType {
    fast_api::CType::Uint32
  }
}

fn flash_respond(
  ctx: &mut ServerContext,
  token: u32,
  shutdown: bool,
  response: &[u8],
) -> u32 {
  let tx = ctx.requests.get_mut(&token).unwrap();
  let sock = tx.socket();

  sock.read_tx.take();
  sock.read_rx.take();

  let nwritten = sock.try_write(response);

  if shutdown && nwritten == response.len() {
    if !tx.keep_alive {
      sock.shutdown();
    }
    ctx.requests.remove(&token).unwrap();
  }

  nwritten as u32
}

unsafe fn op_flash_respond_fast(
  recv: v8::Local<v8::Object>,
  token: u32,
  response: *const fast_api::FastApiTypedArray<u8>,
  shutdown: bool,
) -> u32 {
  let ptr =
    recv.get_aligned_pointer_from_internal_field(V8_WRAPPER_OBJECT_INDEX);
  let ctx = &mut *(ptr as *mut ServerContext);

  let response = &*response;
  if let Some(response) = response.get_storage_if_aligned() {
    flash_respond(ctx, token, shutdown, response)
  } else {
    todo!();
  }
}

macro_rules! get_request {
  ($op_state: ident, $token: ident) => {
    get_request!($op_state, 0, $token)
  };
  ($op_state: ident, $server_id: expr, $token: ident) => {{
    let flash_ctx = $op_state.borrow_mut::<FlashContext>();
    let ctx = flash_ctx.servers.get_mut(&$server_id).unwrap();
    ctx.requests.get_mut(&$token).unwrap()
  }};
}

#[repr(u32)]
pub enum Method {
  GET = 0,
  HEAD,
  CONNECT,
  PUT,
  DELETE,
  OPTIONS,
  TRACE,
  POST,
  PATCH,
}

#[inline]
fn get_method(req: &mut Request) -> u32 {
  let method = match req.method() {
    "GET" => Method::GET,
    "POST" => Method::POST,
    "PUT" => Method::PUT,
    "DELETE" => Method::DELETE,
    "OPTIONS" => Method::OPTIONS,
    "HEAD" => Method::HEAD,
    "PATCH" => Method::PATCH,
    "TRACE" => Method::TRACE,
    "CONNECT" => Method::CONNECT,
    _ => Method::GET,
  };
  method as u32
}

#[op]
fn op_flash_method(state: &mut OpState, server_id: u32, token: u32) -> u32 {
  let req = get_request!(state, server_id, token);
  get_method(req)
}

#[op]
fn op_flash_drive_server(
  state: &mut OpState,
  server_id: u32,
) -> Result<impl Future<Output = Result<(), AnyError>> + 'static, AnyError> {
  let join_handle = {
    let flash_ctx = state.borrow_mut::<FlashContext>();
    flash_ctx
      .join_handles
      .remove(&server_id)
      .ok_or_else(|| type_error("server not found"))?
  };
  Ok(async move {
    join_handle
      .await
      .map_err(|_| type_error("server join error"))??;
    Ok(())
  })
}

#[op]
fn op_flash_close_server(state: &mut OpState, server_id: u32) {
  let flash_ctx = state.borrow_mut::<FlashContext>();
  let ctx = flash_ctx.servers.get(&server_id).unwrap();

  // NOTE: We don't drop ServerContext associated with the given `server_id`,
  // because it may still be in use by some unsettled promise after the flash
  // thread is finished.

  ctx.cancel_handle.cancel();
  let _ = ctx.waker.wake();
}

#[op]
fn op_flash_path(
  state: Rc<RefCell<OpState>>,
  server_id: u32,
  token: u32,
) -> String {
  let mut op_state = state.borrow_mut();
  let flash_ctx = op_state.borrow_mut::<FlashContext>();
  let ctx = flash_ctx.servers.get_mut(&server_id).unwrap();
  ctx
    .requests
    .get(&token)
    .unwrap()
    .inner
    .req
    .path
    .unwrap()
    .to_string()
}

#[inline]
fn next_request_sync(ctx: &mut ServerContext) -> u32 {
  let offset = ctx.next_token;

  while let Ok(token) = ctx.rx.as_mut().unwrap().try_recv() {
    ctx.requests.insert(ctx.next_token, token);
    ctx.next_token += 1;
  }

  ctx.next_token - offset
}

pub struct NextRequestFast;

impl fast_api::FastFunction for NextRequestFast {
  fn function(&self) -> *const c_void {
    op_flash_next_fast as *const c_void
  }

  fn args(&self) -> &'static [fast_api::Type] {
    &[fast_api::Type::V8Value]
  }

  fn return_type(&self) -> fast_api::CType {
    fast_api::CType::Uint32
  }
}

unsafe fn op_flash_next_fast(recv: v8::Local<v8::Object>) -> u32 {
  let ptr =
    recv.get_aligned_pointer_from_internal_field(V8_WRAPPER_OBJECT_INDEX);
  let ctx = &mut *(ptr as *mut ServerContext);
  next_request_sync(ctx)
}

pub struct GetMethodFast;

impl fast_api::FastFunction for GetMethodFast {
  fn function(&self) -> *const c_void {
    op_flash_get_method_fast as *const c_void
  }

  fn args(&self) -> &'static [fast_api::Type] {
    &[fast_api::Type::V8Value, fast_api::Type::Uint32]
  }

  fn return_type(&self) -> fast_api::CType {
    fast_api::CType::Uint32
  }
}

unsafe fn op_flash_get_method_fast(
  recv: v8::Local<v8::Object>,
  token: u32,
) -> u32 {
  let ptr =
    recv.get_aligned_pointer_from_internal_field(V8_WRAPPER_OBJECT_INDEX);
  let ctx = &mut *(ptr as *mut ServerContext);
  let req = ctx.requests.get_mut(&token).unwrap();
  get_method(req)
}

// Fast calls
#[op(v8)]
fn op_flash_make_request<'scope>(
  scope: &mut v8::HandleScope<'scope>,
  state: &mut OpState,
  server_id: u32,
) -> serde_v8::Value<'scope> {
  let object_template = v8::ObjectTemplate::new(scope);
  assert!(object_template
    .set_internal_field_count((V8_WRAPPER_OBJECT_INDEX + 1) as usize));
  let obj = object_template.new_instance(scope).unwrap();
  let ctx = {
    let flash_ctx = state.borrow_mut::<FlashContext>();
    let ctx = flash_ctx.servers.get_mut(&server_id).unwrap();
    ctx as *mut ServerContext
  };
  obj.set_aligned_pointer_in_internal_field(V8_WRAPPER_OBJECT_INDEX, ctx as _);

  // nextRequest
  {
    let builder = v8::FunctionTemplate::builder(
      |_: &mut v8::HandleScope,
       args: v8::FunctionCallbackArguments,
       mut rv: v8::ReturnValue| {
        let external: v8::Local<v8::External> = args.data().try_into().unwrap();
        // SAFETY: This external is guaranteed to be a pointer to a ServerContext
        let ctx = unsafe { &mut *(external.value() as *mut ServerContext) };
        rv.set_uint32(next_request_sync(ctx));
      },
    )
    .data(v8::External::new(scope, ctx as *mut _).into());

    let func = builder.build_fast(scope, &NextRequestFast, None);
    let func: v8::Local<v8::Value> = func.get_function(scope).unwrap().into();

    let key = v8::String::new(scope, "nextRequest").unwrap();
    obj.set(scope, key.into(), func).unwrap();
  }

  // getMethod
  {
    let builder = v8::FunctionTemplate::builder(
      |scope: &mut v8::HandleScope,
       args: v8::FunctionCallbackArguments,
       mut rv: v8::ReturnValue| {
        let external: v8::Local<v8::External> = args.data().try_into().unwrap();
        // SAFETY: This external is guaranteed to be a pointer to a ServerContext
        let ctx = unsafe { &mut *(external.value() as *mut ServerContext) };
        let token = args.get(0).uint32_value(scope).unwrap();
        let req = ctx.requests.get_mut(&token).unwrap();
        rv.set_uint32(get_method(req));
      },
    )
    .data(v8::External::new(scope, ctx as *mut _).into());

    let func = builder.build_fast(scope, &GetMethodFast, None);
    let func: v8::Local<v8::Value> = func.get_function(scope).unwrap().into();

    let key = v8::String::new(scope, "getMethod").unwrap();
    obj.set(scope, key.into(), func).unwrap();
  }

  // respond
  {
    let builder = v8::FunctionTemplate::builder(
      |scope: &mut v8::HandleScope,
       args: v8::FunctionCallbackArguments,
       mut rv: v8::ReturnValue| {
        let external: v8::Local<v8::External> = args.data().try_into().unwrap();
        // SAFETY: This external is guaranteed to be a pointer to a ServerContext
        let ctx = unsafe { &mut *(external.value() as *mut ServerContext) };

        let token = args.get(0).uint32_value(scope).unwrap();

        let response: v8::Local<v8::ArrayBufferView> =
          args.get(1).try_into().unwrap();
        let ab = response.buffer(scope).unwrap();
        let store = ab.get_backing_store();
        let (offset, len) = (response.byte_offset(), response.byte_length());
        // SAFETY: v8::SharedRef<v8::BackingStore> is similar to Arc<[u8]>,
        // it points to a fixed continuous slice of bytes on the heap.
        // We assume it's initialized and thus safe to read (though may not contain meaningful data)
        let response = unsafe {
          &*(&store[offset..offset + len] as *const _ as *const [u8])
        };

        let shutdown = args.get(2).boolean_value(scope);

        rv.set_uint32(flash_respond(ctx, token, shutdown, response));
      },
    )
    .data(v8::External::new(scope, ctx as *mut _).into());

    let func = builder.build_fast(scope, &RespondFast, None);
    let func: v8::Local<v8::Value> = func.get_function(scope).unwrap().into();

    let key = v8::String::new(scope, "respond").unwrap();
    obj.set(scope, key.into(), func).unwrap();
  }

  let value: v8::Local<v8::Value> = obj.into();
  value.into()
}

#[inline]
fn has_body_stream(req: &mut Request) -> bool {
  let sock = req.socket();
  sock.read_rx.is_some()
}

#[op]
fn op_flash_has_body_stream(
  op_state: &mut OpState,
  server_id: u32,
  token: u32,
) -> bool {
  let req = get_request!(op_state, server_id, token);
  has_body_stream(req)
}

#[op]
fn op_flash_headers(
  state: Rc<RefCell<OpState>>,
  server_id: u32,
  token: u32,
) -> Result<Vec<(ByteString, ByteString)>, AnyError> {
  let mut op_state = state.borrow_mut();
  let flash_ctx = op_state.borrow_mut::<FlashContext>();
  let ctx = flash_ctx
    .servers
    .get_mut(&server_id)
    .ok_or_else(|| type_error("server closed"))?;
  let inner_req = &ctx
    .requests
    .get(&token)
    .ok_or_else(|| type_error("request closed"))?
    .inner
    .req;
  Ok(
    inner_req
      .headers
      .iter()
      .map(|h| (h.name.as_bytes().into(), h.value.into()))
      .collect(),
  )
}

// Remember the first packet we read? It probably also has some body data. This op quickly copies it into
// a buffer and sets up channels for streaming the rest.
#[op]
fn op_flash_first_packet(
  op_state: &mut OpState,
  server_id: u32,
  token: u32,
) -> Result<Option<ZeroCopyBuf>, AnyError> {
  let tx = get_request!(op_state, server_id, token);
  let sock = tx.socket();

  if !tx.te_chunked && tx.content_length.is_none() {
    return Ok(None);
  }

  if tx.expect_continue {
    let _ = sock.write(b"HTTP/1.1 100 Continue\r\n\r\n");
    tx.expect_continue = false;
  }

  let buffer = &tx.inner.buffer[tx.inner.body_offset..tx.inner.body_len];
  // Oh there is nothing here.
  if buffer.is_empty() {
    return Ok(Some(ZeroCopyBuf::empty()));
  }

  if tx.te_chunked {
    let mut buf = vec![0; 1024];
    let mut offset = 0;
    let mut decoder = chunked::Decoder::new(
      std::io::Cursor::new(buffer),
      tx.remaining_chunk_size,
    );

    loop {
      match decoder.read(&mut buf[offset..]) {
        Ok(n) => {
          tx.remaining_chunk_size = decoder.remaining_chunks_size;
          offset += n;

          if n == 0 {
            tx.te_chunked = false;
            buf.truncate(offset);
            return Ok(Some(buf.into()));
          }

          if offset < buf.len()
            && decoder.source.position() < buffer.len() as u64
          {
            continue;
          }

          buf.truncate(offset);
          return Ok(Some(buf.into()));
        }
        Err(e) => {
          return Err(type_error(format!("{}", e)));
        }
      }
    }
  }

  tx.content_length
    .ok_or_else(|| type_error("no content-length"))?;
  tx.content_read += buffer.len();

  Ok(Some(buffer.to_vec().into()))
}

#[op]
async fn op_flash_read_body(
  state: Rc<RefCell<OpState>>,
  server_id: u32,
  token: u32,
  mut buf: ZeroCopyBuf,
) -> usize {
  // SAFETY: we cannot hold op_state borrow across the await point. The JS caller
  // is responsible for ensuring this is not called concurrently.
  let ctx = unsafe {
    {
      let op_state = &mut state.borrow_mut();
      let flash_ctx = op_state.borrow_mut::<FlashContext>();
      match flash_ctx.servers.get_mut(&server_id) {
        Some(ctx) => ctx as *mut ServerContext,
        None => return 0,
      }
    }
    .as_mut()
    .unwrap()
  };
  let tx = ctx.requests.get_mut(&token).unwrap();

  if tx.te_chunked {
    let mut decoder =
      chunked::Decoder::new(tx.socket(), tx.remaining_chunk_size);
    loop {
      let sock = tx.socket();

      let _lock = sock.read_lock.lock().unwrap();
      match decoder.read(&mut buf) {
        Ok(n) => {
          tx.remaining_chunk_size = decoder.remaining_chunks_size;
          return n;
        }
        Err(e) if e.kind() == std::io::ErrorKind::InvalidInput => {
          panic!("chunked read error: {}", e);
        }
        Err(_) => {
          drop(_lock);
          sock.read_rx.as_mut().unwrap().recv().await.unwrap();
        }
      }
    }
  }

  if let Some(content_length) = tx.content_length {
    let sock = tx.socket();
    let l = sock.read_lock.clone();

    loop {
      let _lock = l.lock().unwrap();
      if tx.content_read >= content_length as usize {
        return 0;
      }
      match sock.read(&mut buf) {
        Ok(n) => {
          tx.content_read += n;
          return n;
        }
        _ => {
          drop(_lock);
          sock.read_rx.as_mut().unwrap().recv().await.unwrap();
        }
      }
    }
  }

  0
}

// https://github.com/hyperium/hyper/blob/0c8ee93d7f557afc63ca2a5686d19071813ab2b7/src/headers.rs#L67
#[inline]
fn from_digits(bytes: &[u8]) -> Option<u64> {
  // cannot use FromStr for u64, since it allows a signed prefix
  let mut result = 0u64;
  const RADIX: u64 = 10;
  if bytes.is_empty() {
    return None;
  }
  for &b in bytes {
    // can't use char::to_digit, since we haven't verified these bytes
    // are utf-8.
    match b {
      b'0'..=b'9' => {
        result = result.checked_mul(RADIX)?;
        result = result.checked_add((b - b'0') as u64)?;
      }
      _ => {
        return None;
      }
    }
  }
  Some(result)
}

#[inline]
fn connection_has(value: &HeaderValue, needle: &str) -> bool {
  if let Ok(s) = value.to_str() {
    for val in s.split(',') {
      if val.trim().eq_ignore_ascii_case(needle) {
        return true;
      }
    }
  }
  false
}

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListenOpts {
  cert: Option<String>,
  key: Option<String>,
  hostname: String,
  port: u16,
  reuseport: bool,
}

const SERVER_TOKEN: Token = Token(0);
// Token reserved for the thread close signal.
const WAKER_TOKEN: Token = Token(1);

#[allow(clippy::too_many_arguments)]
fn run_server(
  tx: mpsc::Sender<Request>,
  listening_tx: mpsc::Sender<Result<u16, std::io::Error>>,
  addr: SocketAddr,
  maybe_cert: Option<String>,
  maybe_key: Option<String>,
  reuseport: bool,
  mut poll: Poll,
  // We put a waker as an unused argument here as it needs to be alive both in
  // the flash thread and in the main thread (otherwise the notification would
  // not be caught by the event loop on Linux).
  // See the comment in mio's example:
  // https://docs.rs/mio/0.8.4/x86_64-unknown-linux-gnu/mio/struct.Waker.html#examples
  _waker: Arc<Waker>,
) -> Result<(), AnyError> {
  let mut listener = match listen(addr, reuseport) {
    Ok(listener) => listener,
    Err(e) => {
      listening_tx.blocking_send(Err(e)).unwrap();
      return Err(generic_error(
        "failed to start listening on the specified address",
      ));
    }
  };

  // Register server.
  poll
    .registry()
    .register(&mut listener, SERVER_TOKEN, Interest::READABLE)
    .unwrap();

  let tls_context: Option<Arc<rustls::ServerConfig>> = {
    if let Some(cert) = maybe_cert {
      let key = maybe_key.unwrap();
      let certificate_chain: Vec<rustls::Certificate> =
        load_certs(&mut BufReader::new(cert.as_bytes()))?;
      let private_key = load_private_keys(key.as_bytes())?.remove(0);

      let config = rustls::ServerConfig::builder()
        .with_safe_defaults()
        .with_no_client_auth()
        .with_single_cert(certificate_chain, private_key)
        .expect("invalid key or certificate");
      Some(Arc::new(config))
    } else {
      None
    }
  };

  listening_tx
    .blocking_send(Ok(listener.local_addr().unwrap().port()))
    .unwrap();
  let mut sockets = HashMap::with_capacity(1000);
  let mut socket_senders = HashMap::with_capacity(1000);
  let mut counter: usize = 2;
  let mut events = Events::with_capacity(1024);
  'outer: loop {
    match poll.poll(&mut events, None) {
      Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
      Err(e) => panic!("{}", e),
      Ok(()) => (),
    }
    'events: for event in &events {
      let token = event.token();
      match token {
        WAKER_TOKEN => {
          break 'outer;
        }
        SERVER_TOKEN => loop {
          match listener.accept() {
            Ok((mut socket, _)) => {
              counter += 1;
              let token = Token(counter);
              poll
                .registry()
                .register(&mut socket, token, Interest::READABLE)
                .unwrap();

              let socket = match tls_context {
                Some(ref tls_conf) => {
                  let connection =
                    rustls::ServerConnection::new(tls_conf.clone()).unwrap();
                  InnerStream::Tls(Box::new(rustls::StreamOwned::new(
                    connection, socket,
                  )))
                }
                None => InnerStream::Tcp(socket),
              };
              let stream = Box::pin(Stream {
                inner: socket,
                detached: false,
                read_rx: None,
                read_tx: None,
                read_lock: Arc::new(Mutex::new(())),
                parse_done: ParseStatus::None,
                buffer: UnsafeCell::new(vec![0_u8; 1024]),
                _pinned: PhantomPinned,
              });

              trace!("New connection: {}", token.0);
              sockets.insert(token, stream);
            }
            Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
            Err(_) => break,
          }
        },
        token => {
          let socket = sockets.get_mut(&token).unwrap();
          // SAFETY: guarantee that we will never move the data out of the mutable reference.
          let socket = unsafe {
            let mut_ref: Pin<&mut Stream> = Pin::as_mut(socket);
            Pin::get_unchecked_mut(mut_ref)
          };

          if socket.detached {
            match &mut socket.inner {
              InnerStream::Tcp(ref mut socket) => {
                poll.registry().deregister(socket).unwrap();
              }
              InnerStream::Tls(_) => {
                todo!("upgrade tls not implemented");
              }
            }

            let boxed = sockets.remove(&token).unwrap();
            std::mem::forget(boxed);
            socket_senders.remove(&token);
            trace!("Socket detached: {}", token.0);
            continue;
          }

          debug_assert!(event.is_readable());

          trace!("Socket readable: {}", token.0);
          if let Some(tx) = &socket.read_tx {
            {
              let _l = socket.read_lock.lock().unwrap();
            }
            trace!("Sending readiness notification: {}", token.0);
            let _ = tx.blocking_send(());

            continue;
          }

          let mut headers = vec![httparse::EMPTY_HEADER; 40];
          let mut req = httparse::Request::new(&mut headers);
          let body_offset;
          let body_len;
          loop {
            // SAFETY: It is safe for the read buf to be mutable here.
            let buffer = unsafe { &mut *socket.buffer.get() };
            let offset = match socket.parse_done {
              ParseStatus::None => 0,
              ParseStatus::Ongoing(offset) => offset,
            };
            if offset >= buffer.len() {
              buffer.resize(offset * 2, 0);
            }
            let nread = socket.read(&mut buffer[offset..]);

            match nread {
              Ok(0) => {
                trace!("Socket closed: {}", token.0);
                // FIXME: don't remove while JS is writing!
                // sockets.remove(&token);
                continue 'events;
              }
              Ok(read) => {
                match req.parse(&buffer[..offset + read]) {
                  Ok(httparse::Status::Complete(n)) => {
                    body_offset = n;
                    body_len = offset + read;
                    socket.parse_done = ParseStatus::None;
                    // On Windows, We must keep calling socket.read() until it fails with WouldBlock.
                    //
                    // Mio tries to emulate edge triggered events on Windows.
                    // AFAICT it only rearms the event on WouldBlock, but it doesn't when a partial read happens.
                    // https://github.com/denoland/deno/issues/15549
                    #[cfg(target_os = "windows")]
                    match &mut socket.inner {
                      InnerStream::Tcp(ref mut socket) => {
                        poll
                          .registry()
                          .reregister(socket, token, Interest::READABLE)
                          .unwrap();
                      }
                      InnerStream::Tls(ref mut socket) => {
                        poll
                          .registry()
                          .reregister(
                            &mut socket.sock,
                            token,
                            Interest::READABLE,
                          )
                          .unwrap();
                      }
                    };
                    break;
                  }
                  Ok(httparse::Status::Partial) => {
                    socket.parse_done = ParseStatus::Ongoing(offset + read);
                    continue;
                  }
                  Err(_) => {
                    let _ = socket.write(b"HTTP/1.1 400 Bad Request\r\n\r\n");
                    continue 'events;
                  }
                }
              }
              Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                break 'events
              }
              Err(_) => break 'events,
            }
          }

          debug_assert_eq!(socket.parse_done, ParseStatus::None);
          if let Some(method) = &req.method {
            if method == &"POST" || method == &"PUT" {
              let (tx, rx) = mpsc::channel(100);
              socket.read_tx = Some(tx);
              socket.read_rx = Some(rx);
            }
          }

          // SAFETY: It is safe for the read buf to be mutable here.
          let buffer = unsafe { &mut *socket.buffer.get() };
          let inner_req = InnerRequest {
            // SAFETY: backing buffer is pinned and lives as long as the request.
            req: unsafe { transmute::<httparse::Request<'_, '_>, _>(req) },
            // SAFETY: backing buffer is pinned and lives as long as the request.
            _headers: unsafe {
              transmute::<Vec<httparse::Header<'_>>, _>(headers)
            },
            buffer: Pin::new(
              replace(buffer, vec![0_u8; 1024]).into_boxed_slice(),
            ),
            body_offset,
            body_len,
          };
          // h1
          // https://github.com/tiny-http/tiny-http/blob/master/src/client.rs#L177
          // https://github.com/hyperium/hyper/blob/4545c3ef191ce9b5f5d250ee27c4c96f9b71d2c6/src/proto/h1/role.rs#L127
          let mut keep_alive = inner_req.req.version.unwrap() == 1;
          let mut expect_continue = false;
          let mut te = false;
          let mut te_chunked = false;
          let mut content_length = None;
          for header in inner_req.req.headers.iter() {
            match HeaderName::from_bytes(header.name.as_bytes()) {
              Ok(CONNECTION) => {
                // SAFETY: illegal bytes are validated by httparse.
                let value = unsafe {
                  HeaderValue::from_maybe_shared_unchecked(header.value)
                };
                if keep_alive {
                  // 1.1
                  keep_alive = !connection_has(&value, "close");
                } else {
                  // 1.0
                  keep_alive = connection_has(&value, "keep-alive");
                }
              }
              Ok(TRANSFER_ENCODING) => {
                // https://tools.ietf.org/html/rfc7230#section-3.3.3
                debug_assert!(inner_req.req.version.unwrap() == 1);
                // Two states for Transfer-Encoding because we want to make sure Content-Length handling knows it.
                te = true;
                content_length = None;
                // SAFETY: illegal bytes are validated by httparse.
                let value = unsafe {
                  HeaderValue::from_maybe_shared_unchecked(header.value)
                };
                if let Ok(Some(encoding)) =
                  value.to_str().map(|s| s.rsplit(',').next())
                {
                  // Chunked must always be the last encoding
                  if encoding.trim().eq_ignore_ascii_case("chunked") {
                    te_chunked = true;
                  }
                }
              }
              // Transfer-Encoding overrides the Content-Length.
              Ok(CONTENT_LENGTH) if !te => {
                if let Some(len) = from_digits(header.value) {
                  if let Some(prev) = content_length {
                    if prev != len {
                      let _ = socket.write(b"HTTP/1.1 400 Bad Request\r\n\r\n");
                      continue 'events;
                    }
                    continue;
                  }
                  content_length = Some(len);
                } else {
                  let _ = socket.write(b"HTTP/1.1 400 Bad Request\r\n\r\n");
                  continue 'events;
                }
              }
              Ok(EXPECT) if inner_req.req.version.unwrap() != 0 => {
                expect_continue =
                  header.value.eq_ignore_ascii_case(b"100-continue");
              }
              _ => {}
            }
          }

          // There is Transfer-Encoding but its not chunked.
          if te && !te_chunked {
            let _ = socket.write(b"HTTP/1.1 400 Bad Request\r\n\r\n");
            continue 'events;
          }

          let (socket_tx, socket_rx) = oneshot::channel();

          tx.blocking_send(Request {
            socket: socket as *mut _,
            // SAFETY: headers backing buffer outlives the mio event loop ('static)
            inner: inner_req,
            keep_alive,
            te_chunked,
            remaining_chunk_size: None,
            content_read: 0,
            content_length,
            expect_continue,
            socket_rx,
            owned_socket: None,
          })
          .ok();

          socket_senders.insert(token, socket_tx);
        }
      }
    }
  }

  // Now the flash thread is about to finish, but there may be some unsettled
  // promises in the main thread that will use the socket. To make the socket
  // alive longer enough, we move its ownership to the main thread.
  for (tok, socket) in sockets {
    if let Some(sender) = socket_senders.remove(&tok) {
      // Do nothing if the receiver has already been dropped.
      _ = sender.send(socket);
    }
  }

  Ok(())
}

#[inline]
fn listen(
  addr: SocketAddr,
  reuseport: bool,
) -> Result<TcpListener, std::io::Error> {
  let domain = if addr.is_ipv4() {
    socket2::Domain::IPV4
  } else {
    socket2::Domain::IPV6
  };
  let socket = Socket::new(domain, socket2::Type::STREAM, None)?;

  #[cfg(not(windows))]
  socket.set_reuse_address(true)?;
  if reuseport {
    #[cfg(target_os = "linux")]
    socket.set_reuse_port(true)?;
  }

  let socket_addr = socket2::SockAddr::from(addr);
  socket.bind(&socket_addr)?;
  socket.listen(128)?;
  socket.set_nonblocking(true)?;
  let std_listener: std::net::TcpListener = socket.into();
  Ok(TcpListener::from_std(std_listener))
}

fn make_addr_port_pair(hostname: &str, port: u16) -> (&str, u16) {
  // Default to localhost if given just the port. Example: ":80"
  if hostname.is_empty() {
    return ("0.0.0.0", port);
  }

  // If this looks like an ipv6 IP address. Example: "[2001:db8::1]"
  // Then we remove the brackets.
  let addr = hostname.trim_start_matches('[').trim_end_matches(']');
  (addr, port)
}

/// Resolve network address *synchronously*.
pub fn resolve_addr_sync(
  hostname: &str,
  port: u16,
) -> Result<impl Iterator<Item = SocketAddr>, AnyError> {
  let addr_port_pair = make_addr_port_pair(hostname, port);
  let result = addr_port_pair.to_socket_addrs()?;
  Ok(result)
}

fn flash_serve<P>(
  state: &mut OpState,
  opts: ListenOpts,
) -> Result<u32, AnyError>
where
  P: FlashPermissions + 'static,
{
  state
    .borrow_mut::<P>()
    .check_net(&(&opts.hostname, Some(opts.port)), "Deno.serve()")?;

  let addr = resolve_addr_sync(&opts.hostname, opts.port)?
    .next()
    .ok_or_else(|| generic_error("No resolved address found"))?;
  let (tx, rx) = mpsc::channel(100);
  let (listening_tx, listening_rx) = mpsc::channel(1);

  let poll = Poll::new()?;
  let waker = Arc::new(Waker::new(poll.registry(), WAKER_TOKEN).unwrap());
  let ctx = ServerContext {
    _addr: addr,
    tx,
    rx: Some(rx),
    requests: HashMap::with_capacity(1000),
    next_token: 0,
    listening_rx: Some(listening_rx),
    cancel_handle: CancelHandle::new_rc(),
    waker: waker.clone(),
  };
  let tx = ctx.tx.clone();
  let maybe_cert = opts.cert;
  let maybe_key = opts.key;
  let reuseport = opts.reuseport;
  let join_handle = tokio::task::spawn_blocking(move || {
    run_server(
      tx,
      listening_tx,
      addr,
      maybe_cert,
      maybe_key,
      reuseport,
      poll,
      waker,
    )
  });
  let flash_ctx = state.borrow_mut::<FlashContext>();
  let server_id = flash_ctx.next_server_id;
  flash_ctx.next_server_id += 1;
  flash_ctx.join_handles.insert(server_id, join_handle);
  flash_ctx.servers.insert(server_id, ctx);
  Ok(server_id)
}

#[op]
fn op_flash_serve<P>(
  state: &mut OpState,
  opts: ListenOpts,
) -> Result<u32, AnyError>
where
  P: FlashPermissions + 'static,
{
  check_unstable(state, "Deno.serve");
  flash_serve::<P>(state, opts)
}

#[op]
fn op_node_unstable_flash_serve<P>(
  state: &mut OpState,
  opts: ListenOpts,
) -> Result<u32, AnyError>
where
  P: FlashPermissions + 'static,
{
  flash_serve::<P>(state, opts)
}

#[op]
async fn op_flash_wait_for_listening(
  state: Rc<RefCell<OpState>>,
  server_id: u32,
) -> Result<u16, AnyError> {
  let mut listening_rx = {
    let mut op_state = state.borrow_mut();
    let flash_ctx = op_state.borrow_mut::<FlashContext>();
    let server_ctx = flash_ctx
      .servers
      .get_mut(&server_id)
      .ok_or_else(|| type_error("server not found"))?;
    server_ctx.listening_rx.take().unwrap()
  };
  match listening_rx.recv().await {
    Some(Ok(port)) => Ok(port),
    Some(Err(e)) => Err(e.into()),
    _ => Err(generic_error(
      "unknown error occurred while waiting for listening",
    )),
  }
}

// Asychronous version of op_flash_next. This can be a bottleneck under
// heavy load, it should be used as a fallback if there are no buffered
// requests i.e `op_flash_next() == 0`.
#[op]
async fn op_flash_next_async(
  state: Rc<RefCell<OpState>>,
  server_id: u32,
) -> u32 {
  let mut op_state = state.borrow_mut();
  let flash_ctx = op_state.borrow_mut::<FlashContext>();
  let ctx = flash_ctx.servers.get_mut(&server_id).unwrap();
  let cancel_handle = ctx.cancel_handle.clone();
  let mut rx = ctx.rx.take().unwrap();
  // We need to drop the borrow before await point.
  drop(op_state);

  if let Ok(Some(req)) = rx.recv().or_cancel(&cancel_handle).await {
    let mut op_state = state.borrow_mut();
    let flash_ctx = op_state.borrow_mut::<FlashContext>();
    let ctx = flash_ctx.servers.get_mut(&server_id).unwrap();
    ctx.requests.insert(ctx.next_token, req);
    ctx.next_token += 1;
    // Set the rx back.
    ctx.rx = Some(rx);
    return 1;
  }

  // Set the rx back.
  let mut op_state = state.borrow_mut();
  let flash_ctx = op_state.borrow_mut::<FlashContext>();
  if let Some(ctx) = flash_ctx.servers.get_mut(&server_id) {
    ctx.rx = Some(rx);
  }
  0
}

// Synchronous version of op_flash_next_async. Under heavy load,
// this can collect buffered requests from rx channel and return tokens in a single batch.
//
// perf: please do not add any arguments to this op. With optimizations enabled,
// the ContextScope creation is optimized away and the op is as simple as:
//   f(info: *const v8::FunctionCallbackInfo) { let rv = ...; rv.set_uint32(op_flash_next()); }
#[op]
fn op_flash_next(state: &mut OpState) -> u32 {
  let flash_ctx = state.borrow_mut::<FlashContext>();
  let ctx = flash_ctx.servers.get_mut(&0).unwrap();
  next_request_sync(ctx)
}

// Syncrhonous version of op_flash_next_async. Under heavy load,
// this can collect buffered requests from rx channel and return tokens in a single batch.
#[op]
fn op_flash_next_server(state: &mut OpState, server_id: u32) -> u32 {
  let flash_ctx = state.borrow_mut::<FlashContext>();
  let ctx = flash_ctx.servers.get_mut(&server_id).unwrap();
  next_request_sync(ctx)
}

// Wrapper type for tokio::net::TcpStream that implements
// deno_websocket::UpgradedStream
struct UpgradedStream(tokio::net::TcpStream);
impl tokio::io::AsyncRead for UpgradedStream {
  fn poll_read(
    self: Pin<&mut Self>,
    cx: &mut Context,
    buf: &mut tokio::io::ReadBuf,
  ) -> std::task::Poll<std::result::Result<(), std::io::Error>> {
    Pin::new(&mut self.get_mut().0).poll_read(cx, buf)
  }
}

impl tokio::io::AsyncWrite for UpgradedStream {
  fn poll_write(
    self: Pin<&mut Self>,
    cx: &mut Context,
    buf: &[u8],
  ) -> std::task::Poll<Result<usize, std::io::Error>> {
    Pin::new(&mut self.get_mut().0).poll_write(cx, buf)
  }
  fn poll_flush(
    self: Pin<&mut Self>,
    cx: &mut Context,
  ) -> std::task::Poll<Result<(), std::io::Error>> {
    Pin::new(&mut self.get_mut().0).poll_flush(cx)
  }
  fn poll_shutdown(
    self: Pin<&mut Self>,
    cx: &mut Context,
  ) -> std::task::Poll<Result<(), std::io::Error>> {
    Pin::new(&mut self.get_mut().0).poll_shutdown(cx)
  }
}

impl deno_websocket::Upgraded for UpgradedStream {}

#[inline]
pub fn detach_socket(
  ctx: &mut ServerContext,
  token: u32,
) -> Result<tokio::net::TcpStream, AnyError> {
  // Two main 'hacks' to get this working:
  //   * make server thread forget about the socket. `detach_ownership` prevents the socket from being
  //      dropped on the server thread.
  //   * conversion from mio::net::TcpStream -> tokio::net::TcpStream.  There is no public API so we
  //      use raw fds.
  let mut tx = ctx
    .requests
    .remove(&token)
    .ok_or_else(|| type_error("request closed"))?;
  let stream = tx.socket();
  // prevent socket from being dropped on server thread.
  // TODO(@littledivy): Box-ify, since there is no overhead.
  stream.detach_ownership();

  #[cfg(unix)]
  let std_stream = {
    use std::os::unix::prelude::AsRawFd;
    use std::os::unix::prelude::FromRawFd;
    let fd = match stream.inner {
      InnerStream::Tcp(ref tcp) => tcp.as_raw_fd(),
      _ => todo!(),
    };
    // SAFETY: `fd` is a valid file descriptor.
    unsafe { std::net::TcpStream::from_raw_fd(fd) }
  };
  #[cfg(windows)]
  let std_stream = {
    use std::os::windows::prelude::AsRawSocket;
    use std::os::windows::prelude::FromRawSocket;
    let fd = match stream.inner {
      InnerStream::Tcp(ref tcp) => tcp.as_raw_socket(),
      _ => todo!(),
    };
    // SAFETY: `fd` is a valid file descriptor.
    unsafe { std::net::TcpStream::from_raw_socket(fd) }
  };
  let stream = tokio::net::TcpStream::from_std(std_stream)?;
  Ok(stream)
}

#[op]
async fn op_flash_upgrade_websocket(
  state: Rc<RefCell<OpState>>,
  server_id: u32,
  token: u32,
) -> Result<deno_core::ResourceId, AnyError> {
  let stream = {
    let op_state = &mut state.borrow_mut();
    let flash_ctx = op_state.borrow_mut::<FlashContext>();
    detach_socket(flash_ctx.servers.get_mut(&server_id).unwrap(), token)?
  };
  deno_websocket::ws_create_server_stream(
    &state,
    Box::pin(UpgradedStream(stream)),
  )
  .await
}

pub struct Unstable(pub bool);

fn check_unstable(state: &OpState, api_name: &str) {
  let unstable = state.borrow::<Unstable>();

  if !unstable.0 {
    eprintln!(
      "Unstable API '{}'. The --unstable flag must be provided.",
      api_name
    );
    std::process::exit(70);
  }
}

pub trait FlashPermissions {
  fn check_net<T: AsRef<str>>(
    &mut self,
    _host: &(T, Option<u16>),
    _api_name: &str,
  ) -> Result<(), AnyError>;
}

pub fn init<P: FlashPermissions + 'static>(unstable: bool) -> Extension {
  Extension::builder()
    .js(deno_core::include_js_files!(
      prefix "deno:ext/flash",
      "01_http.js",
    ))
    .ops(vec![
      op_flash_serve::decl::<P>(),
      op_node_unstable_flash_serve::decl::<P>(),
      op_flash_respond::decl(),
      op_flash_respond_async::decl(),
      op_flash_respond_chuncked::decl(),
      op_flash_method::decl(),
      op_flash_path::decl(),
      op_flash_headers::decl(),
      op_flash_next::decl(),
      op_flash_next_server::decl(),
      op_flash_next_async::decl(),
      op_flash_read_body::decl(),
      op_flash_upgrade_websocket::decl(),
      op_flash_wait_for_listening::decl(),
      op_flash_first_packet::decl(),
      op_flash_has_body_stream::decl(),
      op_flash_close_server::decl(),
      op_flash_drive_server::decl(),
      op_flash_make_request::decl(),
      op_flash_write_resource::decl(),
      op_try_flash_respond_chuncked::decl(),
    ])
    .state(move |op_state| {
      op_state.put(Unstable(unstable));
      op_state.put(FlashContext {
        next_server_id: 0,
        join_handles: HashMap::default(),
        servers: HashMap::default(),
      });
      Ok(())
    })
    .build()
}