Source

amall / src / amall_http_service.ml

Full commit
  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
(* Services to process http requests to specific pages
   from Amall_http_server. *)

open Am_All;
open Amall_types;
open Printf;

open Cadastr; open Cd_All; open Cdt; open Strings.Latin1;

open Amall_http_server
;


module Service
  (IO : IO_Type)
  (I : It_type.IT with
         type It_IO.m 'a = IO.m 'a
     and type It_IO.input_channel = IO.input_channel
  )
 :
  sig

    module H : module type of Amall_http.Make(IO)(I);
    module HS : module type of Http_server(IO)(I);

    (* Service receives path components relative to "mount point".
       For example, when service is registered on
       "http://host:port/a/b/c"
       ( = [""; "http://host:port"; "a"; "b"; "c"]) and when

       request uri is:                 segpath is:
       http://host:port/a/b/c          [""]
       http://host:port/a/b/c/         [""]
       http://host:port/a/b/c/d/e      ["d"; "e"]
       http://host:port/a/b/c/d?e#f    ["d"]
     *)

    (* Abstract type.  Will be used to control listening and
       accepting connections. *)

    type listener
    ;

    type mount_point 's
    ;

    open Amall_http;

    (* where to install service/fallback. *)

    type endpoint 's =
      (
        mount_point 's
        *
        [= `Service of (segpath * seg)
        |  `Fallback of segpath
        ]
      )
    ;

    (* returns listener and mount point for its root *)

    value listener_create
      : Amall_http_server.listen_addr ->
        ( listener
        * mount_point H.http_service_func
        * mount_point H.websocket_service_func
        )
    ;

    (* IO value for waiting listener *)

    value io_listener_run : listener -> IO.server
    ;

    (* really runs listening/accepting *)

    value listener_run : listener -> unit
    ;

    value listener_stop : listener -> unit
    ;


    (* creates a destination mount point in the specified segpath
       below the source mount point. *)
    value mount_rel_http :
      mount_point H.http_service_func ->
      segpath ->
      mount_point H.http_service_func
    ;
    value mount_rel_ws :
      mount_point H.websocket_service_func ->
      segpath ->
      mount_point H.websocket_service_func
    ;

    value mount_http :
      endpoint H.http_service_func ->
      H.http_service_func ->
      unit
    ;


    (* receives websocket messages *)
    type websocket_service_func_worker =
      H.websocket_service_func_worker
    ;

    (* returns websocket_service_func_worker, run once per connection *)
    type websocket_service_func =
      H.websocket_service_func
    ;

    value mount_websocket :
      endpoint H.websocket_service_func ->
      websocket_service_func ->
      unit
    ;

