/
Server.jl
368 lines (284 loc) · 10.8 KB
/
Server.jl
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
"""
Handles Http server related functionality, manages requests and responses and their logging.
"""
module Server
using HTTP, Sockets, HTTP.WebSockets
import Millboard, Distributed, Logging
import Genie
import Distributed
"""
ServersCollection(webserver::Union{Task,Nothing}, websockets::Union{Task,Nothing})
Represents a object containing references to Genie's web and websockets servers.
"""
Base.@kwdef mutable struct ServersCollection
webserver::Union{Task,Nothing} = nothing
websockets::Union{Task,Nothing} = nothing
end
"""
SERVERS
ServersCollection constant containing references to the current app's web and websockets servers.
"""
const SERVERS = ServersCollection[]
const Servers = SERVERS
function isrunning(server::ServersCollection, prop::Symbol = :webserver) :: Bool
isa(getfield(server, prop), Task) && ! istaskdone(getfield(server, prop))
end
function isrunning(prop::Symbol = :webserver) :: Bool
isempty(SERVERS) ? false : isrunning(SERVERS[1], prop)
end
function server_status(server::ServersCollection, prop::Symbol) :: Nothing
if isrunning(server, prop)
@info("✔️ server is running.")
else
@error("❌ $server is not running.")
isa(getfield(server, prop), Task) && fetch(getfield(server, prop))
end
nothing
end
"""
up(port::Int = Genie.config.server_port, host::String = Genie.config.server_host;
ws_port::Int = Genie.config.websockets_port, async::Bool = ! Genie.config.run_as_server) :: ServersCollection
Starts the web server.
# Arguments
- `port::Int`: the port used by the web server
- `host::String`: the host used by the web server
- `ws_port::Int`: the port used by the Web Sockets server
- `async::Bool`: run the web server task asynchronously
# Examples
```julia-repl
julia> up(8000, "127.0.0.1", async = false)
[ Info: Ready!
Web Server starting at http://127.0.0.1:8000
```
"""
function up(port::Int,
host::String = Genie.config.server_host;
ws_port::Int = port,
async::Bool = ! Genie.config.run_as_server,
verbose::Bool = false,
ratelimit::Union{Rational{Int},Nothing} = nothing,
server::Union{Sockets.TCPServer,Nothing} = nothing,
wsserver::Union{Sockets.TCPServer,Nothing} = server,
open_browser::Bool = false,
reuseaddr::Bool = Distributed.nworkers() > 1,
http_kwargs...) :: ServersCollection
if server !== nothing
try
socket_info = Sockets.getsockname(server)
port = Int(socket_info[2])
host = string(socket_info[1])
catch ex
@error "Failed parsing `server` parameter info."
@error ex
end
end
update_config(port, host, ws_port)
new_server = ServersCollection()
if Genie.config.websockets_server && port != ws_port
print_server_status("Web Sockets server starting at $host:$ws_port")
new_server.websockets = HTTP.listen(host, ws_port; verbose = verbose, rate_limit = ratelimit, server = wsserver,
reuseaddr = reuseaddr, http_kwargs...) do http::HTTP.Stream
if HTTP.WebSockets.isupgrade(http.message)
HTTP.WebSockets.upgrade(http) do ws
setup_ws_handler(http, ws)
end
end
end
end
command = () -> begin
HTTP.listen(parse(Sockets.IPAddr, host), port; verbose = verbose, rate_limit = ratelimit, server = server,
reuseaddr = reuseaddr, http_kwargs...) do http::HTTP.Stream
try
if Genie.config.websockets_server && port == ws_port && HTTP.WebSockets.isupgrade(http.message)
HTTP.WebSockets.upgrade(http) do ws
setup_ws_handler(http, ws)
end
else
setup_http_streamer(http)
end
catch ex
isa(ex, Base.IOError) || @error ex
nothing
end
end
end
server_url = "http://$host:$port"
status = if async
print_server_status("Web Server starting at $server_url")
@async command()
else
print_server_status("Web Server starting at $server_url - press Ctrl/Cmd+C to stop the server.")
command()
end
if status !== nothing && status.state == :runnable
new_server.webserver = status
try
open_browser && openbrowser(server_url)
catch ex
@error "Failed to open browser"
@error ex
end
end
push!(SERVERS, new_server)
new_server
end
function up(; port = Genie.config.server_port, ws_port = Genie.config.websockets_port, kwargs...) :: ServersCollection
up(port; ws_port = ws_port, kwargs...)
end
print_server_status(status::String) = @info "\n$status \n"
@static if Sys.isapple()
openbrowser(url::String) = run(`open $url`)
elseif Sys.islinux()
openbrowser(url::String) = run(`xdg-open $url`)
elseif Sys.iswindows()
openbrowser(url::String) = run(`cmd /C start $url`)
end
"""
serve(path::String = pwd(), params...; kwparams...)
Serves a folder of static files located at `path`. Allows Genie to be used as a static files web server.
The `params` and `kwparams` arguments are forwarded to `Genie.up()`.
# Arguments
- `path::String`: the folder of static files to be served by the server
- `params`: additional arguments which are passed to `Genie.up` to control the web server
- `kwparams`: additional keyword arguments which are passed to `Genie.up` to control the web server
# Examples
```julia-repl
julia> Genie.serve("public", 8888, async = false, verbose = true)
[ Info: Ready!
2019-08-06 16:39:20:DEBUG:Main: Web Server starting at http://127.0.0.1:8888
[ Info: Listening on: 127.0.0.1:8888
[ Info: Accept (1): 🔗 0↑ 0↓ 1s 127.0.0.1:8888:8888 ≣16
```
"""
function serve(path::String = pwd(), params...; kwparams...)
path = abspath(path)
Genie.config.server_document_root = path
Genie.Router.route("/") do
Genie.Router.serve_static_file(path; root = path)
end
Genie.Router.route(".*") do
Genie.Router.serve_static_file(Genie.Router.params(:REQUEST).target; root = path)
end
up(params...; kwparams...)
end
"""
update_config(port::Int, host::String, ws_port::Int) :: Nothing
Updates the corresponding Genie configurations to the corresponding values for
`port`, `host`, and `ws_port`, if these are passed as arguments when starting up the server.
"""
function update_config(port::Int, host::String, ws_port::Int) :: Nothing
Genie.config.server_port = port
Genie.config.server_host = host
Genie.config.websockets_port = ws_port
nothing
end
"""
down(; webserver::Bool = true, websockets::Bool = true) :: ServersCollection
Shuts down the servers optionally indicating which of the `webserver` and `websockets` servers to be stopped.
It does not remove the servers from the `SERVERS` collection. Returns the collection.
"""
function down(; webserver::Bool = true, websockets::Bool = true) :: Vector{ServersCollection}
for i in 1:length(SERVERS)
down(SERVERS[i]; webserver, websockets)
end
SERVERS
end
function down(server::ServersCollection; webserver::Bool = true, websockets::Bool = true) :: ServersCollection
webserver && (@async Base.throwto(server.webserver, InterruptException()))
isnothing(websockets) || (websockets && (@async Base.throwto(server.websockets, InterruptException())))
server
end
"""
function down!(; webserver::Bool = true, websockets::Bool = true) :: Vector{ServersCollection}
Shuts down all the servers and empties the `SERVERS` collection. Returns the empty collection.
"""
function down!() :: Vector{ServersCollection}
down()
empty!(SERVERS)
SERVERS
end
"""
handle_request(req::HTTP.Request, res::HTTP.Response) :: HTTP.Response
Http server handler function - invoked when the server gets a request.
"""
function handle_request(req::HTTP.Request, res::HTTP.Response) :: HTTP.Response
try
req = Genie.Headers.normalize_headers(req)
catch ex
@error ex
end
try
Genie.Headers.set_headers!(req, res, Genie.Router.route_request(req, res))
catch ex
rethrow(ex)
end
end
function setup_http_streamer(http::HTTP.Stream)
if Genie.config.features_peerinfo
try
task_local_storage(:peer, Sockets.getpeername( HTTP.IOExtras.tcpsocket(HTTP.Streams.getrawstream(http)) ))
catch ex
@error ex
end
end
HTTP.Handlers.streamhandler(setup_http_listener)(http)
end
"""
setup_http_listener(req::HTTP.Request, res::HTTP.Response = HTTP.Response()) :: HTTP.Response
Configures the handler for the HTTP Request and handles errors.
"""
function setup_http_listener(req::HTTP.Request, res::HTTP.Response = HTTP.Response()) :: HTTP.Response
try
Distributed.@fetch handle_request(req, res)
catch ex # ex is a Distributed.RemoteException
if isa(ex, Distributed.RemoteException) &&
hasfield(typeof(ex), :captured) && isa(ex.captured, Distributed.CapturedException) &&
hasfield(typeof(ex.captured), :ex) && isa(ex.captured.ex, Genie.Exceptions.RuntimeException)
@error ex.captured.ex
return Genie.Router.error(ex.captured.ex.code, ex.captured.ex.message, Genie.Router.response_mime(),
error_info = string(ex.captured.ex.code, " ", ex.captured.ex.info))
end
error_message = string(sprint(showerror, ex), "\n\n")
@error error_message
message = Genie.Configuration.isprod() ?
"The error has been logged and we'll look into it ASAP." :
error_message
Genie.Router.error(message, Genie.Router.response_mime(), Val(500))
end
end
"""
setup_ws_handler(stream::HTTP.Stream, ws_client) :: Nothing
Configures the handler for WebSockets requests.
"""
function setup_ws_handler(stream::HTTP.Stream, ws_client) :: Nothing
req = stream.message
try
req = stream.message
while ! HTTP.WebSockets.isclosed(ws_client) && ! ws_client.writeclosed && isopen(ws_client.io)
Sockets.send(ws_client, Distributed.@fetch handle_ws_request(req; message = HTTP.WebSockets.receive(ws_client), client = ws_client))
end
catch ex
if isa(ex, Distributed.RemoteException) &&
hasfield(typeof(ex), :captured) && isa(ex.captured, Distributed.CapturedException) &&
hasfield(typeof(ex.captured), :ex) && isa(ex.captured.ex, HTTP.WebSockets.CloseFrameBody) # && ex.captured.ex.code == 1000
@info "WebSocket closed"
return nothing
elseif isa(ex, Distributed.RemoteException) &&
hasfield(typeof(ex), :captured) && isa(ex.captured, Distributed.CapturedException) &&
hasfield(typeof(ex.captured), :ex) && isa(ex.captured.ex, Genie.Exceptions.RuntimeException)
@error ex.captured.ex
return nothing
end
# rethrow(ex)
end
nothing
end
"""
handle_ws_request(req::HTTP.Request, msg::String, ws_client) :: String
Http server handler function - invoked when the server gets a request.
"""
function handle_ws_request(req::HTTP.Request; message::Union{String,Vector{UInt8}}, client::HTTP.WebSockets.WebSocket) :: String
isempty(message) && return "" # keep alive
Genie.Router.route_ws_request(req, message, client)
end
end