Timing start of request

This commit is contained in:
craff 2021-12-15 18:14:17 -10:00
parent 7685505f28
commit 4770e3e729
3 changed files with 11 additions and 4 deletions

View file

@ -10,15 +10,15 @@ let middleware_stat () : S.Middleware.t * (unit -> string) =
let m h req ~resp =
incr n_req;
let t1 = now_ () in
let t1 = S.Request.time req in
h req ~resp:(fun response ->
resp response;
let t2 = now_ () in
total_time_ := !total_time_ +. (t2 -. t1);
)
and get_stat () =
Printf.sprintf "%d requests (average response time: %.3fs)"
!n_req (!total_time_ /. float !n_req)
Printf.sprintf "%d requests (average response time: %.3fms)"
!n_req (!total_time_ /. float !n_req *. 1e3)
in
m, get_stat

View file

@ -367,6 +367,7 @@ module Request = struct
path_components: string list;
query: (string*string) list;
body: 'body;
time: float;
}
let headers self = self.headers
@ -374,6 +375,7 @@ module Request = struct
let meth self = self.meth
let path self = self.path
let body self = self.body
let time self = self.time
let non_query_path self = Tiny_httpd_util.get_non_query_path self.path
@ -485,6 +487,7 @@ module Request = struct
let parse_req_start ~buf (bs:byte_stream) : unit t option resp_result =
try
let line = Byte_stream.read_line ~buf bs in
let time = Unix.gettimeofday () in
let meth, path =
try
let m, p, v = Scanf.sscanf line "%s %s HTTP/1.%d\r" (fun x y z->x,y,z) in
@ -510,7 +513,7 @@ module Request = struct
| Error e -> bad_reqf 400 "invalid query: %s" e
in
Ok (Some {meth; query; host; path; path_components;
headers; body=()})
headers; body=(); time})
with
| End_of_file | Sys_error _ -> Ok None
| Bad_req (c,s) -> Error (c,s)

View file

@ -227,6 +227,7 @@ module Request : sig
path_components: string list;
query: (string*string) list;
body: 'body;
time: float;
}
(** A request with method, path, host, headers, and a body, sent by a client.
@ -280,6 +281,9 @@ module Request : sig
val body : 'b t -> 'b
(** Request body, possibly empty. *)
val time : 'b t -> float
(** time (from [Unix.gettimeofday] after parsing the first line*)
val limit_body_size : max_size:int -> byte_stream t -> byte_stream t
(** Limit the body size to [max_size] bytes, or return
a [413] error.