(*
  todo:
    value umount : endpoint -> unit
    ;
*)

    value it_post_vars : I.iteratee char (list (string * string))
    ;

  end
 =
  struct

    open Uri_type;
    open Amall_http;

    module H = Amall_http.Make(IO)(I);
    module HS = Http_server(IO)(I);

    type websocket_service_func = H.websocket_service_func;
    type websocket_service_func_worker = H.websocket_service_func_worker;

    value it_post_vars = HS.it_post_vars
    ;


    value default_http_fallback _segpath rq =
      (* todo: escape chars for html *)
      let uri = rq.rq_uri in
      let au_opt = uri.authority in
      let (host, port_opt) =
        match au_opt with
        [ None -> ("", "")
        | Some au ->
            ( au.host
            , match au.port with
              [ None -> "" | Some x -> sprintf ":%i" x
              ]
            )
        ] in
      let txt = sprintf "Can't find path \"%s\" on server \"%s%s\". \
                         URI dump follows:<br/>%s"
        uri.path host port_opt
        (Uri.dump_uri uri)
      in
      I.return
        { rs_status_code = 404
        ; rs_reason_phrase = "Not found"
        ; rs_headers = { rs_all = [] }
        ; rs_body = Body_string
           ("<html><body><p>" ^ txt ^ "</p></body></html>\n")
        }
    ;

    value default_ws_fallback = Partapp3.make
      (fun _segpath _rq _ws_out_socket ->
         failwith "websocket service not found"
      )
    ;

    type disp_level 's =
      { seg_map : seg_map 's
      ; fallback : mutable 's
      }
    and disp_handler 's =
      [ Level of disp_level 's
      | Service of 's
      ]
    and seg_map 's = Timp.map_rws seg (disp_handler 's)
    ;

    type listener =
      { io_server_lazy : Lazy.t ( IO.server )
      ; root_http_disp_level : disp_level H.http_service_func
          (* contains just '"" => root' binding when there exists
             at least one service, empty otherwise; and
             fallback with error "no such proto://host:port".
           *)
      ; root_ws_disp_level : disp_level websocket_service_func
      }
    ;

    type mount_point 's = disp_level 's
    ;


    module Tr = Simp.Tree(String);
    class c_seg_map ['s] = Tr.map_rws_tree [disp_handler 's] ();


    value segpath_of_uri uri =
      let host_port_txt =
        match uri.authority with
        [ None -> ""
        | Some au ->
            let port_txt =
              match au.port with
              [ None -> ""
              | Some i -> string_of_int i
              ] in
            sprintf "%s:%s" au.host port_txt
        ] in
      let pre = host_port_txt in

      let path = Uri.normseg_of_uri uri in

      (* из http://host:port/a/b/c?d#e делать
         [""; "host:port"; "a"; "b"; "c"],
         первая пустая строка -- чтобы можно было
         сделать сервис, слушающий [""], то есть,
         все протоколы-хосты-порты.
       *)

       [""; pre :: path]
    ;


    value rec try_find_handler disp_level segpath
     : [= `Ok of (segpath * 's)
       |  `Segpath_finished of disp_level 's
       |  `Seg_not_found of (seg * segpath * disp_level 's)
       ]
     =
      match segpath with
      [ [] -> `Segpath_finished disp_level
      | [seg :: segs] ->
          let () = dbg "S.try_find_handler: %S" seg in
          match disp_level.seg_map#get_opt seg with
          [ None ->
              let () = dbg "S.try_find_handler: .. not found" in
              `Seg_not_found (seg, segs, disp_level)
          | Some (Level disp_level) -> try_find_handler disp_level segs
          | Some (Service f) -> `Ok (segs, f)
          ]
      ]
    ;


    value find_handler (type s)
      (disp_level : disp_level s)
      segpath
      (wrap : s -> H.service_desc)
     :
      (segpath * H.service_desc)
     =
      match try_find_handler disp_level segpath with
      [ `Ok (p, f) -> (p, wrap f)
      | `Segpath_finished dl -> ([], wrap dl.fallback)
      | `Seg_not_found (seg, segs, disp_level) ->
           ([seg :: segs], wrap disp_level.fallback)
      ]
    ;


    exception Already_handled
    ;


    value go_or_create_smallstep ~fb ~disp ~seg : disp_level 's =
      let () = dbg "S.go_or_create_smallstep: seg=%S" seg in
      match disp.seg_map#get_opt seg with
      [ None ->
          let lev =
            { seg_map = new c_seg_map
            ; fallback = fb
            } in
          ( disp.seg_map#replace seg (Level lev)
          ; let () = dbg "S.go_or_create_smallstep: .. created." in
            lev
          )
      | Some (Level lev) ->
          let () = dbg "S.go_or_create_smallstep: .. found." in
          lev
      | Some (Service _f) -> raise Already_handled
      ]
    ;


    value rec go_or_create_bigstep ~fb ~disp ~segs : disp_level 's =
      match segs with
      [ [] -> disp
      | [seg :: segs] ->
          go_or_create_bigstep
            ~fb
            ~disp:(go_or_create_smallstep ~fb ~disp ~seg)
            ~segs
      ]
    ;


    type endpoint 's =
      (
        mount_point 's
      *
        [= `Service of (segpath * seg)
        |  `Fallback of segpath
        ]
      )
    ;


    value mount_rel ~fb mount_point segpath =
      go_or_create_bigstep
        ~disp:mount_point
        ~fb
        ~segs:segpath
    ;

    value mount_rel_http x = mount_rel ~fb:default_http_fallback x
      and mount_rel_ws x = mount_rel ~fb:default_ws_fallback x
    ;

    value (install_handler
     :
      ~endpoint : endpoint 's ->
      ~fb : 's ->
      ~what : 's ->
      unit
     )
      ~endpoint
      ~fb
      ~what
     =
      let (mount_point, how_where) = endpoint in
      let segpath =
        match how_where with
        [ `Service (s, _) -> s
        | `Fallback s -> s
        ]
      in
      let disp_level = go_or_create_bigstep
        ~fb
        ~disp:mount_point
        ~segs:segpath
      in
      match how_where with
      [ `Service (_, p) ->
          match disp_level.seg_map#get_opt p with
          [ None ->
              disp_level.seg_map#replace p (Service what)
          | Some _ -> raise Already_handled
          ]
      | `Fallback _ -> disp_level.fallback := what
      ]
    ;


(*
    value remove_handler ~endpoint =
      (ignore endpoint; raise E_xit)
    ;
*)

    (**********)

    value mount_http endpoint f =
      let () = dbg "S.mount" in
      install_handler ~fb:default_http_fallback ~endpoint ~what:f
    ;

    value mount_websocket endpoint f =
      let () = dbg "S.mount" in
      install_handler ~fb:default_ws_fallback ~endpoint ~what:f
    ;

(*
    value umount endpoint =
      remove_handler ~endpoint
    ;
*)

    (**********)


    value (server_func :
     disp_level H.http_service_func ->
     disp_level H.websocket_service_func ->
     request ->
     (segpath * H.service_desc)
    )
      root_http_disp_level
      root_ws_disp_level
    = fun rq ->
      let open Amall_http in
      let uri = rq.rq_uri in
      match uri.scheme with
      [ None -> invalid_arg "S.server_func: no scheme in uri"
      | Some sch ->
          let segpath = segpath_of_uri uri in
          let () = dbg "S.server_func: proto=%s segpath=[%s]"
            sch
            (String.concat ";" & List.map (sprintf "%S") segpath) in
          match sch with
          [ "http" -> find_handler root_http_disp_level segpath
              (fun s -> `Service_http s)
          | "ws" -> find_handler root_ws_disp_level segpath
              (fun s -> `Service_ws s)
          | _ -> invalid_arg "S.server_func: no scheme %s" sch
          ]
      ]
    ;

    value listener_create addr =
      let root_http_disp_level =
        { seg_map = new c_seg_map
        ; fallback = default_http_fallback
        }
      and root_ws_disp_level =
        { seg_map = new c_seg_map
        ; fallback = default_ws_fallback
        }
      in
      let server_func = server_func root_http_disp_level root_ws_disp_level in
      let io_server_lazy = lazy (HS.run addr server_func) in
      let listener =
        { io_server_lazy = io_server_lazy
        ; root_http_disp_level = root_http_disp_level
        ; root_ws_disp_level = root_ws_disp_level
        }
      in (listener, root_http_disp_level, root_ws_disp_level)
    ;

    value io_listener_run l : IO.server =
      Lazy.force l.io_server_lazy
    ;

    value listener_run l =
      let io_srv = io_listener_run l in
      match IO.runIO (IO.wait_server io_srv) with
      [ `Ok () -> ()
      | `Error e -> raise e
      ]
    ;

    value listener_stop l =
      IO.shutdown_server (Lazy.force l.io_server_lazy)
    ;

  end
;