-
Notifications
You must be signed in to change notification settings - Fork 1
/
websocket_actor.gleam
198 lines (182 loc) · 5.51 KB
/
websocket_actor.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
import actors/calculator_actor.{Solve, is_calculation}
import actors/messages.{
type CustomWebsocketMessage, type RoomActorMessage, ConnectUser,
DisconnectUser, SendToAll, SendToClient,
}
import birl
import gleam/erlang/process.{type Subject, Normal}
import gleam/function
import gleam/http/request.{type Request}
import gleam/http/response.{type Response}
import gleam/int
import gleam/option.{type Option, None, Some}
import gleam/otp/actor.{type Next, Stop}
import gleam/string
import logging
import mist.{
type Connection, type ResponseData, type WebsocketConnection,
type WebsocketMessage, Custom, Text,
}
import shared/src/shared.{ChatMessage}
import process_utils.{process_message_queue_len}
pub type WebsocketActorState {
WebsocketActorState(
name: Option(String),
ws_subject: Subject(CustomWebsocketMessage),
room_subject: Option(Subject(RoomActorMessage)),
)
}
pub fn start(
req: Request(Connection),
room_subject: Subject(RoomActorMessage),
) -> Response(ResponseData) {
mist.websocket(
request: req,
on_init: fn(_) {
let ws_subject = process.new_subject()
let new_selector =
process.new_selector()
|> process.selecting(ws_subject, function.identity)
let state =
WebsocketActorState(
name: None,
ws_subject: ws_subject,
room_subject: Some(room_subject),
)
// register at room
process.send(room_subject, ConnectUser(ws_subject))
#(state, Some(new_selector))
},
on_close: fn(state) {
logging.log(logging.Info, "A connection was closed")
state |> cleanup
Nil
},
handler: handle_message,
)
}
pub fn handle_message(
state: WebsocketActorState,
connection: WebsocketConnection,
message: WebsocketMessage(CustomWebsocketMessage),
) -> Next(CustomWebsocketMessage, WebsocketActorState) {
case message {
// from internal
Custom(message) ->
case message {
SendToClient(message) -> {
// stringify to json
let message_json = shared.message_to_string(message)
let assert Ok(_) = mist.send_text_frame(connection, message_json)
state |> actor.continue
}
}
// from browser
Text(message) -> {
// check queue length of process
// if too high this means client is sending faster than we can process
// we stop calculations if > 3
// in testing it was discovered that this number increases by 1 between
// runs of handle_message. So our view of how much work is queued is
// delayed.
let process_queue_len = process_message_queue_len()
case process_queue_len {
i if i > 3 -> {
logging.log(
logging.Warning,
"queue len:" <> process_queue_len |> int.to_string,
)
}
_ -> Nil
}
// parse from json
let parsed_message = case message |> shared.message_from_string {
Ok(parsed_message) -> {
parsed_message
}
Error(_) -> {
logging.log(logging.Error, "Failed to parse message: " <> message)
let now = birl.now()
ChatMessage(
"Failed to parse message: " <> message,
"System",
birl.to_iso8601(now),
)
}
}
// transform message (calculator)
// forward ChatMessage to room
case parsed_message {
ChatMessage(content, author, created_at) -> {
// calculator (sync)
let parsed_message = case
is_calculation(content) && process_queue_len <= 3
{
False -> parsed_message
True -> {
// start new actor
let calc_actor = calculator_actor.start()
// call actor with timeout ms
let calc_result =
process.try_call(
calc_actor,
fn(reply_to) { Solve(reply_to, content) },
2000,
)
// stop actor
// without the unlink we kill (our)self
process.unlink(process.subject_owner(calc_actor))
process.kill(process.subject_owner(calc_actor))
case calc_result {
Ok(Ok(calc_result)) -> {
ChatMessage(
content <> " = " <> calc_result,
author,
created_at,
)
}
Error(e) -> {
let error = string.inspect(e)
ChatMessage(
content <> " = ? (" <> error <> ")",
author,
created_at,
)
}
_ -> parsed_message
}
}
}
// send to room
{
use room_subject <- option.then(state.room_subject)
Some(process.send(room_subject, SendToAll(parsed_message)))
}
}
_ -> {
logging.log(
logging.Error,
"Received message is not a ChatMessage: " <> message,
)
None
}
}
state |> actor.continue
}
_ -> {
logging.log(logging.Info, "Stopping websocket actor in handle_message")
cleanup(state)
Stop(Normal)
}
}
}
fn cleanup(state: WebsocketActorState) -> WebsocketActorState {
case state.room_subject {
Some(room_subject) -> {
process.send(room_subject, DisconnectUser(state.ws_subject))
WebsocketActorState(..state, room_subject: None)
}
None -> state
}
state
}