Debian Codegraph @

doc/src/manual/cowboy_stream.asciidoc

raw
1 = cowboy_stream(3)
2
3 == Name
4
5 cowboy_stream - Stream handlers
6
7 == Description
8
9 The module `cowboy_stream` defines a callback interface
10 and a protocol for handling HTTP streams.
11
12 An HTTP request and its associated response is called
13 a stream. A connection may have many streams. In HTTP/1.1
14 they are executed sequentially, while in HTTP/2 they are
15 executed concurrently.
16
17 Cowboy calls the stream handler for nearly all events
18 related to a stream. Exceptions vary depending on the
19 protocol.
20
21 Extra care must be taken when implementing stream handlers
22 to ensure compatibility. While some modification of the
23 events and commands is allowed, it is generally not a good
24 idea to completely discard them.
25
26 == Callbacks
27
28 Stream handlers must implement the following interface:
29
30 [source,erlang]
31 ----
32 init(StreamID, Req, Opts) -> {Commands, State}
33 data(StreamID, IsFin, Data, State) -> {Commands, State}
34 info(StreamID, Info, State) -> {Commands, State}
35 terminate(StreamID, Reason, State) -> any()
36 early_error(StreamID, Reason, PartialReq, Resp, Opts) -> Resp
37
38 StreamID :: cowboy_stream:streamid()
39 Req :: cowboy_req:req()
40 Opts :: cowboy:opts()
41 Commands :: cowboy_stream:commands()
42 State :: any()
43 IsFin :: cowboy_stream:fin()
44 Data :: binary()
45 Info :: any()
46 Reason :: cowboy_stream:reason()
47 PartialReq - cowboy_req:req(), except all fields are optional
48 Resp :: cowboy_stream:resp_command()
49 ----
50
51 HTTP/1.1 will initialize a stream only when the request-line
52 and all headers have been received. When errors occur before
53 that point Cowboy will call the callback `early_error/5`
54 with a partial request, the error reason and the response
55 Cowboy intends to send. All other events go through the
56 stream handler using the normal callbacks.
57
58 HTTP/2 will initialize the stream when the `HEADERS` block has
59 been fully received and decoded. Any protocol error occurring
60 before that will not result in a response being sent and
61 will therefore not go through the stream handler. In addition
62 Cowboy may terminate streams without sending an HTTP response
63 back.
64
65 The stream is initialized by calling `init/3`. All streams
66 that are initialized will eventually be terminated by calling
67 `terminate/3`.
68
69 When Cowboy receives data for the stream it will call `data/4`.
70 The data given is the request body after any transfer decoding
71 has been applied.
72
73 When Cowboy receives a message addressed to a stream, or when
74 Cowboy needs to inform the stream handler that an internal
75 event has occurred, it will call `info/3`.
76
77 [[commands]]
78 == Commands
79
80 Stream handlers can return a list of commands to be executed
81 from the `init/3`, `data/4` and `info/3` callbacks. In addition,
82 the `early_error/5` callback must return a response command.
83
84 // @todo The logger option and the {log, Level, Format, Args}
85 // options need to be documented and tested.
86
87 The order in which the commands are given matters. For example,
88 when sending a response and at the same time creating a new child
89 process, the first command should be the `spawn` and the second the
90 `response`. The reason for that is that the sending of the response
91 may result in a socket error which leads to the termination of
92 the connection before the rest of the commands are executed.
93
94 The following commands are defined:
95
96 [[inform_command]]
97 === inform
98
99 Send an informational response to the client.
100
101 [source,erlang]
102 ----
103 {inform, cowboy:http_status(), cowboy:http_headers()}
104 ----
105
106 Any number of informational responses may be sent,
107 but only until the final response is sent.
108
109 [[response_command]]
110 === response
111
112 Send a response to the client.
113
114 [source,erlang]
115 ----
116 {response, cowboy:http_status(), cowboy:http_headers(),
117 cowboy_req:resp_body()}
118 ----
119
120 No more data can be sent after this command.
121
122 Note that in Cowboy it is the `cowboy_req` module that
123 sets the date and server headers. When using the command
124 directly those headers will not be added.
125
126 [[headers_command]]
127 === headers
128
129 Initiate a response to the client.
130
131 [source,erlang]
132 ----
133 {headers, cowboy:http_status(), cowboy:http_headers()}
134 ----
135
136 This initiates a response to the client. The stream
137 will end when a data command with the `fin` flag or
138 a trailer command is returned.
139
140 Note that in Cowboy it is the `cowboy_req` module that
141 sets the date and server headers. When using the command
142 directly those headers will not be added.
143
144 [[data_command]]
145 === data
146
147 Send data to the client.
148
149 [source,erlang]
150 ----
151 {data, fin(), cowboy_req:resp_body()}
152 ----
153
154 [[trailers_command]]
155 === trailers
156
157 Send response trailers to the client.
158
159 [source,erlang]
160 ----
161 {trailers, cowboy:http_headers()}
162 ----
163
164 [[push_command]]
165 === push
166
167 Push a resource to the client.
168
169 [source,erlang]
170 ----
171 {push, Method, Scheme, Host, inet:port_number(),
172 Path, Qs, cowboy:http_headers()}
173
174 Method = Scheme = Host = Path = Qs = binary()
175 ----
176
177 The command will be ignored if the protocol does not provide
178 any server push mechanism.
179
180 === flow
181
182 [source,erlang]
183 ----
184 {flow, pos_integer()}
185 ----
186
187 Request more data to be read from the request body. The
188 exact behavior depends on the protocol.
189
190 === spawn
191
192 Inform Cowboy that a process was spawned and should be
193 supervised.
194
195 [source,erlang]
196 ----
197 {spawn, pid(), timeout()}
198 ----
199
200 === error_response
201
202 Send an error response if no response was sent previously.
203
204 [source,erlang]
205 ----
206 {error_response, cowboy:http_status(), cowboy:http_headers(), iodata()}
207 ----
208
209 [[switch_protocol_command]]
210 === switch_protocol
211
212 Switch to a different protocol.
213
214 [source,erlang]
215 ----
216 {switch_protocol, cowboy:http_headers(), module(), state()}
217 ----
218
219 Contains the headers that will be sent in the 101 response,
220 along with the module implementing the protocol we are
221 switching to and its initial state.
222
223 Note that the 101 informational response will not be sent
224 after a final response.
225
226 === stop
227
228 Stop the stream.
229
230 [source,erlang]
231 ----
232 stop
233 ----
234
235 While no more data can be sent after the `fin` flag was set,
236 the stream is still tracked by Cowboy until it is stopped by
237 the handler.
238
239 The behavior when stopping a stream for which no response
240 has been sent will vary depending on the protocol. The stream
241 will end successfully as far as the client is concerned.
242
243 To indicate that an error occurred, either use `error_response`
244 before stopping, or use `internal_error`.
245
246 No other command can be executed after the `stop` command.
247
248 === internal_error
249
250 Stop the stream with an error.
251
252 [source,erlang]
253 ----
254 {internal_error, Reason, HumanReadable}
255
256 Reason = any()
257 HumanReadable = atom()
258 ----
259
260 This command should be used when the stream cannot continue
261 because of an internal error. An `error_response` command
262 may be sent before that to advertise to the client why the
263 stream is dropped.
264
265 === log
266
267 Log a message.
268
269 [source,erlang]
270 ----
271 {log, logger:level(), io:format(), list()}
272 ----
273
274 This command can be used to log a message using the
275 configured `logger` module.
276
277 === set_options
278
279 Set protocol options.
280
281 [source,erlang]
282 ----
283 {set_options, map()}
284 ----
285
286 This can also be used to override stream handler
287 options. For example this is supported by
288 link:man:cowboy_compress_h(3)[cowboy_compress_h(3)].
289
290 Not all options can be overridden. Please consult the
291 relevant option's documentation for details.
292
293 == Predefined events
294
295 Cowboy will forward all messages sent to the stream to
296 the `info/3` callback. To send a message to a stream,
297 the function link:man:cowboy_req:cast(3)[cowboy_req:cast(3)]
298 can be used.
299
300 Cowboy will also forward the exit signals for the
301 processes that the stream spawned.
302
303 When Cowboy needs to send a response it will trigger
304 an event that looks exactly like the corresponding
305 command. This event must be returned to be processed
306 by Cowboy (which is done automatically when using
307 link:man:cowboy_stream_h(3)[cowboy_stream_h(3)]).
308
309 Cowboy may trigger the following events on its own,
310 regardless of the stream handlers configured:
311 xref:inform_command[inform] (to send a 101
312 informational response when upgrading to HTTP/2 or
313 Websocket), xref:response_command[response],
314 xref:headers_command[headers], xref:data_command[data]
315 and xref:switch_protocol_command[switch_protocol].
316
317 == Exports
318
319 The following function should be called by modules implementing
320 stream handlers to execute the next stream handler in the list:
321
322 * link:man:cowboy_stream:init(3)[cowboy_stream:init(3)] - Initialize a stream
323 * link:man:cowboy_stream:data(3)[cowboy_stream:data(3)] - Handle data for a stream
324 * link:man:cowboy_stream:info(3)[cowboy_stream:info(3)] - Handle a message for a stream
325 * link:man:cowboy_stream:terminate(3)[cowboy_stream:terminate(3)] - Terminate a stream
326 * link:man:cowboy_stream:early_error(3)[cowboy_stream:early_error(3)] - Handle an early error for a stream
327
328 == Types
329
330 === commands()
331
332 [source,erlang]
333 ----
334 commands() :: [Command]
335 ----
336
337 See the xref:commands[list of commands] for details.
338
339 === fin()
340
341 [source,erlang]
342 ----
343 fin() :: fin | nofin
344 ----
345
346 Used in commands and events to indicate that this is
347 the end of a direction of a stream.
348
349 === partial_req()
350
351 [source,erlang]
352 ----
353 req() :: #{
354 method => binary(), %% case sensitive
355 version => cowboy:http_version() | atom(),
356 scheme => binary(), %% lowercase; case insensitive
357 host => binary(), %% lowercase; case insensitive
358 port => inet:port_number(),
359 path => binary(), %% case sensitive
360 qs => binary(), %% case sensitive
361 headers => cowboy:http_headers(),
362 peer => {inet:ip_address(), inet:port_number()}
363 }
364 ----
365
366 Partial request information received when an early error is
367 detected.
368
369 === reason()
370
371 [source,erlang]
372 ----
373 reason() :: normal | switch_protocol
374 | {internal_error, timeout | {error | exit | throw, any()}, HumanReadable}
375 | {socket_error, closed | atom(), HumanReadable}
376 | {stream_error, Error, HumanReadable}
377 | {connection_error, Error, HumanReadable}
378 | {stop, cow_http2:frame() | {exit, any()}, HumanReadable}
379
380 Error = atom()
381 HumanReadable = atom()
382 ----
383
384 Reason for the stream termination.
385
386 === resp_command()
387
388 [source,erlang]
389 ----
390 resp_command() :: {response, cowboy:http_status(),
391 cowboy:http_headers(), cowboy_req:resp_body()}
392 ----
393
394 See the xref:response_command[response command] for details.
395
396 === streamid()
397
398 [source,erlang]
399 ----
400 streamid() :: any()
401 ----
402
403 The identifier for this stream.
404
405 The identifier is unique over the connection process.
406 It is possible to form a unique identifier node-wide and
407 cluster-wide by wrapping it in a `{self(), StreamID}`
408 tuple.
409
410 == Changelog
411
412 * *2.7*: The `log` and `set_options` commands were introduced.
413 * *2.6*: The `data` command can now contain a sendfile tuple.
414 * *2.6*: The `{stop, {exit, any()}, HumanReadable}` terminate reason was added.
415 * *2.2*: The `trailers` command was introduced.
416 * *2.0*: Module introduced.
417
418 == See also
419
420 link:man:cowboy(7)[cowboy(7)],
421 link:man:cowboy_http(3)[cowboy_http(3)],
422 link:man:cowboy_http2(3)[cowboy_http2(3)],
423 link:man:cowboy_req:cast(3)[cowboy_req:cast(3)]