Source

amall / src / amall_http_service.ml

  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
(* 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.Utf8;

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

    type seg = string;

    (* segpath contains path from uri, split by '/' and normalized.
       absolute segpath for url "http://host:port/a/b/c?d#e" is
       [""; "http://host:port"; "a"; "b"; "c"].  Note that query and
       fragment components are available in the Uri record.
       First item is the empty string always, it is introduced to
       make possible handling of requests to any host by
       registering a service on path [""].
     *)

    type segpath = list seg;

    (* 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"]
     *)
    
    type http_service_func =
      segpath ->
      Amall_http.request ->
      I.iteratee char Amall_http.response
    ;

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

    type listener
    ;

    type mount_point
    ;

    (* where to install service/fallback. *)

    type endpoint =
      (
        mount_point
        *
        [= `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)
    ;

    (* 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 : mount_point -> segpath -> mount_point
    ;

    value mount : endpoint -> http_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 HS = Http_server(IO)(I);

    value it_post_vars = HS.it_post_vars
    ;

    type http_server_func = HS.http_server_func
    ;

    type seg = string
    ;

    type segpath = list string
    ;

    type http_service_func =
      segpath -> http_server_func
    ;


    value default_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 host_fallback = default_fallback
    ;

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

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

    type mount_point = disp_level
    ;


(*
    class c_seg_map = Simp.map_rw_assoc [seg, disp_handler] ~keq:String.eq;
*)
    module Tr = Simp.Tree(String);
    class c_seg_map = Tr.map_rw_tree [disp_handler];
(*
*)


    value segpath_of_uri uri =
      let scheme_txt =
        match uri.scheme with
        [ None -> ""
        | Some s -> s
        ] in
      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 = sprintf "%s://%s" scheme_txt host_port_txt in

      let path = Uri.normseg_of_uri uri in

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

       [""; pre :: path]
    ;


    value rec try_find_handler disp_level segpath
     : [= `Ok of (segpath * http_service_func)
       |  `Segpath_finished of disp_level
       |  `Seg_not_found of (seg * segpath * disp_level)
       ]
     =
      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 disp_level segpath : (segpath * http_service_func) =
      match try_find_handler disp_level segpath with
      [ `Ok ((_p, _f) as pf) -> pf
      | `Segpath_finished dl -> ([], dl.fallback)
      | `Seg_not_found (seg, segs, disp_level) ->
           ([seg :: segs], disp_level.fallback)
      ]
    ;


    exception Already_handled
    ;


    value go_or_create_smallstep ~fb ~disp ~seg : disp_level =
      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 =
      match segs with
      [ [] -> disp
      | [seg :: segs] ->
          go_or_create_bigstep
            ~fb
            ~disp:(go_or_create_smallstep ~fb ~disp ~seg)
            ~segs
      ]
    ;


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


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


    value (install_handler
     :
      ~endpoint : endpoint ->
      ~what : http_service_func ->
      unit
     )
      ~endpoint
      ~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:default_fallback
        ~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 Exit)
    ;
*)

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

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

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

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


    value (server_func : disp_level -> http_server_func)
      root_disp_level
    = fun rq ->
      let uri = rq.Amall_http.rq_uri in
      let segpath = segpath_of_uri uri in
      let () = dbg "S.server_func: segpath=[%s]"
        (String.concat ";" & List.map (sprintf "%S") segpath) in
      let (segpath, func) = find_handler root_disp_level segpath in
      ((func segpath) : http_server_func) rq
    ;

    value listener_create addr =
      let root_seg_map = new c_seg_map in
      let root_disp_level =
        { seg_map = root_seg_map
        ; fallback = host_fallback  (* "ни один хост не сконфигурен" *)
        } in
      let server_func = server_func root_disp_level in
      let io_server_lazy = lazy (HS.run addr server_func) in
      let listener =
        { io_server_lazy = io_server_lazy
        ; root_disp_level = root_disp_level
        }
      in (listener, root_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
;
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.