Skip to content

Commit 5caef14

Browse files
committed
buffer pool for lwt server
1 parent 76cefc0 commit 5caef14

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

src/lwt/tiny_httpd_lwt.ml

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,14 @@ let io_backend ?addr ?port ?unix_sock ?max_connections ?max_buf_pool_size
111111
let running = Atomic.make true in
112112
let active_conns = Atomic.make 0 in
113113

114+
(* a pool of buffers, to reduce allocations *)
115+
let buf_pool =
116+
Pool.create ~max_size:pool_size
117+
~clear:(fun buf -> Bytes.fill buf 0 (Bytes.length buf) '\x00')
118+
~mk_item:(fun () -> Bytes.create buf_size)
119+
()
120+
in
121+
114122
(* Eio.Switch.on_release sw (fun () -> Atomic.set running false); *)
115123
let port = ref port in
116124

@@ -139,33 +147,31 @@ let io_backend ?addr ?port ?unix_sock ?max_connections ?max_buf_pool_size
139147
let handle_client client_addr fd : unit =
140148
Atomic.incr active_conns;
141149
Lwt_direct.run_in_the_background @@ fun () ->
142-
let buf_ic = Bytes.create buf_size in
143-
let buf_oc = Bytes.create buf_size in
144-
(*
145150
let@ buf_ic = Pool.with_resource buf_pool in
146151
let@ buf_oc = Pool.with_resource buf_pool in
147-
*)
148152

149153
(* close FD when both ends are closed *)
150154
let num_open = ref 2 in
151155
let ic = ic_of_fd ~num_open ~bytes:buf_ic fd in
152156
let oc = oc_of_fd ~num_open ~bytes:buf_oc fd in
153157

154-
let cleanup () =
158+
let cleanup ~shutdown () =
155159
Log.debug (fun k ->
156160
k "Tiny_httpd_lwt: client handler returned");
157161
Atomic.decr active_conns;
158-
(try Lwt_unix.shutdown fd SHUTDOWN_ALL with _ -> ());
162+
if shutdown then (
163+
try Lwt_unix.shutdown fd SHUTDOWN_ALL with _ -> ()
164+
);
159165
ic#close ();
160166
oc#close ()
161167
in
162168

163169
try
164170
handle.handle ~client_addr ic oc;
165-
cleanup ()
171+
cleanup ~shutdown:true ()
166172
with exn ->
167173
let bt = Printexc.get_raw_backtrace () in
168-
cleanup ();
174+
cleanup ~shutdown:false ();
169175
Log.error (fun k ->
170176
k "Client handler for %s failed with %s\n%s"
171177
(show_sockaddr client_addr)

0 commit comments

Comments
 (0)