/
apigenlib.opa
1829 lines (1659 loc) · 68.4 KB
/
apigenlib.opa
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
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright © 2012 MLstate
This file is part of Opa.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* Support code for apigen.
*
* @category web
* @author Norman Scaife, 2012
* @destination public
* @stability Work in progress
*/
import stdlib.core.wbxml
import stdlib.apis.common
import stdlib.apis.oauth
import stdlib.io.socket
import stdlib.crypto
type Apigen.expected_type =
{BOOL}
or {INT}
or {OBJECT}
or {LIST}
type Apigen.content =
{xml_document xmldoc}
or {xmlns xmlns}
or {xhtml xhtml}
or {string plain}
or {binary binary}
or {(string,string) unknown}
or {(string,binary) unknown_binary}
or {none}
type Apigen.failure =
{string bad_path}
or {WebClient.failure network}
or {RPC.Json.json error_json}
or {RPC.Json.json bad_json}
or {string post_process}
or {string socket}
or {string pack}
or {string bad_xml}
or {string bad_wbxml}
or {Apigen.content bad_content}
or {string error}
or {xhtml error_html}
type Apigen.outcome('a) = outcome('a,Apigen.failure)
type ApigenAuth.credentials = {
string access_token,
string access_secret
}
type ApigenLib.auth =
{string user, string password}
or {none}
type ApigenLib.general_value =
{string String}
or {int Int}
or {bool Bool}
or {float Float}
or {binary Binary}
or {Date.date Datetime}
or {string Base64}
or {bool Numbool}
or {xmlns Verbatim}
or {list(ApigenLib.general_value) List}
or {ApigenLibXml.simple_seq Nested}
or {Empty}
type ApigenLibXml.simple_seq = list((string,ApigenLib.general_value))
private (binary -> string) bindump = %% BslPervasives.bindump %%
private (string -> string) memdump = %% BslPervasives.memdump %%
function Ansi_print(colour, str) {
Ansi.print(colour,str)
//_ = colour; str
}
module ApigenOauth(OAuth.parameters params) {
function alOAuth(http_method) { OAuth({params with ~http_method}) }
private function generic(string base, string path, wget_fun, parse_fun) {
API_libs_private.apijlog("ApigenOauth.generic: uri={base}{path}")
(t, res) = Duration.execution_time(function () { wget_fun("{base}{path}") })
match (res) {
case {success:res}:
API_libs_private.apijlog("ApigenOauth.generic: got={res}")
API_libs_private.apijlog("Download: {Duration.in_seconds(t)} seconds")
(t, res) = Duration.execution_time(function () { parse_fun(res.content) })
API_libs_private.apijlog("ApigenOauth.generic: parsed={res}")
API_libs_private.apijlog("Parsing: {Duration.in_seconds(t)} seconds")
res
case {failure:f}:
API_libs_private.apijlog("ApigenOauth.generic: Network failure {f}")
{failure:{network:f}}
}
}
function GET(base, path, params, ApigenAuth.credentials credentials, parse_fun) {
function f(uri) { alOAuth({GET}).get_protected_resource_2(uri,params,credentials.access_token,credentials.access_secret) }
generic(base, path, f, parse_fun)
}
function POST(base, path, params, content, ApigenAuth.credentials credentials, parse_fun) {
_ = content
function f(uri) { alOAuth({POST}).get_protected_resource_2(uri,params,credentials.access_token,credentials.access_secret) }
generic(base, path, f, parse_fun)
}
}
type ApigenLib.logpkg = {
int debug,
(string -> void) logfn
}
module ApigenLib {
debug = Mutable.make(0)
private tzfmt = Date.generate_printer("%z")
private fmt = Date.generate_printer("%FT%T")
function date_to_string(Date.date d) {
tz = Date.to_formatted_string(tzfmt, d)
tz =
match (String.length(tz)) {
case 4: String.sub(0,2,tz)^":"^String.sub(2,2,tz)
case 5: String.sub(0,3,tz)^":"^String.sub(3,2,tz)
default: tz
}
"{Date.to_formatted_string(fmt, d)}{tz}"
}
// YYYY-MM-DDTHH:MM:SS.MSSZ
private date2fmtstr = "%FT%T.%xZ"
private fmtp2 = Date.generate_printer(date2fmtstr)
function date_to_string2(Date.date d) { Date.to_formatted_string(fmtp2, d) }
private fmts2 = Date.generate_scanner(date2fmtstr)
function date_of_string2(string s) { Date.of_formatted_string(fmts2, s) }
// 2006-01-17T00:00:00Z
private date3fmtstr = "%FT%TZ"
private fmtp3 = Date.generate_printer(date2fmtstr)
function date_to_string3(Date.date d) { Date.to_formatted_string(fmtp3, d) }
private fmts3 = Date.generate_scanner(date3fmtstr)
function date_of_string3(string s) { Date.of_formatted_string(fmts3, s) }
private function generic_build_path(path, options) {
if (options == []) path else "{path}?{API_libs.form_urlencode(options)}"
}
function authentication(http_options, ApigenLib.auth auth) {
match (auth) {
case ~{user, password}:
auth = Crypto.Base64.encode(binary_of_string("{user}:{password}"))
{http_options with custom_headers:List.append(http_options.custom_headers,["Authorization: Basic {auth}"])};
//{http_options with headers:List.append(http_options.headers,[("Authorization","Basic {auth}")])};
default: http_options;
}
}
/**
* Make a HTTP GET on [path] at [base] with [options]
*/
function GET(base, path, options, parse_fun) {
final_path = generic_build_path("{base}{path}", options)
//API_libs_private.apijlog("GET {final_path}")
match (Uri.of_string(final_path)) {
case {none}: {failure:{bad_path:final_path}}
case {some:uri}:
match (WebClient.Get.try_get(uri)) {
case {success:res}: parse_fun(res)
case {failure:f}: {failure:{network:f}}
}
}
}
function content_only(res) {
match (res) {
case {failure:f}: {failure:{network:f}}
case {success:s}: /*API_libs_private.apijlog("HTTP {s.code}\n{s.content}");*/ {success:s.content}
}
}
// header_get doesn't work on node.
private function find_header(name,headers) {
List.fold(function (h, acc) {
if (String.has_prefix(name,h)) {
len = String.length(name)
{some:String.sub(len+2,String.length(h)-(len+2),h)}
} else acc
},headers,none)
}
function content_with_type(res) {
match (res) {
case {failure:f}: {failure:{network:f}}
case {success:s}:
//API_libs_private.apijlog("hdrs=\n{String.concat("\n",s.headers)}")
content_type = Option.default("unknown/unknown",find_header("content-type",s.headers))
location = Option.default("",find_header("location",s.headers))
//API_libs_private.apijlog("HTTP {s.code} type={content_type} location={location}")
{success:(content_type,location,s.content)}
}
}
function redirect(res) {
match (res) {
case {failure:f}: {failure:{network:f}}
case {success:s}:
//API_libs_private.apijlog("HTTP {s.code}")
if (s.code == 302) {
match (find_header("location",s.headers)) {
case {some:hdr}: {success:hdr}
default: {failure:{post_process:"header location not found"}}
}
} else {failure:{bad_code:s.code}}
}
}
function bool islog(ApigenLib.logpkg logpkg, level) { logpkg.debug >= level }
function void dolog(ApigenLib.logpkg logpkg, string msg) { logpkg.logfn(msg) }
private POSTstr = Ansi_print({magenta},"POST")
private function hdrstr(string hdr) {
match (String.explode(":",hdr)) {
case [hdr,text]: "{Ansi_print({blue},hdr)}: {text}";
case [hdr|rest]: "{Ansi_print({blue},hdr)}: {String.concat(":",rest)}";
default: hdr;
}
}
/**
* Make a HTTP POST on [path] at [base] with string [data]
*/
function POST_GENERIC(ApigenLib.logpkg logpkg, string base, string path, list((string,string)) options,
ApigenLib.auth auth, WebClient.Post.options(string) http_options, parse_fun) {
//ApigenLib.auth auth, WebClient.options(binary) http_options, parse_fun) {
//API_libs_private.apijlog("POST {base}{path}\n{http_options.content}\n")
final_path = generic_build_path("{base}{path}", options)
match (Uri.of_string(final_path)) {
case {none}:
if (islog(logpkg,10)) dolog(logpkg,"ApigenLib: {Ansi_print({red},"Bad path {final_path}")}")
{failure:{bad_path:final_path}};
case {some:uri}:
//http_options = {http_options with method:"POST"}
http_options = authentication(http_options, auth)
if (logpkg.debug >= 10) {
if (islog(logpkg,10)) dolog(logpkg,"ApigenLib: {POSTstr} {uri}")
if (islog(logpkg,11)) {
dolog(logpkg,"ApigenLib: {hdrstr("Content-Type: {http_options.mimetype}")}")
List.iter(function (hdr) { dolog(logpkg,"ApigenLib: {hdrstr(hdr)}") },http_options.custom_headers)
}
if (Option.is_some(http_options.content) && islog(logpkg,12))
dolog(logpkg,"ApigenLib: content=\n{memdump(Option.get(http_options.content))}")
}
match (WebClient.Post.try_post_with_options(uri,http_options)) {
//match (WebClient.request(uri,http_options)) {
case {success:res}:
if (logpkg.debug >= 10) {
if (islog(logpkg,10)) dolog(logpkg,"ApigenLib: {Ansi_print({magenta},"{res.code}")}")
if (islog(logpkg,11)) List.iter(function (hdr) { dolog(logpkg,"ApigenLib: {hdrstr(hdr)}") },res.headers)
if (islog(logpkg,12)) dolog(logpkg,"ApigenLib: content=\n{memdump(res.content)}")
}
parse_fun(res)
case {failure:f}:
if (islog(logpkg,10)) dolog(logpkg,"ApigenLib: {Ansi_print({red},"Network failure {f}")}")
{failure:{network:f}}
}
}
}
/**
* Make a HTTP POST on [path] at [base] with string [content]
*/
function POST(ApigenLib.logpkg logpkg, base, path, options, content, auth, parse_fun) {
POST_GENERIC(logpkg, base, path, options, auth, {WebClient.Post.default_options with content:{some:content}}, parse_fun)
//POST_GENERIC(base, path, options, auth, {WebClient.default_options with content:{some:content}}, parse_fun)
}
/**
* Make a HTTP POST on [path] at [base] with form [data]
*/
function POST_FORM(ApigenLib.logpkg logpkg, base, path, options, data, auth, parse_fun) {
content = API_libs.form_urlencode(data)
POST_GENERIC(logpkg, base, path, options, auth, {WebClient.Post.default_options with content:{some:content}}, parse_fun)
//content = binary_of_string(API_libs.form_urlencode(data))
//POST_GENERIC(base, path, options, auth, {WebClient.default_options with content:{some:content}}, parse_fun)
}
/**
* Make a HTTP POST on [path] at [base] with string [xmlns]
*/
function POST_XML(ApigenLib.logpkg logpkg, base, path, options, timeout, auth, custom_headers, xmlns, parse_fun) {
http_options = {WebClient.Post.default_options with mimetype:"text/xml", ~custom_headers, content:{some:xmlns}}
http_options =
match (timeout) {
case {none}: http_options;
case timeout_sec: {http_options with ~timeout_sec};
}
POST_GENERIC(logpkg, base, path, options, auth, http_options, parse_fun)
//headers = [("Content-Type","text/xml")|custom_headers]
//http_options = {WebClient.default_options with ~headers, content:{some:xmlns}}
//POST_GENERIC(base, path, options, auth, http_options, parse_fun)
}
/**
* Make a HTTP POST on [path] at [base] with string [xmlns]
*/
function POST_WBXML(ApigenLib.logpkg logpkg, base, path, options, timeout, auth, custom_headers, wbxml, parse_fun) {
http_options = {WebClient.Post.default_options with mimetype:"application/vnd.ms-sync.wbxml",
~custom_headers,
content:{some:wbxml}}
http_options =
match (timeout) {
case {none}: http_options;
case timeout_sec: {http_options with ~timeout_sec};
}
POST_GENERIC(logpkg, base, path, options, auth, http_options, parse_fun)
//headers = [("Content-Type","application/vnd.ms-sync.wbxml")|custom_headers]
//http_options = {WebClient.default_options with ~headers, content:{some:wbxml}}
//POST_GENERIC(base, path, options, auth, http_options, parse_fun)
}
/** Generic http operation */
private function WebClient.Generic.options default_options(op) {
{ operation : op,
auth : {none},
custom_headers : [],
custom_agent : {none},
redirect : {none},
timeout_sec : {some:36.0},
ssl_key : {none},
ssl_policy : {none}
}
}
private function void try_generic_with_options_async(string op, Uri.uri location, string content,
WebClient.Generic.options options,
(WebClient.result(string) -> void) on_result) {
generic_options = { options with
operation : op,
custom_headers : ["Content-Length: {String.length(content)}"]++options.custom_headers
}
function on_success(x) { on_result({success:x}) }
function on_failure(x) { on_result({failure:x}) }
WebClient.Generic.try_request_with_options_async(location, op, generic_options, {some:content}, on_success, on_failure)
}
private function WebClient.result(string) try_generic_with_options(string op, Uri.uri location,
string content, WebClient.Generic.options options) {
@callcc(function (k) {
function on_result(x) { Continuation.return(k, x) }
try_generic_with_options_async(op, location, content, options, on_result)
})
}
private function WebClient.result(string) try_generic(string op, Uri.uri location, string content) {
try_generic_with_options(op, location, content, default_options(op))
}
/**
* Make a HTTP OPTIONS on [path] at [base] with form [data]
*/
function try_options(location, content) { try_generic("OPTIONS", location, content) }
function try_options_with_options(location, content, options) {
try_generic_with_options("OPTIONS", location, content, options)
}
/**
* Make a HTTP OPTIONS on [path] at [base] with string [data]
*/
function OPTIONS(base, path, options, http_options, content, parse_fun) {
//API_libs_private.apijlog("OPTIONS {base}{path}\n{content}\n")
final_path = generic_build_path("{base}{path}", options)
match (Uri.of_string(final_path)) {
case {none}: {failure:{bad_path:final_path}};
case {some:uri}:
match (try_options_with_options(uri,content, http_options)) {
case {success:res}: parse_fun(res)
case {failure:f}: {failure:{network:f}}
}
}
}
function OPTIONS_XML(base, path, options, content, parse_fun) {
http_options = {default_options("OPTIONS") with custom_headers:["Content-Type: text/xml"]}
//content = "<?xml version=\"1.0\"?>\n"^Xmlns.to_string(xmlns)
OPTIONS(base, path, options, http_options, content, parse_fun)
}
/** Generic HTTP parameters, sreq=required string, bopt=optional bool etc. */
function params(parameters) {
List.fold(function (p, data) {
match (p) {
case {nes:(name,v)}: if (v == "") data else List.add((name,v),data)
case {sreq:(name,v)}: List.add((name,v),data)
case {sopt:(name,v)}: if (Option.is_none(v)) data else List.add((name, Option.get(v)), data)
case {ireq:(name,v)}: List.add((name,Int.to_string(v)),data)
case {iopt:(name,v)}: if (Option.is_none(v)) data else List.add((name, Int.to_string(Option.get(v))),data)
case {breq:(name,v)}: List.add((name,Bool.to_string(v)),data)
case {bopt:(name,v)}: if (Option.is_none(v)) data else List.add((name, Bool.to_string(Option.get(v))),data)
case {dreq:(name,v)}: List.add((name,date_to_string(v)),data)
case {dopt:(name,v)}: if (Option.is_none(v)) data else List.add((name, date_to_string(Option.get(v))),data)
case {jreq:(name,toj,v)}: List.add((name, Json.serialize(toj(v))), data)
case {jopt:(name,toj,v)}: if (Option.is_none(v)) data else List.add((name, Json.serialize(toj(Option.get(v)))), data)
case {creq:(name,tos,v)}: List.add((name,tos(v)),data)
case {copt:(name,tos,v)}: if (Option.is_none(v)) data else List.add((name, tos(Option.get(v))),data)
case {aopt:(name,toj,v)}: if (v == []) data else List.add((name, Json.serialize({List:List.map(toj,v)})), data)
case {lopt:(name,tos,v)}: if (v == []) data else List.add((name, String.concat(",",List.map(tos,v))), data)
}
},parameters,[])
}
/** Generic HTTP forms, file=binary file definition, bopt=optional bool etc. */
function forms(forms) {
List.fold(function (f, forms) {
match (f) {
case {file:(name,filename,content_type,content)}: List.add(~{name, filename, content_type, content},forms)
case {nes:(name,v)}: if (v == "") forms else List.add({~name, content:v},forms)
case {sreq:(name,v)}: List.add({~name, content:v},forms)
case {sopt:(name,v)}: if (Option.is_none(v)) forms else List.add({~name, content:Option.get(v)},forms)
case {breq:(name,v)}: List.add({~name, content:Bool.to_string(v)},forms)
case {bopt:(name,v)}: if (Option.is_none(v)) forms else List.add({~name, content:Bool.to_string(Option.get(v))},forms)
case {dreq:(name,v)}: List.add({~name, content:date_to_string(v)},forms)
case {dopt:(name,v)}: if (Option.is_none(v)) forms else List.add({~name, content:date_to_string(Option.get(v))},forms)
case {ireq:(name,v)}: List.add({~name, content:Int.to_string(v)},forms)
case {iopt:(name,v)}: if (Option.is_none(v)) forms else List.add({~name, content:Int.to_string(Option.get(v))},forms)
case {jreq:(name,toj,v)}: List.add({~name, content:Json.serialize(toj(v))}, forms)
case {jopt:(name,toj,v)}:
if (Option.is_none(v)) forms else List.add({~name, content:Json.serialize(toj(Option.get(v)))},forms)
case {creq:(name,tos,v)}: List.add({~name, content:tos(v)},forms)
case {copt:(name,tos,v)}: if (Option.is_none(v)) forms else List.add({~name, content:tos(Option.get(v))},forms)
case {aopt:(name,toj,v)}: if (v == []) forms else List.add({~name, content:Json.serialize({List:List.map(toj,v)})}, forms)
}
},forms,[])
}
function get_json_int(json) { match (json) { case {Int:i}: i default: -1 } }
function get_json_string(json) { match (json) { case {String:s}: s default: "" } }
function get_json_date(json) { match (json) { case {String:s}: s default: "" } }
function get_unknown(name, map) { Map.get(name, map) ? {String:"missing unknown type"} }
get_int = API_libs_private.map_get_int
get_float = API_libs_private.map_get_float
get_string = API_libs_private.map_get_string
get_bool = API_libs_private.map_get_bool
function get_date(name, map) { Json.to_string(Map.get(name, map) ? {String:"Error in date" }) }
function get_raw_obj(json, get_elt) { get_elt(json) }
function get_obj(name, map, get_elt) { get_raw_obj((Map.get(name, map)) ? {Record:[]}, get_elt) }
function get_raw_list(json, get_elt) {
match (json) {
case {List:_}: {success:List.map(get_elt, JsonOpa.to_list(json) ? [])}
default: {failure:{bad_json:json}}
}
}
function get_list(name, map, get_elt) { get_raw_list(Map.get(name, map) ? {List:[]}, get_elt) }
function Apigen.outcome('a) check_errors(string s, string error_field, Apigen.expected_type expected_type,
(RPC.Json.json -> Apigen.outcome('a)) on_ok) {
json = API_libs_private.parse_json(s)
match ((expected_type,json)) {
case (_,{Record:r}):
if (error_field != "") {
match (List.assoc(error_field,r)) {
case {some:error_json}: {failure:{~error_json}}
case {none}: if (expected_type == {OBJECT}) on_ok(json) else {failure:{bad_json:json}}
}
} else if (expected_type == {OBJECT}) on_ok(json) else {failure:{bad_json:json}}
case ({LIST},{List:_}): on_ok(json)
case ({BOOL},{Bool:_}): on_ok(json)
case ({INT},{Int:_}): on_ok(json)
default: {failure:{bad_json:json}}
}
}
function Apigen.outcome(bool) expect_bool(RPC.Json.json json) {
match (json) {
case {Bool:b}: {success:b}
default: {failure:{bad_json:json}}
}
}
function build_bool(WebClient.success res, string error_field) {
if (error_field != "")
check_errors(res.content, error_field, {BOOL}, expect_bool)
else
expect_bool(API_libs_private.parse_json(res.content))
}
function Apigen.outcome(int) expect_int(RPC.Json.json json) {
match (json) {
case {Int:i}: {success:i}
default: {failure:{bad_json:json}}
}
}
function build_int(WebClient.success res, string error_field) {
if (error_field != "")
check_errors(res.content, error_field, {INT}, expect_int)
else
expect_int(API_libs_private.parse_json(res.content))
}
function build_xml(WebClient.success res) {
//jlog(Ansi_print({yellow},"res:{res}"))
if (String.has_prefix("<!DOCTYPE html",res.content))
{success:{xhtml:Xhtml.of_string(res.content)}}
else
match (Xmlns.try_parse_document(res.content)) {
case {some:xmldoc}: {success:{xmldoc:xmldoc}};
case {none}: {failure:{bad_xml:res.content}};
}
}
function build_wbxml(WebClient.success res, WBXml.context context) {
match (WBXml.to_xmlns(context, %%bslBinary.of_encoding%%(res.content,"binary"))) {
case {success:(_ctxt,xmlns)}: {success:xmlns};
case {~failure}: {failure:{bad_wbxml:failure}};
}
}
function outcome(Apigen.content,Apigen.failure) build_from_content_type(WebClient.success(string) res,
option(WBXml.context) context) {
//jlog(Ansi_print({yellow},"res:{res}"))
content_type = Option.default("unknown/unknown",find_header("content-type",res.headers))
match (List.map(String.trim,String.explode(";",content_type))) {
case ["text/plain"|_]:
{success:{plain:res.content}};
//{success:{plain:%%bslBinary.to_encoding%%(res.content,"binary")}};
case ["text/html"|_]:
{success:{xhtml:Xhtml.of_string(res.content)}};
//{success:{xhtml:Xhtml.of_string(%%bslBinary.to_encoding%%(res.content,"binary"))}};
case ["text/xml"|_]:
match (Xmlns.try_parse_document(res.content)) {
//match (Xmlns.try_parse_document(%%bslBinary.to_encoding%%(res.content,"binary"))) {
case {some:xmldoc}: {success:{xmldoc:xmldoc}};
case {none}: {failure:{bad_xml:res.content}};
//case {none}: {failure:{bad_xml:%%bslBinary.to_encoding%%(res.content,"binary")}};
}
case ["application/vnd.ms-sync.wbxml"|_]:
match (context) {
case {some:context}:
//jlog("res.content:\n{memdump(res.content)}")
match (WBXml.to_xmlns(context, %%bslBinary.of_encoding%%(res.content,"binary"))) {
//match (WBXml.to_xmlns({context with debug:2}, res.content)) {
case {success:(_ctxt,xmlns)}:
List.iter(function (header) {
//jlog("header: \"{header}\"")
if (String.has_prefix("x-ms-aserror:",header))
jlog("x-ms-aserror: \"{Ansi_print({red},String.sub(13,String.length(header)-13,header))}\"")
},res.headers)
{success:xmlns};
case {~failure}: {failure:{bad_wbxml:failure}};
}
case {none}: {failure:{error:"No WBXml context"}};
}
case ["unknown/unknown"|_]:
if (String.length(res.content) == 0)
{success:{none}}
else
{failure:{bad_content:{unknown:(content_type,res.content)}}};
default:
//jlog("content_type:\"{content_type}\"")
{failure:{bad_content:{unknown:(content_type,res.content)}}};
//{failure:{bad_content:{unknown_binary:(content_type,res.content)}}};
}
}
function outcome('a,Apigen.failure) build_from_ct_process_xml(WebClient.success(string) res,
option(WBXml.context) context,
(list(xmlns) -> option('a)) process) {
match (build_from_content_type(res, context)) {
case {success:~{xmlns}}:
match (process([xmlns])) {
case {some:'a result}: {success:result};
case {none}: {failure:{bad_xml:Xmlns.to_string(xmlns)}};
};
//case {success:~{xmldoc}}: ???
case {success:~{xhtml}}: {failure:{error_html:xhtml}};
case {success:bad_content}: {failure:~{bad_content}};
case ~{failure}: ~{failure};
}
}
}
/**
* Generalized configuration for API and protocol code.
* Only contains the basics, in future this may be customizable.
*/
type ApigenLib.conf = {
Socket.host default_host,
string user,
string password,
int bufsize,
int poolmax,
int timeout,
bool verbose,
}
/**
* Length definition, describes where in a packet to find the length information.
*/
type ApigenLib.length = {
int offset,
bool le,
bool signed,
Pack.s size
}
/**
* Wrapper type for configuration, will be used to host customized parameters later.
*/
type ApigenLib.params = {
ApigenLib.conf conf
}
protected @package
module ApigenLibConf(Socket.host default_host) {
private
ApigenLib.conf default_conf_ = {
~default_host,
user : "user",
password : "password",
bufsize : 50*1024,
poolmax : 10,
timeout : 60 * 60 * 1000,
verbose : false,
}
private Hashtbl.t(string, ApigenLib.params) params = Hashtbl.create(3)
private
auth_parser = parser {
case user=((![:] .)+)[:] password=((![@] .)+):
{user:Text.to_string(user), password:Text.to_string(password)}
}
private
function (string,option(int)) host_of_string(string s) {
match (String.explode(":",s)) {
case [host|[port|[]]]: (host,{some:Int.of_string(port)})
default: (s,none)
}
}
private
function family(family_name, name) {
family_name = if (family_name == "") "apigenlib" else family_name
name = if (name == "") "" else ":{name}"
{
title:"Options for {family_name} connection",
init:{conf:default_conf_},
anonymous:[],
parsers:[ // TODO: filter these out, not all possible clients will need all options. (Also allow custom options).
{CommandLine.default_parser with
names:["--{family_name}-bufsize{name}"],
description:"Hint for initial {name} connection buffer size",
param_doc:"<int>",
on_param:function (p) {
parser {
case n={Rule.natural}:
{no_params:{ p with conf.bufsize:n }}
}
}
},
{CommandLine.default_parser with
names:["--{family_name}-pool{name}"],
description:"Number of sockets in socket pool (>=2 enables socket pool)",
param_doc:"<int>",
on_param:function (p) {
parser {
case n={Rule.natural}:
{no_params:{ p with conf.poolmax:Int.max(n,1) }}
}
}
},
{CommandLine.default_parser with
names:["--{family_name}-timeout{name}"],
description:"Timeout for read/write operations",
param_doc:"<int>",
on_param:function (p) {
parser {
case n={Rule.natural}:
{no_params:{ p with conf.timeout:Int.max(n,1) }}
}
}
},
{CommandLine.default_parser with
names:["--{family_name}-log{name}"],
description:"Enable logging",
param_doc:"<bool>",
on_param:function (p) {
parser {
case b={Rule.bool}:
{no_params:{ p with conf.verbose:b }}
}
}
},
{CommandLine.default_parser with
names:["--{family_name}-default-host{name}"],
description:"Set the host for connection {name}",
param_doc:"<host>[:<port>]",
on_param:function (p) {
parser {
case s={Rule.consume}:
{no_params:
match (host_of_string(s)) {
case (host,{some:port}): { p with conf.default_host:(host,port) }
case (host,{none}): { p with conf.default_host:(host,p.conf.default_host.f2) }
}
}
}
}
},
{CommandLine.default_parser with
names:["--{family_name}-auth{name}"],
description:"Generic user authentication for connection {name}",
param_doc:"user:password",
on_param:function (p) {
parser {
case auth={auth_parser}:
{no_params:{p with conf.user:auth.user, conf.password:auth.password}}
}
}
},
]
}
}
private
function command_line_conf(family_name, name) {
match (Hashtbl.try_find(params, "{family_name}{name}")) {
case {some:conf}: conf
case {none}:
conf = CommandLine.filter(family(family_name, name))
Hashtbl.add(params, "{family_name}{name}", conf)
conf
}
}
private
function ApigenLib.params overload(c0, c1) {
c1 = if (c1.conf.default_host == default_conf_.default_host) {c1 with conf.default_host:c0.conf.default_host} else c1
c1 = if (c1.conf.user == default_conf_.user) {c1 with conf.user:c0.conf.user} else c1
c1 = if (c1.conf.password == default_conf_.password) {c1 with conf.password:c0.conf.password} else c1
c1 = if (c1.conf.bufsize == default_conf_.bufsize) {c1 with conf.bufsize:c0.conf.bufsize} else c1
c1 = if (c1.conf.poolmax == default_conf_.poolmax) {c1 with conf.poolmax:c0.conf.poolmax} else c1
c1 = if (c1.conf.timeout == default_conf_.timeout) {c1 with conf.timeout:c0.conf.timeout} else c1
c1 = if (c1.conf.verbose == default_conf_.verbose) {c1 with conf.verbose:c0.conf.verbose} else c1
c1
}
/**
* Returns configuration for the database [name], overloaded by the command
* line options.
* @param conf The default configuration.
* @param name The name of the configuration.
* @return The same configuration of [conf] but overloaded by the command line.
*/
function get(conf, family_name, name) {
overload(~{conf}, command_line_conf(family_name, name))
}
/**
* As get but with the default configuration.
*/
function get_default(family_name, name) { get(default_conf_, family_name, name).conf }
}
type ApigenLib.read_packet = Socket.connection, int, Mailbox.t -> outcome((Mailbox.t,binary),string)
/**
* Basic connection information.
* Has the configuration data plus the temporary data to manage the socket pool, etc.
*/
type ApigenLib.connection = {
string name,
ApigenLib.conf conf,
bool retain, // total mass
option(Socket.t) conn,
option(SocketPool.auth) auth,
SocketPool.t pool,
ApigenLib.read_packet read_packet
}
private
type ApigenLib.sr =
{recv} // Expect reply
or {int recvraw} // Expect raw reply
or {binary send} // Send and forget
or {binary sendrecv} // Send and expect reply
or {stop} // Stop the cell
private
type ApigenLib.srr =
{ApigenLib.connection sendresult}
or {(ApigenLib.connection,binary) sndrcvresult}
or {(ApigenLib.connection,binary) rcvresult}
or {(ApigenLib.connection,binary) rcvrawresult}
or {stopresult}
or {Apigen.failure failure}
module ApilibConnection(Socket.host default_host) {
Conf = ApigenLibConf(default_host)
private module Log {
private function gen(level, col, _f, m, string fn, msg) {
//if (m.conf.verbose) f("ApilibConnection({m.name}).{fn}", msg) else void
//if (m.conf.verbose) Ansi.jlog("ApilibConnection({m.name}).{fn}: {msg}") else void
if (ApigenLib.debug.get() >= level) Ansi.jlog("{col}ApilibConnection({m.name}).{fn}%d: {msg}") else void
}
function info(m, fn, msg) { gen(7,"%c",@toplevel.Log.info, m, fn, msg) }
function debug(m, fn, msg) { gen(8,"%b",@toplevel.Log.debug, m, fn, msg) }
function error(m, fn, msg) { gen(1,"%r",@toplevel.Log.error, m, fn, msg) }
}
/** Default length object, no offset, big endian, signed and 32-bit length. */
ApigenLib.length default_length = { offset : 0, le : false, signed : false, size : {L} }
/**
* Initialize a generalized connection.
* @param name The name of the connection to open.
* @param conf The configuration of the connection to open.
* @param secure Optional SSL secure_type value.
* @param preamble Optional function called on socket before SSL handshake.
* @param retain Retain allocated sockets between calls.
* @return A connection object (not connected).
*/
function ApigenLib.connection init(family_name, name, secure, preamble, retain) {
conf = Conf.get_default(family_name, name)
~{ name, conf, retain, conn:{none}, auth:{none},
pool:SocketPool.make_secure(conf.default_host,{hint:conf.bufsize, max:conf.poolmax, verbose:conf.verbose},secure,preamble),
read_packet:read_packet_prefixed(default_length)
}
}
/**
* Install a custom packet reader. Needed to ensure a complete packet is present
* in the buffer when message decode takes place.
* @param conn The connection object.
* @param read_packet A function to perform the read (see read_packet_prefixed for an example).
* @returns Updated connection object.
*/
function ApigenLib.connection custom_read_packet(ApigenLib.connection conn, ApigenLib.read_packet read_packet) {
{conn with ~read_packet}
}
/**
* Ensure that a socket is allocated to the connection.
* @param conn The connection object.
*/
function Apigen.outcome(ApigenLib.connection) allocate(ApigenLib.connection conn) {
match (conn.conn) {
case {some:_}: {success:conn};
case {none}:
match (SocketPool.get_auth(conn.pool)) {
case ~{failure}: {failure:{socket:failure}};
case {success:(c,auth)}: {success:{conn with conn:{some:c}, auth:{some:auth}}};
}
}
}
/**
* Release an allocated socket.
* @param conn The connection object.
*/
function ApigenLib.connection release(ApigenLib.connection conn) {
match (conn.conn) {
case {some:c}:
SocketPool.release_auth(conn.pool,c,conn.auth?{authenticated:false, i1:-1, i2:-1});
{conn with conn:none, auth:none};
case {none}: conn;
}
}
/**
* Connect to the server (actually makes a physical connection).
* @param conn The connection object.
* @param host The socket host definition (host, port).
* @returns Updated connection object with the physical connection installed.
*/
function Apigen.outcome(ApigenLib.connection) connect(ApigenLib.connection conn, Socket.host host) {
conn = release(conn);
Log.info(conn, "connect","addr={host.f1} port={host.f2}")
SocketPool.reconnect(conn.pool,(host.f1,host.f2))
{success:conn}
}
/**
* Check if the connection is ready.
* Note that this will break the connection if it is already allocated.
* @param m The connection to check
* @returns connection object with the same allocated state as on call.
*/
function Apigen.outcome(ApigenLib.connection) check(ApigenLib.connection conn) {
allocated = Option.is_some(conn.conn)
conn = release(conn)
match (SocketPool.get(conn.pool)) {
case ~{failure}: {failure:{socket:failure}}
case {success:c}:
conn =
if (allocated)
{conn with conn:{some:c}}
else {
SocketPool.release(conn.pool, c)
conn
}
{success:conn}
}
}
/**
* Close the physical connection.
*/
function ApigenLib.connection close(ApigenLib.connection conn) {
conn = release(conn)
Log.info(conn, "close","{SocketPool.gethost(conn.pool)}")
SocketPool.stop(conn.pool)
conn
}
private function set_mbox(c, mbox) {
// We MUST update the mailbox in the connection before release.
c =
match ((mbox,c.conn)) {
case ({some:mbox},{some:conn}): {c with conn:{some:{conn with ~mbox}}};
default: c;
}
if (c.retain) c else release(c)
}
private function ApigenLib.srr send_no_reply(ApigenLib.connection c, binary msg) {
match (c.conn) {
case {some:conn}:
len = Binary.length(msg)
Log.debug(c, "send", "\n{bindump(msg)}")
match (Socket.binary_write_len_with_err_cont(conn.conn,c.conf.timeout,msg,len)) {
case {success:cnt}: if (cnt==len) {sendresult:set_mbox(c,none)} else {failure:{socket:"Write failure"}}
case {~failure}: {failure:{socket:failure}};
}
case {none}:
Log.error(c, "send", "No socket")
{failure:{socket:"ApigenLib.send: No socket"}}
}
}
private function ApigenLib.srr send_with_reply(ApigenLib.connection c, binary msg) {
match (c.conn) {
case {some:conn}:
match (send_no_reply(c,msg)) {
case {sendresult:c}:
match (c.read_packet(conn.conn, c.conf.timeout, conn.mbox)) {
case {success:(mailbox,reply)}:
Log.debug(c, "receive", "\n{bindump(reply)}")
{sndrcvresult:(set_mbox(c,{some:mailbox}),reply)}
case {~failure}:
Log.info(c, "receive","failure={failure}")
_ = Mailbox.reset(conn.mbox)
{failure:{socket:failure}}
}
case {~failure}:
Log.info(c, "receive","failure={failure}")
_ = Mailbox.reset(conn.mbox)
{~failure};
default: @fail("bad sendresult");
}
case {none}:
Log.error(c, "receive","No socket")
{failure:{socket:"No socket"}}
}
}
private function ApigenLib.srr get_reply(ApigenLib.connection c) {
match (c.conn) {
case {some:conn}:
match (c.read_packet(conn.conn, c.conf.timeout, conn.mbox)) {
case {success:(mailbox,reply)}:
Log.debug(c, "receive", "\n{bindump(reply)}")
{rcvresult:(set_mbox(c,{some:mailbox}),reply)}
case {~failure}: