aboutsummaryrefslogtreecommitdiffstats
path: root/doc/src/manual/gun.asciidoc
blob: d130d6258fb85585393289bf22292ee53de04fcc (plain) (blame)
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
= gun(3)

== Name

gun - Asynchronous HTTP client

== Description

The `gun` module provides an asynchronous interface for
connecting and communicating with Web servers over HTTP,
HTTP/2 or Websocket.

== Exports

Connection:

* link:man:gun:open(3)[gun:open(3)] - Open a connection to the given host and port
* link:man:gun:open_unix(3)[gun:open_unix(3)] - Open a connection to the given Unix domain socket
* link:man:gun:set_owner(3)[gun:set_owner(3)] - Set a new owner for the connection
* link:man:gun:shutdown(3)[gun:shutdown(3)] - Gracefully close the connection
* link:man:gun:close(3)[gun:close(3)] - Brutally close the connection
* link:man:gun:info(3)[gun:info(3)] - Obtain information about the connection

Requests:

* link:man:gun:get(3)[gun:get(3)] - Get a resource representation
* link:man:gun:head(3)[gun:head(3)] - Get headers of a resource representation
* link:man:gun:options(3)[gun:options(3)] - Query the capabilities of the server or a resource
* link:man:gun:patch(3)[gun:patch(3)] - Apply a set of changes to a resource
* link:man:gun:post(3)[gun:post(3)] - Process the enclosed representation according to a resource's own semantics
* link:man:gun:put(3)[gun:put(3)] - Create or replace a resource
* link:man:gun:delete(3)[gun:delete(3)] - Delete a resource
* link:man:gun:headers(3)[gun:headers(3)] - Initiate the given request
* link:man:gun:request(3)[gun:request(3)] - Perform the given request
* link:man:gun:data(3)[gun:data(3)] - Stream the body of a request

Proxies:

* link:man:gun:connect(3)[gun:connect(3)] - Establish a tunnel to the origin server

Messages:

* link:man:gun:await(3)[gun:await(3)] - Wait for a response
* link:man:gun:await_body(3)[gun:await_body(3)] - Wait for the complete response body
* link:man:gun:await_up(3)[gun:await_up(3)] - Wait for the connection to be up
* link:man:gun:flush(3)[gun:flush(3)] - Flush all messages related to a connection or a stream

Streams:

* link:man:gun:update_flow(3)[gun:update_flow(3)] - Update a stream's flow control value
* link:man:gun:cancel(3)[gun:cancel(3)] - Cancel the given stream
* link:man:gun:stream_info(3)[gun:stream_info(3)] - Obtain information about a stream

Websocket:

* link:man:gun:ws_upgrade(3)[gun:ws_upgrade(3)] - Upgrade to Websocket
* link:man:gun:ws_send(3)[gun:ws_send(3)] - Send Websocket frames

== Messages

Gun will inform the calling process of events asynchronously
by sending any of the following messages:

Connection:

* link:man:gun_up(3)[gun_up(3)] - The connection is up
* link:man:gun_tunnel_up(3)[gun_tunnel_up(3)] - The tunnel is up
* link:man:gun_down(3)[gun_down(3)] - The connection is down
* link:man:gun_upgrade(3)[gun_upgrade(3)] - Successful protocol upgrade
* link:man:gun_error(3)[gun_error(3)] - Stream or connection-wide error

Responses:

* link:man:gun_push(3)[gun_push(3)] - Server-initiated push
* link:man:gun_inform(3)[gun_inform(3)] - Informational response
* link:man:gun_response(3)[gun_response(3)] - Response
* link:man:gun_data(3)[gun_data(3)] - Response body
* link:man:gun_trailers(3)[gun_trailers(3)] - Response trailers

Websocket:

* link:man:gun_ws(3)[gun_ws(3)] - Websocket frame

The response messages will be sent to the process that opened
the connection by default. The `reply_to` request option can
be used to redirect request-specific messages to a different
process.

== Types

=== connect_destination()

[source,erlang]
----
connect_destination() :: #{
    host      := inet:hostname() | inet:ip_address(),
    port      := inet:port_number(),

    username  => iodata(),
    password  => iodata(),
    protocols => protocols(),
    transport => tcp | tls,

    tls_opts              => [ssl:tls_client_option()],
    tls_handshake_timeout => timeout()
}
----

Destination of a CONNECT request.

The default value, if any, is given next to the option name:

host, port::

Destination hostname and port number. Mandatory.
+
Upon successful completion of the CONNECT request, Gun will
begin using these as the host and port of the origin server
for subsequent requests.

username, password::

Proxy authorization credentials. They are only sent when
both options are provided.

protocols - see below::

Ordered list of preferred protocols. Please refer to the
`protocols()` type documentation for details.
+
Defaults to `[http]` when the transport is `tcp`,
and `[http2, http]` when the transport is `tls`.

transport (tcp)::

Transport that will be used for tunneled requests.

tls_opts ([])::

Options to use for tunneled TLS connections.

tls_handshake_timeout (infinity)::

Handshake timeout for tunneled TLS connections.

=== http_opts()

[source,erlang]
----
http_opts() :: #{
    closing_timeout             => timeout(),
    cookie_ignore_informational => boolean(),
    flow                        => pos_integer(),
    keepalive                   => timeout(),
    transform_header_name       => fun((binary()) -> binary()),
    version                     => 'HTTP/1.1' | 'HTTP/1.0'
}
----

Configuration for the HTTP protocol.

The default value is given next to the option name:

// @todo Document content_handlers and gun_sse_h.

closing_timeout (15000)::

Time to wait before brutally closing the connection when a
graceful shutdown was requested via a call to
link:man:gun:shutdown(3)[gun:shutdown(3)].

cookie_ignore_informational (false)::

Whether cookies received inside informational responses
(1xx status code) must be ignored.

flow - see below::

The initial flow control value for all HTTP/1.1 streams.
By default flow control is disabled.

keepalive (infinity)::

Time between pings in milliseconds. Since the HTTP protocol has
no standardized way to ping the server, Gun will simply send an
empty line when the connection is idle. Gun only makes a best
effort here as servers usually have configurable limits to drop
idle connections. Disabled by default due to potential
incompatibilities.

transform_header_name - see below::

A function that will be applied to all header names before they
are sent to the server. Gun assumes that all header names are in
lower case. This function is useful if you, for example, need to
re-case header names in the event that the server incorrectly
considers the case of header names to be significant.

version (`'HTTP/1.1'`)::

HTTP version to use.

=== http2_opts()

[source,erlang]
----
http2_opts() :: #{
    closing_timeout             => timeout(),
    cookie_ignore_informational => boolean(),
    flow                        => pos_integer(),
    keepalive                   => timeout(),

    %% HTTP/2 state machine configuration.
    connection_window_margin_size  => 0..16#7fffffff,
    connection_window_update_threshold => 0..16#7fffffff,
    enable_connect_protocol        => boolean(),
    initial_connection_window_size => 65535..16#7fffffff,
    initial_stream_window_size     => 0..16#7fffffff,
    max_concurrent_streams         => non_neg_integer() | infinity,
    max_connection_window_size     => 0..16#7fffffff,
    max_decode_table_size          => non_neg_integer(),
    max_encode_table_size          => non_neg_integer(),
    max_frame_size_received        => 16384..16777215,
    max_frame_size_sent            => 16384..16777215 | infinity,
    max_stream_buffer_size         => non_neg_integer(),
    max_stream_window_size         => 0..16#7fffffff,
    preface_timeout                => timeout(),
    settings_timeout               => timeout(),
    stream_window_margin_size      => 0..16#7fffffff,
    stream_window_update_threshold => 0..16#7fffffff
}
----

Configuration for the HTTP/2 protocol.

The default value is given next to the option name:

// @todo Document content_handlers and gun_sse_h.

closing_timeout (15000)::

Time to wait before brutally closing the connection when a
graceful shutdown was requested either via a call to
link:man:gun:shutdown(3)[gun:shutdown(3)] or by the server.

cookie_ignore_informational (false)::

Whether cookies received inside informational responses
(1xx status code) must be ignored.

flow - see below::

The initial flow control value for all HTTP/2 streams.
By default flow control is disabled.

keepalive (infinity)::

Time between pings in milliseconds.

=== opts()

[source,erlang]
----
opts() :: #{
    connect_timeout       => timeout(),
    cookie_store          => gun_cookies:store(),
    domain_lookup_timeout => timeout(),
    http_opts             => http_opts(),
    http2_opts            => http2_opts(),
    protocols             => protocols(),
    retry                 => non_neg_integer(),
    retry_fun             => fun(),
    retry_timeout         => pos_integer(),
    supervise             => boolean(),
    tcp_opts              => [gen_tcp:connect_option()],
    tls_handshake_timeout => timeout(),
    tls_opts              => [ssl:tls_client_option()],
    trace                 => boolean(),
    transport             => tcp | tls,
    ws_opts               => ws_opts()
}
----

Configuration for the connection.

The default value is given next to the option name:

connect_timeout (infinity)::

Connection timeout.

cookie_store - see below::

The cookie store that Gun will use for this connection.
When configured, Gun will query the store for cookies
and include them in the request headers; and add cookies
found in response headers to the store.
+
By default no cookie store will be used.

domain_lookup_timeout (infinity)::

Domain lookup timeout.

http_opts (#{})::

Options specific to the HTTP protocol.

http2_opts (#{})::

Options specific to the HTTP/2 protocol.

protocols - see below::

Ordered list of preferred protocols. Please refer to the
`protocols()` type documentation for details.
+
Defaults to `[http]` when the transport is `tcp`,
and `[http2, http]` when the transport is `tls`.

retry (5)::

Number of times Gun will try to reconnect on failure before giving up.

retry_fun - see below::

A fun that will be called before every reconnect attempt. It receives
the current number of retries left and the Gun options. It returns the
next number of retries left and the timeout to apply before reconnecting.

The default fun will remove one to the number of retries and set the
timeout to the `retry_timeout` value.

The fun must be defined as follow:

[source,erlang]
----
fun ((non_neg_integer(), opts()) -> #{
    retries => non_neg_integer(),
    timeout => pos_integer()
})
----

The fun will never be called when the `retry` option is set to 0. When
this function returns 0 in the `retries` value, Gun will do one last
reconnect attempt before giving up.

retry_timeout (5000)::

Time between retries in milliseconds.

supervise (true)::

Whether the Gun process should be started under the `gun_sup`
supervisor. Set to `false` to use your own supervisor.

tcp_opts ([])::

TCP options used when establishing the connection.

tls_handshake_timeout (infinity)::

TLS handshake timeout.

tls_opts ([])::

TLS options used for the TLS handshake after the connection
has been established, when the transport is set to `tls`.

trace (false)::

Whether to enable `dbg` tracing of the connection process. Should
only be used during debugging.

transport - see below::

Whether to use TLS or plain TCP. The default varies depending on the
port used. Port 443 defaults to `tls`. All other ports default to `tcp`.

ws_opts (#{})::

Options specific to the Websocket protocol.

=== protocols()

[source,erlang]
----
Protocol :: http | {http, http_opts()}
          | http2 | {http2, http2_opts()}
          | raw | {raw, raw_opts()}
          | socks | {socks, socks_opts()}

protocols() :: [Protocol]
----

Ordered list of preferred protocols. When the transport is `tcp`,
this list must contain exactly one protocol. When the transport
is `tls`, this list must contain at least one protocol and will be
used to negotiate a protocol via ALPN. When the server does not
support ALPN then `http` will be used, except when the list of
preferred protocols is set to only accept `socks`.

Defaults to `[http]` when the transport is `tcp`,
and `[http2, http]` when the transport is `tls`.

=== raw_opts()

[source,erlang]
----
raw_opts() :: #{
}
----

Configuration for the "raw" protocol.

// The default value is given next to the option name:

=== req_headers()

[source,erlang]
----
req_headers() :: [{binary() | string() | atom(),   iodata()}]
               | #{binary() | string() | atom() => iodata()}
----

Request headers.

=== req_opts()

[source,erlang]
----
req_opts() :: #{
    flow     => pos_integer(),
    reply_to => pid()
}
----

Configuration for a particular request.

The default value is given next to the option name:

flow - see below::

The initial flow control value for the stream. By default
flow control is disabled.

reply_to (`self()`)::

The pid of the process that will receive the response messages.

=== socks_opts()

