]> Cypherpunks.ru repositories - gostls13.git/blob - src/net/http/roundtrip_js.go
net/http: close req.Body only when it's non-nil on js
[gostls13.git] / src / net / http / roundtrip_js.go
1 // Copyright 2018 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 //go:build js && wasm
6
7 package http
8
9 import (
10         "errors"
11         "fmt"
12         "io"
13         "strconv"
14         "strings"
15         "syscall/js"
16 )
17
18 var uint8Array = js.Global().Get("Uint8Array")
19
20 // jsFetchMode is a Request.Header map key that, if present,
21 // signals that the map entry is actually an option to the Fetch API mode setting.
22 // Valid values are: "cors", "no-cors", "same-origin", "navigate"
23 // The default is "same-origin".
24 //
25 // Reference: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters
26 const jsFetchMode = "js.fetch:mode"
27
28 // jsFetchCreds is a Request.Header map key that, if present,
29 // signals that the map entry is actually an option to the Fetch API credentials setting.
30 // Valid values are: "omit", "same-origin", "include"
31 // The default is "same-origin".
32 //
33 // Reference: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters
34 const jsFetchCreds = "js.fetch:credentials"
35
36 // jsFetchRedirect is a Request.Header map key that, if present,
37 // signals that the map entry is actually an option to the Fetch API redirect setting.
38 // Valid values are: "follow", "error", "manual"
39 // The default is "follow".
40 //
41 // Reference: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters
42 const jsFetchRedirect = "js.fetch:redirect"
43
44 // jsFetchMissing will be true if the Fetch API is not present in
45 // the browser globals.
46 var jsFetchMissing = js.Global().Get("fetch").IsUndefined()
47
48 // jsFetchDisabled controls whether the use of Fetch API is disabled.
49 // It's set to true when we detect we're running in Node.js, so that
50 // RoundTrip ends up talking over the same fake network the HTTP servers
51 // currently use in various tests and examples. See go.dev/issue/57613.
52 //
53 // TODO(go.dev/issue/60810): See if it's viable to test the Fetch API
54 // code path.
55 var jsFetchDisabled = js.Global().Get("process").Type() == js.TypeObject &&
56         strings.HasPrefix(js.Global().Get("process").Get("argv0").String(), "node")
57
58 // Determine whether the JS runtime supports streaming request bodies.
59 // Courtesy: https://developer.chrome.com/articles/fetch-streaming-requests/#feature-detection
60 func supportsPostRequestStreams() bool {
61         requestOpt := js.Global().Get("Object").New()
62         requestBody := js.Global().Get("ReadableStream").New()
63
64         requestOpt.Set("method", "POST")
65         requestOpt.Set("body", requestBody)
66
67         // There is quite a dance required to define a getter if you do not have the { get property() { ... } }
68         // syntax available. However, it is possible:
69         // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get#defining_a_getter_on_existing_objects_using_defineproperty
70         duplexCalled := false
71         duplexGetterObj := js.Global().Get("Object").New()
72         duplexGetterFunc := js.FuncOf(func(this js.Value, args []js.Value) any {
73                 duplexCalled = true
74                 return "half"
75         })
76         defer duplexGetterFunc.Release()
77         duplexGetterObj.Set("get", duplexGetterFunc)
78         js.Global().Get("Object").Call("defineProperty", requestOpt, "duplex", duplexGetterObj)
79
80         // Slight difference here between the aforementioned example: Non-browser-based runtimes
81         // do not have a non-empty API Base URL (https://html.spec.whatwg.org/multipage/webappapis.html#api-base-url)
82         // so we have to supply a valid URL here.
83         requestObject := js.Global().Get("Request").New("https://www.example.org", requestOpt)
84
85         hasContentTypeHeader := requestObject.Get("headers").Call("has", "Content-Type").Bool()
86
87         return duplexCalled && !hasContentTypeHeader
88 }
89
90 // RoundTrip implements the RoundTripper interface using the WHATWG Fetch API.
91 func (t *Transport) RoundTrip(req *Request) (*Response, error) {
92         // The Transport has a documented contract that states that if the DialContext or
93         // DialTLSContext functions are set, they will be used to set up the connections.
94         // If they aren't set then the documented contract is to use Dial or DialTLS, even
95         // though they are deprecated. Therefore, if any of these are set, we should obey
96         // the contract and dial using the regular round-trip instead. Otherwise, we'll try
97         // to fall back on the Fetch API, unless it's not available.
98         if t.Dial != nil || t.DialContext != nil || t.DialTLS != nil || t.DialTLSContext != nil || jsFetchMissing || jsFetchDisabled {
99                 return t.roundTrip(req)
100         }
101
102         ac := js.Global().Get("AbortController")
103         if !ac.IsUndefined() {
104                 // Some browsers that support WASM don't necessarily support
105                 // the AbortController. See
106                 // https://developer.mozilla.org/en-US/docs/Web/API/AbortController#Browser_compatibility.
107                 ac = ac.New()
108         }
109
110         opt := js.Global().Get("Object").New()
111         // See https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
112         // for options available.
113         opt.Set("method", req.Method)
114         opt.Set("credentials", "same-origin")
115         if h := req.Header.Get(jsFetchCreds); h != "" {
116                 opt.Set("credentials", h)
117                 req.Header.Del(jsFetchCreds)
118         }
119         if h := req.Header.Get(jsFetchMode); h != "" {
120                 opt.Set("mode", h)
121                 req.Header.Del(jsFetchMode)
122         }
123         if h := req.Header.Get(jsFetchRedirect); h != "" {
124                 opt.Set("redirect", h)
125                 req.Header.Del(jsFetchRedirect)
126         }
127         if !ac.IsUndefined() {
128                 opt.Set("signal", ac.Get("signal"))
129         }
130         headers := js.Global().Get("Headers").New()
131         for key, values := range req.Header {
132                 for _, value := range values {
133                         headers.Call("append", key, value)
134                 }
135         }
136         opt.Set("headers", headers)
137
138         if req.Body != nil {
139                 if !supportsPostRequestStreams() {
140                         body, err := io.ReadAll(req.Body)
141                         if err != nil {
142                                 req.Body.Close() // RoundTrip must always close the body, including on errors.
143                                 return nil, err
144                         }
145                         req.Body.Close()
146                         if len(body) != 0 {
147                                 buf := uint8Array.New(len(body))
148                                 js.CopyBytesToJS(buf, body)
149                                 opt.Set("body", buf)
150                         }
151                 } else {
152                         readableStreamCtorArg := js.Global().Get("Object").New()
153                         readableStreamCtorArg.Set("type", "bytes")
154                         readableStreamCtorArg.Set("autoAllocateChunkSize", t.writeBufferSize())
155
156                         readableStreamPull := js.FuncOf(func(this js.Value, args []js.Value) any {
157                                 controller := args[0]
158                                 byobRequest := controller.Get("byobRequest")
159                                 if byobRequest.IsNull() {
160                                         controller.Call("close")
161                                 }
162
163                                 byobRequestView := byobRequest.Get("view")
164
165                                 bodyBuf := make([]byte, byobRequestView.Get("byteLength").Int())
166                                 readBytes, readErr := io.ReadFull(req.Body, bodyBuf)
167                                 if readBytes > 0 {
168                                         buf := uint8Array.New(byobRequestView.Get("buffer"))
169                                         js.CopyBytesToJS(buf, bodyBuf)
170                                         byobRequest.Call("respond", readBytes)
171                                 }
172
173                                 if readErr == io.EOF || readErr == io.ErrUnexpectedEOF {
174                                         controller.Call("close")
175                                 } else if readErr != nil {
176                                         readErrCauseObject := js.Global().Get("Object").New()
177                                         readErrCauseObject.Set("cause", readErr.Error())
178                                         readErr := js.Global().Get("Error").New("io.ReadFull failed while streaming POST body", readErrCauseObject)
179                                         controller.Call("error", readErr)
180                                 }
181                                 // Note: This a return from the pull callback of the controller and *not* RoundTrip().
182                                 return nil
183                         })
184                         defer func() {
185                                 readableStreamPull.Release()
186                                 req.Body.Close()
187                         }()
188                         readableStreamCtorArg.Set("pull", readableStreamPull)
189
190                         opt.Set("body", js.Global().Get("ReadableStream").New(readableStreamCtorArg))
191                         // There is a requirement from the WHATWG fetch standard that the duplex property of
192                         // the object given as the options argument to the fetch call be set to 'half'
193                         // when the body property of the same options object is a ReadableStream:
194                         // https://fetch.spec.whatwg.org/#dom-requestinit-duplex
195                         opt.Set("duplex", "half")
196                 }
197         }
198
199         fetchPromise := js.Global().Call("fetch", req.URL.String(), opt)
200         var (
201                 respCh           = make(chan *Response, 1)
202                 errCh            = make(chan error, 1)
203                 success, failure js.Func
204         )
205         success = js.FuncOf(func(this js.Value, args []js.Value) any {
206                 success.Release()
207                 failure.Release()
208
209                 result := args[0]
210                 header := Header{}
211                 // https://developer.mozilla.org/en-US/docs/Web/API/Headers/entries
212                 headersIt := result.Get("headers").Call("entries")
213                 for {
214                         n := headersIt.Call("next")
215                         if n.Get("done").Bool() {
216                                 break
217                         }
218                         pair := n.Get("value")
219                         key, value := pair.Index(0).String(), pair.Index(1).String()
220                         ck := CanonicalHeaderKey(key)
221                         header[ck] = append(header[ck], value)
222                 }
223
224                 contentLength := int64(0)
225                 clHeader := header.Get("Content-Length")
226                 switch {
227                 case clHeader != "":
228                         cl, err := strconv.ParseInt(clHeader, 10, 64)
229                         if err != nil {
230                                 errCh <- fmt.Errorf("net/http: ill-formed Content-Length header: %v", err)
231                                 return nil
232                         }
233                         if cl < 0 {
234                                 // Content-Length values less than 0 are invalid.
235                                 // See: https://datatracker.ietf.org/doc/html/rfc2616/#section-14.13
236                                 errCh <- fmt.Errorf("net/http: invalid Content-Length header: %q", clHeader)
237                                 return nil
238                         }
239                         contentLength = cl
240                 default:
241                         // If the response length is not declared, set it to -1.
242                         contentLength = -1
243                 }
244
245                 b := result.Get("body")
246                 var body io.ReadCloser
247                 // The body is undefined when the browser does not support streaming response bodies (Firefox),
248                 // and null in certain error cases, i.e. when the request is blocked because of CORS settings.
249                 if !b.IsUndefined() && !b.IsNull() {
250                         body = &streamReader{stream: b.Call("getReader")}
251                 } else {
252                         // Fall back to using ArrayBuffer
253                         // https://developer.mozilla.org/en-US/docs/Web/API/Body/arrayBuffer
254                         body = &arrayReader{arrayPromise: result.Call("arrayBuffer")}
255                 }
256
257                 code := result.Get("status").Int()
258                 respCh <- &Response{
259                         Status:        fmt.Sprintf("%d %s", code, StatusText(code)),
260                         StatusCode:    code,
261                         Header:        header,
262                         ContentLength: contentLength,
263                         Body:          body,
264                         Request:       req,
265                 }
266
267                 return nil
268         })
269         failure = js.FuncOf(func(this js.Value, args []js.Value) any {
270                 success.Release()
271                 failure.Release()
272
273                 err := args[0]
274                 // The error is a JS Error type
275                 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
276                 // We can use the toString() method to get a string representation of the error.
277                 errMsg := err.Call("toString").String()
278                 // Errors can optionally contain a cause.
279                 if cause := err.Get("cause"); !cause.IsUndefined() {
280                         // The exact type of the cause is not defined,
281                         // but if it's another error, we can call toString() on it too.
282                         if !cause.Get("toString").IsUndefined() {
283                                 errMsg += ": " + cause.Call("toString").String()
284                         } else if cause.Type() == js.TypeString {
285                                 errMsg += ": " + cause.String()
286                         }
287                 }
288                 errCh <- fmt.Errorf("net/http: fetch() failed: %s", errMsg)
289                 return nil
290         })
291
292         fetchPromise.Call("then", success, failure)
293         select {
294         case <-req.Context().Done():
295                 if !ac.IsUndefined() {
296                         // Abort the Fetch request.
297                         ac.Call("abort")
298                 }
299                 return nil, req.Context().Err()
300         case resp := <-respCh:
301                 return resp, nil
302         case err := <-errCh:
303                 return nil, err
304         }
305 }
306
307 var errClosed = errors.New("net/http: reader is closed")
308
309 // streamReader implements an io.ReadCloser wrapper for ReadableStream.
310 // See https://fetch.spec.whatwg.org/#readablestream for more information.
311 type streamReader struct {
312         pending []byte
313         stream  js.Value
314         err     error // sticky read error
315 }
316
317 func (r *streamReader) Read(p []byte) (n int, err error) {
318         if r.err != nil {
319                 return 0, r.err
320         }
321         if len(r.pending) == 0 {
322                 var (
323                         bCh   = make(chan []byte, 1)
324                         errCh = make(chan error, 1)
325                 )
326                 success := js.FuncOf(func(this js.Value, args []js.Value) any {
327                         result := args[0]
328                         if result.Get("done").Bool() {
329                                 errCh <- io.EOF
330                                 return nil
331                         }
332                         value := make([]byte, result.Get("value").Get("byteLength").Int())
333                         js.CopyBytesToGo(value, result.Get("value"))
334                         bCh <- value
335                         return nil
336                 })
337                 defer success.Release()
338                 failure := js.FuncOf(func(this js.Value, args []js.Value) any {
339                         // Assumes it's a TypeError. See
340                         // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
341                         // for more information on this type. See
342                         // https://streams.spec.whatwg.org/#byob-reader-read for the spec on
343                         // the read method.
344                         errCh <- errors.New(args[0].Get("message").String())
345                         return nil
346                 })
347                 defer failure.Release()
348                 r.stream.Call("read").Call("then", success, failure)
349                 select {
350                 case b := <-bCh:
351                         r.pending = b
352                 case err := <-errCh:
353                         r.err = err
354                         return 0, err
355                 }
356         }
357         n = copy(p, r.pending)
358         r.pending = r.pending[n:]
359         return n, nil
360 }
361
362 func (r *streamReader) Close() error {
363         // This ignores any error returned from cancel method. So far, I did not encounter any concrete
364         // situation where reporting the error is meaningful. Most users ignore error from resp.Body.Close().
365         // If there's a need to report error here, it can be implemented and tested when that need comes up.
366         r.stream.Call("cancel")
367         if r.err == nil {
368                 r.err = errClosed
369         }
370         return nil
371 }
372
373 // arrayReader implements an io.ReadCloser wrapper for ArrayBuffer.
374 // https://developer.mozilla.org/en-US/docs/Web/API/Body/arrayBuffer.
375 type arrayReader struct {
376         arrayPromise js.Value
377         pending      []byte
378         read         bool
379         err          error // sticky read error
380 }
381
382 func (r *arrayReader) Read(p []byte) (n int, err error) {
383         if r.err != nil {
384                 return 0, r.err
385         }
386         if !r.read {
387                 r.read = true
388                 var (
389                         bCh   = make(chan []byte, 1)
390                         errCh = make(chan error, 1)
391                 )
392                 success := js.FuncOf(func(this js.Value, args []js.Value) any {
393                         // Wrap the input ArrayBuffer with a Uint8Array
394                         uint8arrayWrapper := uint8Array.New(args[0])
395                         value := make([]byte, uint8arrayWrapper.Get("byteLength").Int())
396                         js.CopyBytesToGo(value, uint8arrayWrapper)
397                         bCh <- value
398                         return nil
399                 })
400                 defer success.Release()
401                 failure := js.FuncOf(func(this js.Value, args []js.Value) any {
402                         // Assumes it's a TypeError. See
403                         // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
404                         // for more information on this type.
405                         // See https://fetch.spec.whatwg.org/#concept-body-consume-body for reasons this might error.
406                         errCh <- errors.New(args[0].Get("message").String())
407                         return nil
408                 })
409                 defer failure.Release()
410                 r.arrayPromise.Call("then", success, failure)
411                 select {
412                 case b := <-bCh:
413                         r.pending = b
414                 case err := <-errCh:
415                         return 0, err
416                 }
417         }
418         if len(r.pending) == 0 {
419                 return 0, io.EOF
420         }
421         n = copy(p, r.pending)
422         r.pending = r.pending[n:]
423         return n, nil
424 }
425
426 func (r *arrayReader) Close() error {
427         if r.err == nil {
428                 r.err = errClosed
429         }
430         return nil
431 }