-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJarvis.dyalog
More file actions
1783 lines (1602 loc) · 74.2 KB
/
Copy pathJarvis.dyalog
File metadata and controls
1783 lines (1602 loc) · 74.2 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
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
:Class Jarvis
⍝ Dyalog Web Service Server
⍝ See https://github.com/dyalog/jarvis/wiki for documentation
(⎕ML ⎕IO)←1 1
⍝ User hooks settings
:Field Public AppCloseFn←'' ⍝ name of the function to run on application (server) shutdown
:Field Public AppInitFn←'' ⍝ name of the application "bootstrap" function
:Field Public AuthenticateFn←'' ⍝ name of function to perform authentication,if empty, no authentication is necessary
:Field Public SessionInitFn←'' ⍝ Function name to call when initializing a session
:Field Public ValidateRequestFn←'' ⍝ name of the request validation function
⍝ Operational settings
:Field Public CodeLocation←'' ⍝ reference to application code location, if the user specifies a folder, that value is saved in Folder
:Field Public ConnectionTimeout←30 ⍝ HTTP/1.1 connection timeout in seconds
:Field Public Debug←0 ⍝ 0 = all errors are trapped, 1 = stop on an error, 2 = stop on intentional error before processing request, 4 = Jarvis framework debugging
:Field Public DefaultContentType←'application/json; charset=utf-8'
:Field Public ErrorInfoLevel←1 ⍝ level of information to provide if an APL error occurs, 0=none, 1=⎕EM, 2=⎕SI
:Field Public ExcludeFns←'' ⍝ vector of vectors for function names to be excluded (can use regex or ? and * as wildcards)
:Field Public Folder←'' ⍝ folder that user supplied in CodeLocation from which to load code
:Field Public Hostname←'' ⍝ external-facing host name
:Field Public HTTPAuthentication←'basic' ⍝ valid settings are currently 'basic' or ''
:Field Public IncludeFns←'' ⍝ vector of vectors for function names to be included (can use regex or ? and * as wildcards)
:Field Public JarvisConfig←'' ⍝ configuration file path (if any). This parameter was formerly named ConfigFile
:Field Public LoadableFiles←'*.apl?,*.dyalog' ⍝ file patterns that can be loaded if loading from folder
:Field Public Logging←1 ⍝ turn logging on/off
:Field Public Paradigm←'JSON' ⍝ either 'JSON' or 'REST'
:Field Public Report404InHTML←1 ⍝ Report HTTP 404 status (not found) in HTML (only valid if HTML interface is enabled)
⍝ Container-related settings
:Field Public DYALOG_JARVIS_THREAD←'' ⍝ 0 = Run in thread 0, 1 = Use separate thread and ⎕TSYNC, 'DEBUG' = Use separate thread and return to immediate execution, "AUTO" = if InTerm use "DEBUG" otherwise 1
:Field Public DYALOG_JARVIS_CODELOCATION←'' ⍝ If supplied, overrides CodeLocation in config file
:Field Public DYALOG_JARVIS_PORT←'' ⍝ If supplied, overrides Port both default port and config file
⍝ Session settings
:Field Public SessionIdHeader←'Jarvis-SessionID' ⍝ Name of the header field for the session token
:Field Public SessionUseCookie←0 ⍝ 0 - just use the header; 1 - use an HTTP cookie
:Field Public SessionPollingTime←1 ⍝ how frequently (in minutes) we should poll for timed out sessions
:Field Public SessionTimeout←0 ⍝ 0 = do not use sessions, ¯1 = no timeout , 0< session timeout time (in minutes)
:Field Public SessionCleanupTime←60 ⍝ how frequently (in minutes) do we clean up timed out session info from _sessionsInfo
⍝ JSON mode settings
:Field Public AllowFormData←0 ⍝ do we allow POST form data in JSON paradigm?
:Field Public HTMLInterface←¯1 ⍝ ¯1=unassigned, 0/1=dis/allow the HTML interface, or Path to HTML[/home-page]
:Field Public JSONInputFormat←'D' ⍝ set this to 'M' to have Jarvis convert JSON request payloads to the ⎕JSON matrix format
⍝ REST mode settings
:Field Public ParsePayload←1 ⍝ 1=parse request payload based on content-type header (REST only)
:Field Public RESTMethods←'Get,Post,Put,Delete,Patch,Options'
⍝ CORS settings
:Field Public EnableCORS←1 ⍝ set to 0 to disable CORS
:Field Public CORS_Origin←'*' ⍝ default value for Access-Control-Allow-Origin header (set to 1 to reflect request Origin)
:Field Public CORS_Methods←¯1 ⍝ ¯1 = set based on paradigm, 1 = reflect the request's requested method
:Field Public CORS_Headers←'*' ⍝ default value for Access-Control-Allow-Headers header (set to 1 to reflect request Headers)
:Field Public CORS_MaxAge←60 ⍝ default value (in seconds) for Access-Control-Max-Age header
⍝ Conga-related settings
:Field Public AcceptFrom←⍬ ⍝ Conga: IP addresses to accept requests from - empty means accept from any IP address
:Field Public BufferSize←10000 ⍝ Conga: buffer size
:Field Public DenyFrom←⍬ ⍝ Conga: IP addresses to refuse requests from - empty means deny none
:Field Public DOSLimit←¯1 ⍝ Conga: DOSLimit, ¯1 means use default
:Field Public Port←8080 ⍝ Conga: Default port to listen on
:Field Public RootCertDir←'' ⍝ Conga: Root CA certificate folder
:field Public Priority←'NORMAL:!CTYPE-OPENPGP' ⍝ Conga: Priorities for GnuTLS when negotiation connection
:Field Public Secure←0 ⍝ 0 = use HTTP, 1 = use HTTPS
:field Public ServerCertSKI←'' ⍝ Conga: Server cert's Subject Key Identifier from store
:Field Public ServerCertFile←'' ⍝ Conga: public certificate file
:Field Public ServerKeyFile←'' ⍝ Conga: private key file
:Field Public ServerName←'' ⍝ Server name, '' means Conga assigns it
:Field Public SSLValidation←64 ⍝ Conga: request, but do not require a client certificate
:Field Public WaitTimeout←15000 ⍝ ms to wait in LDRC.Wait
:Field Public Shared LDRC←'' ⍝ Jarvis-set reference to Conga after CongaRef has been resolved
:Field Public Shared CongaPath←'' ⍝ user-supplied path to Conga workspace and/or shared libraries
:Field Public Shared CongaRef←'' ⍝ user-supplied reference to Conga library instance
:Field CongaVersion←'' ⍝ Conga version
⍝↓↓↓ some of these private fields are also set in ∇init so that a server can be stopped, updated, and restarted
:Field _rootFolder←'' ⍝ root folder for relative file paths
:Field _configLoaded←0 ⍝ indicates whether config was already loaded by Autostart
:Field _htmlFolder←'' ⍝ folder containing HTML interface files, if any
:Field _htmlDefaultPage←'index.html' ⍝ default page name if HTMLInterface is set to serve from a folder
:Field _htmlEnabled←0 ⍝ is the HTML interface enabled?
:Field _stop←0 ⍝ set to 1 to stop server
:Field _started←0 ⍝ is the server started
:Field _stopped←1 ⍝ is the server stopped
:field _paused←0 ⍝ is the server paused
:Field _sessionThread←¯1 ⍝ thread for the session cleanup process
:Field _serverThread←¯1 ⍝ thread for the HTTP server
:Field _taskThreads←⍬ ⍝ vector of thread handling requests
:Field _sessions←⍬ ⍝ vector of session namespaces
:Field _sessionsInfo←0 5⍴'' '' 0 0 0 ⍝ [;1] id [;2] ip addr [;3] creation time [;4] last active time [;5] ref to session
:Field _includeRegex←'' ⍝ private compiled regex from IncludeFns
:Field _excludeRegex←'' ⍝ private compiled regex from ExcludeFns
:Field _connections ⍝ namespace containing open connections
:Field _conxRef ⍝ reference to _connections⍎ServerName
∇ r←Version
:Access public shared
r←'Jarvis' '1.11.8' '2022-10-04'
∇
∇ r←Config
⍝ returns current configuration
:Access public
r←↑{⍵(⍎⍵)}¨⎕THIS⍎'⎕NL ¯2.2 ¯2.1'
∇
∇ r←{value}DebugLevel level
⍝ monadic: return 1 if level is within Debug (powers of 2)
⍝ example: stopIf DebugLevel 2 ⍝ sets a stop if Debug contains 2
⍝ dyadic: return value unless level is within Debug (powers of 2)
⍝ example: :Trap 0 DebugLevel 5 ⍝ set Trap 0 unless Debug contains 1 or 4 in its
:Access public
r←∨/(2 2 2⊤⊃Debug)∨.∧2 2 2⊤level
:If 0≠⎕NC'value'
r←value/⍨~r
:EndIf
∇
∇ {r}←{level}Log msg;ts
:Access public overridable
:If Logging>0∊⍴msg
ts←fmtTS ⎕TS
:If 1=≢⍴msg←⍕msg
:OrIf 1=⊃⍴msg
r←ts,' - ',msg
:Else
r←ts,∊(⎕UCS 13),msg
:EndIf
⎕←r
:EndIf
∇
∇ r←New arg
⍝ create a new instance of Jarvis
:Access public shared
:If 0∊⍴arg
r←##.⎕NEW ⎕THIS
:Else
r←##.⎕NEW ⎕THIS arg
:EndIf
∇
∇ make
:Access public
:Implements constructor
MakeCommon
∇
∇ make1 args;rc;msg;char;t
:Access public
:Implements constructor
⍝ args is one of
⍝ - a simple character vector which is the name of a configuration file
⍝ - a reference to a namespace containing named configuration settings
⍝ - a depth 1 or 2 vector of
⍝ [1] integer port to listen on
⍝ [2] charvec function folder or ref to code location
⍝ [3] paradigm to use ('JSON' or 'REST')
MakeCommon
:If char←isChar args ⍝ character argument? it's either config filename or CodeLocation folder
:If ~⎕NEXISTS args
→0⊣Log'Unable to find "',args,'"'
:ElseIf 2=t←1 ⎕NINFO args ⍝ normal file
:If (lc⊢/⎕NPARTS args)∊'.json' '.json5' ⍝ json files are configuration
:If 0≠⊃(rc msg)←LoadConfiguration JarvisConfig←args
Log'Error loading configuration: ',msg
:EndIf
:Else
CodeLocation←args ⍝ might be a namespace script or class
:EndIf
:ElseIf 1=t ⍝ folder means it's CodeLocation
CodeLocation←args
:Else ⍝ not a file or folder
Log'Invalid constructor argument "',args,'"'
:EndIf
:ElseIf 9.1={⎕NC⊂,'⍵'}args ⍝ namespace?
:If 0≠⊃(rc msg)←LoadConfiguration args
Log'Error loading configuration: ',msg
:EndIf
:Else
:If 326=⎕DR args
:AndIf 0∧.=≡¨2↑args ⍝ if 2↑args is (port ref) (both scalar)
args[1]←⊂,args[1] ⍝ nest port so ∇default works properly
:EndIf
(Port CodeLocation Paradigm JarvisConfig)←args default Port CodeLocation Paradigm JarvisConfig
:EndIf
∇
∇ MakeCommon
:Trap 11
JSONin←{##.##.⎕JSON⍠('Dialect' 'JSON5')('Format'JSONInputFormat)⊢⍵} ⋄ {}JSONin 1
JSONout←##.##.⎕JSON⍠'HighRank' 'Split' ⋄ {}JSONout 1
JSONread←##.##.⎕JSON⍠'Dialect' 'JSON5' ⍝ for reading configuration files
:Else
JSONin←{##.##.⎕JSON⍠('Format'JSONInputFormat)⊢⍵}
JSONread←JSONout←##.##.⎕JSON
:EndTrap
∇
∇ r←args default defaults
args←,⊆args
r←(≢defaults)↑args,(≢args)↓defaults
∇
∇ Close
:Implements destructor
{0:: ⋄ {}LDRC.Close ServerName}⍬
∇
∇ UpdateRegex arg;t
⍝ updates the regular expression for inclusion/exclusion of functions whenever IncludeFns or ExcludeFns is changed
:Implements Trigger IncludeFns, ExcludeFns
t←makeRegEx¨(⊂'')~⍨∪,⊆arg.NewValue
:If arg.Name≡'IncludeFns'
_includeRegex←t
:Else
_excludeRegex←t
:EndIf
∇
∇ r←Run args;msg;rc
⍝ args is one of
⍝ - a simple character vector which is the name of a configuration file
⍝ - a reference to a namespace containing named configuration settings
⍝ - a depth 1 or 2 vector of
⍝ [1] integer port to listen on
⍝ [2] charvec function folder or ref to code location
⍝ [3] paradigm to use ('JSON' or 'REST')
:Access shared public
:Trap 0
(rc msg)←(r←⎕NEW ⎕THIS args).Start
:Else
(r rc msg)←'' ¯1 ⎕DMX.EM
:EndTrap
r←(r(rc msg))
∇
∇ (rc msg)←Start;html;homePage
:Access public
:Trap 0 DebugLevel 1
Log'Starting ',⍕2↑Version
:If _started
:If 0(,2)≡LDRC.GetProp ServerName'Pause'
rc←1⊃LDRC.SetProp ServerName'Pause' 0
→0 If(rc'Failed to unpause server')
(rc msg)←0 'Server resuming operations'
→0
:EndIf
→0 If(rc msg)←¯1 'Server thinks it''s already started'
:EndIf
:If _stop
→0 If(rc msg)←¯1 'Server is in the process of stopping'
:EndIf
:If 'CLEAR WS'≡⎕WSID
:If ⎕NEXISTS JarvisConfig
:AndIf 2=⊃1 ⎕NINFO JarvisConfig
_rootFolder←⊃1 ⎕NPARTS JarvisConfig
:Else
_rootFolder←⊃1 ⎕NPARTS SourceFile
:EndIf
:Else
_rootFolder←⊃1 ⎕NPARTS ⎕WSID
:EndIf
→0 If(rc msg)←LoadConfiguration JarvisConfig
→0 If(rc msg)←CheckPort
→0 If(rc msg)←CheckCodeLocation
→0 If(rc msg)←Setup
→0 If(rc msg)←LoadConga
homePage←1 ⍝ default is to use built-in home page
:Select ⊃HTMLInterface
:Case 0 ⍝ explicitly no HTML interface, carry on
_htmlEnabled←0
:Case 1 ⍝ explicitly turned on
:If Paradigm≢'JSON'
Log'HTML interface is only available using JSON paradigm'
:Else
_htmlEnabled←1
:EndIf
:Case ¯1
_htmlEnabled←Paradigm≡'JSON' ⍝ if not specified, HTML interface is enabled for JSON paradigm
:Else
_htmlEnabled←1
html←1 ⎕NPARTS((isRelPath HTMLInterface)/_rootFolder),HTMLInterface
:If isDir∊html
_htmlFolder←{⍵,('/'=⊢/⍵)↓'/'}∊html
:Else
_htmlFolder←1⊃html
_htmlDefaultPage←∊1↓html
:EndIf
homePage←⎕NEXISTS html←_htmlFolder,_htmlDefaultPage
Log(~homePage)/'HTML home page file "',(∊html),'" not found.'
:EndSelect
:If EnableCORS ⍝ if we've enabled CORS
:AndIf ¯1∊CORS_Methods ⍝ but not set any pre-flighted methods
:If Paradigm≡'JSON'
CORS_Methods←'GET,POST,OPTIONS' ⍝ allowed JSON methods are GET, POST, and OPTIONS
:Else
CORS_Methods←1↓∊',',¨RESTMethods[;1] ⍝ allowed REST methods are what the service supports
:EndIf
:EndIf
CORS_Methods←uc CORS_Methods
→0 If(rc msg)←StartServer
Log'Jarvis starting in "',Paradigm,'" mode on port ',⍕Port
Log'Serving code in ',(⍕CodeLocation),(Folder≢'')/' (populated with code from "',Folder,'")'
Log(_htmlEnabled∧homePage)/'Click http',(~Secure)↓'s://',MyAddr,':',(⍕Port),' to access web interface'
:Else ⍝ :Trap
(rc msg)←¯1 ⎕DMX.EM
:EndTrap
∇
∇ (rc msg)←Stop;ts
:Access public
:If _stop
→0⊣(rc msg)←¯1 'Server is already stopping'
:EndIf
:If ~_started
→0⊣(rc msg)←¯1 'Server is not running'
:EndIf
ts←⎕AI[3]
_stop←1
Log'Stopping server...'
{0:: ⋄ LDRC.Close 2⊃LDRC.Clt'' ''Port'http'}''
:While ~_stopped
:If WaitTimeout<⎕AI[3]-ts
→0⊣(rc msg)←¯1 'Server seems stuck'
:EndIf
:EndWhile
(rc msg)←0 'Server stopped'
∇
∇ (rc msg)←Pause;ts
:Access public
:If 0 2≡2⊃LDRC.GetProp ServerName'Pause'
→0⊣(rc msg)←¯1 'Server is already paused'
:EndIf
:If ~_started
→0⊣(rc msg)←¯1 'Server is not running'
:EndIf
ts←⎕AI[3]
LDRC.SetProp ServerName'Pause' 2
Log'Pausing server...'
(rc msg)←0 'Server paused'
∇
∇ (rc msg)←Reset
:Access Public
⎕TKILL _serverThread,_sessionThread,_taskThreads
_sessions←⍬
_sessionsInfo←0 5⍴0
_stopped←~_stop←_started←0
(rc msg)←0 'Server reset (previously set options are still in effect)'
∇
∇ r←Running
:Access public
r←~_stop
∇
∇ (rc msg)←CheckPort;p
⍝ check for valid port number
:If DYALOG_JARVIS_PORT≢'' ⍝ environment variable takes precedence
Port←DYALOG_JARVIS_PORT
:EndIf
(rc msg)←3('Invalid port: ',∊⍕Port)
→0 If 0=p←⊃⊃(//)⎕VFI⍕Port
→0 If{(⍵>32767)∨(⍵<1)∨⍵≠⌊⍵}p
(rc msg)←0 ''
∇
∇ (rc msg)←{force}LoadConfiguration value;config;public;set;file
:Access public
:If 0=⎕NC'force' ⋄ force←0 ⋄ :EndIf
(rc msg)←0 ''
→(_configLoaded>force)⍴0 ⍝ did we already load from AutoStart?
:Trap 0 DebugLevel 1
:If isChar value
:If '#.'≡2↑value ⍝ check if a namespace reference
:AndIf 9.1=⎕NC⊂value
config←⍎value
→Load
:EndIf
file←JarvisConfig
:If ~0∊⍴value
file←value
:EndIf
→0 If 0∊⍴file
:If ⎕NEXISTS file
config←JSONread⊃⎕NGET file
:Else
→0⊣(rc msg)←6('Configuation file "',file,'" not found')
:EndIf
:ElseIf 9.1={⎕NC⊂,'⍵'}value ⍝ namespace?
config←value
:EndIf
Load:
public←⎕THIS⍎'⎕NL ¯2.2 ¯2.1' ⍝ find all the public fields in this class
:If ~0∊⍴set←public{⍵/⍨⍵∊⍺}config.⎕NL ¯2 ¯9
config{⍎⍵,'←⍺⍎⍵'}¨set
:EndIf
_configLoaded←1
:Else
→0⊣(rc msg)←⎕DMX.EN ⎕DMX.('Error loading configuration: ',EM,(~0∊⍴Message)/' (',Message,')')
:EndTrap
∇
∇ (rc msg)←LoadConga;ref;root;nc;n;ns;congaCopied;class;path
⍝↓↓↓ Check if LDRC exists (VALUE ERROR (6) if not), and is LDRC initialized? (NONCE ERROR (16) if not)
(rc msg)←1 ''
:Hold 'JarvisInitConga'
:If {6 16 999::1 ⋄ ''≡LDRC:1 ⋄ 0⊣LDRC.Describe'.'}''
LDRC←''
:If ~0∊⍴CongaRef ⍝ did the user supply a reference to Conga?
LDRC←ResolveCongaRef CongaRef
→∆END↓⍨0∊⍴msg←(''≡LDRC)/'CongaRef (',(⍕CongaRef),') does not point to a valid instance of Conga'
:Else
:For root :In ##.## #
ref nc←root{1↑¨⍵{(×⍵)∘/¨⍺ ⍵}⍺.⎕NC ⍵}ns←'Conga' 'DRC'
:If 9=⊃⌊nc ⋄ :Leave ⋄ :EndIf
:EndFor
:If 9=⊃⌊nc
LDRC←ResolveCongaRef root⍎∊ref
→∆END↓⍨0∊⍴msg←(''≡LDRC)/(⍕root),'.',(∊ref),' does not point to a valid instance of Conga'
→∆COPY↓⍨{999::0 ⋄ 1⊣LDRC.Describe'.'}'' ⍝ it's possible that Conga was saved in a semi-initialized state
Log'Conga library found at ',(⍕root),'.',∊ref
:Else
∆COPY:
class←⊃⊃⎕CLASS ⎕THIS
congaCopied←0
:For n :In ns
:For path :In (1+0∊⍴CongaPath)⊃(⊂CongaPath)((DyalogRoot,'ws/')'') ⍝ if CongaPath specified, use it exclusively
:Trap Debug↓0
n class.⎕CY path,'conga'
LDRC←ResolveCongaRef(class⍎n)
→∆END↓⍨0∊⍴msg←(''≡LDRC)/n,' was copied from ',path,'conga but is not valid'
Log n,' copied from ',path,'conga'
→∆COPIED⊣congaCopied←1
:EndTrap
:EndFor
:EndFor
→∆END↓⍨0∊⍴msg←(~congaCopied)/'Neither Conga nor DRC were successfully copied from [DYALOG]/ws/conga'
∆COPIED:
:EndIf
:EndIf
:EndIf
CongaVersion←0.1⊥2↑LDRC.Version
LDRC.X509Cert.LDRC←LDRC ⍝ reset X509Cert.LDRC reference
Log'Local Conga reference is ',⍕LDRC
rc←0
∆END:
:EndHold
∇
∇ LDRC←ResolveCongaRef CongaRef;z;failed
⍝ Attempt to resolve what CongaRef refers to
⍝ CongaRef can be a charvec, reference to the Conga or DRC namespaces, or reference to an iConga instance
⍝ LDRC is '' if Conga could not be initialized, otherwise it's a reference to the the Conga.LIB instance or the DRC namespace
LDRC←'' ⋄ failed←0
:Select nameClass CongaRef ⍝ what is it?
:Case 9.1 ⍝ namespace? e.g. CongaRef←DRC or Conga
∆TRY:
:Trap 0 DebugLevel 1
:If ∨/'.Conga'⍷⍕CongaRef ⋄ LDRC←CongaPath CongaRef.Init'Jarvis' ⍝ is it Conga?
:ElseIf 0≡⊃CongaPath CongaRef.Init'' ⋄ LDRC←CongaRef ⍝ DRC?
:Else ⋄ →∆EXIT⊣LDRC←''
:End
:Else ⍝ if Jarvis is reloaded and re-executed in rapid succession, Conga initialization may fail, so we try twice
:If failed ⋄ →∆EXIT⊣LDRC←''
:Else ⋄ →∆TRY⊣failed←1
:EndIf
:EndTrap
:Case 9.2 ⍝ instance? e.g. CongaRef←Conga.Init ''
LDRC←CongaRef ⍝ an instance is already initialized
:Case 2.1 ⍝ variable? e.g. CongaRef←'#.Conga'
:Trap 0 DebugLevel 1
LDRC←ResolveCongaRef(⍎∊⍕CongaRef)
:EndTrap
:EndSelect
∆EXIT:
∇
∇ (rc msg secureParams)←CreateSecureParams;cert;certs;msg;mask;matchID
⍝ return Conga parameters for running HTTPS, if Secure is set to 1
LDRC.X509Cert.LDRC←LDRC ⍝ make sure the X509 instance points to the right LDRC
(rc secureParams msg)←0 ⍬''
:If Secure
:If ~0∊⍴RootCertDir ⍝ on Windows not specifying RootCertDir will use MS certificate store
→∆EXIT If(rc msg)←'RootCertDir'Exists RootCertDir
→∆EXIT If(rc msg)←{(⊃⍵)'Error setting RootCertDir'}LDRC.SetProp'.' 'RootCertDir'RootCertDir
:ElseIf 0∊⍴ServerCertSKI
→∆EXIT If(rc msg)←'ServerCertFile'Exists ServerCertFile
→∆EXIT If(rc msg)←'ServerKeyFile'Exists ServerKeyFile
:Trap 0 DebugLevel 1
cert←⊃LDRC.X509Cert.ReadCertFromFile ServerCertFile
:Else
(rc msg)←⎕DMX.EN('Unable to decode ServerCertFile "',(∊⍕ServerCertFile),'" as a certificate')
→∆EXIT
:EndTrap
cert.KeyOrigin←'DER'ServerKeyFile
:ElseIf isWin
certs←LDRC.X509Cert.ReadCertUrls
:If 0∊⍴certs
→∆EXIT⊣(rc msg)←8 'No certificates found in Microsoft Certificate Store'
:Else
matchID←{'id=(.*);'⎕S'\1'⍠'Greedy' 0⊢2⊃¨z.CertOrigin}2⊃¨certs.CertOrigin
mask←ServerCertSKI{∨/¨(⊂⍺)⍷¨2⊃¨⍵}certs.CertOrigin
:If 1≠+/mask
rc←9
msg←(0 2⍸+/mask)⊃('Certificate with id "',ServerCertSKI,'" was not found in the Microsoft Certificate Store')('There is more than one certificate with Subject Key Identifier "',ServerCertSKI,'" in the Microsoft Certificate Store')
→∆EXIT
:EndIf
cert←certs[⊃⍸mask]
:EndIf
:Else ⍝ ServerCertSKI is defined, but we're not running Windows
→∆EXIT⊣(rc msg)←10 'ServerCertSKI is currently valid only under Windows'
:EndIf
secureParams←('X509'cert)('SSLValidation'SSLValidation)('Priority'Priority)
:EndIf
∆EXIT:
∇
∇ (rc msg)←CheckCodeLocation;root;m;res;tmp;fn;path
(rc msg)←0 ''
:If DYALOG_JARVIS_CODELOCATION≢'' ⍝ environment variable take precedence
CodeLocation←DYALOG_JARVIS_CODELOCATION
:EndIf
:If 0∊⍴CodeLocation
:If 0∊⍴JarvisConfig ⍝ if there's a configuration file, use its folder for CodeLocation
→0⊣(rc msg)←4 'CodeLocation is empty!'
:Else
CodeLocation←⊃1 ⎕NPARTS JarvisConfig
:EndIf
:EndIf
:Select ⊃{⎕NC'⍵'}CodeLocation ⍝ need dfn because CodeLocation is a field and will always be nameclass 2
:Case 9 ⍝ reference, just use it
:Case 2 ⍝ variable, could be file path or ⍕ of reference from JarvisConfig
:If 326=⎕DR tmp←{0::⍵ ⋄ '#'≠⊃⍵:⍵ ⋄ ⍎⍵}CodeLocation
:AndIf 9={⎕NC'⍵'}tmp ⋄ CodeLocation←tmp
:Else
root←(isRelPath CodeLocation)/_rootFolder
path←∊1 ⎕NPARTS root,CodeLocation
:Trap 0 DebugLevel 1
:If 1=t←1 ⎕NINFO path ⍝ folder?
CodeLocation←⍎'CodeLocation'#.⎕NS''
→0 If(rc msg)←CodeLocation LoadFromFolder Folder←path
:ElseIf 2=t ⍝ file?
CodeLocation←#.⎕FIX'file://',path
:Else
→0⊣(rc msg)←5('CodeLocation "',(∊⍕CodeLocation),'" is not a folder or script file.')
:EndIf
:Case 22 ⍝ file name error
→0⊣(rc msg)←6('CodeLocation "',(∊⍕CodeLocation),'" was not found.')
:Else ⍝ anything else
→0⊣(rc msg)←7((⎕DMX.(EM,' (',Message,') ')),'occured when validating CodeLocation "',(∊⍕CodeLocation),'"')
:EndTrap
:EndIf
:Else
→0⊣(rc msg)←5 'CodeLocation is not valid, it should be either a namespace/class reference or a file path'
:EndSelect
:For fn :In AppInitFn AppCloseFn ValidateRequestFn AuthenticateFn SessionInitFn~⊂''
:If 3≠CodeLocation.⎕NC fn
msg,←(0∊⍴msg)↓',"CodeLocation.',fn,'" was not found '
:EndIf
:EndFor
→0 If rc←8×~0∊⍴msg
:If ~0∊⍴AppInitFn ⍝ initialization function specified?
:If 1 0 0≡⊃CodeLocation.⎕AT AppInitFn ⍝ result-returning niladic?
stopIf DebugLevel 2
res←CodeLocation⍎AppInitFn ⍝ run it
:If 0≠⊃res
→0⊣(rc msg)←2↑res,(≢res)↓¯1('"',(⍕CodeLocation),'.',AppInitFn,'" did not return a 0 return code')
:EndIf
:Else
→0⊣(rc msg)←8('"',(⍕CodeLocation),'.',AppInitFn,'" is not a niladic result-returning function')
:EndIf
:EndIf
:If ~0∊⍴AppCloseFn ⍝ application close function specified?
:If 1 0 0≢⊃CodeLocation.⎕AT AppCloseFn ⍝ result-returning niladic?
→0⊣(rc msg)←8('"',(⍕CodeLocation),'.',AppCloseFn,'" is not a niladic result-returning function')
:EndIf
:EndIf
Validate←{0} ⍝ dummy validation function
:If ~0∊⍴ValidateRequestFn ⍝ Request validation function specified?
:If 1 1 0≡⊃CodeLocation.⎕AT ValidateRequestFn ⍝ result-returning monadic?
Validate←CodeLocation⍎ValidateRequestFn
:Else
→0⊣(rc msg)←8('"',(⍕CodeLocation),'.',ValidateRequestFn,'" is not a monadic result-returning function')
:EndIf
:EndIf
Authenticate←{0} ⍝ dummy authentication function
:If ~0∊⍴AuthenticateFn ⍝ authentication function specified?
:If 1 1 0≡⊃CodeLocation.⎕AT AuthenticateFn ⍝ result-returning monadic?
Authenticate←CodeLocation⍎AuthenticateFn
:Else
→0⊣(rc msg)←8('"',(⍕CodeLocation),'.',Authenticate,'" is not a monadic result-returning function')
:EndIf
:EndIf
∇
∇ (rc msg)←Setup
⍝ perform final setup before starting server
(rc msg)←0 ''
Paradigm←uc Paradigm
:Select Paradigm
:Case 'JSON'
RequestHandler←HandleJSONRequest
:Case 'REST'
RequestHandler←HandleRESTRequest
:If 2>≢⍴RESTMethods
RESTMethods←↑2⍴¨'/'(≠⊆⊢)¨','(≠⊆⊢),RESTMethods
:EndIf
:Else
(rc msg)←¯1 'Invalid paradigm'
:EndSelect
∇
Exists←{0:: ¯1 (⍺,' "',⍵,'" is not a valid folder name.') ⋄ ⎕NEXISTS ⍵:0 '' ⋄ ¯1 (⍺,' "',⍵,'" was not found.')}
∇ (rc msg)←StartServer;r;cert;secureParams;accept;deny;mask;certs;options
msg←'Unable to start server'
accept←'Accept'ipRanges AcceptFrom
deny←'Deny'ipRanges DenyFrom
→∆EXIT If⊃(rc msg secureParams)←CreateSecureParams
{}LDRC.SetProp'.' 'EventMode' 1 ⍝ report Close/Timeout as events
options←''
:If 3.3≤CongaVersion ⍝ can we set DecodeBuffers at server creation?
options←⊂'Options' 5 ⍝ DecodeBuffers + WSAutoAccept
:EndIf
_connections←⎕NS''
_connections.index←2 0⍴'' 0
_connections.lastCheck←0
:If 0=rc←1⊃r←LDRC.Srv ServerName''Port'http'BufferSize,secureParams,accept,deny,options
ServerName←2⊃r
ServerName _connections.⎕NS''
_conxRef←_connections⍎ServerName
:If 3.3>CongaVersion
{}LDRC.SetProp ServerName'FIFOMode' 0 ⍝ deprecated in Conga v3.2
{}LDRC.SetProp ServerName'DecodeBuffers' 15 ⍝ 15 ⍝ decode all buffers
{}LDRC.SetProp ServerName'WSFeatures' 1 ⍝ auto accept WS requests
:EndIf
:If 0∊⍴Hostname ⍝ if Host hasn't been set, set it to the default
Hostname←'http',(~Secure)↓'s://',(2 ⎕NQ'.' 'TCPGetHostID'),((~Port∊80 443)/':',⍕Port),'/'
:EndIf
InitSessions
(rc msg)←RunServer
:Else
Log msg←'Error ',(⍕rc),' creating server',(rc∊98 10048)/': port ',(⍕Port),' is already in use' ⍝ 98=Linux, 10048=Windows
:EndIf
∆EXIT:
∇
∇ (rc msg)←RunServer;thread
thread←lc,⍕DYALOG_JARVIS_THREAD
:If (⊂thread)∊'' 'auto'
:If InTerm ⍝ do we have an interactive terminal?
thread←'debug'
:Else
thread←,'1'
:EndIf
:EndIf
:Select thread
:Case ,'0' ⍝ Run in thread 0
(rc msg)←Server''
QuadOFF
:Case ,'1' ⍝ Run in non-0 thread, use ⎕TSYNC
(rc msg)←⎕TSYNC _serverThread←Server&⍬
QuadOFF
:Case 'debug'
_serverThread←Server&⍬
(rc msg)←0 'Server started'
:Else
(rc msg)←¯1 'Invalid setting for DYALOG_JARVIS_THREAD'
:EndSelect
∇
∇ {r}←Server arg;wres;rc;obj;evt;data;ref;ip;msg;tmp
(_started _stopped)←1 0
:While ~_stop
:Trap 0 DebugLevel 1
wres←LDRC.Wait ServerName WaitTimeout ⍝ Wait for WaitTimeout before timing out
⍝ wres: (return code) (object name) (command) (data)
(rc obj evt data)←4↑wres
:Select rc
:Case 0
:Select evt
:Case 'Error'
_stop←ServerName≡obj ⍝ if we got an error on the server itself, signal to stop
:If 0≠4⊃wres
Log'Server: DRC.Wait reported error ',(⍕4⊃wres),' on ',(2⊃wres),GetIP obj
:EndIf
RemoveConnection obj ⍝ Conga closes object on an Error event
:Case 'Connect'
AddConnection obj
:CaseList 'HTTPHeader' 'HTTPTrailer' 'HTTPChunk' 'HTTPBody'
:If 0≠_connections.⎕NC obj
ref←_connections⍎obj
_taskThreads←⎕TNUMS∩_taskThreads,ref{⍺ HandleRequest ⍵}&wres
ref.Time←⎕AI[3]
:Else
Log'Server: Object ''_connections.',obj,''' was not found.'
{}{0:: ⋄ LDRC.Close ⍵}obj
:EndIf
:Case 'Closed'
RemoveConnection obj
:Case 'Timeout'
:Else ⍝ unhandled event
Log'Server: Unhandled Conga event:'
Log⍕wres
:EndSelect ⍝ evt
:Case 1010 ⍝ Object Not found
:If ~_stop
Log'Server: Object ''',ServerName,''' has been closed - Jarvis shutting down'
_stop←1
:EndIf
:Else
Log'Server: Conga wait failed:'
Log wres
:EndSelect ⍝ rc
CleanupConnections
:Else ⍝ :Trap
Log'*** Server error ',msg←(JSONout⍠'Compact' 0)⎕DMX
r←¯1 msg
→Exit
:EndTrap
:EndWhile
r←0 'Server stopped'
Exit:
:If ~0∊⍴AppCloseFn
r←CodeLocation⍎AppCloseFn
:EndIf
Close
⎕TKILL _sessionThread
(_stop _started _stopped)←0 0 1
∇
∇ AddConnection name
:Hold '_connections'
name _connections.⎕NS''
_connections.index,←(name(⍳↓⊣)'.')(⎕AI[3])
(_connections⍎name).IP←2⊃2⊃LDRC.GetProp obj'PeerAddr'
:EndHold
∇
∇ RemoveConnection name
:Hold '_connections'
_connections.⎕EX name
_connections.index/⍨←_connections.index[1;]≢¨⊂name(⍳↓⊣)'.'
:EndHold
∇
∇ CleanupConnections;conxNames;timedOut;dead;kids;connecting;connected
:If _connections.lastCheck<⎕AI[3]-ConnectionTimeout×1000
:Hold '_connections'
connecting←connected←⍬
:If ~0∊⍴kids←2 2⊃LDRC.Tree ServerName
(connecting connected)←2↑{((2 2⍴3 1 3 4)⍪⍵[;2 3]){⊂1↓⍵}⌸'' '',⍵[;1]}↑⊃¨kids
:EndIf
conxNames←_connections.index[1;]~connecting
timedOut←_connections.index[1;]/⍨ConnectionTimeout<0.001×⎕AI[3]-_connections.index[2;]
:If ∨/~0∘∊∘⍴¨connected conxNames
{0∊⍴⍵: ⋄ {}LDRC.Close ServerName,'.',⍵}¨dead←(connected~conxNames),timedOut
_conxRef.⎕EX(conxNames~connected~dead),timedOut
_connections.index/⍨←_connections.index[1;]∊_conxRef.⎕NL ¯9
:EndIf
_connections.lastCheck←⎕AI[3]
:EndHold
:EndIf
∇
:Section RequestHandling
∇ req←MakeRequest args
⍝ create a request, use MakeRequest '' for interactive debugging
:Access public
:If 0∊⍴args
req←⎕NEW Request
:Else
req←⎕NEW Request args
:EndIf
req.(Server ErrorInfoLevel)←⎕THIS ErrorInfoLevel
∇
∇ ns HandleRequest req;data;evt;obj;rc;cert;fn
(rc obj evt data)←req ⍝ from Conga.Wait
:Hold obj
:Select evt
:Case 'HTTPHeader'
ns.Req←MakeRequest data
ns.Req.PeerCert←''
ns.Req.PeerAddr←2⊃2⊃LDRC.GetProp obj'PeerAddr'
ns.Req.Server←⎕THIS
:If Secure
(rc cert)←2↑LDRC.GetProp obj'PeerCert'
:If rc=0
ns.Req.PeerCert←cert
:Else
ns.Req.PeerCert←'Could not obtain certificate'
:EndIf
:EndIf
:Case 'HTTPBody'
ns.Req.ProcessBody data
:Case 'HTTPChunk'
ns.Req.ProcessChunk data
:Case 'HTTPTrailer'
ns.Req.ProcessTrailer data
:EndSelect
:If ns.Req.Complete
:If ns.Req.Charset≡'utf-8'
ns.Req.Body←'UTF-8'⎕UCS ⎕UCS ns.Req.Body
:EndIf
:If _htmlEnabled∧ns.Req.Response.Status≠200
ns.Req.Response.Headers←1 2⍴'Content-Type' 'text/html; charset=utf-8'
ns.Req.Response.Payload←'<h3>',(⍕ns.Req.Response.((⍕Status),' ',StatusText)),'</h3>'
→resp
:EndIf
⍝ Application-specified validation
stopIf DebugLevel 4+2×~0∊⍴ValidateRequestFn
rc←Validate ns.Req
ns.Req.Fail 400×(ns.Req.Response.Status=200)∧0≠rc ⍝ default status 400 if not set by application
→resp If rc≠0
fn←1↓'.'@('/'∘=)ns.Req.Endpoint
fn RequestHandler ns ⍝ RequestHandler is either HandleJSONRequest or HandleRESTRequest
resp: obj Respond ns.Req
:EndIf
:EndHold
∇
∇ fn HandleJSONRequest ns;payload;resp;valence;nc;debug;ind;file
→handle If'get'≢ns.Req.Method
→0 If('Request method should be POST')ns.Req.Fail 405×~_htmlEnabled
→handleHtml If~0∊⍴_htmlFolder
ind←'' 'favicon.ico'⍳⊂fn
→0 If(ind=2)∨'(Bad URI)'ns.Req.Fail 400×ind=3 ⍝ either fail with a bad URI or exit if favicon.ico (no-op)
ns.Req.Response.Headers←1 2⍴'Content-Type' 'text/html; charset=utf-8'
ns.Req.Response.Payload←HtmlPage
→0
handleHtml:
:If (,'/')≡ns.Req.Endpoint
file←_htmlFolder,_htmlDefaultPage
:Else
file←_htmlFolder,('/'=⊣/ns.Req.Endpoint)↓ns.Req.Endpoint
:EndIf
file←∊1 ⎕NPARTS file
file,←(isDir file)/'/',_htmlDefaultPage
→0 If ns.Req.Fail 400×~_htmlFolder begins file
:If 0≠ns.Req.Fail 404×~⎕NEXISTS file
→0 If 0=Report404InHTML
ns.Req.Response.Headers←1 2⍴'Content-Type' 'text/html; charset=utf-8'
ns.Req.Response.Payload←'<h3>Not found: ',(file↓⍨≢_htmlFolder),'</h3>'
→0
:EndIf
ns.Req.Response.Payload←''file
'Content-Type'ns.Req.DefaultHeader ns.Req.ContentTypeForFile file
→0
handle:
→0 If HandleCORSRequest ns.Req
→0 If('No function specified')ns.Req.Fail 400×0∊⍴fn
→0 If('Unsupported request method')ns.Req.Fail 405×ns.Req.Method≢'post'
→0 If('(Content-Type should be application/json',AllowFormData/' or multipart/form-data')ns.Req.Fail 400×(0∊⍴ns.Req.Body)⍱(⊂ns.Req.ContentType)∊(~AllowFormData)↓'multipart/form-data' 'application/json'
→0 If'(Cannot accept query parameters)'ns.Req.Fail 400×~0∊⍴ns.Req.QueryParams
:Select ns.Req.ContentType
:Case 'application/json'
:Trap 0 DebugLevel 1
ns.Req.Payload←{0∊⍴⍵:⍵ ⋄ 0 JSONin ⍵}ns.Req.Body
:Else
→0⊣'Could not parse payload as JSON'ns.Req.Fail 400
:EndTrap
:Case 'multipart/form-data'
:Trap 0 DebugLevel 1
ns.Req.Payload←ParseMultipartForm ns.Req
:Else
→0⊣'Could not parse payload as multipart/form-data'ns.Req.Fail 400
:EndTrap
:EndSelect
→0 If CheckAuthentication ns.Req
→0 If('Invalid function "',fn,'"')ns.Req.Fail CheckFunctionName fn
→0 If('Invalid function "',fn,'"')ns.Req.Fail 404×3≠⌊|{0::0 ⋄ CodeLocation.⎕NC⊂⍵}fn ⍝ is it a function?
valence←|⊃CodeLocation.⎕AT fn
nc←CodeLocation.⎕NC⊂fn
→0 If('"',fn,'" is not a monadic result-returning function')ns.Req.Fail 400×(1 1 0≢×valence)>(0∧.=valence)∧3.3=nc
resp←''
:Trap 0 DebugLevel 1
:Trap 85
:If (2=valence[2])>3.3=nc ⍝ dyadic and not tacit
stopIf DebugLevel 2
resp←ns.Req{1 CodeLocation.(85⌶)'⍺ ',fn,' ⍵'}ns.Req.Payload ⍝ intentional stop for application-level debugging
:Else
stopIf DebugLevel 2
resp←{1 CodeLocation.(85⌶)fn,' ⍵'}ns.Req.Payload ⍝ intentional stop for application-level debugging
:EndIf
:EndTrap
:Else
→0⊣ns.Req.Fail 500
:EndTrap
⍝ ↓↓↓ removed this next line because a non-2XX response might still have a payload
⍝ →0 If 2≠⌊0.01×ns.Req.Response.Status ⍝ exit if not a successful HTTP code
→0 If 0∊⍴resp ⍝ exit if there's no response payload
'content-type'ns.Req.DefaultHeader'application/json; charset=utf-8' ⍝ set the header if not set
→0 If~'application/json'⍷ns.Req.(Response.Headers GetHeader'content-type') ⍝ if the response is JSON
ns.Req.Response ToJSON resp ⍝ convert it
∇
∇ formData←ParseMultipartForm req;boundary;body;part;headers;payload;disposition;type;name;filename;tmp
boundary←crlf,'--',req.Boundary ⍝ the HTTP standard prepends '--' to the boundary
body←req.Body
formData←⎕NS''
body←⊃body splitOnFirst boundary,'--' ⍝ drop off trailing boundary ('--' is appended to the trailing boundary)
:For part :In (crlf,body)splitOn boundary ⍝ split into parts
(headers payload)←part splitOnFirst crlf,crlf
(disposition type)←deb¨2↑headers splitOn crlf
(name filename)←deb¨2↑1↓disposition splitOn';'
name←'"'~⍨2⊃name splitOn'='
tmp←⎕NS''
:If {¯1=⎕NC ⍵}name
→0⊣'Invalid form field name for Jarvis'req.Fail 400
:EndIf
filename←'"'~⍨2⊃2↑filename splitOn'='
tmp.(Name Filename)←name filename
tmp.Content←payload
tmp.Content_Type←deb 2⊃2↑type splitOn':'
:If 0=formData.⎕NC name ⋄ formData{⍺⍎⍵,'←⍬'}name ⋄ :EndIf
formData(name{⍺⍎⍺⍺,',←⍵'})tmp
:EndFor
∇
∇ fn HandleRESTRequest ns;ind;exec;valence;ct;resp
→0 If HandleCORSRequest ns.Req
→0 If CheckAuthentication ns.Req
:If ParsePayload
:Trap 0 DebugLevel 1
:Select ns.Req.ContentType
:Case 'application/json'
ns.Req.Payload←0 JSONin ns.Req.Body
:Case 'application/xml'
ns.Req.(Payload←⎕XML Body)
:EndSelect
:Else
→0⊣('Unable to parse request body as ',ct)ns.Req.Fail 400
:EndTrap
:EndIf
ind←RESTMethods[;1](⍳nocase)⊂ns.Req.Method