-
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
-
420
-
421
-
422
-
423
-
424
-
425
-
426
-
427
-
428
-
429
-
430
-
431
-
432
-
433
-
434
-
435
-
436
-
437
-
438
-
439
-
440
-
441
-
442
-
443
-
444
-
445
-
446
-
447
-
448
-
449
-
450
-
451
-
452
-
453
-
454
-
455
-
456
-
457
-
458
-
459
-
460
-
461
-
462
-
463
-
464
-
465
-
466
-
467
-
468
-
469
-
470
-
471
-
472
-
473
-
474
-
475
-
476
-
477
-
478
-
479
-
480
-
481
-
482
-
483
-
484
-
485
-
486
-
487
-
488
-
489
-
490
-
491
-
492
-
493
-
494
-
495
-
496
-
497
-
498
-
499
-
500
// Copyright 2025 Shota FUJI
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
const std = @import("std");
const moo = @import("moo");
const websocket = @import("websocket");
const Response = struct {
wrote: *std.Thread.ResetEvent,
/// `null` on OOM.
data: ?[]const u8,
/// If this field is `true`, `data` property does not have meaningful data.
canceled: bool = false,
};
const ResponsesStore = std.AutoHashMap(i64, *Response);
const RequestHandler = *const fn (
response_writer: anytype,
meta: moo.Metadata,
header_ctx: moo.HeaderParsingContext,
message: []const u8,
) anyerror!bool;
pub const Connection = struct {
allocator: std.mem.Allocator,
thread_safe_allocator: *std.heap.ThreadSafeAllocator,
// Making this non-pointer causes invalid read/write when thread terminates.
ws: *websocket.Client,
addr: []const u8,
rng: std.Random.Xoshiro256,
pool: *std.Thread.Pool,
responses: ResponsesStore,
responses_mutex: *std.Thread.Mutex,
subscription_id_cnt: u64 = 0,
state: State = .connecting,
state_mutex: std.Thread.Mutex = .{},
const State = enum {
connecting,
connected,
closed,
};
pub const InitError = error{
WebSocketClientCreationError,
WebSocketHandshakeError,
PRNGSeedGenerationFailure,
} || std.mem.Allocator.Error;
pub fn init(child_allocator: std.mem.Allocator, address: std.net.Address, pool: *std.Thread.Pool) InitError!@This() {
var tsa = try child_allocator.create(std.heap.ThreadSafeAllocator);
tsa.* = std.heap.ThreadSafeAllocator{ .child_allocator = child_allocator };
const allocator = tsa.allocator();
var addr = std.ArrayList(u8).init(allocator);
defer addr.deinit();
try addr.writer().print("{}", .{address});
var addr_string = try addr.toOwnedSlice();
errdefer allocator.free(addr_string);
// Zig std always prints "<addr>:<port>" for IPv4 and IPv6
const port_start = std.mem.lastIndexOfScalar(u8, addr_string, ':') orelse {
unreachable;
};
var client = try allocator.create(websocket.Client);
client.* = websocket.Client.init(allocator, .{
.port = address.getPort(),
.host = addr_string[0..port_start],
}) catch return InitError.WebSocketClientCreationError;
errdefer client.deinit();
std.log.debug("Performing WebSocket handshake...", .{});
client.handshake("/api", .{
.timeout_ms = 1_000,
}) catch return InitError.WebSocketHandshakeError;
const responses = ResponsesStore.init(allocator);
const responses_mutex = try allocator.create(std.Thread.Mutex);
responses_mutex.* = std.Thread.Mutex{};
return .{
.allocator = allocator,
.ws = client,
.addr = addr_string,
.rng = std.Random.DefaultPrng.init(seed: {
var seed: u64 = undefined;
std.posix.getrandom(std.mem.asBytes(&seed)) catch {
return InitError.PRNGSeedGenerationFailure;
};
break :seed seed;
}),
.pool = pool,
.responses = responses,
.responses_mutex = responses_mutex,
.thread_safe_allocator = tsa,
};
}
pub fn listen(self: *Connection, on_request: RequestHandler) std.Thread.SpawnError!void {
std.log.debug("Spawning WebSocket request handler thread...", .{});
self.pool.spawn(readLoop, .{ self, on_request }) catch |err| {
// From user's perspective, normal spawn error and pool's error is no
// different.
std.log.warn(
"Spawning a thread from pool failed, simplifying error ({s})",
.{@errorName(err)},
);
return std.Thread.SpawnError.Unexpected;
};
}
pub fn deinit(self: *Connection) void {
const state = state: {
self.state_mutex.lock();
defer self.state_mutex.unlock();
break :state self.state;
};
if (state != .closed) {
self.close();
}
std.log.debug("Releasing WebSocket resources...", .{});
self.ws.deinit();
self.allocator.destroy(self.ws);
std.log.debug("Releasing stale responses...", .{});
self.responses_mutex.lock();
var iter = self.responses.iterator();
while (iter.next()) |entry| {
std.log.debug("Releasing response handler for request ID={}...", .{entry.key_ptr.*});
if (entry.value_ptr.*.data) |data| {
self.allocator.free(data);
}
}
self.responses.deinit();
self.responses_mutex.unlock();
std.log.debug("Releasing connection objects...", .{});
self.allocator.destroy(self.responses_mutex);
self.allocator.free(self.addr);
self.thread_safe_allocator.child_allocator.destroy(self.thread_safe_allocator);
}
/// Closes connection and cancels active message listeners.
fn close(self: *Connection) void {
// Intentionally blocks `deinit` during closing procedure, so it'll run after closed.
self.state_mutex.lock();
defer self.state_mutex.unlock();
std.log.debug("Closing WebSocket connection...", .{});
// websocket.zig cannot terminate ongoing read via ".close()".
// Manually shutting-down socket seems necessary.
// Related: https://github.com/karlseguin/websocket.zig/issues/46
std.posix.shutdown(self.ws.stream.stream.handle, .recv) catch |err| {
std.log.warn("Failed to shutdown socket handle of WebSocket: {s}", .{@errorName(err)});
};
self.ws.close(.{ .code = 4000, .reason = "bye" }) catch |err| {
std.log.warn("Unable to close WebSocket client, proceeding: {s}", .{@errorName(err)});
};
{
self.responses_mutex.lock();
defer self.responses_mutex.unlock();
var iter = self.responses.iterator();
while (iter.next()) |entry| {
entry.value_ptr.*.canceled = true;
entry.value_ptr.*.wrote.set();
}
}
self.state = .closed;
}
pub fn newRequestId(self: *Connection) i64 {
return self.rng.random().int(i64);
}
pub const RequestError = error{
Canceled,
};
pub fn request(self: *Connection, request_id: i64, message: []u8) ![]const u8 {
var wrote = std.Thread.ResetEvent{};
var response = Response{
.wrote = &wrote,
.data = null,
};
{
self.responses_mutex.lock();
defer self.responses_mutex.unlock();
try self.responses.put(request_id, &response);
}
defer {
self.responses_mutex.lock();
_ = self.responses.remove(request_id);
self.responses_mutex.unlock();
}
try self.ws.writeBin(message);
wrote.wait();
if (response.canceled) {
return RequestError.Canceled;
}
return response.data orelse return std.mem.Allocator.Error.OutOfMemory;
}
fn newSubscriptionId(self: *@This()) u64 {
const id = self.subscription_id_cnt;
self.subscription_id_cnt += 1;
return id;
}
/// Returns an interface object for subscription management.
///
/// `service_id` is an ID of the service.
/// `subject` is an entity name to subscribe.
///
/// The resulted service name would be `<service_id>/subscribe_<subject>` and
/// `<service_id>/unsubscribe_<subject>`.
///
/// Both `service_id` and `subject` must be pointer stable during lifetime of the
/// returned struct.
///
/// Caller have to call `.activate()` method on the returned struct to receive updates.
/// To capture received updates, use `.next()` method on the returned struct.
pub fn subscribe(self: *@This(), service_id: []const u8, subject: []const u8) Subscription {
return Subscription{
.request_id = self.newRequestId(),
.subscription_id = self.newSubscriptionId(),
.conn = self,
.response = Response{
.wrote = undefined,
.data = null,
},
.response_wrote = std.Thread.ResetEvent{},
.service_id = service_id,
.subject = subject,
};
}
pub const Subscription = struct {
request_id: i64,
subscription_id: u64,
conn: *Connection,
response: Response,
response_wrote: std.Thread.ResetEvent,
service_id: []const u8,
subject: []const u8,
request_message: []u8 = undefined,
/// Sets up a response listener.
pub fn activate(self: *@This(), allocator: std.mem.Allocator) !void {
self.response.wrote = &self.response_wrote;
{
self.conn.responses_mutex.lock();
defer self.conn.responses_mutex.unlock();
try self.conn.responses.put(self.request_id, &self.response);
}
const service_tmpl = "{s}/subscribe_{s}";
const service_len = std.fmt.count(service_tmpl, .{ self.service_id, self.subject });
const service = try allocator.alloc(u8, service_len);
defer allocator.free(service);
var service_fbs = std.io.fixedBufferStream(service);
try std.fmt.format(service_fbs.writer(), service_tmpl, .{ self.service_id, self.subject });
const meta = moo.Metadata{
.service = service_fbs.getWritten(),
.verb = "REQUEST",
};
const body_tmpl = "{{\"subscription_key\":{}}}";
const body_len = comptime std.fmt.count(body_tmpl, .{std.math.maxInt(u64)});
var body_bytes: [body_len]u8 = undefined;
var body_bytes_fbs = std.io.fixedBufferStream(&body_bytes);
try std.fmt.format(body_bytes_fbs.writer(), body_tmpl, .{self.subscription_id});
const body = moo.RawBody{
.bytes = body_bytes_fbs.getWritten(),
};
var header = body.getHeader(self.request_id);
header.content_type = "application/json";
const req_buffer = try allocator.alloc(
u8,
meta.getEncodeSize() + header.getEncodeSize() + body.getEncodeSize(),
);
defer allocator.free(req_buffer);
var req_fbs = std.io.fixedBufferStream(req_buffer);
try moo.encode(req_fbs.writer(), meta, header, body);
try self.conn.ws.writeBin(req_fbs.getWritten());
}
/// Release resources and unregister response handler.
/// This does not sends unsubscribe command to the server.
/// Call to this function after a call to `Connection.deinit()` is useless and invalid:
/// `Connection.deinit()` releases this struct's resource as well.
pub fn deinit(self: *@This()) void {
self.conn.responses_mutex.lock();
defer self.conn.responses_mutex.unlock();
_ = self.conn.responses.remove(self.request_id);
}
/// Sends unsubscribe request to the server.
pub fn unsubscribe(self: *@This(), allocator: std.mem.Allocator) !void {
const request_id = self.conn.newRequestId();
const service_tmpl = "{s}/unsubscribe_{s}";
const service_len = std.fmt.count(service_tmpl, .{ self.service_id, self.subject });
const service = try allocator.alloc(u8, service_len);
defer allocator.free(service);
var service_fbs = std.io.fixedBufferStream(service);
try std.fmt.format(service_fbs.writer(), service_tmpl, .{ self.service_id, self.subject });
const meta = moo.Metadata{
.service = service_fbs.getWritten(),
.verb = "REQUEST",
};
const body_tmpl = "{{\"subscription_key\":{}}}";
const body_len = comptime std.fmt.count(body_tmpl, .{std.math.maxInt(u64)});
var body_bytes: [body_len]u8 = undefined;
var body_bytes_fbs = std.io.fixedBufferStream(&body_bytes);
try std.fmt.format(body_bytes_fbs.writer(), body_tmpl, .{self.subscription_id});
const body = moo.RawBody{
.bytes = body_bytes_fbs.getWritten(),
};
var header = body.getHeader(request_id);
header.content_type = "application/json";
const req_buffer = try allocator.alloc(
u8,
meta.getEncodeSize() + header.getEncodeSize() + body.getEncodeSize(),
);
defer allocator.free(req_buffer);
var req_fbs = std.io.fixedBufferStream(req_buffer);
try moo.encode(req_fbs.writer(), meta, header, body);
try self.conn.ws.writeBin(req_fbs.getWritten());
}
/// Returns incoming updates to the subject. If the subscription is unsubscribed,
/// this function returns null.
///
/// Calling this function before `.activate()` blocks the thread indefinetely.
///
/// Caller have to release the returned memory using `Connection.allocator`.
pub fn next(self: *@This(), allocator: std.mem.Allocator) std.mem.Allocator.Error!?[]const u8 {
var entry = self.conn.responses.get(self.request_id) orelse {
return null;
};
entry.wrote.wait();
if (entry.canceled) {
return null;
}
const data = entry.data orelse {
return std.mem.Allocator.Error.OutOfMemory;
};
defer self.conn.allocator.free(data);
{
self.conn.responses_mutex.lock();
defer self.conn.responses_mutex.unlock();
entry.canceled = false;
entry.data = null;
entry.wrote.reset();
}
return try allocator.dupe(u8, data);
}
};
};
fn readLoop(conn: *Connection, on_request: RequestHandler) void {
{
conn.state_mutex.lock();
defer conn.state_mutex.unlock();
conn.state = .connected;
}
while (true) {
const msg = (conn.ws.read() catch return) orelse unreachable;
defer conn.ws.done(msg);
switch (msg.type) {
// NOTE: roon-node-api does not check whether message is binaryType.
.text, .binary => {
const meta, const header_ctx = moo.Metadata.parse(msg.data) catch |err| {
std.log.warn("Failed to parse MOO metadata: {s}", .{@errorName(err)});
continue;
};
// We just want to know Request-Id header.
const header, _ = moo.NoBodyHeaders.parse(msg.data, header_ctx) catch |err| {
std.log.warn("Failed to parse MOO headers: {s}", .{@errorName(err)});
continue;
};
{
const response = response: {
conn.responses_mutex.lock();
defer conn.responses_mutex.unlock();
break :response conn.responses.get(header.request_id);
};
if (response) |store| {
if (store.wrote.isSet()) {
std.log.warn(
"Received more than one message having same Request-Id({d})",
.{header.request_id},
);
continue;
}
defer store.wrote.set();
const bytes = conn.allocator.dupe(u8, msg.data) catch |err| {
std.log.err("Unable to release incoming WS message: {s}", .{@errorName(err)});
return;
};
store.data = bytes;
continue;
}
}
var buffer = std.ArrayList(u8).init(conn.allocator);
defer buffer.deinit();
const wrote = on_request(buffer.writer(), meta, header_ctx, msg.data) catch |err| {
std.log.warn("Service server handler returned an error: {s}", .{@errorName(err)});
continue;
};
if (!wrote) {
std.log.info("Unhandled incoming request: service={s}\n", .{meta.service});
continue;
}
const bytes = buffer.toOwnedSlice() catch |err| {
std.log.warn("Unable to prepare response bytes: {s}\n", .{@errorName(err)});
continue;
};
defer conn.allocator.free(bytes);
conn.ws.writeBin(bytes) catch |err| {
std.log.warn("Failed to write response message: {s}\n", .{@errorName(err)});
continue;
};
},
.ping => conn.ws.writePong(msg.data) catch {},
.pong => {},
.close => {
// TODO: Release Connection or notify to upstream
conn.ws.close(.{}) catch return;
return;
},
}
}
}