[source,erlang]
----
socks_opts() :: #{
    host := inet:hostname() | inet:ip_address(),
    port := inet:port_number(),

    auth      => [{username_password, binary(), binary()} | none],
    protocols => protocols(),
    transport => tcp | tls,
    version   => 5,

    tls_opts              => [ssl:tls_client_option()],
    tls_handshake_timeout => timeout()
}
----

Configuration for the Socks protocol.

The default value, if any, is given next to the option name:

host, port::

Destination hostname and port number. Mandatory.
+
Upon successful completion of the Socks connection, Gun will
begin using these as the host and port of the origin server
for subsequent requests.

auth ([none])::

Authentication methods Gun advertises to the Socks proxy.

protocols - see below::

Ordered list of preferred protocols. Please refer to the
`protocols()` type documentation for details.
+
Defaults to `[http]` when the transport is `tcp`,
and `[http2, http]` when the transport is `tls`.

transport (tcp)::

Transport that will be used for tunneled requests.

tls_opts ([])::

Options to use for tunneled TLS connections.

tls_handshake_timeout (infinity)::

Handshake timeout for tunneled TLS connections.

version (5)::

Version of the Socks protocol to use.

=== stream_ref()

[source,erlang]
----
stream_ref() - see below
----

Unique identifier for a stream.

The exact type is considered to be an implementation
detail.

=== ws_opts()

[source,erlang]
----
ws_opts() :: #{
    closing_timeout => timeout(),
    compress        => boolean(),
    flow            => pos_integer(),
    keepalive       => timeout(),
    protocols       => [{binary(), module()}],
    silence_pings   => boolean()
}
----

Configuration for the Websocket protocol.

The default value is given next to the option name:

closing_timeout (15000)::

Time to wait before brutally closing the connection when a
graceful shutdown was requested either via a call to
link:man:gun:shutdown(3)[gun:shutdown(3)] or by the server.

compress (false)::

Whether to enable permessage-deflate compression. This does
not guarantee that compression will be used as it is the
server that ultimately decides. Defaults to false.

flow - see below::

The initial flow control value for the Websocket connection.
By default flow control is disabled.

keepalive (infinity)::

Time between pings in milliseconds.

protocols ([])::

A non-empty list enables Websocket protocol negotiation. The
list of protocols will be sent in the sec-websocket-protocol
request header. The handler module interface is currently
undocumented and must be set to `gun_ws_h`.

silence_pings (true)::

Whether the ping and pong frames should be sent to the user.
In all cases Gun will automatically send a pong frame back
when receiving a ping.

// @todo Document default_protocol and user_opts.

== Changelog

* *2.0*: The `stream_ref()` type was added.
* *2.0*: The option `cookie_store` was added. It can be used
         to configure a cookie store that Gun will use
         automatically. A related option, `cookie_ignore_informational`,
         was added to both `http_opts()` and `http2_opts()`.
* *2.0*: The types `protocols()` and `socks_opts()` have been
         added. Support for the Socks protocol has been added
         in every places where protocol selection is available.
         In addition it is now possible to specify separate
         HTTP options for the CONNECT proxy and the origin server.
* *2.0*: The `connect_timeout` option has been split into
         three options: `domain_lookup_timeout`, `connect_timeout`
         and when applicable `tls_handshake_timeout`.
* *2.0*: The option `retry_fun` was added. It can be used to
         implement different reconnect strategies.
* *2.0*: The `transport_opts` option has been split into
         two options: `tcp_opts` and `tls_opts`.
* *2.0*: Function `gun:update_flow/3` introduced. The `flow`
         option was added to request options and HTTP/1.1,
         HTTP/2 and Websocket options as well.
* *2.0*: Introduce the type `req_headers()` and extend the
         types accepted for header names for greater
         interoperability. Header names are automatically
         lowercased as well.
* *2.0*: Function `gun:headers/4,5` introduced.
* *2.0*: The `keepalive` option is now set to `infinity` by
         default for all protocols. This means it is disabled.
* *2.0*: Websocket options `keepalive` and `silence_pings` introduced.
* *2.0*: Remove the `protocol` option from `connect_destination()`.
* *1.3*: Add the CONNECT destination's `protocols` option and
         deprecate the previously introduced `protocol` option.
* *1.2*: Introduce the type `connect_destination()`.

== See also

link:man:gun(7)[gun(7)]