-
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
// 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 sood = @import("sood");
const Connection = @import("./roon/connection.zig").Connection;
const discovery = @import("./roon/discovery.zig");
const Extension = @import("./roon/extension.zig").Extension;
const PingService = @import("./roon/services/ping.zig").PingService;
const RegistryService = @import("./roon/services/registry.zig").RegistryService;
const TransportService = @import("./roon/services/transport.zig").TransportService;
const callback = @import("./App/callback.zig");
pub const Server = @import("./App/Server.zig");
pub const ServerSelector = @import("./App/ServerSelector.zig");
const App = @This();
const AppExtension = Extension(.{
.id = "jp.pocka.plac",
.display_name = "Plac",
.version = "0.0.0-dev",
.publisher = "Shota FUJI",
.email = "pockawoooh@gmail.com",
.required_services = &.{TransportService},
.optional_services = &.{},
.provided_services = &.{PingService},
});
const OnServerChange = callback.Callback(struct {});
const OnConnectionChange = callback.Callback(struct {});
const ServerConnInfo = struct {
allocator: std.mem.Allocator,
addr: std.net.Address,
id: []const u8,
name: []const u8,
version: []const u8,
pub const FromSoodResponseError = std.mem.Allocator.Error;
pub fn fromSoodResponse(
allocator: std.mem.Allocator,
addr: std.net.Address,
resp: *const sood.discovery.Response,
) FromSoodResponseError!@This() {
var ws_addr = addr;
ws_addr.setPort(resp.http_port);
const id = try allocator.dupe(u8, resp.unique_id);
errdefer allocator.free(id);
const name = try allocator.dupe(u8, resp.name);
errdefer allocator.free(name);
const version = try allocator.dupe(u8, resp.display_version);
errdefer allocator.free(version);
return .{
.allocator = allocator,
.addr = ws_addr,
.id = id,
.name = name,
.version = version,
};
}
pub fn deinit(self: @This()) void {
self.allocator.free(self.version);
self.allocator.free(self.name);
self.allocator.free(self.id);
}
pub fn getKey(self: @This()) []const u8 {
return self.id;
}
};
allocator: std.mem.Allocator,
on_server_change: OnServerChange.Store,
on_connection_change: OnConnectionChange.Store,
capi_lock: std.Thread.Mutex,
pub fn init(allocator: std.mem.Allocator) App {
return .{
.allocator = allocator,
.on_server_change = OnServerChange.Store.init(allocator),
.on_connection_change = OnConnectionChange.Store.init(allocator),
.capi_lock = std.Thread.Mutex{},
};
}
pub fn deinit(self: *App) void {
self.on_connection_change.deinit();
self.on_server_change.deinit();
}
pub const CApi = extern struct {
internal: *App,
server_selector: *ServerSelector.CApi,
connection: ConnectionState = .idle,
server: ?*Server.CApi = null,
pub const ConnectionState = enum(c_int) {
idle = 0,
busy = 1,
err_unexpected = 2,
err_network_unavailable = 3,
err_socket_permission = 4,
err_out_of_memory = 5,
err_socket = 6,
err_registry_down = 7,
err_failed_to_register = 8,
err_thread_spawn = 9,
err_websocket = 10,
err_not_found = 11,
};
pub fn init(allocator: std.mem.Allocator) std.mem.Allocator.Error!*CApi {
const internal = try allocator.create(App);
errdefer allocator.destroy(internal);
internal.* = App.init(allocator);
errdefer internal.deinit();
const server_selector = try ServerSelector.CApi.init(allocator);
errdefer server_selector.deinit(allocator);
const capi = try allocator.create(CApi);
capi.* = .{
.internal = internal,
.server_selector = server_selector,
};
return capi;
}
pub fn new() callconv(.C) ?*CApi {
return CApi.init(std.heap.c_allocator) catch return null;
}
pub fn deinit(self: *CApi, allocator: std.mem.Allocator) void {
if (self.server) |server| {
server.internal.conn.deinit();
self.internal.allocator.destroy(server.internal.conn);
server.deinit();
self.internal.allocator.destroy(server);
}
self.server_selector.deinit(allocator);
self.internal.deinit();
allocator.destroy(self.internal);
allocator.destroy(self);
}
pub fn destroy(self_ptr: ?*CApi) callconv(.C) void {
const self = self_ptr orelse return;
self.deinit(std.heap.c_allocator);
}
pub fn connect(
self_ptr: ?*CApi,
server_id: [*:0]const u8,
server_id_len: usize,
saved_token_ptr: ?[*:0]const u8,
saved_token_len: usize,
) callconv(.C) void {
const self = self_ptr orelse return;
if (self.connection == .busy) {
return;
}
const id = server_id[0..server_id_len];
const saved_token = if (saved_token_ptr) |tok| tok[0..saved_token_len] else null;
if (self.server) |server| {
if (std.mem.eql(u8, server.id[0..server.id_len], id)) {
return;
}
}
{
self.internal.capi_lock.lock();
defer self.internal.capi_lock.unlock();
self.connection = .busy;
self.internal.on_connection_change.runAll(.{});
}
const thread = std.Thread.spawn(.{}, connectWorker, .{ self, id, saved_token }) catch {
self.internal.capi_lock.lock();
defer self.internal.capi_lock.unlock();
self.connection = .err_thread_spawn;
self.internal.on_connection_change.runAll(.{});
return;
};
thread.detach();
}
pub fn onServerChange(capi_ptr: ?*CApi, cb: OnServerChange.Fn, userdata: callback.UserData) callconv(.C) void {
const capi = capi_ptr orelse return;
// TODO: Notify error to caller
capi.internal.on_server_change.add(OnServerChange.init(cb, userdata)) catch {};
}
pub fn onServerChangeDisarm(capi_ptr: ?*CApi, cb: OnServerChange.Fn) callconv(.C) void {
const capi = capi_ptr orelse return;
capi.internal.on_server_change.remove(cb);
}
pub fn onConnectionChange(capi_ptr: ?*CApi, cb: OnConnectionChange.Fn, userdata: callback.UserData) callconv(.C) void {
const capi = capi_ptr orelse return;
// TODO: Notify error to caller
capi.internal.on_connection_change.add(OnConnectionChange.init(cb, userdata)) catch {};
}
pub fn onConnectionChangeDisarm(capi_ptr: ?*CApi, cb: OnConnectionChange.Fn) callconv(.C) void {
const capi = capi_ptr orelse return;
capi.internal.on_connection_change.remove(cb);
}
};
fn connectWorker(self: *CApi, server_id: []const u8, saved_token: ?[]const u8) void {
if (self.server) |server| {
server.internal.conn.deinit();
self.internal.allocator.destroy(server.internal.conn);
server.deinit();
self.internal.allocator.destroy(server);
self.server = null;
}
for (self.server_selector.entries[0..self.server_selector.entries_len]) |entry| {
if (std.mem.eql(u8, entry.id[0..entry.id_len], server_id)) {
const conn, const token = register(
self.internal.allocator,
entry.getAddr(),
server_id,
saved_token,
) catch |err| {
std.log.warn("Unable to connect to pre-scanned sever, skipping: {s}", .{
@errorName(err),
});
continue;
};
defer self.internal.allocator.free(token);
const server = self.internal.allocator.create(Server.CApi) catch {
self.internal.capi_lock.lock();
defer self.internal.capi_lock.unlock();
self.connection = .err_out_of_memory;
self.internal.on_connection_change.runAll(.{});
return;
};
server.* = Server.CApi.init(
self.internal.allocator,
entry.getAddr(),
conn,
entry.getId(),
entry.getName(),
entry.getVersion(),
token,
) catch {
self.internal.capi_lock.lock();
defer self.internal.capi_lock.unlock();
self.connection = .err_out_of_memory;
self.internal.on_connection_change.runAll(.{});
return;
};
self.internal.capi_lock.lock();
defer self.internal.capi_lock.unlock();
self.server = server;
self.connection = .idle;
self.internal.on_server_change.runAll(.{});
self.internal.on_connection_change.runAll(.{});
return;
}
}
const info = discovery.resolve(ServerConnInfo, self.internal.allocator, server_id, .{}) catch |err| {
self.internal.capi_lock.lock();
defer self.internal.capi_lock.unlock();
self.connection = switch (err) {
error.OutOfMemory => App.CApi.ConnectionState.err_out_of_memory,
error.SocketPermissionDenied => App.CApi.ConnectionState.err_socket_permission,
error.SocketCreationError,
error.UDPRecvError,
error.UDPSendError,
=> App.CApi.ConnectionState.err_socket,
error.NetworkUnavailable => App.CApi.ConnectionState.err_network_unavailable,
else => App.CApi.ConnectionState.err_unexpected,
};
self.internal.on_connection_change.runAll(.{});
return;
} orelse {
self.internal.capi_lock.lock();
defer self.internal.capi_lock.unlock();
self.connection = .err_not_found;
self.internal.on_connection_change.runAll(.{});
return;
};
defer info.deinit();
const conn, const token = register(
self.internal.allocator,
info.addr,
server_id,
saved_token,
) catch |err| {
std.log.err("Unable to connect sever: {s}", .{@errorName(err)});
self.internal.capi_lock.lock();
defer self.internal.capi_lock.unlock();
self.connection = switch (err) {
error.OutOfMemory => App.CApi.ConnectionState.err_out_of_memory,
RegisterError.RegistryInfoError => App.CApi.ConnectionState.err_registry_down,
RegisterError.RegistryRegisterError => App.CApi.ConnectionState.err_failed_to_register,
RegisterError.ListeningThreadSpawnError => App.CApi.ConnectionState.err_thread_spawn,
RegisterError.ServerIdMismatch => App.CApi.ConnectionState.err_not_found,
Connection.InitError.WebSocketClientCreationError,
Connection.InitError.WebSocketHandshakeError,
=> App.CApi.ConnectionState.err_websocket,
else => App.CApi.ConnectionState.err_unexpected,
};
self.internal.on_connection_change.runAll(.{});
return;
};
defer self.internal.allocator.free(token);
const server = self.internal.allocator.create(Server.CApi) catch {
self.internal.capi_lock.lock();
defer self.internal.capi_lock.unlock();
self.connection = .err_out_of_memory;
self.internal.on_connection_change.runAll(.{});
return;
};
server.* = Server.CApi.init(
self.internal.allocator,
info.addr,
conn,
info.id,
info.name,
info.version,
token,
) catch {
self.internal.capi_lock.lock();
defer self.internal.capi_lock.unlock();
self.connection = .err_out_of_memory;
self.internal.on_connection_change.runAll(.{});
return;
};
self.internal.capi_lock.lock();
defer self.internal.capi_lock.unlock();
self.server = server;
self.connection = .idle;
self.internal.on_server_change.runAll(.{});
self.internal.on_connection_change.runAll(.{});
return;
}
const RegisterError = error{
RegistryInfoError,
RegistryRegisterError,
ListeningThreadSpawnError,
ServerIdMismatch,
} || Connection.InitError;
fn register(
allocator: std.mem.Allocator,
address: std.net.Address,
server_id: []const u8,
saved_token: ?[]const u8,
) !struct { *Connection, []const u8 } {
const conn = try allocator.create(Connection);
errdefer allocator.destroy(conn);
conn.* = try Connection.init(allocator, address);
errdefer conn.deinit();
conn.listen(PingService.handleRequest) catch {
return RegisterError.ListeningThreadSpawnError;
};
std.log.debug("Querying registry status...", .{});
const info = RegistryService.info(allocator, conn) catch |err| {
std.log.err("Failed to get extension registry status: {s}", .{@errorName(err)});
return RegisterError.RegistryInfoError;
};
defer info.deinit();
if (!std.mem.eql(u8, info.value.core_id, server_id)) {
return RegisterError.ServerIdMismatch;
}
const extension = AppExtension{
.token = saved_token,
};
std.log.debug("Registering extension {s} token...", .{if (saved_token) |_| "with" else "without"});
const r = RegistryService.register(AppExtension, allocator, conn, extension) catch |err| {
std.log.err("Failed to register extension: {s}", .{@errorName(err)});
return RegisterError.RegistryRegisterError;
};
defer r.deinit();
std.log.debug("Extension registered, connection is ready", .{});
const token = try allocator.dupe(u8, r.value.token);
return .{ conn, token };
}