forked from OxygenFramework/Oxygen.jl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.jl
More file actions
927 lines (775 loc) · 32.4 KB
/
Copy pathcore.jl
File metadata and controls
927 lines (775 loc) · 32.4 KB
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
module Core
using Base: @kwdef
using HTTP
using HTTP: Router
using Sockets
using JSON
using Base
using Dates
using Reexport
using RelocatableFolders
using DataStructures: CircularDeque
import Base.Threads: lock, nthreads
import ..WAS_LOADED_AFTER_REVISE
include("errors.jl"); @reexport using .Errors
include("util.jl"); @reexport using .Util
include("types.jl"); @reexport using .Types
include("constants.jl"); @reexport using .Constants
include("context.jl"); @reexport using .AppContext
include("handlers.jl"); @reexport using .Handlers
include("middleware.jl"); @reexport using .Middleware
include("routerhof.jl"); @reexport using .RouterHOF
include("cron.jl"); @reexport using .Cron
include("repeattasks.jl"); @reexport using .RepeatTasks
include("metrics.jl"); @reexport using .Metrics
include("reflection.jl"); @reexport using .Reflection
include("extractors.jl"); @reexport using .Extractors
using .Extractors: Form # Prefer over HTTP.Form
include("autodoc.jl"); @reexport using .AutoDoc
export start, serve, serveparallel, terminate,
internalrequest, staticfiles, dynamicfiles
oxygen_title = raw"""
____
/ __ \_ ____ ______ ____ ____
/ / / / |/_/ / / / __ `/ _ \/ __ \
/ /_/ /> </ /_/ / /_/ / __/ / / /
\____/_/|_|\__, /\__, /\___/_/ /_/
/____//____/
"""
function serverwelcome(external_url::String, prefix::Nullable{String}, docs::Bool, metrics::Bool, parallel::Bool, docspath::String)
printstyled(oxygen_title, color=:blue, bold=true)
server_url = join_url_path(external_url, prefix)
@info "📦 Version 1.10.2 (2026-04-18)"
if !isnothing(prefix)
@info "🏷️ Global path prefix: $prefix"
end
@info "✅ Started server: $server_url"
if docs
@info "📖 Documentation: $(join_url_path(server_url, docspath))"
end
if docs && metrics
@info "📊 Metrics: $(join_url_path(server_url, "$docspath/metrics"))"
end
if parallel
@info "🚀 Running in parallel mode with $(Threads.nthreads()) threads"
# Add a warning if the interactive threadpool is empty when running in parallel mode
if nthreads(:interactive) == 0
@warn """
🚨 Interactive threadpool is empty. This can hurt performance when running in parallel mode.
Try launching julia like \"julia --threads 3,1\" to add 1 thread to the interactive threadpool.
"""
end
end
end
function ReviseHandler()
return function (handle)
return function (req::HTTP.Request)
Revise = Main.Revise
if !isempty(Revise.revision_queue)
@info "🔴 Starting pre-request revision"
Revise.revise()
@info "🟢 Pre-request revision finished"
end
invokelatest(handle, req)
end
end
end
"""
serve(; middleware::Vector=[], handler=stream_handler, host="127.0.0.1", port=8080, async=false, parallel=false, serialize=true, catch_errors=true, docs=true, metrics=true, show_errors=true, show_banner=true, docs_path="/docs", schema_path="/schema", external_url=nothing, revise, kwargs...)
Start the webserver with your own custom request handler
"""
function serve(ctx::ServerContext;
middleware = [],
handler = stream_handler,
host = "127.0.0.1",
port = 8080,
async = false,
parallel = false,
serialize = true,
catch_errors= true,
docs = true,
metrics = true,
show_errors = true,
show_banner = true,
docs_path = "/docs",
schema_path = "/schema",
external_url = nothing,
prefix = nothing,
context = missing,
revise = :none, # :none, :lazy, :eager
kwargs...) :: Server
if !ismissing(context)
ctx.app_context[] = Context(context)
end
# set the external url if it's passed
ctx.service.external_url[] = external_url isa String ? external_url : "http://$host:$port"
# Set the global path prefix (defaults to nothing)
ctx.service.prefix[] = prefix isa String ? prefix : nothing
# overwrite docs & schema paths
ctx.docs.enabled[] = docs
ctx.docs.docspath[] = docs_path
ctx.docs.schemapath[] = schema_path
# intitialize documenation router (used by docs and metrics)
ctx.docs.router[] = Router()
# setup revise if requested
if revise == :lazy || revise == :eager
if parallel
@warn "You are attempting to use Revise with multiple threads. Please note that Revise 3.5.18 and earlier are not threadsafe."
end
if !WAS_LOADED_AFTER_REVISE[]
error("You must load Revise.jl before Oxygen.jl to use the `revise` option")
end
if ctx.mod === nothing
@warn "You are trying to use the `revise` option without @oxidize. Code in the `Main` module, which likely includes your routes, will not be tracked and revised."
end
middleware = convert(Vector{Any}, middleware)
insert!(middleware, 1, ReviseHandler())
end
# compose our middleware ahead of time (so it only has to be built up once)
configured_middelware = setupmiddleware(ctx; middleware, serialize, catch_errors, docs, metrics, show_errors)
# setup the primary stream handler function (can be customized by the caller)
handle_stream = handler(configured_middelware)
if parallel
if Threads.nthreads() <= 1
@warn "serveparallel() only has 1 thread available to use, try launching julia like this: \"julia -t auto\" to leverage multiple threads"
end
if haskey(kwargs, :queuesize)
@warn "Deprecated: The `queuesize` parameter is no longer used / supported in serveparallel()"
end
# wrap top level handler with parallel handler
handle_stream = parallel_stream_handler(handle_stream)
end
if revise == :eager
ctx.service.eager_revise[] = start_revise_service()
end
# The cleanup of resources are put at the topmost level in `methods.jl`
try
return startserver(ctx; host, port, show_banner, docs, metrics, parallel, async, kwargs, start=(kwargs) ->
HTTP.listen!(handle_stream, host, port; kwargs...))
finally
if ctx.service.eager_revise[] !== nothing && async == false
close(ctx.service.eager_revise[])
end
end
end
function start_revise_service()
revise_task_done = Ref(false)
revise_task = @async begin
Revise = Main.Revise
while true
if revise_task_done[]
break
end
wait(Revise.revision_event)
reset(Revise.revision_event)
if revise_task_done[]
break
end
@info "🗘 Starting eager revision"
Revise.revise()
@info "👍 Eager revision finished"
end
end
EagerReviseService(revise_task, revise_task_done)
end
"""
terminate(ctx)
Gracefully shuts down the webserver
"""
function terminate(context::ServerContext)
if isopen(context.service)
# stop background cron jobs
stopcronjobs(context.cron)
clearcronjobs(context.cron)
# stop repeating tasks
stoptasks(context.tasks)
cleartasks(context.tasks)
# cleanup lifecycle middleware
shutdown.(context.service.lifecycle_middleware)
empty!(context.service.lifecycle_middleware)
# clear any cached middleware strategies so new servers pick up updated middleware
empty!(context.service.middleware_cache)
# Set the external url to nothing when the server is terminated
context.service.external_url[] = nothing
# stop the server
close(context.service)
end
end
"""
Register all cron jobs defined through our router() HOF
"""
function registercronjobs(ctx::ServerContext)
for job in ctx.cron.job_definitions
path, httpmethod, expression = job.path, job.httpmethod, job.expression
cron(ctx.cron.registered_jobs, expression, path, () -> internalrequest(ctx, HTTP.Request(httpmethod, path)))
end
end
"""
Register all repeat tasks defined through our router() HOF
"""
function registertasks(ctx::ServerContext)
for task_def in ctx.tasks.task_definitions
path, httpmethod, interval = task_def.path, task_def.httpmethod, task_def.interval
task(ctx.tasks.registered_tasks, interval, path, () -> internalrequest(ctx, HTTP.Request(httpmethod, path)))
end
end
"""
decorate_request(ip::IPAddr)
This function can be used to add additional usefull metadata to the incoming
request context dictionary. At the moment, it just inserts the caller's ip address
"""
function decorate_request(ip::IPAddr, stream::HTTP.Stream)
return function (handle)
return function (req::HTTP.Request)
req.context[:ip] = ip
req.context[:stream] = stream
handle(req)
end
end
end
"""
This is our root stream handler used in both serve() and serveparallel().
This function determines how we handle all incoming requests
"""
"""
Convert the `HTTP.peeraddr` result (a `Reseau.TCP.SocketAddr`-like struct with a
`.ip` tuple of octets, or `nothing` if unavailable) into a `Sockets.IPAddr`.
"""
function peeraddr_to_ip(addr) :: IPAddr
addr === nothing && return ip"0.0.0.0"
octets = addr.ip
if length(octets) == 4
return IPv4(octets...)
else
groups = ntuple(i -> UInt16(octets[2i - 1]) << 8 | UInt16(octets[2i]), 8)
return IPv6(groups...)
end
end
function stream_handler(middleware::Function)
return function (stream::HTTP.Stream)
# extract the caller's ip address
ip = peeraddr_to_ip(HTTP.peeraddr(stream))
# build up a streamhandler to handle our incoming requests
handle_stream = HTTP.streamhandler(middleware |> decorate_request(ip, stream))
# handle the incoming request
return handle_stream(stream)
end
end
"""
parallel_stream_handler(handle_stream::Function)
This function uses `Threads.@spawn` to schedule a new task on any available thread.
Inside this task, `@async` is used for cooperative multitasking, allowing the task to yield during I/O operations.
"""
function parallel_stream_handler(handle_stream::Function)
function (stream::HTTP.Stream)
task = Threads.@spawn begin
handle = @async handle_stream(stream)
wait(handle)
end
wait(task)
end
end
"""
Compose the user & internally defined middleware functions together. Practically, this allows
users to 'chain' middleware functions like `serve(handler1, handler2, handler3)` when starting their
application and have them execute in the order they were passed (left to right) for each incoming request
"""
function setupmiddleware(ctx::ServerContext; middleware::Vector=[], docs::Bool=true, metrics::Bool=true, serialize::Bool=true, catch_errors::Bool=true, show_errors=true)::Function
# determine if we have any special router or route-specific middleware
raw_middleware = reverse(middleware)
processed_middleware = process_middleware(ctx, raw_middleware)
custom_middleware = if !isempty(ctx.service.custommiddleware)
[compose(ctx.service.router, ctx.service.middleware_cache_lock, processed_middleware, ctx.service.custommiddleware, ctx.service.middleware_cache)]
else
processed_middleware
end
# If a global prefix is passed, then we inject middleware to remove the prefix at runtime before routing
global_prefix_middleware = !isnothing(ctx.service.prefix[]) ? [PrefixStripMiddleware(ctx.service.prefix[])] : []
# Docs middleware should only be available at runtime when serve() or serveparallel is called
docs_middleware = docs && !isnothing(ctx.docs.router[]) ? [DocsMiddleware(ctx.docs.router[], ctx.docs.docspath[])] : []
# check if we should use our default serialization middleware function
serializer = serialize ? [DefaultSerializer(catch_errors; show_errors)] : []
# check if we need to track metrics
collect_metrics = metrics ? [MetricsMiddleware(ctx.service, metrics)] : []
# combine all our middleware functions
return reduce(|>, [
ctx.service.router,
serializer...,
custom_middleware...,
collect_metrics...,
docs_middleware...,
global_prefix_middleware...
])
end
"""
Internal helper function to launch the server in a consistent way
"""
function startserver(ctx::ServerContext; host, port, show_banner=false, docs=false, metrics=false, parallel=false, async=false, kwargs, start)::Server
docs && setupdocs(ctx)
metrics && setupmetrics(ctx)
show_banner && serverwelcome(ctx.service.external_url[], ctx.service.prefix[], docs, metrics, parallel, ctx.docs.docspath[])
# start the HTTP server
ctx.service.server[] = start(preprocesskwargs(kwargs))
# Register & Start all repeat tasks
registertasks(ctx)
starttasks(ctx.tasks)
# Register & Start all cron jobs
registercronjobs(ctx)
startcronjobs(ctx.cron)
# Signal start of server to LifecycleMiddleware functions
startup.(ctx.service.lifecycle_middleware)
if !async
try
wait(ctx.service)
catch error
!isa(error, InterruptException) && @error "ERROR: " exception = (error, catch_backtrace())
finally
println() # this pushes the "[ Info: Server on 127.0.0.1:8080 closing" to the next line
end
end
return ctx.service.server[]
end
"""
Removes deprecated keys from incoming keyword arguments, currently: :stream, :access_log, and :queuesize.
"""
function preprocesskwargs(kwargs)
kwargs_dict = Dict{Symbol,Any}(kwargs)
delete!(kwargs_dict, :stream)
delete!(kwargs_dict, :access_log)
delete!(kwargs_dict, :queuesize)
return kwargs_dict
end
"""
internalrequest(req::HTTP.Request; middleware::Vector=[], serialize::Bool=true, catch_errors::Bool=true)
Directly call one of our other endpoints registered with the router, using your own middleware
and bypassing any globally defined middleware
"""
function internalrequest(ctx::ServerContext, req::HTTP.Request; middleware::Vector=[], metrics::Bool=false, serialize::Bool=true, catch_errors=true)::HTTP.Response
req.context[:ip] = IPv4("127.0.0.1") # label internal requests
return req |> setupmiddleware(ctx; middleware, metrics, serialize, catch_errors)
end
"""
If a global prefix is passed through the serve() function then we want to inject a
middleware function to intercept requests and strip off the prefix so it's compatible
with the actual registered routes - which doesn't include the prefix.
"""
function PrefixStripMiddleware(prefix::String)
plen = length(prefix)
NOT_FOUND = HTTP.Response(404, "Not Found")
return function (handler)
return function (req::HTTP.Request)
if startswith(req.target, prefix)
newtarget = req.target[plen+1:end]
req.target = isempty(newtarget) ? "/" : newtarget
return handler(req)
else
return NOT_FOUND
end
end
end
end
function DocsMiddleware(docsrouter::Router, docspath::String)
return function (handle)
return function (req::HTTP.Request)
if startswith(req.target, docspath)
response = docsrouter(req)
else
response = handle(req)
end
return format_response(req, response)
end
end
end
"""
Create a default serializer function that handles HTTP requests and formats the responses.
"""
function DefaultSerializer(catch_errors::Bool; show_errors::Bool)
return function (handle)
return function (req::HTTP.Request)
return handlerequest(catch_errors; show_errors) do
response = handle(req)
return format_response(req, response)
end
end
end
end
function MetricsMiddleware(service::Service, catch_errors::Bool)
return function (handler)
return function (req::HTTP.Request)
return handlerequest(catch_errors) do
start_time = time()
# Handle the request
response = handler(req)
# Log response time
response_time = (time() - start_time) * 1000
# Make sure we update the History object in a thread-safe way
lock(service.history_lock) do
if response.status == 200
push_history(service.history, HTTPTransaction(
string(req.context[:ip]),
string(req.target),
now(UTC),
response_time,
true,
response.status,
nothing
))
else
push_history(service.history, HTTPTransaction(
string(req.context[:ip]),
string(req.target),
now(UTC),
response_time,
false,
response.status,
text(response)
))
end
end
return response
end
end
end
end
# Case 1: If we are given a string - just return it
function parse_route(::String, route::String) :: String
return route
end
# Case 2: Call OuterRouter with default args to get InnerRouter, then call with http_method
function parse_route(http_method::String, router::OuterRouter) :: String
inner_router::InnerRouter = router()
return inner_router(http_method)
end
# Case 3: Call InnerRouter with http_method to get the final path
function parse_route(http_method::String, router::InnerRouter) :: String
return router(http_method)
end
function parse_func_params(route::String, func::Function)
"""
Parsing Rules:
1. path parameters are detected by their presence in the route string
2. query parameters are not in the route string and can have default values
3. path extractors can be used instead of traditional path parameters
4. extractors can be used alongside traditional path & query params
"""
info = splitdef(func, start=2) # skip the identifying first arg
# collect path param definitions from the route string
hasBraces = r"({)|(})"
route_params = Vector{Symbol}()
for value in HTTP.URIs.splitpath(route)
if contains(value, hasBraces)
variable = replace(value, hasBraces => "") |> strip
push!(route_params, Symbol(variable))
end
end
# Identify all path & query params (can be declared as regular variables or extractors)
pathnames = Vector{Symbol}()
querynames = Vector{Symbol}()
headernames = Vector{Symbol}()
bodynames = Vector{Symbol}()
path_params = []
query_params = []
header_params = []
body_params = []
for param in info.args
# case 1: it's an Context type it will be injected by the framework (so we skip it)
if param.type <: Context
continue
# case 2: it's an extractor type
elseif param.type <: Extractor
innner_type = param.type |> extracttype
# push the variables from the struct into the params array
if param.type <: Path
append!(pathnames, fieldnames(innner_type))
push!(path_params, param)
elseif param.type <: Query
append!(querynames, fieldnames(innner_type))
push!(query_params, param)
elseif param.type <: Header
append!(headernames, fieldnames(innner_type))
push!(header_params, param)
else
append!(bodynames, fieldnames(innner_type))
push!(body_params, param)
end
# case 3: It's a path parameter
elseif param.name in route_params
push!(pathnames, param.name)
push!(path_params, param)
# Case 4: It's a query parameter
else
push!(querynames, param.name)
push!(query_params, param)
end
end
# make sure all the path params are present in the route
if !isempty(route_params)
missing_params = [
route_param
for route_param in route_params
if !any(path_param -> path_param == route_param, pathnames)
]
if !isempty(missing_params)
throw(ArgumentError("Your request handler is missing path parameters: {$(join(missing_params, ", "))} defined in this route: $route"))
end
end
return (
info=info, pathparams=path_params,
pathnames=pathnames, queryparams=query_params,
querynames=querynames, headers=header_params,
headernames=headernames, bodyargs=body_params,
bodynames=bodynames
)
end
"""
register(ctx::ServerContext, httpmethod::String, route::String, func::Function)
Register a request handler function with a path to the ROUTER
"""
function register(ctx::ServerContext, httpmethod::String, route::Union{String,HOFRouter}, func::Function)
# Parse & validate path parameters
route = parse_route(httpmethod, route)
func_details = parse_func_params(route, func)
# only generate the schema if the docs are enabled
if ctx.docs.enabled[]
# Even if docs are enabled, we don't want to let any docs generation related errors prevent the server from running
try
# Pull out the request parameters
queryparams = func_details.queryparams
pathparams = func_details.pathparams
headers = func_details.headers
bodyparams = func_details.bodyargs
# Register the route schema with out autodocs module
registerschema(ctx.docs, route, httpmethod, pathparams, queryparams, headers, bodyparams, Base.return_types(func))
catch error
@warn "Failed to generate openapi schema for route: $route"
@warn error
end
end
# Register the route with the router
registerhandler(ctx, ctx.service.router, httpmethod, route, func, func_details)
end
"""
This registers a route wihout generating any documentation for it. Used primarily for internal routes like
docs and metrics
"""
function register_internal(ctx::ServerContext, router::Router, httpmethod::String, route::Union{String,HOFRouter}, func::Function)
# Parse & validate path parameters
route = parse_route(httpmethod, route)
func_details = parse_func_params(route, func)
# Register the route with the router
registerhandler(ctx, router, httpmethod, route, func, func_details)
end
"""
Generate the parser strategy to apply to incoming requests. It will return a function
which accepts a HTTP.Request and returns a Vector of the parsed parameters
"""
function create_param_parser(ctx::ServerContext, func_details)
info = func_details.info
pathparams = func_details.pathnames
queryparams = func_details.querynames
strategies = Vector{Function}()
"""
Listed below are the different parsing strategies that can
be used on incoming HTTP Requests
"""
function context_strategy(_::LazyRequest)
return ctx.app_context[]
end
function extractor_strategy(lr::LazyRequest, param::Param{T}) where T
return extract(param, lr)
end
function pathparam_strategy(lr::LazyRequest, param::Param{T}, name::String) where T
raw_pathparams = Types.pathparams(lr)
return parseparam(param.type, raw_pathparams[name])
end
function queryparam_strategy(lr::LazyRequest, param::Param{T}, name::String) where T
raw_queryparams = Types.queryvars(lr)
if !haskey(raw_queryparams, name) && param.hasdefault
return param.default
else
return parseparam(param.type, raw_queryparams[name])
end
end
function queryparam_strategy_no_default(lr::LazyRequest, param::Param{T}, name::String) where T
raw_queryparams = Types.queryvars(lr)
return parseparam(param.type, raw_queryparams[name])
end
"""
Figure out which strategy to use for each parameter,
based on the parameter's type, name, and position
"""
for param in info.sig
name = param.name
str_name = String(name)
if param.type <: Context
push!(strategies, context_strategy)
elseif param.type <: Extractor
push!(strategies, lr -> extractor_strategy(lr, param))
elseif name in pathparams
push!(strategies, lr -> pathparam_strategy(lr, param, str_name))
elseif name in queryparams
query_parsing_strat = param.hasdefault ? queryparam_strategy : queryparam_strategy_no_default
push!(strategies, lr -> query_parsing_strat(lr, param, str_name))
end
end
strat_length = length(strategies)
# The final function is used to apply the strategies and extract the parameters
return function(req::HTTP.Request)
lr = LazyRequest(request=req)
results = Vector{Any}(undef, strat_length)
@inbounds for i in 1:strat_length
results[i] = strategies[i](lr)
end
return results
end
end
function registerhandler(ctx::ServerContext, router::Router, httpmethod::String, route::String, func::Function, func_details::NamedTuple)
# Get information about the function's arguments
method = first(methods(func))
no_args = method.nargs == 1
# check if handler has a :request kwarg
info = func_details.info
has_req_kwarg = :request in Base.kwarg_decl(method)
has_ctx_kwarg = :context in Base.kwarg_decl(method)
has_path_params = !isempty(info.args)
# Generate the function handler based on the input types
arg_type = first_arg_type(method, httpmethod)
func_handle = select_handler(arg_type, has_ctx_kwarg, has_req_kwarg, has_path_params, ctx; no_args=no_args)
# Generate the parameter parsing strategy for each endpoint
parse_params = create_param_parser(ctx, func_details)
# Generate the parameter parsing strategy for each endpoint
parse_params = create_param_parser(ctx, func_details)
# Figure out if we need to include parameter parsing logic for this route
if isempty(info.sig)
handle = function (req::HTTP.Request)
func_handle(req, func)
end
else
handle = function (req::HTTP.Request)
params = parse_params(req)
func_handle(req, func; parameters=params)
end
end
# Use method aliases for special methods
resolved_httpmethod = get(METHOD_ALIASES, httpmethod, httpmethod)
HTTP.register!(router, resolved_httpmethod, route, handle)
end
function setupdocs(ctx::ServerContext)
setupdocs(ctx, ctx.docs.router[], ctx.docs.schema, ctx.docs.docspath[], ctx.docs.schemapath[])
end
"""
Map over all keys in the paths dict and append the global prefix (if available)
"""
function prefix_schema_paths(schema::Dict, prefix::Nullable{String})
if isnothing(prefix)
return schema
else
paths = get(schema, "paths", Dict())
new_paths = Dict(join_url_path(prefix, k) => v for (k, v) in paths)
return merge(schema, Dict("paths" => new_paths))
end
end
# add the swagger and swagger/schema routes
function setupdocs(ctx::ServerContext, router::Router, schema::Dict, docspath::String, schemapath::String)
full_schema = "$docspath$schemapath"
# If a global prefix is assigned, then we need to make sure we inject the prefixes into the source url as well.
prefixed_schema = join_url_path(ctx.service.prefix[], full_schema)
prefixed_docspath = join_url_path(ctx.service.prefix[], docspath)
# Need to update the "path" in our open-api schema to include the global prefix
prefixed_openapi_schema = prefix_schema_paths(schema, ctx.service.prefix[])
register_internal(ctx, router, "GET", "$docspath", () -> swaggerhtml(prefixed_schema, prefixed_docspath))
register_internal(ctx, router, "GET", "$docspath/swagger", () -> swaggerhtml(prefixed_schema, prefixed_docspath))
register_internal(ctx, router, "GET", "$docspath/redoc", () -> redochtml(prefixed_schema, prefixed_docspath))
register_internal(ctx, router, "GET", full_schema, () -> prefixed_openapi_schema)
end
function setupmetrics(context::ServerContext)
setupmetrics(context, context.docs.router[], context.service.history, context.docs.docspath[], context.service.history_lock)
end
# add the swagger and swagger/schema routes
function setupmetrics(ctx::ServerContext, router::Router, history::History, docspath::String, history_lock::ReentrantLock)
# If a global prefix is assigned, then we need to make sure we inject the prefixes into the source url as well.
prefixed_docspath = join_url_path(ctx.service.prefix[], docspath)
# This allows us to customize the path to the metrics dashboard
function loadfile(filepath)::String
content = readfile(filepath)
# only replace content if it's in a generated file
ext = lowercase(last(splitext(filepath)))
if ext in [".html", ".css", ".js"]
return replace(content, "/df9a0d86-3283-4920-82dc-4555fc0d1d8b/" => "$prefixed_docspath/metrics/")
else
return content
end
end
staticfiles(ctx, router, "$DATA_PATH/dashboard", "$docspath/metrics"; loadfile=loadfile)
# Create a thread-safe copy of the history object and it's internal data
function safe_get_transactions(history::History)::Vector{HTTPTransaction}
transactions = []
lock(history_lock) do
transactions = collect(history)
end
return transactions
end
function innermetrics(req::HTTP.Request, window::Nullable{Int}, latest::Nullable{DateTime})
# create a threadsafe copy of the current transactions in our history object
transactions = safe_get_transactions(history)
# Figure out how far back to read from the history object
window_value = !isnothing(window) && window > 0 ? Minute(window) : nothing
lower_bound = !isnothing(latest) ? latest : window_value
return Dict(
"server" => server_metrics(transactions, nothing),
"endpoints" => all_endpoint_metrics(transactions, nothing),
"errors" => error_distribution(transactions, nothing),
"avg_latency_per_second" => avg_latency_per_unit(transactions, Second, lower_bound) |> prepare_timeseries_data(),
"requests_per_second" => requests_per_unit(transactions, Second, lower_bound) |> prepare_timeseries_data(),
"avg_latency_per_minute" => avg_latency_per_unit(transactions, Minute, lower_bound) |> prepare_timeseries_data(),
"requests_per_minute" => requests_per_unit(transactions, Minute, lower_bound) |> prepare_timeseries_data()
)
end
register_internal(ctx, router, GET, "$docspath/metrics/data/{window}/{latest}", innermetrics)
end
"""
staticfiles(folder::String, mountdir::String; headers::Vector{Pair{String,String}}=[], loadfile::Union{Function,Nothing}=nothing)
Mount all files inside the /static folder (or user defined mount point).
The `headers` array will get applied to all mounted files
"""
function staticfiles(
ctx::ServerContext,
router::HTTP.Router,
folder::String,
mountdir::String="static";
headers::Vector=[],
loadfile::Nullable{Function}=nothing
)
# remove the leading slash
if first(mountdir) == '/'
mountdir = mountdir[2:end]
end
function addroute(currentroute, filepath)
resp = file(filepath; loadfile=loadfile, headers=headers)
register_internal(ctx, router, GET, currentroute, () -> resp)
end
mountfolder(folder, mountdir, addroute)
end
"""
dynamicfiles(folder::String, mountdir::String; headers::Vector{Pair{String,String}}=[], loadfile::Union{Function,Nothing}=nothing)
Mount all files inside the /static folder (or user defined mount point),
but files are re-read on each request. The `headers` array will get applied to all mounted files
"""
function dynamicfiles(
ctx::ServerContext,
router::Router,
folder::String,
mountdir::String="static";
headers::Vector=[],
loadfile::Nullable{Function}=nothing
)
# remove the leading slash
if first(mountdir) == '/'
mountdir = mountdir[2:end]
end
function addroute(currentroute, filepath)
register_internal(ctx, router, GET, currentroute, () -> file(filepath; loadfile=loadfile, headers=headers))
end
mountfolder(folder, mountdir, addroute)
end
end