forked from samcamwilliams/HyperBEAM
-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathhb_http_server.erl
More file actions
724 lines (699 loc) · 27.8 KB
/
Copy pathhb_http_server.erl
File metadata and controls
724 lines (699 loc) · 27.8 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
%%% @doc A router that attaches a HTTP server to the AO-Core resolver.
%%% Because AO-Core is built to speak in HTTP semantics, this module
%%% only has to marshal the HTTP request into a message, and then
%%% pass it to the AO-Core resolver.
%%%
%%% `hb_http:reply/4' is used to respond to the client, handling the
%%% process of converting a message back into an HTTP response.
%%%
%%% The router uses an `Opts' message as its Cowboy initial state,
%%% such that changing it on start of the router server allows for
%%% the execution parameters of all downstream requests to be controlled.
-module(hb_http_server).
-export([start/0, start/1, allowed_methods/2, init/2]).
-export([set_opts/1, set_opts/2, get_opts/0, get_opts/1]).
-export([set_default_opts/1, set_proc_server_id/1]).
-export([static/3, static/4]).
-export([start_node/0, start_node/1]).
-include_lib("eunit/include/eunit.hrl").
-include("include/hb.hrl").
%% Define the max size we can return in 500 error details field.
-define(DEFAULT_ERROR_DETAILS_MAX_SIZE, 32*1024).
%% @doc Starts the HTTP server. Optionally accepts an `Opts' message, which
%% is used as the source for server configuration settings, as well as the
%% `Opts' argument to use for all AO-Core resolution requests downstream.
start() ->
?event(http, {start_store, <<"cache-mainnet">>}),
EnvConfig = hb_opts:default_message_with_env(),
Loc = hb_opts:get(hb_config_location, <<"config.flat">>, EnvConfig),
Loaded =
case hb_opts:load(Loc, EnvConfig) of
{ok, Conf} ->
?event(boot, {loaded_config, {path, Loc}, {config, Conf}}),
Conf;
{error, Reason} ->
?event(boot, {failed_to_load_config, Loc, Reason}),
#{}
end,
MergedConfig = hb_maps:merge(EnvConfig, Loaded),
hb_http_client:setup_conn(MergedConfig),
%% Apply store defaults before starting store
StoreOpts = hb_opts:get(store, no_store, MergedConfig),
StoreDefaults = hb_opts:get(store_defaults, #{}, MergedConfig),
UpdatedStoreOpts =
case StoreOpts of
no_store -> no_store;
_ when is_list(StoreOpts) ->
hb_store_opts:apply(StoreOpts, StoreDefaults);
_ -> StoreOpts
end,
hb_store:start(UpdatedStoreOpts),
% Also start default stores
hb_store:start(hb_opts:get(<<"store">>, [], #{})),
PrivWallet =
hb:wallet(
hb_opts:get(
priv_key_location,
<<"hyperbeam-key.json">>,
Loaded
)
),
maybe_greeter(Loaded, PrivWallet),
start(
Loaded#{
<<"priv-wallet">> => PrivWallet,
<<"store">> => UpdatedStoreOpts,
<<"port">> => hb_opts:get(port, 8734, Loaded),
<<"cache-writers">> =>
[hb_util:human_id(ar_wallet:to_address(PrivWallet))]
}
).
start(Opts) ->
application:ensure_all_started([
kernel,
stdlib,
inets,
ssl,
ranch,
cowboy,
gun,
os_mon
]),
hb:init(),
BaseOpts = set_default_opts(Opts),
ok = hb_process_sampler:ensure_started(BaseOpts),
ok = hb_system_monitor:ensure_started(BaseOpts),
{ok, Listener, _Port} = new_server(BaseOpts),
{ok, Listener}.
%% @doc Print the greeter message to the console if we are not running tests.
maybe_greeter(MergedConfig, PrivWallet) ->
case hb_features:test() of
false ->
print_greeter(MergedConfig, PrivWallet);
true ->
ok
end.
%% @doc Read a static file from a device's HTML asset directory.
static(Device, Name, Opts) ->
static(Device, Name, #{}, Opts).
static(Device, Name, Template, _Opts) ->
Base = hb_util:bin(code:priv_dir(hb)),
Filename = <<Base/binary, "/html/", Device/binary, "/", Name/binary>>,
?event({serving_static, Filename}),
case file:read_file(Filename) of
{ok, RawBody} ->
Body = apply_static_template(RawBody, Template),
{ok, #{
<<"body">> => Body,
<<"content-type">> => content_type(Filename)
}};
{error, _} ->
{error, not_found}
end.
%% @doc Return the content type for a static file.
content_type(Filename) ->
case filename:extension(Filename) of
<<".html">> -> <<"text/html">>;
<<".js">> -> <<"text/javascript">>;
<<".css">> -> <<"text/css">>;
<<".png">> -> <<"image/png">>;
<<".ico">> -> <<"image/x-icon">>;
<<".ttf">> -> <<"font/ttf">>;
<<".json">> -> <<"application/json">>;
_ -> <<"text/plain">>
end.
%% @doc Apply a simple binary replacement template to a static file.
apply_static_template(Body, Template) when is_map(Template) ->
apply_static_template(Body, maps:to_list(Template));
apply_static_template(Body, []) ->
Body;
apply_static_template(Body, [{Key, Value} | Rest]) ->
apply_static_template(
re:replace(
Body,
<<"\\{\\{", Key/binary, "\\}\\}">>,
hb_util:bin(Value),
[global, {return, binary}]
),
Rest
).
%% @doc Print the greeter message to the console. Includes the version, operator
%% address, URL to access the node, and the wider configuration (including the
%% keys inherited from the default configuration).
print_greeter(Config, PrivWallet) ->
FormattedConfig = hb_format:term(Config, Config, 2),
io:format("~n"
"===========================================================~n"
"== ██╗ ██╗██╗ ██╗██████╗ ███████╗██████╗ ==~n"
"== ██║ ██║╚██╗ ██╔╝██╔══██╗██╔════╝██╔══██╗ ==~n"
"== ███████║ ╚████╔╝ ██████╔╝█████╗ ██████╔╝ ==~n"
"== ██╔══██║ ╚██╔╝ ██╔═══╝ ██╔══╝ ██╔══██╗ ==~n"
"== ██║ ██║ ██║ ██║ ███████╗██║ ██║ ==~n"
"== ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝ ==~n"
"== ==~n"
"== ██████╗ ███████╗ █████╗ ███╗ ███╗ VERSION: ==~n"
"== ██╔══██╗██╔════╝██╔══██╗████╗ ████║ v~s. ==~n"
"== ██████╔╝█████╗ ███████║██╔████╔██║ ==~n"
"== ██╔══██╗██╔══╝ ██╔══██║██║╚██╔╝██║ EAT GLASS, ==~n"
"== ██████╔╝███████╗██║ ██║██║ ╚═╝ ██║ BUILD THE ==~n"
"== ╚═════╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ FUTURE. ==~n"
"===========================================================~n"
"== Node live at: ~s ==~n"
"== Operator: ~s ==~n"
"===========================================================~n"
"== Config: ==~n"
"===========================================================~n"
" ~s~n~n"
"===========================================================~n",
[
?HYPERBEAM_VERSION,
string:pad(
lists:flatten(
io_lib:format(
"http://~s:~p",
[
hb_opts:get(node_host, <<"localhost">>, Config),
hb_opts:get(port, 8734, Config)
]
)
),
39,
leading,
$ % Note: Space after `$` is functional, not garbage.
),
hb_util:human_id(ar_wallet:to_address(PrivWallet)),
FormattedConfig
]
).
%% @doc Trigger the creation of a new HTTP server node. Accepts a `NodeMsg'
%% message, which is used to configure the server. This function executed the
%% `start' hook on the node, giving it the opportunity to modify the `NodeMsg'
%% before it is used to configure the server. The `start' hook expects gives and
%% expects the node message to be in the `body' key.
new_server(RawNodeMsg) ->
RawNodeMsgWithDefaults =
hb_maps:merge(
hb_opts:default_message_with_env(),
RawNodeMsg#{ <<"only">> => local }
),
HookMsg = #{ <<"body">> => RawNodeMsgWithDefaults },
NodeMsg =
case hb_hook:on(<<"start">>, HookMsg, RawNodeMsgWithDefaults) of
{ok, #{ <<"body">> := NodeMsgAfterHook }} -> NodeMsgAfterHook;
Unexpected ->
?event(http,
{failed_to_start_server,
{unexpected_hook_result, Unexpected}
}
),
throw(
{failed_to_start_server,
{unexpected_hook_result, Unexpected}
}
)
end,
% Put server ID into node message so it's possible to update current server
hb_http:start(),
ServerID =
hb_util:human_id(
ar_wallet:to_address(
hb_opts:get(
priv_wallet,
no_wallet,
NodeMsg
)
)
),
% Put server ID into node message so it's possible to update current server
% params.
NodeMsgWithID = hb_maps:put(<<"http-server">>, ServerID, NodeMsg),
Dispatcher = cowboy_router:compile([{'_', [{'_', ?MODULE, ServerID}]}]),
ProtoOpts = #{
env => #{ dispatch => Dispatcher, node_msg => NodeMsgWithID },
stream_handlers => [cowboy_stream_h],
max_connections => infinity,
idle_timeout => hb_opts:get(idle_timeout, 300000, NodeMsg)
},
PrometheusOpts =
case hb_opts:get(prometheus, not hb_features:test(), NodeMsg) of
true ->
?event(prometheus,
{starting_prometheus, {test_mode, hb_features:test()}}
),
% Attempt to start the prometheus application, if possible.
try
application:ensure_all_started([prometheus, prometheus_cowboy, prometheus_ranch]),
prometheus_registry:register_collectors([hb_metrics_collector]),
ProtoOpts#{
metrics_callback =>
fun prometheus_cowboy2_instrumenter:observe/1,
stream_handlers => [cowboy_metrics_h, cowboy_stream_h]
}
catch
Type:Reason ->
% If the prometheus application is not started, we can
% still start the HTTP server, but we won't have any
% metrics.
?event(prometheus,
{prometheus_not_started, {type, Type}, {reason, Reason}}
),
ProtoOpts
end;
false ->
?event(prometheus,
{prometheus_not_started, {test_mode, hb_features:test()}}
),
ProtoOpts
end,
DefaultProto =
case hb_features:http3() of
true -> http3;
false -> http2
end,
{ok, Port, Listener} =
case Protocol = hb_opts:get(protocol, DefaultProto, NodeMsg) of
http3 ->
start_http3(ServerID, PrometheusOpts, NodeMsg);
Pro when Pro =:= http2; Pro =:= http1 ->
% The HTTP/2 server has fallback mode to 1.1 as necessary.
start_http2(ServerID, PrometheusOpts, NodeMsg);
_ -> {error, {unknown_protocol, Protocol}}
end,
% Update the node message with the actual port that was used, in the event
% that the OS assigned a different port. This happens, for example, when we
% use port 0.
set_opts(NodeMsg#{ <<"port">> => Port }),
?event(http,
{http_server_started,
{listener, Listener},
{server_id, ServerID},
{port, Port},
{protocol, Protocol},
{store, hb_opts:get(store, no_store, NodeMsg)}
}
),
{ok, Listener, Port}.
start_http3(ServerID, ProtoOpts, NodeMsg) ->
?event(http, {start_http3, ServerID}),
Parent = self(),
ServerPID =
spawn(fun() ->
application:ensure_all_started(quicer),
{ok, Listener} =
cowboy:start_quic(
ServerID,
TransOpts = #{
socket_opts => [
{certfile, "test/test-tls.pem"},
{keyfile, "test/test-tls.key"},
{port, hb_opts:get(port, 0, NodeMsg)}
]
},
ProtoOpts
),
ActualPort = ranch:get_port(ServerID),
ranch_server:set_new_listener_opts(
ServerID,
1024,
ranch:normalize_opts(
hb_maps:to_list(TransOpts#{ port => ActualPort })
),
ProtoOpts,
[]
),
ranch_server:set_addr(ServerID, {<<"localhost">>, ActualPort}),
% Bypass ranch's requirement to have a connection supervisor define
% to support updating protocol opts.
% Quicer doesn't use a connection supervisor, so we just spawn one
% that does nothing.
ConnSup = spawn(fun() -> http3_conn_sup_loop() end),
ranch_server:set_connections_sup(ServerID, ConnSup),
Parent ! {ok, ActualPort},
receive stop -> stopped end
end),
receive {ok, Port} -> {ok, Port, ServerPID}
after 2000 ->
{error, {timeout, starting_http3_server, ServerID}}
end.
http3_conn_sup_loop() ->
receive
_ ->
% Ignore any other messages
http3_conn_sup_loop()
end.
start_http2(ServerID, ProtoOpts, NodeMsg) ->
?event(http, {start_http2, ServerID}),
MaxConnections = maps:get(<<"max-connections">>, NodeMsg, 10000),
NumAcceptors =
maps:get(
<<"num-acceptors">>,
NodeMsg,
erlang:system_info(schedulers) * 4
),
TransportOpts = #{
socket_opts => [{port, RequestedPort = hb_opts:get(port, 0, NodeMsg)}],
max_connections => MaxConnections,
num_acceptors => NumAcceptors
},
StartRes =
cowboy:start_clear(
ServerID,
TransportOpts,
ProtoOpts
),
case StartRes of
{ok, Listener} ->
ActualPort = ranch:get_port(ServerID),
?event(
debug_router_info,
{http2_started,
{listener, Listener},
{requested_port, RequestedPort},
{actual_port, ActualPort}
},
NodeMsg
),
{ok, ActualPort, Listener};
{error, {already_started, Listener}} ->
?event(http, {http2_already_started, {listener, Listener}}),
?event(debug_router_info,
{restarting,
{id, ServerID},
{node_msg, NodeMsg}
}
),
cowboy:set_env(ServerID, node_msg, #{}),
cowboy:stop_listener(ServerID),
start_http2(ServerID, ProtoOpts, NodeMsg)
end.
%% @doc Entrypoint for all HTTP requests. Receives the Cowboy request option and
%% the server ID, which can be used to lookup the node message.
init(Req, ServerID) ->
case cowboy_req:method(Req) of
<<"OPTIONS">> -> cors_reply(Req, ServerID);
_ ->
{ok, Body} = read_body(Req),
handle_request(Req, Body, ServerID)
end.
%% @doc Helper to grab the full body of a HTTP request, even if it's chunked.
read_body(Req) -> read_body(Req, <<>>).
read_body(Req0, Acc) ->
case cowboy_req:read_body(Req0) of
{ok, Data, _Req} -> {ok, << Acc/binary, Data/binary >>};
{more, Data, Req} -> read_body(Req, << Acc/binary, Data/binary >>)
end.
%% @doc Reply to CORS preflight requests.
cors_reply(Req, _ServerID) ->
Req2 = cowboy_req:reply(204, #{
<<"access-control-allow-origin">> => <<"*">>,
<<"access-control-allow-headers">> => <<"*">>,
<<"access-control-allow-methods">> =>
<<"GET, POST, PUT, DELETE, OPTIONS, PATCH">>
}, Req),
?event(debug_http, {cors_reply, {req, Req}, {req2, Req2}}),
{ok, Req2, no_state}.
%% @doc Handle all non-CORS preflight requests as AO-Core requests. Execution
%% starts by parsing the HTTP request into HyerBEAM's message format, then
%% passing the message directly to `meta@1.0' which handles calling AO-Core in
%% the appropriate way.
handle_request(RawReq, Body, ServerID) ->
% Insert the start time into the request so that it can be used by the
% `hb_http' module to calculate the duration of the request.
StartTime = os:system_time(millisecond),
Req = RawReq#{ start_time => StartTime },
NodeMsg = get_opts(#{ <<"http-server">> => ServerID }),
put(server_id, ServerID),
% The request is of normal AO-Core form, so we parse it and invoke
% the meta@1.0 device to handle it.
?event(http,
{
http_inbound,
{cowboy_req, {explicit, Req}, {body, {string, Body}}}
}
),
% Parse the HTTP request into HyerBEAM's message format.
try hb_http:req_to_tabm_singleton(Req, Body, NodeMsg) of
ReqSingleton ->
try
CommitmentCodec =
hb_http:accept_to_codec(ReqSingleton, NodeMsg),
?event(http,
{parsed_singleton,
{req_singleton, ReqSingleton},
{accept_codec, CommitmentCodec}},
#{}
),
% Invoke the meta@1.0 device to handle the request.
Meta =
hb_device:message_to_device(
#{ <<"device">> => <<"meta@1.0">> },
NodeMsg
),
{ok, Res} =
Meta:handle(
NodeMsg#{
<<"commitment-device">> => CommitmentCodec
},
ReqSingleton
),
hb_http:reply(Req, ReqSingleton, Res, NodeMsg)
catch
Type:Details:Stacktrace ->
handle_error(
Req,
ReqSingleton,
Type,
Details,
Stacktrace,
NodeMsg
)
end
catch ParseError:ParseDetails:ParseStacktrace ->
handle_error(
Req,
#{},
ParseError,
ParseDetails,
ParseStacktrace,
NodeMsg
)
end.
%% @doc Return a 500 error response to the client.
handle_error(Req, Singleton, Type, Details, Stacktrace, NodeMsg) ->
DetailsStr = hb_util:bin(hb_format:message(Details, NodeMsg, 1)),
StacktraceStr = hb_util:bin(hb_format:trace(Stacktrace)),
ErrorMsg =
#{
<<"status">> => 500,
<<"type">> => hb_util:bin(hb_format:message(Type)),
<<"details">> => DetailsStr,
<<"stacktrace">> => StacktraceStr
},
ErrorBin = hb_format:error(ErrorMsg, NodeMsg),
?event(
http_error,
{returning_500_error,
{method, cowboy_req:method(Req)},
{path, {string, cowboy_req:path(Req)}},
{string,
hb_format:indent_lines(
<<"\n", ErrorBin/binary, "\n">>,
1
)
}
},
NodeMsg
),
ErrorDetailsMaxSize = hb_opts:get(error_details_max_size, ?DEFAULT_ERROR_DETAILS_MAX_SIZE, NodeMsg),
% Remove leading and trailing noise from the stacktrace and details.
FormattedErrorMsg =
ErrorMsg#{
<<"stacktrace">> => hb_util:bin(hb_format:remove_noise(StacktraceStr)),
<<"details">> => hb_format:truncate(hb_util:bin(hb_format:remove_noise(DetailsStr)), ErrorDetailsMaxSize)
},
hb_http:reply(Req, Singleton, FormattedErrorMsg, NodeMsg).
%% @doc Return the list of allowed methods for the HTTP server.
allowed_methods(Req, State) ->
{
[<<"GET">>, <<"POST">>, <<"PUT">>, <<"DELETE">>, <<"OPTIONS">>, <<"PATCH">>],
Req,
State
}.
%% @doc Merges the provided `Opts' with uncommitted values from `Request',
%% preserves the http-server value, and updates node-history by prepending
%% the `Request'. If a server reference exists, updates the Cowboy environment
%% variable 'node_msg' with the resulting options map.
set_opts(Opts) ->
case hb_opts:get(http_server, no_server_ref, Opts) of
no_server_ref ->
ok;
ServerRef ->
ok = cowboy:set_env(ServerRef, node_msg, Opts)
end.
set_opts(Request, Opts) ->
PreparedOpts = Opts,
PreparedRequest = hb_message:uncommitted(Request),
MergedOpts =
maps:merge(
PreparedOpts,
PreparedRequest
),
?event(set_opts, {merged_opts, {explicit, MergedOpts}}),
History =
hb_opts:get(node_history, [], Opts)
++
[
hb_private:reset(
maps:without([<<"node-history">>], PreparedRequest)
)
],
FinalOpts = MergedOpts#{
<<"http-server">> => hb_opts:get(http_server, no_server, Opts),
<<"node-history">> => History
},
{set_opts(FinalOpts), FinalOpts}.
%% @doc Get the node message for the current process.
get_opts() ->
get_opts(#{ <<"http-server">> => get(server_id) }).
get_opts(NodeMsg) ->
ServerRef = hb_opts:get(http_server, no_server_ref, NodeMsg),
cowboy:get_env(ServerRef, node_msg, no_node_msg).
%% @doc Initialize the server ID for the current process.
set_proc_server_id(ServerID) ->
put(server_id, ServerID).
%% @doc Apply the default node message to the given opts map.
set_default_opts(Opts) ->
% Create a temporary opts map that does not include the defaults.
TempOpts = Opts#{ <<"only">> => local },
% Get the port to use for the server. If no port is provided, we use port 0
% will the operating system assign a free port.
Port = hb_opts:get(port, 0, TempOpts),
Wallet =
case hb_opts:get(priv_wallet, no_viable_wallet, TempOpts) of
no_viable_wallet -> ar_wallet:new();
PassedWallet -> PassedWallet
end,
Store =
case hb_opts:get(store, no_store, TempOpts) of
no_store ->
hb_store:start(Stores = [hb_test_utils:test_store()]),
Stores;
PassedStore -> PassedStore
end,
?event({set_default_opts,
{given, TempOpts},
{port, Port},
{store, Store},
{priv_wallet, Wallet}
}),
Opts#{
<<"port">> => Port,
<<"store">> => Store,
<<"priv-wallet">> => Wallet,
<<"address">> => hb_util:human_id(ar_wallet:to_address(Wallet)),
<<"force-signed">> => true
}.
%% @doc Test that we can start the server, send a message, and get a response.
start_node() ->
start_node(#{}).
start_node(Opts) ->
application:ensure_all_started([
kernel,
stdlib,
inets,
ssl,
ranch,
cowboy,
gun,
os_mon
]),
hb:init(),
hb_sup:start_link(Opts),
ServerOpts = set_default_opts(Opts),
ok = hb_process_sampler:ensure_started(ServerOpts),
ok = hb_system_monitor:ensure_started(ServerOpts),
{ok, _Listener, Port} = new_server(ServerOpts),
<<"http://localhost:", (hb_util:bin(Port))/binary, "/">>.
%%% Tests
%%% The following only covering the HTTP server initialization process. For tests
%%% of HTTP server requests/responses, see `hb_http.erl'.
%% @doc Ensure that the `start' hook can be used to modify the node options. We
%% do this by creating a message with a device that has a `start' key. This
%% key takes the message's body (the anticipated node options) and returns a
%% modified version of that body, which will be used to configure the node. We
%% then check that the node options were modified as we expected.
set_node_opts_test() ->
Node =
start_node(#{
<<"on">> => #{
<<"start">> => #{
<<"device">> =>
#{
<<"start">> =>
fun(_, #{ <<"body">> := NodeMsg }, _) ->
{ok, #{
<<"body">> =>
NodeMsg#{ <<"test-success">> => true }
}}
end
}
}
}
}),
{ok, LiveOpts} = hb_http:get(Node, <<"/~meta@1.0/info">>, #{}),
?assert(hb_ao:get(<<"test-success">>, LiveOpts, false, #{})).
%% @doc Test the set_opts/2 function that merges request with options,
%% manages node history, and updates server state.
set_opts_test() ->
DefaultOpts = hb_opts:default_message_with_env(),
start_node(DefaultOpts#{
<<"priv-wallet">> => Wallet = ar_wallet:new(),
<<"port">> => rand:uniform(10000) + 10000
}),
Opts = get_opts(#{
<<"http-server">> => hb_util:human_id(ar_wallet:to_address(Wallet))
}),
NodeHistory = hb_opts:get(node_history, [], Opts),
?event(debug_node_history, {node_history_length, length(NodeHistory)}),
?assert(length(NodeHistory) == 0),
% Test case 1: Empty node-history case
Request1 = #{
<<"hello">> => <<"world">>
},
{ok, UpdatedOpts1} = set_opts(Request1, Opts),
NodeHistory1 = hb_opts:get(node_history, not_found, UpdatedOpts1),
Key1 = hb_opts:get(<<"hello">>, not_found, UpdatedOpts1),
?event(debug_node_history, {node_history_length, length(NodeHistory1)}),
?assert(length(NodeHistory1) == 1),
?assert(Key1 == <<"world">>),
% Test case 2: Non-empty node-history case
Request2 = #{
<<"hello2">> => <<"world2">>
},
{ok, UpdatedOpts2} = set_opts(Request2, UpdatedOpts1),
NodeHistory2 = hb_opts:get(node_history, not_found, UpdatedOpts2),
Key2 = hb_opts:get(<<"hello2">>, not_found, UpdatedOpts2),
?event(debug_node_history, {node_history_length, length(NodeHistory2)}),
?assert(length(NodeHistory2) == 2),
?assert(Key2 == <<"world2">>),
% Test case 3: Non-empty node-history case
{ok, UpdatedOpts3} = set_opts(#{}, UpdatedOpts2#{ <<"hello3">> => <<"world3">> }),
NodeHistory3 = hb_opts:get(node_history, not_found, UpdatedOpts3),
Key3 = hb_opts:get(<<"hello3">>, not_found, UpdatedOpts3),
?event(debug_node_history, {node_history_length, length(NodeHistory3)}),
?assert(length(NodeHistory3) == 3),
?assert(Key3 == <<"world3">>).
restart_server_test() ->
% We force HTTP2, overriding the HTTP3 feature, because HTTP3 restarts don't work yet.
Wallet = ar_wallet:new(),
BaseOpts = #{
<<"test-key">> => <<"server-1">>,
<<"priv-wallet">> => Wallet,
<<"protocol">> => http2
},
_ = start_node(BaseOpts),
N2 = start_node(BaseOpts#{ <<"test-key">> => <<"server-2">> }),
?assertEqual(
{ok, <<"server-2">>},
hb_http:get(N2, <<"/~meta@1.0/info/test-key">>, #{ <<"protocol">> => http2 })
).