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
|
(* Eyre - HTTP Server Driver with Eio
*
* This is the HTTP server for serving web requests to Urbit ships.
* Uses Eio.Net for async TCP connections - can handle thousands of concurrent clients!
*
* Key innovation vs C Vere:
* - C Vere: Blocking HTTP with libh2o, sequential request processing
* - Overe: Async HTTP with Eio, concurrent request handling with fiber-per-connection
*)
(* HTTP request *)
type http_method =
| GET
| POST
| PUT
| DELETE
| HEAD
| OPTIONS
| Other of string
type http_request = {
method_: http_method;
path: string;
version: string;
headers: (string * string) list;
body: bytes;
}
(* HTTP response *)
type http_response = {
status: int;
status_text: string;
headers: (string * string) list;
body: bytes;
}
(* Eyre configuration *)
type config = {
port: int;
host: string;
}
(* Eyre driver state *)
type t = {
config: config;
mutable stats: stats;
}
and stats = {
mutable requests_total: int64;
mutable requests_active: int;
mutable bytes_sent: int64;
mutable bytes_recv: int64;
}
(* Create Eyre driver *)
let create config = {
config;
stats = {
requests_total = 0L;
requests_active = 0;
bytes_sent = 0L;
bytes_recv = 0L;
};
}
(* Parse HTTP method *)
let parse_method str =
match String.uppercase_ascii str with
| "GET" -> GET
| "POST" -> POST
| "PUT" -> PUT
| "DELETE" -> DELETE
| "HEAD" -> HEAD
| "OPTIONS" -> OPTIONS
| other -> Other other
(* Method to string *)
let method_to_string = function
| GET -> "GET"
| POST -> "POST"
| PUT -> "PUT"
| DELETE -> "DELETE"
| HEAD -> "HEAD"
| OPTIONS -> "OPTIONS"
| Other s -> s
(* Parse HTTP request line *)
let parse_request_line line =
match String.split_on_char ' ' line with
| [method_str; path; version] ->
Ok (parse_method method_str, path, version)
| _ ->
Error "Invalid request line"
(* Parse HTTP header *)
let parse_header line =
match String.index_opt line ':' with
| Some idx ->
let key = String.sub line 0 idx |> String.trim in
let value = String.sub line (idx + 1) (String.length line - idx - 1) |> String.trim in
Ok (key, value)
| None ->
Error "Invalid header"
(* Parse HTTP request from string *)
let parse_request data =
let lines = String.split_on_char '\n' data in
match lines with
| [] -> Error "Empty request"
| request_line :: header_lines ->
(match parse_request_line (String.trim request_line) with
| Error e -> Error e
| Ok (method_, path, version) ->
(* Parse headers until blank line *)
let rec parse_headers acc = function
| [] -> (List.rev acc, "")
| "" :: rest | "\r" :: rest ->
(List.rev acc, String.concat "\n" rest)
| line :: rest ->
(match parse_header (String.trim line) with
| Ok header -> parse_headers (header :: acc) rest
| Error _ -> parse_headers acc rest)
in
let headers, body_str = parse_headers [] header_lines in
Ok {
method_;
path;
version;
headers;
body = Bytes.of_string body_str;
})
(* Generate HTTP response *)
let generate_response resp =
let status_line = Printf.sprintf "HTTP/1.1 %d %s\r\n" resp.status resp.status_text in
let headers_str = List.map (fun (k, v) ->
Printf.sprintf "%s: %s\r\n" k v
) resp.headers |> String.concat "" in
let response_header = status_line ^ headers_str ^ "\r\n" in
(* Combine header and body *)
let header_bytes = Bytes.of_string response_header in
let total_len = Bytes.length header_bytes + Bytes.length resp.body in
let result = Bytes.create total_len in
Bytes.blit header_bytes 0 result 0 (Bytes.length header_bytes);
Bytes.blit resp.body 0 result (Bytes.length header_bytes) (Bytes.length resp.body);
result
(* Handle single HTTP connection *)
let handle_connection eyre ~sw:_ ~event_stream flow addr =
Printf.printf "[Eyre] New connection from %s\n%!"
(Format.asprintf "%a" Eio.Net.Sockaddr.pp addr);
eyre.stats.requests_active <- eyre.stats.requests_active + 1;
try
(* Read request *)
let buf = Cstruct.create 16384 in (* 16KB buffer *)
let recv_len = Eio.Flow.single_read flow buf in
let request_data = Cstruct.to_string (Cstruct.sub buf 0 recv_len) in
eyre.stats.bytes_recv <- Int64.add eyre.stats.bytes_recv (Int64.of_int recv_len);
Printf.printf "[Eyre] Received %d bytes\n%!" recv_len;
(* Parse request *)
(match parse_request request_data with
| Ok request ->
eyre.stats.requests_total <- Int64.succ eyre.stats.requests_total;
Printf.printf "[Eyre] %s %s %s\n%!"
(method_to_string request.method_)
request.path
request.version;
(* Create ovum for runtime *)
let ovum = Nock_lib.Effects.make_ovum
~wire:(Nock_lib.Noun.atom 0)
~card:(Nock_lib.Noun.cell
(Nock_lib.Noun.atom 3) (* eyre tag *)
(Nock_lib.Noun.atom 0)) (* simplified request data *)
in
(* Send to runtime event queue *)
Eio.Stream.add event_stream ovum;
(* Generate simple response *)
let response = {
status = 200;
status_text = "OK";
headers = [
("Content-Type", "text/plain");
("Content-Length", "13");
("Server", "Overe/0.1");
];
body = Bytes.of_string "Hello, Urbit!";
} in
let response_bytes = generate_response response in
eyre.stats.bytes_sent <- Int64.add eyre.stats.bytes_sent
(Int64.of_int (Bytes.length response_bytes));
(* Send response *)
Eio.Flow.write flow [Cstruct.of_bytes response_bytes];
Printf.printf "[Eyre] Sent %d byte response\n%!" (Bytes.length response_bytes)
| Error err ->
Printf.printf "[Eyre] Failed to parse request: %s\n%!" err;
(* Send 400 Bad Request *)
let response = {
status = 400;
status_text = "Bad Request";
headers = [("Content-Length", "0")];
body = Bytes.empty;
} in
let response_bytes = generate_response response in
Eio.Flow.write flow [Cstruct.of_bytes response_bytes]
);
eyre.stats.requests_active <- eyre.stats.requests_active - 1
with
| End_of_file ->
Printf.printf "[Eyre] Client closed connection\n%!";
eyre.stats.requests_active <- eyre.stats.requests_active - 1
| e ->
Printf.printf "[Eyre] Connection error: %s\n%!" (Printexc.to_string e);
eyre.stats.requests_active <- eyre.stats.requests_active - 1
(* Accept fiber - continuously accepts connections *)
let accept_fiber eyre ~env:_ ~sw ~event_stream listening_socket =
Printf.printf "[Eyre] Accept fiber started\n%!";
let rec loop () =
try
(* Accept connection - blocks this fiber but not others! *)
Eio.Net.accept_fork listening_socket ~sw
~on_error:(fun exn ->
Printf.printf "[Eyre] Accept error: %s\n%!" (Printexc.to_string exn)
)
(fun flow addr ->
(* Handle connection in its own fiber *)
handle_connection eyre ~sw ~event_stream flow addr
);
(* Loop forever *)
loop ()
with
| End_of_file ->
Printf.printf "[Eyre] Accept fiber closed\n%!"
| Eio.Cancel.Cancelled _ ->
Printf.printf "[Eyre] Accept fiber cancelled\n%!"
in
loop ()
(* Run Eyre driver - spawns accept fiber *)
let run eyre ~env ~sw ~event_stream =
Printf.printf "[Eyre] Starting HTTP server on %s:%d\n%!"
eyre.config.host eyre.config.port;
(* Create listening socket *)
let net = Eio.Stdenv.net env in
let addr = `Tcp (Eio.Net.Ipaddr.V4.any, eyre.config.port) in
let listening_socket = Eio.Net.listen net ~sw ~reuse_addr:true ~backlog:128 addr in
Printf.printf "[Eyre] Listening on port %d\n%!" eyre.config.port;
(* Spawn accept fiber *)
Eio.Fiber.fork ~sw (fun () ->
accept_fiber eyre ~env ~sw ~event_stream listening_socket
);
Printf.printf "[Eyre] HTTP server running!\n%!"
(* Get statistics *)
let get_stats eyre = eyre.stats
|