/
mist.gleam
617 lines (560 loc) · 19.2 KB
/
mist.gleam
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
613
614
615
616
617
import gleam/bytes_builder.{type BytesBuilder}
import gleam/bit_array
import gleam/erlang/process.{type ProcessDown, type Selector, type Subject}
import gleam/function
import gleam/http/request.{type Request}
import gleam/http/response.{type Response}
import gleam/http.{type Scheme, Http, Https} as gleam_http
import gleam/int
import gleam/io
import gleam/iterator.{type Iterator}
import gleam/list
import gleam/option.{type Option, None, Some}
import gleam/otp/actor
import gleam/otp/supervisor
import gleam/result
import gleam/string_builder.{type StringBuilder}
import glisten
import glisten/transport
import mist/internal/buffer.{type Buffer, Buffer}
import mist/internal/encoder
import mist/internal/file
import mist/internal/handler.{
type ResponseData as InternalResponseData, Bytes as InternalBytes,
Chunked as InternalChunked, CloseEvents as InternalCloseEvents,
File as InternalFile, Websocket as InternalWebsocket,
}
import mist/internal/http.{type Connection as InternalConnection}
import mist/internal/websocket.{
type HandlerMessage, type WebsocketConnection as InternalWebsocketConnection,
BinaryFrame, Data, Internal, TextFrame, User,
}
/// Re-exported type that represents the default `Request` body type. See
/// `mist.read_body` to convert this type into a `BitString`. The `Connection`
/// also holds some additional information about the request. Currently, the
/// only useful field is `client_ip` which is a `Result` with a tuple of
/// integers representing the IPv4 address.
pub type Connection =
InternalConnection
/// The response body type. This allows `mist` to handle these different cases
/// for you. `Bytes` is the regular data return. `Websocket` will upgrade the
/// socket to websockets, but should not be used directly. See the
/// `mist.upgrade` function for usage. `Chunked` will use
/// `Transfer-Encoding: chunked` to send an iterator in chunks. `File` will use
/// Erlang's `sendfile` to more efficiently return a file to the client.
pub type ResponseData {
Websocket(Selector(ProcessDown))
Bytes(BytesBuilder)
Chunked(Iterator(BytesBuilder))
/// See `mist.send_file` to use this response type.
File(descriptor: file.FileDescriptor, offset: Int, length: Int)
CloseEvents
}
/// Potential errors when opening a file to send. This list is
/// currently not exhaustive with POSIX errors.
pub type FileError {
IsDir
NoAccess
NoEntry
UnknownFileError
}
fn convert_file_errors(err: file.FileError) -> FileError {
case err {
file.IsDir -> IsDir
file.NoAccess -> NoAccess
file.NoEntry -> NoEntry
file.UnknownFileError -> UnknownFileError
}
}
/// To respond with a file using Erlang's `sendfile`, use this function
/// with the specified offset and limit (optional). It will attempt to open the
/// file for reading, get its file size, and then send the file. If the read
/// errors, this will return the relevant `FileError`. Generally, this will be
/// more memory efficient than manually doing this process with `mist.Bytes`.
pub fn send_file(
path: String,
offset offset: Int,
limit limit: Option(Int),
) -> Result(ResponseData, FileError) {
path
|> bit_array.from_string
|> file.stat
|> result.map_error(convert_file_errors)
|> result.map(fn(stat) {
File(
descriptor: stat.descriptor,
offset: offset,
length: option.unwrap(limit, stat.file_size),
)
})
}
/// The possible errors from reading the request body. If the size is larger
/// than the provided value, `ExcessBody` is returned. If there is an error
/// reading the body from the socket or the body is malformed (i.e a chunked
/// request with invalid sizes), `MalformedBody` is returned.
pub type ReadError {
ExcessBody
MalformedBody
}
/// The request body is not pulled from the socket until requested. The
/// `content-length` header is used to determine whether the socket is read
/// from or not. The read may also fail, and a `ReadError` is raised.
pub fn read_body(
req: Request(Connection),
max_body_limit max_body_limit: Int,
) -> Result(Request(BitArray), ReadError) {
req
|> request.get_header("content-length")
|> result.then(int.parse)
|> result.unwrap(0)
|> fn(content_length) {
case content_length {
value if value <= max_body_limit -> {
http.read_body(req)
|> result.replace_error(MalformedBody)
}
_ -> {
Error(ExcessBody)
}
}
}
}
/// The values returning from streaming the request body. The `Chunk`
/// variant gives back some data and the next token. `Done` signifies
/// that we have completed reading the body.
pub type Chunk {
Chunk(data: BitArray, consume: fn(Int) -> Result(Chunk, ReadError))
Done
}
fn do_stream(
req: Request(Connection),
buffer: Buffer,
) -> fn(Int) -> Result(Chunk, ReadError) {
fn(size) {
let socket = req.body.socket
let transport = req.body.transport
let byte_size = bit_array.byte_size(buffer.data)
case buffer.remaining, byte_size {
0, 0 -> Ok(Done)
0, _buffer_size -> {
let #(data, rest) = buffer.slice(buffer, size)
Ok(Chunk(data, do_stream(req, buffer.new(rest))))
}
_, buffer_size if buffer_size >= size -> {
let #(data, rest) = buffer.slice(buffer, size)
let new_buffer = Buffer(..buffer, data: rest)
Ok(Chunk(data, do_stream(req, new_buffer)))
}
_, _buffer_size -> {
http.read_data(socket, transport, buffer.empty(), http.InvalidBody)
|> result.replace_error(MalformedBody)
|> result.map(fn(data) {
let fetched_data = bit_array.byte_size(data)
let new_buffer =
Buffer(
data: bit_array.append(buffer.data, data),
remaining: int.max(0, buffer.remaining - fetched_data),
)
let #(new_data, rest) = buffer.slice(new_buffer, size)
Chunk(new_data, do_stream(req, Buffer(..new_buffer, data: rest)))
})
}
}
}
}
type ChunkState {
ChunkState(data_buffer: Buffer, chunk_buffer: Buffer, done: Bool)
}
fn do_stream_chunked(
req: Request(Connection),
state: ChunkState,
) -> fn(Int) -> Result(Chunk, ReadError) {
let socket = req.body.socket
let transport = req.body.transport
fn(size) {
case fetch_chunks_until(socket, transport, state, size) {
Ok(#(data, ChunkState(done: True, ..))) -> {
Ok(Chunk(data, fn(_size) { Ok(Done) }))
}
Ok(#(data, state)) -> {
Ok(Chunk(data, do_stream_chunked(req, state)))
}
Error(_) -> Error(MalformedBody)
}
}
}
fn fetch_chunks_until(
socket: glisten.Socket,
transport: transport.Transport,
state: ChunkState,
byte_size: Int,
) -> Result(#(BitArray, ChunkState), ReadError) {
let data_size = bit_array.byte_size(state.data_buffer.data)
case state.done, data_size {
_, size if size >= byte_size -> {
let #(value, rest) = buffer.slice(state.data_buffer, byte_size)
Ok(#(value, ChunkState(..state, data_buffer: buffer.new(rest))))
}
True, _ -> {
Ok(#(state.data_buffer.data, ChunkState(..state, done: True)))
}
False, _ -> {
case http.parse_chunk(state.chunk_buffer.data) {
http.Complete -> {
let updated_state =
ChunkState(..state, chunk_buffer: buffer.empty(), done: True)
fetch_chunks_until(socket, transport, updated_state, byte_size)
}
http.Chunk(<<>>, next_buffer) -> {
http.read_data(socket, transport, next_buffer, http.InvalidBody)
|> result.replace_error(MalformedBody)
|> result.then(fn(new_data) {
let updated_state =
ChunkState(..state, chunk_buffer: buffer.new(new_data))
fetch_chunks_until(socket, transport, updated_state, byte_size)
})
}
http.Chunk(data, next_buffer) -> {
let updated_state =
ChunkState(
..state,
data_buffer: buffer.append(state.data_buffer, data),
chunk_buffer: next_buffer,
)
fetch_chunks_until(socket, transport, updated_state, byte_size)
}
}
}
}
}
/// Rather than explicitly reading either the whole body (optionally up to
/// `N` bytes), this function allows you to consume a stream of the request
/// body. Any errors reading the body will propagate out, or `Chunk`s will be
/// emitted. This provides a `consume` method to attempt to grab the next
/// `size` chunk from the socket.
pub fn stream(
req: Request(Connection),
) -> Result(fn(Int) -> Result(Chunk, ReadError), ReadError) {
let continue =
req
|> http.handle_continue
|> result.replace_error(MalformedBody)
use _nil <- result.map(continue)
let is_chunked = case request.get_header(req, "transfer-encoding") {
Ok("chunked") -> True
_ -> False
}
let assert http.Initial(data) = req.body.body
case is_chunked {
True -> {
let state = ChunkState(buffer.new(<<>>), buffer.new(data), False)
do_stream_chunked(req, state)
}
False -> {
let content_length =
req
|> request.get_header("content-length")
|> result.then(int.parse)
|> result.unwrap(0)
let initial_size = bit_array.byte_size(data)
let buffer =
Buffer(data: data, remaining: int.max(0, content_length - initial_size))
do_stream(req, buffer)
}
}
}
pub opaque type Builder(request_body, response_body) {
Builder(
port: Int,
handler: fn(Request(request_body)) -> Response(response_body),
after_start: fn(Int, Scheme) -> Nil,
)
}
/// Create a new `mist` handler with a given function. The default port is
/// 4000.
pub fn new(handler: fn(Request(in)) -> Response(out)) -> Builder(in, out) {
Builder(port: 4000, handler: handler, after_start: fn(port, scheme) {
let message =
"Listening on "
<> gleam_http.scheme_to_string(scheme)
<> "://localhost:"
<> int.to_string(port)
io.println(message)
})
}
/// Assign a different listening port to the service.
pub fn port(builder: Builder(in, out), port: Int) -> Builder(in, out) {
Builder(..builder, port: port)
}
/// This function allows for implicitly reading the body of requests up
/// to a given size. If the size is too large, or the read fails, the provided
/// `failure_response` will be sent back as the response.
pub fn read_request_body(
builder: Builder(BitArray, out),
bytes_limit bytes_limit: Int,
failure_response failure_response: Response(out),
) -> Builder(Connection, out) {
let handler = fn(request) {
case read_body(request, bytes_limit) {
Ok(request) -> builder.handler(request)
Error(_) -> failure_response
}
}
Builder(builder.port, handler, builder.after_start)
}
/// Override the default function to be called after the service starts. The
/// default is to log a message with the listening port.
pub fn after_start(
builder: Builder(in, out),
after_start: fn(Int, Scheme) -> Nil,
) -> Builder(in, out) {
Builder(..builder, after_start: after_start)
}
fn convert_body_types(
resp: Response(ResponseData),
) -> Response(InternalResponseData) {
let new_body = case resp.body {
Websocket(selector) -> InternalWebsocket(selector)
Bytes(data) -> InternalBytes(data)
File(descriptor, offset, length) -> InternalFile(descriptor, offset, length)
Chunked(iter) -> InternalChunked(iter)
CloseEvents -> InternalCloseEvents
}
response.set_body(resp, new_body)
}
/// Start a `mist` service over HTTP with the provided builder.
pub fn start_http(
builder: Builder(Connection, ResponseData),
) -> Result(Subject(supervisor.Message), glisten.StartError) {
builder.handler
fn(req) { convert_body_types(builder.handler(req)) }
|> handler.with_func
|> glisten.handler(fn() { #(handler.new_state(), None) }, _)
|> glisten.serve(builder.port)
|> result.map(fn(subj) {
builder.after_start(builder.port, Http)
subj
})
}
/// These are the types of errors raised by trying to read the certificate and
/// key files.
pub type CertificateError {
NoCertificate
NoKey
NoKeyOrCertificate
}
/// These are the possible errors raised when trying to start an Https server.
/// If there are issues reading the certificate or key files, those will be
/// returned.
pub type HttpsError {
GlistenError(glisten.StartError)
CertificateError(CertificateError)
}
/// Start a `mist` service over HTTPS with the provided builder. This method
/// requires both a certificate file and a key file. The library will attempt
/// to read these files off of the disk.
pub fn start_https(
builder: Builder(Connection, ResponseData),
certfile certfile: String,
keyfile keyfile: String,
) -> Result(Subject(supervisor.Message), HttpsError) {
let cert = file.open(bit_array.from_string(certfile))
let key = file.open(bit_array.from_string(keyfile))
let res = case cert, key {
Error(_), Error(_) -> Error(CertificateError(NoKeyOrCertificate))
Ok(_), Error(_) -> Error(CertificateError(NoKey))
Error(_), Ok(_) -> Error(CertificateError(NoCertificate))
Ok(_), Ok(_) -> Ok(Nil)
}
use _ <- result.then(res)
fn(req) { convert_body_types(builder.handler(req)) }
|> handler.with_func
|> glisten.handler(fn() { #(handler.new_state(), None) }, _)
|> glisten.serve_ssl(builder.port, certfile, keyfile)
|> result.map_error(GlistenError)
|> result.map(fn(subj) {
builder.after_start(builder.port, Https)
subj
})
}
/// These are the types of messages that a websocket handler may receive.
pub type WebsocketMessage(custom) {
Text(String)
Binary(BitArray)
Closed
Shutdown
Custom(custom)
}
fn internal_to_public_ws_message(
msg: HandlerMessage(custom),
) -> Result(WebsocketMessage(custom), Nil) {
case msg {
Internal(Data(TextFrame(_length, data))) -> {
data
|> bit_array.to_string
|> result.map(Text)
}
Internal(Data(BinaryFrame(_length, data))) -> Ok(Binary(data))
User(msg) -> Ok(Custom(msg))
_ -> Error(Nil)
}
}
/// Upgrade a request to handle websockets. If the request is
/// malformed, or the websocket process fails to initialize, an empty
/// 400 response will be sent to the client.
///
/// The `on_init` method will be called when the actual WebSocket process
/// is started, and the return value is the initial state and an optional
/// selector for receiving user messages.
///
/// The `on_close` method is called when the WebSocket process shuts down
/// for any reason, valid or otherwise.
pub fn websocket(
request request: Request(Connection),
handler handler: fn(state, WebsocketConnection, WebsocketMessage(message)) ->
actor.Next(message, state),
on_init on_init: fn(WebsocketConnection) ->
#(state, Option(process.Selector(message))),
on_close on_close: fn(state) -> Nil,
) -> Response(ResponseData) {
let handler = fn(state, connection, message) {
message
|> internal_to_public_ws_message
|> result.map(handler(state, connection, _))
|> result.unwrap(actor.continue(state))
}
let socket = request.body.socket
let transport = request.body.transport
request
|> http.upgrade(socket, transport, _)
|> result.then(fn(_nil) {
websocket.initialize_connection(
on_init,
on_close,
handler,
socket,
transport,
)
})
|> result.map(fn(subj) {
let ws_process = process.subject_owner(subj)
let monitor = process.monitor_process(ws_process)
let selector =
process.new_selector()
|> process.selecting_process_down(monitor, function.identity)
response.new(200)
|> response.set_body(Websocket(selector))
})
|> result.lazy_unwrap(fn() {
response.new(400)
|> response.set_body(Bytes(bytes_builder.new()))
})
}
pub type WebsocketConnection =
InternalWebsocketConnection
/// Sends a binary frame across the websocket.
pub fn send_binary_frame(
connection: WebsocketConnection,
frame: BitArray,
) -> Result(Nil, glisten.SocketReason) {
frame
|> websocket.to_binary_frame
|> transport.send(connection.transport, connection.socket, _)
}
/// Sends a text frame across the websocket.
pub fn send_text_frame(
connection: WebsocketConnection,
frame: String,
) -> Result(Nil, glisten.SocketReason) {
frame
|> websocket.to_text_frame
|> transport.send(connection.transport, connection.socket, _)
}
// Returned by `init_server_sent_events`. This type must be passed to
// `send_event` since we need to enforce that the correct headers / data shapw
// is provided.
pub opaque type SSEConnection {
SSEConnection(Connection)
}
// Represents each event. Only `data` is required. The `event` name will
// default to `message`. If an `id` is provided, it will be included in the
// event received by the client.
pub type SSEEvent {
SSEEvent(id: Option(String), event: Option(String), data: StringBuilder)
}
// Builder for generating the base event
pub fn event(data: StringBuilder) -> SSEEvent {
SSEEvent(id: None, event: None, data: data)
}
// Adds an `id` to the event
pub fn event_id(event: SSEEvent, id: String) -> SSEEvent {
SSEEvent(..event, id: Some(id))
}
// Sets the `event` name field
pub fn event_name(event: SSEEvent, name: String) -> SSEEvent {
SSEEvent(..event, event: Some(name))
}
/// Sets up the connection for server-sent events. The existing connection
/// _must_ no longer be used. After initializing this connection, the valid
/// actions are `send_event` or `end_events`.
///
/// Here is an example of using it:
/// ```gleam
/// let assert Ok(sse_connection) =
/// mist.start_sse(conn, response.new() |> response.add_header(...))
/// let event = mist.event(data) |> mist.event_id("1234")
/// let resp = mist.send_event(sse_connection, event)
/// mist.end_events(sse_connection)
/// ```
pub fn init_server_sent_events(
conn: Connection,
resp: Response(Nil),
) -> Result(SSEConnection, Nil) {
let with_default_headers =
resp
|> response.set_header("content-type", "text/event-stream")
|> response.set_header("cache-control", "no-cache")
|> response.set_header("connection", "keep-alive")
transport.send(
conn.transport,
conn.socket,
encoder.response_builder(200, with_default_headers.headers),
)
|> result.replace(SSEConnection(conn))
|> result.nil_error
}
// This constructs an event from the provided type. If `id` or `event` are
// provided, they are included in the message. The data provided is split
// across newlines, which I think is per the spec? The `Result` returned here
// can be used to determine whether the event send has succeeded.
pub fn send_event(conn: SSEConnection, event: SSEEvent) -> Result(Nil, Nil) {
let SSEConnection(conn) = conn
let id =
event.id
|> option.map(fn(id) { "id: " <> id <> "\n" })
|> option.unwrap("")
let event_name =
event.event
|> option.map(fn(name) { "event: " <> name <> "\n" })
|> option.unwrap("")
let data =
event.data
|> string_builder.split("\n")
|> list.map(fn(row) { string_builder.prepend(row, "data: ") })
|> string_builder.join("\n")
let message =
data
|> string_builder.prepend(event_name)
|> string_builder.prepend(id)
|> string_builder.append("\n\n")
|> bytes_builder.from_string_builder
transport.send(conn.transport, conn.socket, message)
|> result.replace(Nil)
|> result.nil_error
}
// This completes the stream of server-sent events. It will close the
// connection to the client.
pub fn end_events(_conn: SSEConnection) -> Response(ResponseData) {
response.new(204)
|> response.set_body(CloseEvents)
}