deno_net 0.199.0

Networking for Deno
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
// Copyright 2018-2025 the Deno authors. MIT license.
import { core, primordials } from "ext:core/mod.js";
import {
  op_quic_connecting_0rtt,
  op_quic_connecting_1rtt,
  op_quic_connection_accept_bi,
  op_quic_connection_accept_uni,
  op_quic_connection_close,
  op_quic_connection_closed,
  op_quic_connection_get_max_datagram_size,
  op_quic_connection_get_protocol,
  op_quic_connection_get_remote_addr,
  op_quic_connection_get_server_name,
  op_quic_connection_handshake,
  op_quic_connection_open_bi,
  op_quic_connection_open_uni,
  op_quic_connection_read_datagram,
  op_quic_connection_send_datagram,
  op_quic_endpoint_close,
  op_quic_endpoint_connect,
  op_quic_endpoint_create,
  op_quic_endpoint_get_addr,
  op_quic_endpoint_listen,
  op_quic_incoming_accept,
  op_quic_incoming_accept_0rtt,
  op_quic_incoming_ignore,
  op_quic_incoming_local_ip,
  op_quic_incoming_refuse,
  op_quic_incoming_remote_addr,
  op_quic_incoming_remote_addr_validated,
  op_quic_listener_accept,
  op_quic_listener_stop,
  op_quic_recv_stream_get_id,
  op_quic_send_stream_get_id,
  op_quic_send_stream_get_priority,
  op_quic_send_stream_set_priority,
  op_webtransport_accept,
  op_webtransport_connect,
} from "ext:core/ops";
import {
  getReadableStreamResourceBacking,
  getWritableStreamResourceBacking,
  ReadableStream,
  readableStreamForRid,
  WritableStream,
  writableStreamForRid,
} from "ext:deno_web/06_streams.js";
import { loadTlsKeyPair } from "ext:deno_net/02_tls.js";
const {
  BadResourcePrototype,
} = core;
const {
  ObjectPrototypeIsPrototypeOf,
  PromisePrototypeThen,
  ReflectConstruct,
  Symbol,
  SymbolAsyncIterator,
} = primordials;

let getEndpointResource;

function promiseFinallyWithoutUnhandled(p, f) {
  return PromisePrototypeThen(p, f, f);
}

function transportOptions({
  keepAliveInterval,
  maxIdleTimeout,
  maxConcurrentBidirectionalStreams,
  maxConcurrentUnidirectionalStreams,
  preferredAddressV4,
  preferredAddressV6,
  congestionControl,
}) {
  return {
    keepAliveInterval,
    maxIdleTimeout,
    maxConcurrentBidirectionalStreams,
    maxConcurrentUnidirectionalStreams,
    preferredAddressV4,
    preferredAddressV6,
    congestionControl,
  };
}

const kRid = Symbol("rid");

class QuicEndpoint {
  #endpoint;

  constructor(
    { hostname = "::", port = 0, [kRid]: rid } = { __proto__: null },
  ) {
    this.#endpoint = rid ?? op_quic_endpoint_create({ hostname, port }, true);
  }

  get addr() {
    return op_quic_endpoint_get_addr(this.#endpoint);
  }

  listen(options) {
    const keyPair = loadTlsKeyPair("Deno.QuicEndpoint.listen", {
      cert: options.cert,
      key: options.key,
    });
    const listener = op_quic_endpoint_listen(
      this.#endpoint,
      { alpnProtocols: options.alpnProtocols },
      transportOptions(options),
      keyPair,
    );
    return new QuicListener(listener, this);
  }

  close({ closeCode = 0, reason = "" } = { __proto__: null }) {
    op_quic_endpoint_close(this.#endpoint, closeCode, reason);
  }

  static {
    getEndpointResource = (e) => e.#endpoint;
  }
}

class QuicListener {
  #listener;
  #endpoint;

  constructor(listener, endpoint) {
    this.#listener = listener;
    this.#endpoint = endpoint;
  }

  get endpoint() {
    return this.#endpoint;
  }

  async incoming() {
    const incoming = await op_quic_listener_accept(this.#listener);
    return new QuicIncoming(incoming, this.#endpoint);
  }

  async accept() {
    const incoming = await this.incoming();
    const connection = await incoming.accept();
    return connection;
  }

  async next() {
    try {
      const connection = await this.accept();
      return { value: connection, done: false };
    } catch (error) {
      if (ObjectPrototypeIsPrototypeOf(BadResourcePrototype, error)) {
        return { value: undefined, done: true };
      }
      throw error;
    }
  }

  [SymbolAsyncIterator]() {
    return this;
  }

  stop() {
    op_quic_listener_stop(this.#listener);
  }
}

class QuicIncoming {
  #incoming;
  #endpoint;

  constructor(incoming, endpoint) {
    this.#incoming = incoming;
    this.#endpoint = endpoint;
  }

  get localIp() {
    return op_quic_incoming_local_ip(this.#incoming);
  }

  get remoteAddr() {
    return op_quic_incoming_remote_addr(this.#incoming);
  }

  get remoteAddressValidated() {
    return op_quic_incoming_remote_addr_validated(this.#incoming);
  }

  accept(options) {
    const tOptions = options ? transportOptions(options) : null;
    if (options?.zeroRtt) {
      const conn = op_quic_incoming_accept_0rtt(
        this.#incoming,
        tOptions,
      );
      return new QuicConn(conn, this.#endpoint);
    }
    return PromisePrototypeThen(
      op_quic_incoming_accept(this.#incoming, tOptions),
      (conn) => new QuicConn(conn, this.#endpoint),
    );
  }

  refuse() {
    op_quic_incoming_refuse(this.#incoming);
  }

  ignore() {
    op_quic_incoming_ignore(this.#incoming);
  }
}

let webtransportConnect;
let webtransportAccept;

class QuicConn {
  #resource;
  #bidiStream = null;
  #uniStream = null;
  #closed;
  #handshake;
  #endpoint;

  constructor(resource, endpoint) {
    this.#resource = resource;
    this.#endpoint = endpoint;

    this.#closed = op_quic_connection_closed(this.#resource);
    core.unrefOpPromise(this.#closed);
  }

  get endpoint() {
    return this.#endpoint;
  }

  get protocol() {
    return op_quic_connection_get_protocol(this.#resource);
  }

  get remoteAddr() {
    return op_quic_connection_get_remote_addr(this.#resource);
  }

  get serverName() {
    return op_quic_connection_get_server_name(this.#resource);
  }

  async createBidirectionalStream(
    { sendOrder, waitUntilAvailable } = { __proto__: null },
  ) {
    const { 0: txRid, 1: rxRid } = await op_quic_connection_open_bi(
      this.#resource,
      waitUntilAvailable ?? false,
    );
    if (sendOrder !== null && sendOrder !== undefined) {
      op_quic_send_stream_set_priority(txRid, sendOrder);
    }
    return new QuicBidirectionalStream(txRid, rxRid, this.#closed);
  }

  async createUnidirectionalStream(
    { sendOrder, waitUntilAvailable } = { __proto__: null },
  ) {
    const rid = await op_quic_connection_open_uni(
      this.#resource,
      waitUntilAvailable ?? false,
    );
    if (sendOrder !== null && sendOrder !== undefined) {
      op_quic_send_stream_set_priority(rid, sendOrder);
    }
    return writableStream(rid, this.#closed);
  }

  get incomingBidirectionalStreams() {
    if (this.#bidiStream === null) {
      this.#bidiStream = ReadableStream.from(
        bidiStream(this.#resource, this.#closed),
      );
    }
    return this.#bidiStream;
  }

  get incomingUnidirectionalStreams() {
    if (this.#uniStream === null) {
      this.#uniStream = ReadableStream.from(
        uniStream(this.#resource, this.#closed),
      );
    }
    return this.#uniStream;
  }

  get maxDatagramSize() {
    return op_quic_connection_get_max_datagram_size(this.#resource);
  }

  async readDatagram() {
    const buffer = await op_quic_connection_read_datagram(this.#resource);
    return buffer;
  }

  async sendDatagram(data) {
    await op_quic_connection_send_datagram(this.#resource, data);
  }

  get handshake() {
    if (!this.#handshake) {
      this.#handshake = op_quic_connection_handshake(this.#resource);
    }
    return this.#handshake;
  }

  get closed() {
    core.refOpPromise(this.#closed);
    return this.#closed;
  }

  close({ closeCode = 0, reason = "" } = { __proto__: null }) {
    op_quic_connection_close(this.#resource, closeCode, reason);
  }

  static {
    webtransportConnect = async function webtransportConnect(conn, url) {
      const {
        0: connectTxRid,
        1: connectRxRid,
        2: settingsTxRid,
        3: settingsRxRid,
      } = await op_webtransport_connect(conn.#resource, url);
      const connect = new QuicBidirectionalStream(
        connectTxRid,
        connectRxRid,
        conn.closed,
      );
      const settingsTx = writableStream(settingsTxRid, conn.closed);
      const settingsRx = readableStream(settingsRxRid, conn.closed);
      return { connect, settingsTx, settingsRx };
    };

    webtransportAccept = async function webtransportAccept(conn) {
      const {
        0: url,
        1: connectTxRid,
        2: connectRxRid,
        3: settingsTxRid,
        4: settingsRxRid,
      } = await op_webtransport_accept(conn.#resource);
      const connect = new QuicBidirectionalStream(
        connectTxRid,
        connectRxRid,
        conn.closed,
      );
      const settingsTx = writableStream(settingsTxRid, conn.closed);
      const settingsRx = readableStream(settingsRxRid, conn.closed);
      return { url, connect, settingsTx, settingsRx };
    };
  }
}

class QuicSendStream extends WritableStream {
  get sendOrder() {
    return op_quic_send_stream_get_priority(
      getWritableStreamResourceBacking(this).rid,
    );
  }

  set sendOrder(p) {
    op_quic_send_stream_set_priority(
      getWritableStreamResourceBacking(this).rid,
      p,
    );
  }

  get id() {
    return op_quic_send_stream_get_id(
      getWritableStreamResourceBacking(this).rid,
    );
  }
}

class QuicReceiveStream extends ReadableStream {
  get id() {
    return op_quic_recv_stream_get_id(
      getReadableStreamResourceBacking(this).rid,
    );
  }
}

function readableStream(rid, closed) {
  // stream can be indirectly closed by closing connection.
  promiseFinallyWithoutUnhandled(closed, () => {
    core.tryClose(rid);
  });
  return readableStreamForRid(
    rid,
    true,
    (...args) => ReflectConstruct(QuicReceiveStream, args),
  );
}

function writableStream(rid, closed) {
  // stream can be indirectly closed by closing connection.
  promiseFinallyWithoutUnhandled(closed, () => {
    core.tryClose(rid);
  });
  return writableStreamForRid(
    rid,
    true,
    (...args) => ReflectConstruct(QuicSendStream, args),
  );
}

class QuicBidirectionalStream {
  #readable;
  #writable;

  constructor(txRid, rxRid, closed) {
    this.#readable = readableStream(rxRid, closed);
    this.#writable = writableStream(txRid, closed);
  }

  get readable() {
    return this.#readable;
  }

  get writable() {
    return this.#writable;
  }
}

async function* bidiStream(conn, closed) {
  try {
    while (true) {
      const r = await op_quic_connection_accept_bi(conn);
      yield new QuicBidirectionalStream(r[0], r[1], closed);
    }
  } catch (error) {
    if (ObjectPrototypeIsPrototypeOf(BadResourcePrototype, error)) {
      return;
    }
    throw error;
  }
}

async function* uniStream(conn, closed) {
  try {
    while (true) {
      const uniRid = await op_quic_connection_accept_uni(conn);
      yield readableStream(uniRid, closed);
    }
  } catch (error) {
    if (ObjectPrototypeIsPrototypeOf(BadResourcePrototype, error)) {
      return;
    }
    throw error;
  }
}

function connectQuic(options) {
  const endpoint = options.endpoint ??
    new QuicEndpoint({
      [kRid]: op_quic_endpoint_create({ hostname: "::", port: 0 }, 0, false),
    });
  const keyPair = loadTlsKeyPair("Deno.connectQuic", {
    cert: options.cert,
    key: options.key,
  });
  const connecting = op_quic_endpoint_connect(
    getEndpointResource(endpoint),
    {
      addr: {
        hostname: options.hostname,
        port: options.port,
      },
      caCerts: options.caCerts,
      alpnProtocols: options.alpnProtocols,
      serverName: options.serverName,
      serverCertificateHashes: options.serverCertificateHashes,
    },
    transportOptions(options),
    keyPair,
  );

  if (options.zeroRtt) {
    const conn = op_quic_connecting_0rtt(connecting);
    if (conn) {
      return new QuicConn(conn, endpoint);
    }
  }

  return PromisePrototypeThen(
    op_quic_connecting_1rtt(connecting),
    (conn) => new QuicConn(conn, endpoint),
  );
}

export {
  connectQuic,
  QuicBidirectionalStream,
  QuicConn,
  QuicEndpoint,
  QuicIncoming,
  QuicListener,
  QuicReceiveStream,
  QuicSendStream,
  webtransportAccept,
  webtransportConnect,
};