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
open Lwt.Infix
module System_core = struct
include Caqti_lwt.System_core
type stdenv = unit
end
include System_core
module Alarm = struct
type t = {cancel: unit -> unit}
let schedule ~sw:_ ~stdenv:() t f =
let t_now = Mtime_clock.now () in
let delay =
if Mtime.is_later t ~than:t_now then
Lwt.pause ()
else
Lwt_unix.sleep (Mtime.Span.to_float_ns (Mtime.span t t_now) *. 1e-9)
in
let task = delay >|= f in
{cancel = (fun () -> Lwt.cancel task)}
let unschedule alarm = alarm.cancel ()
end
module Stream = Caqti_lwt.Stream
module Pool = Caqti_platform.Pool.Make (System_core) (Alarm)
module Net = struct
module Sockaddr = struct
type t = Unix.sockaddr
let unix s = Unix.ADDR_UNIX s
let tcp (addr, port) =
Unix.ADDR_INET (Unix.inet_addr_of_string (Ipaddr.to_string addr), port)
end
type in_channel = Lwt_io.input_channel
type out_channel = Lwt_io.output_channel
let getaddrinfo ~stdenv:() host port =
Lwt.catch
(fun () ->
let opts = Unix.[AI_SOCKTYPE SOCK_STREAM] in
Lwt_unix.getaddrinfo
(Domain_name.to_string host) (string_of_int port) opts
>|= List.map (fun ai -> ai.Unix.ai_addr) >|= Result.ok)
(function
| Not_found -> Lwt.return_ok []
| Unix.Unix_error (code, _, _) ->
Lwt.return_error
(`Msg ("Cannot resolve host name: " ^ Unix.error_message code))
| exn -> Lwt.fail exn)
let connect ~sw:_ ~stdenv:() sockaddr =
Lwt.catch
(fun () -> Lwt_io.open_connection sockaddr >|= Result.ok)
(function
| Unix.Unix_error (code, _, _) ->
Lwt.return_error
(`Msg ("Cannot connect: " ^ Unix.error_message code))
| exn -> Lwt.fail exn)
let output_char = Lwt_io.write_char
let output_string = Lwt_io.write
let flush = Lwt_io.flush
let input_char = Lwt_io.read_char
let really_input = Lwt_io.read_into_exactly
let close_in = Lwt_io.close
end