-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.pl
467 lines (408 loc) · 15.4 KB
/
server.pl
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
:- module(server, [server/1, shutdown/1, server/2]).
%% Load this file in prolog, and use server(Port). to launch it.
:- use_module(library(http/thread_httpd)).
:- use_module(library(http/http_dispatch)).
:- use_module(library(http/http_error)).
:- use_module(library(http/http_parameters)).
:- use_module(library(http/http_json)).
:- use_module(library(http/json)).
:- use_module(library(http/html_write)).
:- use_module(library(http/http_files)).
:- use_module(function).
:- use_module(function/parse).
:- use_module(function/serde).
:- use_module(constraints, [and_constraint/5, no_constraint/3]).
:- use_module(string_constraints, [add_string_constraint/5]).
:- use_module(func_constraints).
:- use_module(path_constraints).
:- use_module(search).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Register handlers
:- http_handler(
root(openapi),
openapi,
[method(get)]
).
:- http_handler(
root(.),
http_reply_from_files('./web_content', []),
[prefix]
).
:- http_handler(
root(func),
fn_endpoint(Method),
[method(Method), methods([get, post, delete])]
).
:- http_handler(
root(type),
type_endpoint(Method),
[method(Method), methods([get, post, delete])]
).
:- http_handler(
root(path),
path_endpoint,
[method(get)]
).
:- http_handler(
root(main),
main_endpoint,
[method(get)]
).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Starting and stopping server
suppress_start_msg :-
getenv('IN_DOCKER', '1').
server(Port, silent) :- http_server(http_dispatch, [port(Port), silent(true)]), !.
server(Port) :- suppress_start_msg,
http_server(http_dispatch, [port(Port), silent(true)]), !.
server(Port) :- \+suppress_start_msg,
http_server(http_dispatch, [port(Port), silent(true)]),
ansi_format([fg(blue)], 'Started server at ', []),
ansi_format([bold, fg(blue)], 'http://localhost:~w/~n', [Port]),
ansi_format([fg(blue)], 'Go to ', []),
ansi_format([bold, fg(blue)], 'http://localhost:~w/openapi', [Port]),
ansi_format([fg(blue)], ' to interact with the OpenAPI specification~n', []),
ansi_format([fg(blue)], 'Go to ', []),
ansi_format([bold, fg(blue)], 'http://localhost:~w/main', [Port]),
ansi_format([fg(blue)], ' to interact with the application~n', []).
shutdown(Port) :- http_stop_server(Port, []).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Hide unconstrained variables.
render_param(Param, "?") :- var(Param), !.
render_param(Param, Param) :- !.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Defining, searching, and deleting functions
%% Finds a single function with the constraints and prints it.
find_and_fmt_func(Constraint) :-
find_items(Constraint, [Fn|Fns]),
jsonify_fns([Fn|Fns], JsonFuncs),
reply_json_dict(_{msg:"Found functions", functions: JsonFuncs}), !.
find_and_fmt_func(_) :-
format('Status: 404~n'), % Not found
format('Content-type: application/json~n~n'),
json_write_dict(current_output, _{msg:"Functions matching query not found"}), !.
%% Helper for correctly constraining lists.
nonempty_list([], true, []) :- !.
nonempty_list([], false, _) :- !.
nonempty_list(NonEmpty, _, NonEmpty) :- !.
%% Parses parameters for search requests.
% Can be partially specified
parse_func_search_request(Request, Constraint) :-
Choices = [re, eq, lev, substr, subseq, fsubstr, sim, subsim],
http_parameters(Request,
[
name(Name, [string, default(none)]),
name_cmp(NameCmp, [default(lev), oneof(Choices)]),
docs(Docs, [string, default(none)]),
doc_cmp(DocCmp, [default(substr), oneof(Choices)]),
uuid(Uuid, [atom, default(none)]),
uuid_cmp(UuidCmp, [default(eq), oneof(Choices)]),
inputs(Inputs0, [list(string)]),
no_inputs(NoInputs, [boolean, default(false)]),
outputs(Outputs0, [list(string)]),
no_outputs(NoOutputs, [boolean, default(false)])
]),
nonempty_list(Inputs0, NoInputs, Inputs),
nonempty_list(Outputs0, NoOutputs, Outputs),
fn_member_constraint(Fns),
add_string_constraint(function:func_field(name), Name, NameCmp, Fns, C0),
add_string_constraint(function:func_field(docs), Docs, DocCmp, C0, C1),
add_string_constraint(function:func_field(uuid), Uuid, UuidCmp, C1, C2),
Constraint = constraints:and_constraint(
C2,
constraints:and_constraint(
func_constraints:input_constraint(Inputs),
func_constraints:output_constraint(Outputs)
)
).
%% Gets and deletes the function - if it is specialized, errors and informs
%% the client to delete the parent uuid if they'd like.
attempt_fn_deletion(Uuid) :-
specialized(Parent, Uuid),
format('Status: 405~n'), % HTTP not allowed
format('Content-type: application/json~n~n'),
json_write_dict(current_output,
_{
msg:"Can not remove specialization - try deleting parent uuid",
parent_uuid:Parent
}
), !.
attempt_fn_deletion(Uuid) :-
get_function(Uuid, Fn),
retractall(Fn),
findall(
Child,
(
specialized(Uuid, Child),
retractall(specialized(Uuid, Child)),
retractall(function(Child, _, _, _, _, _))
),
Children
),
reply_json_dict(_{msg: "Removed", uuids:[Uuid|Children]}), !.
attempt_fn_deletion(Uuid) :-
format('Status: 404~n'), % Not found
format('Content-type: application/json~n~n'),
json_write_dict(current_output,
_{
msg:"Uuid not found",
uuid:Uuid
}
).
%% Function endpoint
fn_endpoint(get, Request) :-
parse_func_search_request(Request, Constraint),
find_and_fmt_func(Constraint).
fn_endpoint(post, Request) :-
http_read_json(Request, JsonIn, [json_object(dict)]),
jsonify_fns([Fn], [JsonIn]),
Fn = function(Uuid, Name, Generics, Inputs, Outputs, Docs),
add_function(Uuid, Name, Generics, Inputs, Outputs, Docs),
format(string(Msg), "Created func ~w", [Name]),
reply_json_dict(_{msg: Msg, uuid:Uuid}).
fn_endpoint(delete, Request) :-
http_parameters(Request, [
uuid(Uuid, [atom])
]),
attempt_fn_deletion(Uuid).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Defining, searching, and deleting types
parse_type_search_request(Request, C2) :-
Choices = [re, eq, lev, substr, subseq, fsubstr, sim, subsim],
http_parameters(Request, [
name(Name, [string, default(none)]),
name_cmp(NameCmp, [default(lev), oneof(Choices)]),
docs(Docs, [string, default(none)]),
doc_cmp(DocCmp, [default(substr), oneof(Choices)]),
uuid(Uuid, [atom, default(none)]),
uuid_cmp(UuidCmp, [default(eq), oneof(Choices)])
]),
add_string_constraint(type_field(name), Name, NameCmp, no_constraint, C0),
add_string_constraint(type_field(docs), Docs, DocCmp, C0, C1),
add_string_constraint(type_field(uuid), Uuid, UuidCmp, C1, C2).
find_and_fmt_types(Constraint) :-
find_items(Constraint, [Uuid|Uuids]),
maplist(get_type, [Uuid|Uuids], Types),
jsonify_types(Types, JsonTypes),
reply_json_dict(_{msg:"Found types", types: JsonTypes}), !.
find_and_fmt_types(_) :-
format('Status: 404~n'), % Not found
format('Content-type: application/json~n~n'),
json_write_dict(current_output, _{msg:"Types matching query not found"}), !.
attempt_type_deletion(Uuid) :-
type(Uuid, Name, Generics, Impls, Docs),
retractall(type(Uuid, Name, Generics, Impls, Docs)),
reply_json_dict(_{msg: "Removed type", uuid:Uuid}), !.
attempt_type_deletion(Uuid) :-
format('Status: 404~n'), % Not found
format('Content-type: application/json~n~n'),
json_write_dict(current_output,
_{
msg:"Uuid not found",
uuid:Uuid
}
).
type_endpoint(get, Request) :-
parse_type_search_request(Request, Constraint),
find_and_fmt_types(Constraint).
type_endpoint(post, Request) :-
http_read_json(Request, JsonIn, [json_object(dict)]),
jsonify_type(Ty, JsonIn),
Ty = type(Uuid, Name, Generics, Impls, Docs),
add_type(Uuid, Name, Generics, Impls, Docs),
format(string(Msg), "Created type ~w", [Name]),
reply_json_dict(_{msg: Msg, uuid:Uuid}), !.
type_endpoint(post, _) :-
format('Status: 400~n'), % User error
format('Content-type: application/json~n~n'),
json_write_dict(current_output, _{msg: "Malformed input"}).
type_endpoint(delete, Request) :-
http_parameters(
Request,
[uuid(Uuid, [atom])]
),
attempt_type_deletion(Uuid).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% OpenAPI endpoint
%% favicon generated using https://redketchup.io/favicon-generator
openapi(_) :-
reply_html_page(
\['<!doctype html>\n'],
[
title('FastFunc OpenAPI'),
\['<meta charset="utf-8">'],
script(
[
type='module',
src='https://unpkg.com/rapidoc/dist/rapidoc-min.js'
],
[]
),
\['<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">'],
\['<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">'],
\['<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">'],
\['<link rel="manifest" href="/site.webmanifest">']
],
[
\['<rapi-doc spec-url="./openapi.json"></rapi-doc>']
]
).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Path endpoint
add_cycle_constraint(true, Constraint, Constraint).
add_cycle_constraint(
false,
Constraint,
constraints:and_constraint(
constraints:cycle_constraint(function:uuid, []),
Constraint
)
).
parse_path_search_request(Request, Strategy, FnConstraint, path_constraints:output_constraint(Outputs)) :-
Choices = [re, eq, lev, substr, subseq, fsubstr, sim, subsim],
http_parameters(Request,
[
name(Name, [string, default(none)]),
name_cmp(NameCmp, [default(lev), oneof(Choices)]),
docs(Docs, [string, default(none)]),
doc_cmp(DocCmp, [default(substr), oneof(Choices)]),
uuid(Uuid, [atom, default(none)]),
uuid_cmp(UuidCmp, [default(eq), oneof(Choices)]),
inputs(Inputs0, [list(string)]),
no_inputs(NoInputs, [boolean, default(false)]),
outputs(Outputs0, [list(string)]),
no_outputs(NoOutputs, [boolean, default(false)]),
path_length(Length, [integer, default(999)]),
strategy(Strategy, [oneof(dfs, bfs, bestfs), default(dfs)]),
cycles(Cycles, [boolean, default(false)])
% this would be cool to have if we could figure out a good way to do pagination.
% num_paths(Num, [integer, default(25)])
]),
nonempty_list(Inputs0, NoInputs, Inputs),
nonempty_list(Outputs0, NoOutputs, Outputs),
fn_member_constraint(Fns),
% String cmp methods
add_string_constraint(function:func_field(name), Name, NameCmp, Fns, C0),
add_string_constraint(function:func_field(docs), Docs, DocCmp, C0, C1),
add_string_constraint(function:func_field(uuid), Uuid, UuidCmp, C1, C2),
% Cycles + inputs
add_cycle_constraint(Cycles, func_constraints:input_constraint(Inputs), C3),
FnConstraint = constraints:and_constraint(C2,
constraints:and_constraint(
C3,
% Path length
constraints:at_most_n_constraint(Length, no_constraint)
)
).
%% Helpers for extracting a list of unique UUIDS
add_fn(Fn, Assoc, Out) :-
uuid(Fn, Uuid),
put_assoc(Uuid, Assoc, Fn, Out).
unique_fns(Paths, UniqueFns) :-
empty_assoc(Assoc),
foldl(foldl(add_fn), Paths, Assoc, Final),
assoc_to_values(Final, UniqueFns).
path_to_uuids(Path, Uuids) :-
maplist(function:uuid, Path, Uuids).
paths_to_uuids(Paths, Uuids) :-
maplist(path_to_uuids, Paths, Uuids).
%% Produces JSON data which contains a list of paths of function UUIDs, and the
%% actual functions, as well as a message.
find_and_fmt_paths(Strategy, FnConstraint, PathConstraint) :-
time((
findall(
Path,
func_path_init(Strategy, FnConstraint, PathConstraint, Path),
FnPaths
),
unique_fns(FnPaths, Fns),
paths_to_uuids(FnPaths, PathsU),
list_to_set(PathsU, Paths)
)),
length(Paths, PLen),
PLen >= 1,
jsonify_fns(Fns, JsonFns),
length(Fns, FLen),
format(string(Msg), "Found ~w paths (~w functions)", [PLen, FLen]),
reply_json_dict(_{msg:Msg, paths: Paths, functions:JsonFns}), !.
find_and_fmt_paths(_, _, _) :-
format('Status: 404~n'), % Not found
format('Content-type: application/json~n~n'),
json_write_dict(current_output, _{msg:"Paths matching query not found"}), !.
path_endpoint(Request) :-
parse_path_search_request(Request, Strategy, FnConstraint, PathConstraint),
find_and_fmt_paths(Strategy, FnConstraint, PathConstraint).
%%
:- use_module(library(st/st_render)).
:- use_module(function/parse).
pluralize(1, Unplural, _, Unplural).
pluralize(N, _, Plural, Plural) :- N \= 1.
%% Turns the function into JSON, plus signature.
fn_json(
fn(Fn),
JSON
) :-
jsonify_fn(
Fn,
JSONA
),
format_signature(Fn, Signature),
JSONB = JSONA.put(signature, Signature),
JSON = JSONB.put(generic, 0).
fn_json(
gfn(Fn, Signatures),
JSON
) :-
jsonify_fn(
Fn,
JSONA
),
format_signature(Fn, Signature),
JSONB = JSONA.put(signature, Signature),
JSONC = JSONB.put(generic, 1),
JSON = JSONC.put(specializations, Signatures).
%%
get_all_specializations(_, [], [], _) :- !.
get_all_specializations(SUuid, [Fn|Rest], [Signature|SigRest], Rem) :-
func_field(uuid, Fn, Uuid),
specialized(SUuid, Uuid), !,
format_signature(Fn, Signature), !,
get_all_specializations(SUuid, Rest, SigRest, Rem), !.
get_all_specializations(SUuid, [Fn|Rest], [], [Fn|Rest]) :-
func_field(uuid, Fn, Uuid),
\+specialized(SUuid, Uuid), !.
most_general_fns([], []).
most_general_fns([Fn|RestFn], [fn(Fn)|Rest]) :-
func_field(uuid, Fn, Uuid),
\+specialized(_, Uuid),
most_general_fns(RestFn, Rest).
most_general_fns([Fn|RestFn], [gfn(SFn, Signatures)|Rest]) :-
func_field(uuid, Fn, Uuid),
specialized(SUuid, Uuid),
get_function(SUuid, SFn),
get_all_specializations(SUuid, [Fn|RestFn], Signatures, Rem),
most_general_fns(Rem, Rest).
main_page(JSON) :-
current_output(Out),
format('Status: 200~n'),
format('Content-type: text/html~n~n'),
st_render_file('web_content/main_template', JSON, Out, []).
find_and_fmt_func_template(Constraint) :-
find_items(Constraint, [Fn|Fns]),
most_general_fns([Fn|Fns], GenFns), !,
maplist(fn_json, GenFns, JsonFns),
length(GenFns, N),
pluralize(N, "function", "functions", Pl),
format(string(Msg), "<h2>Found ~w ~w</h2>", [N, Pl]),
main_page(_{
msg: Msg,
functions: JsonFns
}), !.
find_and_fmt_func_template(_) :-
main_page(_{
msg: "<h2 style=\"color:red\">Functions matching query not found</h2>",
functions: []
}).
main_endpoint(Request) :-
parse_func_search_request(Request, Constraint),
find_and_fmt_func_template(Constraint).