-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJarvis.dyalog
2209 lines (1981 loc) · 94.7 KB
/
Jarvis.dyalog
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://dyalog.github.io/Jarvis for documentation
(⎕ML ⎕IO)←1 1
∇ r←Version
:Access public shared
r←'Jarvis' '1.18.4' '2024-09-11'
∇
∇ Documentation
:Access public shared
⎕←'See https://dyalog.github.io/Jarvis'
∇
⍝ 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 or file, that value is saved in CodeSource
: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, 8 = Conga event logging
: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 Hostname←'' ⍝ external-facing host name
:Field Public HTTPAuthentication←'basic' ⍝ valid settings are currently 'basic' or ''
: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)
:Field Public UseZip←0 ⍝ Use compression if client allows it, 0- don't compress, 0<- compress if UseZip≤≢payload
:Field Public ZipLevel←3 ⍝ default compression level (0-9)
:Field APLVersion ⍝ Dyalog APL major.minor version number
:Field TokenBase←0 ⍝ base for tokens (possibly updated in Start if ⎕TALLOC is available)
⍝ 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 AllowGETs←0 ⍝ do we allow calling endpoints with HTTP GETs?
:Field Public HTMLInterface←¯1 ⍝ ¯1=unassigned, 0/1=dis/allow the HTML interface, 'Path to HTML[/home-page]', or '' 'fn'
: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 FIFO←1 ⍝ Conga: Use FIFO mode?
: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
:Property CodeSource
:Access Public
∇ r←get
r←_codeSource
∇
:EndProperty
⍝ IncludeFns/ExcludeFns Properties
:Property IncludeFns, ExcludeFns
⍝ IncludeFns and ExcludeFns are vectors the defined endpoint (function) names to expose or hide respectively
⍝ They can be function names, simple wildcarded patterns (e.g. 'Foo*'), or regex
:Access Public
∇ r←get ipa
r←⍎'_',ipa.Name
∇
∇ set ipa
:Select ipa.Name
:Case 'IncludeFns'
_includeRegex←makeRegEx¨(⊂'')~⍨∪,⊆_IncludeFns←ipa.NewValue
:Case 'ExcludeFns'
_excludeRegex←makeRegEx¨(⊂'')~⍨∪,⊆_ExcludeFns←ipa.NewValue
:EndSelect
∇
:EndProperty
⍝↓↓↓ 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 _codeSource←'' ⍝ file or folder that code was loaded from, if applicable
: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 _htmlRootFn←'' ⍝ function name if serving HTML root from a function rather than file
: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 _IncludeFns←'' ⍝ private IncludeFns
:Field _ExcludeFns←'' ⍝ private ExcludeFns
:Field _includeRegex←'' ⍝ private compiled regex from _IncludeFns
:Field _excludeRegex←'' ⍝ private compiled regex from _ExcludeFns
:Field _connections ⍝ namespace containing open connections
∇ r←Config
⍝ returns current configuration
:Access public
r←↑{⍵(⍎⍵)}¨⎕THIS⍎'⎕NL ¯2.2 ¯2.1 ¯2.3'
∇
∇ 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
r←∨/(2 2 2 2⊤⊃Debug)∨.∧2 2 2 2⊤level
:If 0≠⎕NC'value'
r←value/⍨~r
:EndIf
∇
∇ r←Thread
⍝ return the thread that the server is running in
:Access public
r←_serverThread
∇
∇ {msg}←{level}Log msg;ts;fmsg
:Access public overridable
:If Logging>0∊⍴msg
ts←((ErrorInfoLevel=2)/(2⊃⎕SI),'[',(⍕2⊃⎕LC),'] '),fmtTS ⎕TS
:If 1=≢⍴fmsg←⍕msg
:OrIf 1=⊃⍴fmsg
fmsg←ts,' - ',fmsg
:Else
fmsg←ts,∊(⎕UCS 13),fmsg
:EndIf
⎕←fmsg
: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
APLVersion←⊃⊃(//)⎕VFI{⍵/⍨2>+\'.'=⍵}2⊃#.⎕WG'APLVersion'
:Trap 11
JSONin←0 ##.##.⎕JSON⍠('Dialect' 'JSON5')('Format'JSONInputFormat)⊢ ⋄ {}JSONin'1'
JSONout←1 ##.##.⎕JSON⍠'HighRank' 'Split'⊢ ⋄ {}JSONout 1
JSONread←0 ##.##.⎕JSON⍠'Dialect' 'JSON5'⊢ ⍝ for reading configuration files
:Else
JSONin←0 ##.##.⎕JSON⍠('Format'JSONInputFormat)⊢
JSONout←1 ##.##.⎕JSON⊢
JSONread←0 ##.##.⎕JSON⊢
:EndTrap
∇
∇ r←args default defaults
args←,⊆args
r←(≢defaults)↑args,(≢args)↓defaults
∇
∇ Close
:Implements destructor
{0:: ⋄ {}LDRC.Close ServerName}⍬
∇
∇ 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 args).Start
:Else
(r rc msg)←'' ¯1 ⎕DMX.EM
:EndTrap
r←(r(rc msg))
∇
∇ (rc msg)←Start;html;homePage;t
: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
:If 19≤APLVersion ⍝ ⎕TALLOC appeared in v19.0
TokenBase←⎕TALLOC 1 'Jarvis'
:EndIf
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 ⍝ turn on if JSON paradigm
_htmlEnabled←Paradigm≡'JSON' ⍝ if not specified, HTML interface is enabled for JSON paradigm
:Else
:If 1<|≡HTMLInterface ⍝ is it '' 'function'?
t←2⊃HTMLInterface
:If 1 1 0≡⊃CodeLocation.⎕AT t
_htmlRootFn←t
_htmlEnabled←1
:Else
→0 If(rc msg)←¯1('HTML root function "',(⍕CodeLocation),'.',t,'" is not a monadic, result-returning function.')
:EndIf
:Else ⍝ otherwise it's 'file/folder'
_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.'
:EndIf
: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),(CodeSource≢'')/' (populated with code from "',CodeSource,'")'
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;tokens
: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
:If 0≠TokenBase
:If ~0∊⍴tokens←TokenBase ⎕TALLOC 2 ⍝ any lingering tokens?
{}⎕TGET tokens ⍝ remove them
:EndIf
TokenBase ⎕TALLOC ¯1 ⍝ remove token pool
:Else
{}⎕TGET{⍵/⍨1=1 100000000⍸⍵}⎕TPOOL ⍝ remove tokens in the Conga connection number range
:EndIf
(rc msg)←0 'Server stopped'
∇
∇ (rc msg)←Pause
:Access public
→0 If~_started⊣(rc msg)←¯1 'Server is not running'
→0 If 2=⊃2⊃LDRC.GetProp ServerName'Pause'⊣(rc msg)←¯2 Error'Server is already paused'
→0 If 0≠rc←⊃LDRC.SetProp ServerName'Pause' 2⊣msg←'Error attempting to pause server'
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←~_stopped
∇
∇ (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 ¯2.3' ⍝ 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←1 0.1+.×2↑LDRC.Version
LDRC.X509Cert.LDRC←LDRC ⍝ reset X509Cert.LDRC reference
Log'Local Conga v',(⍕CongaVersion),' 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≡⊃CongaRef.Init CongaPath ⋄ 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;inds
⍝ 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
⍝ The following is commented out because it seems the GnuTLS knows to use the operating system's certificate collection even on non-Windows platforms
⍝ :ElseIf ~isWin
⍝ →∆EXIT⊣(rc msg)←¯1 'No RootCertDir spcified'
:EndIf
:If 0∊⍴ServerCertSKI ⍝ no certificate ID specified, check for Cert and Key files
→∆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 ⍝ ServerCertSKI only on Windows
certs←LDRC.X509Cert.ReadCertUrls
:If 0∊⍴certs
→∆EXIT⊣(rc msg)←8 'No certificates found in Microsoft Certificate Store'
:Else
inds←1+('id=',ServerCertSKI,';')⎕S{⍵.BlockNum}⍠'Greedy' 0⊢2⊃¨certs.CertOrigin
:If 1≠≢inds
rc←9
msg←(0 2⍸≢inds)⊃('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[⊃inds]
: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''
_codeSource←path
→0 If(rc msg)←CodeLocation LoadFromFolder path
:ElseIf 2=t ⍝ file?
CodeLocation←#.⎕FIX'file://',path
_codeSource←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 _htmlRootFn~⊂''
: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?
:Select ⊃CodeLocation.⎕AT AppInitFn
:Case 1 0 0 ⍝ result-returning niladic?
stopIf DebugLevel 2
res←CodeLocation⍎AppInitFn ⍝ run it
:Case 1 1 0 ⍝ result-returning monadic?
stopIf DebugLevel 2
res←(CodeLocation⍎AppInitFn)⎕THIS ⍝ run it
:Else
→0⊣(rc msg)←8('"',(⍕CodeLocation),'.',AppInitFn,'" is not a niladic or monadic result-returning function')
:EndSelect
:If 0≠⊃res
→0⊣(rc msg)←2↑res,(≢res)↓¯1('"',(⍕CodeLocation),'.',AppInitFn,'" did not return a 0 return code')
: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 ∧/(⊃CodeLocation.⎕AT ValidateRequestFn)∊¨1(1 ¯2)0 ⍝ result-returning monadic or ambivalent?
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 ∧/(⊃CodeLocation.⎕AT AuthenticateFn)∊¨1(1 ¯2)0 ⍝ result-returning monadic or ambivalent?
Authenticate←CodeLocation⍎AuthenticateFn
:Else
→0⊣(rc msg)←8('"',(⍕CodeLocation),'.',AuthenticateFn,'" 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+32×FIFO) ⍝ WSAutoAccept (1) + DecodeBuffers (4) + EnableFifo (32)
:EndIf
:If 3.4≤CongaVersion ⍝ DOSLimit support started with v3.4
:AndIf DOSLimit≠¯1 ⍝ not using Conga's default value
:If 0≠⊃LDRC.SetProp'.' 'DOSLimit'DOSLimit
→∆EXIT⊣(rc msg)←¯1 'Invalid DOSLimit setting: ',∊⍕DOSLimit
:EndIf
:EndIf
_connections←⎕NS''
_connections.index←2 0⍴'' 0 ⍝ row-oriented for faster lookup
_connections.lastCheck←0
:If 0=rc←1⊃r←LDRC.Srv ServerName''Port'http'BufferSize,secureParams,accept,deny,options
ServerName←2⊃r
:If 3.3>CongaVersion
{}LDRC.SetProp ServerName'FIFOMode'FIFO ⍝ 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
_serverThread←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;conx;conn
(_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
:If DebugLevel 8
:AndIf evt≢'Timeout'
Log'Server: ',∊⍕rc obj evt
:EndIf
conx←obj(⍳↓⊣)'.'
conn←TokenForConnection⍣(~0∊⍴conx)⊢conx ⍝ connection (token) number - need to add 1 because connections start at 0
: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 conx ⍝ Conga closes object on an Error event
:Case 'Connect'
obj AddConnection conx
:CaseList 'HTTPHeader' 'HTTPTrailer' 'HTTPChunk' 'HTTPBody'
:If (DebugLevel 8)∧evt≡'HTTPHeader'
Log'Server: HTTPHeader Method/URL: ',∊⍕2↑4⊃wres
:EndIf
:If 0≠_connections.⎕NC conx
ref←_connections⍎conx
wres ⎕TPUT conn
_taskThreads←⎕TNUMS∩_taskThreads,ref{⍺ HandleRequest ⍵}&(obj conn)
ref.Time←⎕AI[3]
:Else
Log'Server: Object ''_connections.',conx,''' was not found.'
{0:: ⋄ {}LDRC.Close ⍵}obj
:EndIf
:Case 'Closed'
RemoveConnection conx
: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←1 ⎕JSON⍠'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
∇
∇ r←TokenForConnection conx
⍝ return token for connection name (CONnnnnnnnn)
r←1+⊃⊃(//)⎕VFI conx∩⎕D
:If 0≠TokenBase ⍝ if ⎕TALLOC is available...
r←⍎,('<',(⍕TokenBase),'.>,ZI8')⎕FMT r
:EndIf
∇
∇ obj AddConnection conx;IP;res
:Hold '_connections'
conx _connections.⎕NS''
_connections.index,←conx(⎕AI[3])
IP←''
:Trap 0 DebugLevel 1
:If 0=⊃res←LDRC.GetProp obj'PeerAddr'
IP←2⊃2⊃res
:EndIf
:EndTrap
(_connections⍎conx).IP←IP
:EndHold
∇
∇ RemoveConnection conx;ref
:Hold '_connections'
:If 0=_connections.⎕NC conx
Log'Attempt to remove non-existent connection ',⍕conx
:Else
ref←_connections⍎conx
:If 9=|⌊ref.⎕NC⊂'Req'
:AndIf ref.Req.KillOnDisconnect
⎕TKILL ref.Req.Thread
:EndIf
:EndIf
_connections.⎕EX conx
_connections.index/⍨←_connections.index[1;]≢¨⊂conx
:EndHold
CleanupTokens conx
∇
∇ CleanupConnections;conxNames;timedOut;dead;kids;connecting;connected;killed
:If _connections.lastCheck<⎕AI[3]-ConnectionTimeout×1000
killed←⍬
:Hold '_connections'
connecting←connected←⍬
:If ~0∊⍴kids←2 2⊃LDRC.Tree ServerName ⍝ retrieve children of server
⍝ LDRC.Tree
⍝ connecting → status 3 1 - incoming connection
⍝ connected → status 3 4 - connected connection
(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
:If ~0∊⍴timedOut
timedOut/⍨←{6::1 ⋄ 0=(_connections⍎⍵).⎕NC⊂'Req'}¨timedOut
:EndIf
:If ~0∊⍴dead←(connected~conxNames),timedOut ⍝ (connections not in the index), timed out
{0∊⍴⍵: ⋄ {}LDRC.Close ServerName,'.',⍵}¨dead ⍝ attempt to close them
:EndIf
⍝ remove timed out, or connections that are
_connections.⎕EX killed←(conxNames~connected~dead),timedOut
_connections.index/⍨←_connections.index[1;]∊_connections.⎕NL ¯9
:EndIf
_connections.lastCheck←⎕AI[3]
:EndHold
CleanupTokens killed
:EndIf
∇
∇ CleanupTokens conx
⍝ remove any lingering tokens from dead/removed connections
:If ~0∊⍴conx
conx←,⊆conx
{}⎕TGET ⎕TPOOL∩TokenForConnection¨{⊃¯1↑⍵(≠⊆⊣)'.'}¨conx
:EndIf
∇
:Section RequestHandling
∇ r←ErrorInfo
:Trap 0
r←⍕ErrorInfoLevel↑⎕DMX.(EM({⍵↑⍨⍵⍳']'}2⊃DM))
:Else
r←''
:EndTrap
∇
∇ req←MakeRequest args
⍝ create a request, use MakeRequest '' for interactive debugging
⍝ :Access public ⍝ uncomment for debugging
:If 0∊⍴args
req←⎕NEW Request
:Else
req←⎕NEW Request args
:EndIf
req.(Server ErrorInfoLevel)←⎕THIS ErrorInfoLevel
∇
∇ ns HandleRequest(obj conn);data;evt;obj;rc;cert;fn
:Hold obj
(rc obj evt data)←⊃⎕TGET conn ⍝ from Conga.Wait
:Select evt
:Case 'HTTPHeader'
ns.Req←MakeRequest data
ns.Req.Thread←⎕TID
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'
⍝↓↓↓ if Req doesn't exist, it's because it was marked complete previously and removed, and we just ignore this event
⍝ this can happen in the case where:
⍝ - the request is a POST request
⍝ - and no content-length header was provided
⍝ - and transfer-encoding is not "chunked"
⍝ Conga 3.5 addresses this by issuing and HTTPError event, but earlier Conga's
→0⍴⍨0=ns.⎕NC'Req'
ns.Req.Thread←⎕TID
ns.Req.ProcessBody data
:Case 'HTTPChunk'
ns.Req.Thread←⎕TID
ns.Req.ProcessChunk data
:Case 'HTTPTrailer'
ns.Req.Thread←⎕TID
ns.Req.ProcessTrailer data
:EndSelect
ns.Req.Thread←⎕TID
:If ns.Req.Complete
:Select lc ns.Req.GetHeader'content-encoding' ⍝ zipped request?
:Case '' ⍝ no encoding
:If ns.Req.Charset≡'utf-8'
ns.Req.Body←'UTF-8'⎕UCS ⎕UCS ns.Req.Body
:EndIf
:Case 'gzip'
ns.Req.Body←⎕UCS 256|¯3 Zipper 83 ⎕DR ns.Req.Body
:Case 'deflate'
ns.Req.Body←⎕UCS 256|¯2 Zipper 83 ⎕DR ns.Req.Body
:Else