summaryrefslogtreecommitdiff
path: root/runtime/js/40_http.js
blob: cfb015edd76c95b74bca3d50d7c56e4c445a413f (plain)
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
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
"use strict";

((window) => {
  const { Request, dontValidateUrl, fastBody, Response } =
    window.__bootstrap.fetch;
  const { Headers } = window.__bootstrap.headers;
  const errors = window.__bootstrap.errors.errors;
  const core = window.Deno.core;
  const { ReadableStream } = window.__bootstrap.streams;

  function flatEntries(obj) {
    const entries = [];
    for (const key in obj) {
      entries.push(key);
      entries.push(obj[key]);
    }
    return entries;
  }

  function startHttp(conn) {
    const rid = Deno.core.jsonOpSync("op_http_start", conn.rid);
    return new HttpConn(rid);
  }

  class HttpConn {
    #rid = 0;

    constructor(rid) {
      this.#rid = rid;
    }

    /** @returns {number} */
    get rid() {
      return this.#rid;
    }

    /** @returns {Promise<ResponseEvent | null>} */
    async nextRequest() {
      let nextRequest;
      try {
        nextRequest = await Deno.core.jsonOpAsync(
          "op_http_request_next",
          this.#rid,
        );
      } catch (error) {
        if (error instanceof errors.BadResource) {
          return null;
        } else if (error instanceof errors.Interrupted) {
          return null;
        }
        throw error;
      }
      if (nextRequest === null) return null;

      const [
        requestBodyRid,
        responseSenderRid,
        method,
        headersList,
        url,
      ] = nextRequest;

      /** @type {ReadableStream<Uint8Array> | undefined} */
      let body = undefined;
      if (typeof requestBodyRid === "number") {
        body = createRequestBodyStream(requestBodyRid);
      }

      const request = new Request(url, {
        body,
        method,
        headers: new Headers(headersList),
        [dontValidateUrl]: true,
      });

      const respondWith = createRespondWith(responseSenderRid, this.#rid);

      return { request, respondWith };
    }

    /** @returns {void} */
    close() {
      core.close(this.#rid);
    }

    [Symbol.asyncIterator]() {
      const httpConn = this;
      return {
        async next() {
          const reqEvt = await httpConn.nextRequest();
          if (reqEvt === null) return { value: undefined, done: true };
          return { value: reqEvt, done: false };
        },
      };
    }
  }

  function readRequest(requestRid, zeroCopyBuf) {
    return Deno.core.jsonOpAsync(
      "op_http_request_read",
      requestRid,
      zeroCopyBuf,
    );
  }

  function respond(responseSenderRid, resp, zeroCopyBuf) {
    return Deno.core.jsonOpSync("op_http_response", [
      responseSenderRid,
      resp.status ?? 200,
      flatEntries(resp.headers ?? {}),
    ], zeroCopyBuf);
  }

  function createRespondWith(responseSenderRid, connRid) {
    return async function (resp) {
      if (resp instanceof Promise) {
        resp = await resp;
      }

      if (!(resp instanceof Response)) {
        throw new TypeError(
          "First argument to respondWith must be a Response or a promise resolving to a Response.",
        );
      }
      // If response body is Uint8Array it will be sent synchronously
      // in a single op, in other case a "response body" resource will be
      // created and we'll be streaming it.
      const body = resp[fastBody]();
      let zeroCopyBuf;
      if (body instanceof ArrayBuffer) {
        zeroCopyBuf = new Uint8Array(body);
      } else if (!body) {
        zeroCopyBuf = new Uint8Array(0);
      } else {
        zeroCopyBuf = null;
      }

      const responseBodyRid = respond(
        responseSenderRid,
        resp,
        zeroCopyBuf,
      );

      // If `respond` returns a responseBodyRid, we should stream the body
      // to that resource.
      if (typeof responseBodyRid === "number") {
        if (!body || !(body instanceof ReadableStream)) {
          throw new Error(
            "internal error: recieved responseBodyRid, but response has no body or is not a stream",
          );
        }
        for await (const chunk of body) {
          const data = new Uint8Array(
            chunk.buffer,
            chunk.byteOffset,
            chunk.byteLength,
          );
          await Deno.core.jsonOpAsync(
            "op_http_response_write",
            responseBodyRid,
            data,
          );
        }

        // Once all chunks are sent, and the request body is closed, we can close
        // the response body.
        await Deno.core.jsonOpAsync("op_http_response_close", responseBodyRid);
      }
    };
  }

  function createRequestBodyStream(requestBodyRid) {
    return new ReadableStream({
      type: "bytes",
      async pull(controller) {
        try {
          // This is the largest possible size for a single packet on a TLS
          // stream.
          const chunk = new Uint8Array(16 * 1024 + 256);
          const read = await readRequest(
            requestBodyRid,
            chunk,
          );
          if (read > 0) {
            // We read some data. Enqueue it onto the stream.
            controller.enqueue(chunk.subarray(0, read));
          } else {
            // We have reached the end of the body, so we close the stream.
            controller.close();
            core.close(requestBodyRid);
          }
        } catch (err) {
          // There was an error while reading a chunk of the body, so we
          // error.
          controller.error(err);
          controller.close();
          core.close(requestBodyRid);
        }
      },
      cancel() {
        core.close(requestBodyRid);
      },
    });
  }

  window.__bootstrap.http = {
    startHttp,
  };
})(this);