-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathbridge.zig
More file actions
408 lines (356 loc) · 13.8 KB
/
bridge.zig
File metadata and controls
408 lines (356 loc) · 13.8 KB
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
const std = @import("std");
const CdpClient = @import("../cdp/client.zig").CdpClient;
const HarRecorder = @import("../cdp/har.zig").HarRecorder;
const A11yNode = @import("../snapshot/a11y.zig").A11yNode;
pub const TabEntry = struct {
id: []const u8,
url: []const u8,
title: []const u8,
ws_url: []const u8,
created_at: i64,
last_accessed: i64,
};
pub const RefCache = struct {
refs: std.StringHashMap(u32),
node_count: usize,
pub fn init(allocator: std.mem.Allocator) RefCache {
return .{
.refs = std.StringHashMap(u32).init(allocator),
.node_count = 0,
};
}
pub fn clear(self: *RefCache) void {
var it = self.refs.keyIterator();
while (it.next()) |key| {
self.refs.allocator.free(key.*);
}
self.refs.clearRetainingCapacity();
self.node_count = 0;
}
pub fn deinit(self: *RefCache) void {
self.clear();
self.refs.deinit();
}
};
pub const Bridge = struct {
allocator: std.mem.Allocator,
tabs: std.StringHashMap(TabEntry),
snapshots: std.StringHashMap(RefCache),
prev_snapshots: std.StringHashMap([]const A11yNode),
cdp_clients: std.StringHashMap(*CdpClient),
har_recorders: std.StringHashMap(*HarRecorder),
mu: std.Thread.RwLock,
pub fn init(allocator: std.mem.Allocator) Bridge {
return .{
.allocator = allocator,
.tabs = std.StringHashMap(TabEntry).init(allocator),
.snapshots = std.StringHashMap(RefCache).init(allocator),
.prev_snapshots = std.StringHashMap([]const A11yNode).init(allocator),
.cdp_clients = std.StringHashMap(*CdpClient).init(allocator),
.har_recorders = std.StringHashMap(*HarRecorder).init(allocator),
.mu = .{},
};
}
pub fn deinit(self: *Bridge) void {
var har_it = self.har_recorders.valueIterator();
while (har_it.next()) |rec| {
rec.*.deinit();
self.allocator.destroy(rec.*);
}
self.har_recorders.deinit();
var cdp_it = self.cdp_clients.valueIterator();
while (cdp_it.next()) |client| {
client.*.deinit();
self.allocator.destroy(client.*);
}
self.cdp_clients.deinit();
var prev_it = self.prev_snapshots.iterator();
while (prev_it.next()) |entry| {
self.allocator.free(entry.key_ptr.*);
freeSnapshot(self.allocator, entry.value_ptr.*);
}
self.prev_snapshots.deinit();
var snap_it = self.snapshots.valueIterator();
while (snap_it.next()) |cache| {
cache.deinit();
}
self.snapshots.deinit();
var tab_it = self.tabs.valueIterator();
while (tab_it.next()) |tab| {
self.allocator.free(tab.id);
self.allocator.free(tab.url);
self.allocator.free(tab.title);
self.allocator.free(tab.ws_url);
}
self.tabs.deinit();
}
pub fn tabCount(self: *Bridge) usize {
self.mu.lockShared();
defer self.mu.unlockShared();
return self.tabs.count();
}
pub fn getTab(self: *Bridge, tab_id: []const u8) ?TabEntry {
self.mu.lockShared();
defer self.mu.unlockShared();
return self.tabs.get(tab_id);
}
pub fn putTab(self: *Bridge, entry: TabEntry) !void {
self.mu.lock();
defer self.mu.unlock();
// Dupe all strings into bridge allocator for ownership
const owned = TabEntry{
.id = try self.allocator.dupe(u8, entry.id),
.url = try self.allocator.dupe(u8, entry.url),
.title = try self.allocator.dupe(u8, entry.title),
.ws_url = try self.allocator.dupe(u8, entry.ws_url),
.created_at = entry.created_at,
.last_accessed = entry.last_accessed,
};
errdefer {
self.allocator.free(owned.id);
self.allocator.free(owned.url);
self.allocator.free(owned.title);
self.allocator.free(owned.ws_url);
}
// Remove old entry first (frees old key from map)
if (self.tabs.fetchRemove(entry.id)) |old_kv| {
self.allocator.free(old_kv.key);
self.allocator.free(old_kv.value.url);
self.allocator.free(old_kv.value.title);
self.allocator.free(old_kv.value.ws_url);
// old_kv.key == old_kv.value.id, already freed above
}
try self.tabs.put(owned.id, owned);
}
pub fn removeTab(self: *Bridge, tab_id: []const u8) void {
self.mu.lock();
defer self.mu.unlock();
// Grab owned strings before removing from map
const tab = self.tabs.get(tab_id) orelse {
if (self.snapshots.getPtr(tab_id)) |cache| cache.deinit();
_ = self.snapshots.remove(tab_id);
if (self.prev_snapshots.fetchRemove(tab_id)) |kv| {
self.allocator.free(kv.key);
freeSnapshot(self.allocator, kv.value);
}
if (self.cdp_clients.fetchRemove(tab_id)) |kv| {
kv.value.deinit();
self.allocator.destroy(kv.value);
}
if (self.har_recorders.fetchRemove(tab_id)) |kv| {
kv.value.deinit();
self.allocator.destroy(kv.value);
}
return;
};
_ = self.tabs.remove(tab_id);
self.allocator.free(tab.id);
self.allocator.free(tab.url);
self.allocator.free(tab.title);
self.allocator.free(tab.ws_url);
if (self.snapshots.getPtr(tab_id)) |cache| cache.deinit();
_ = self.snapshots.remove(tab_id);
if (self.prev_snapshots.fetchRemove(tab_id)) |kv| {
self.allocator.free(kv.key);
freeSnapshot(self.allocator, kv.value);
}
if (self.cdp_clients.fetchRemove(tab_id)) |kv| {
kv.value.deinit();
self.allocator.destroy(kv.value);
}
if (self.har_recorders.fetchRemove(tab_id)) |kv| {
kv.value.deinit();
self.allocator.destroy(kv.value);
}
}
pub fn listTabs(self: *Bridge, allocator: std.mem.Allocator) ![]TabEntry {
self.mu.lockShared();
defer self.mu.unlockShared();
var list: std.ArrayList(TabEntry) = .empty;
var it = self.tabs.valueIterator();
while (it.next()) |entry| {
try list.append(allocator, entry.*);
}
return list.toOwnedSlice(allocator);
}
/// Get or create a CDP client for a tab.
/// Returns a stable heap-allocated pointer that survives HashMap resizes.
pub fn getCdpClient(self: *Bridge, tab_id: []const u8) ?*CdpClient {
self.mu.lock();
defer self.mu.unlock();
if (self.cdp_clients.get(tab_id)) |client| {
return client;
}
const tab = self.tabs.get(tab_id) orelse return null;
if (tab.ws_url.len == 0) return null;
const client = self.allocator.create(CdpClient) catch return null;
client.* = CdpClient.init(self.allocator, tab.ws_url);
self.cdp_clients.put(tab_id, client) catch {
self.allocator.destroy(client);
return null;
};
return client;
}
pub fn exportState(self: *Bridge, allocator: std.mem.Allocator) ![]const u8 {
self.mu.lockShared();
defer self.mu.unlockShared();
var json_buf: std.ArrayList(u8) = .empty;
const writer = json_buf.writer(allocator);
try writer.writeAll("[");
var it = self.tabs.valueIterator();
var first = true;
while (it.next()) |tab| {
if (!first) try writer.writeAll(",");
first = false;
try writer.print("{{\"id\":\"{s}\",\"url\":\"{s}\",\"title\":\"{s}\",\"ws_url\":\"{s}\"}}", .{ tab.id, tab.url, tab.title, tab.ws_url });
}
try writer.writeAll("]");
return json_buf.toOwnedSlice(allocator);
}
pub fn importState(self: *Bridge, json: []const u8, allocator: std.mem.Allocator) !usize {
_ = allocator;
var count: usize = 0;
var pos: usize = 0;
while (pos < json.len) {
const obj_start = std.mem.indexOfScalarPos(u8, json, pos, '{') orelse break;
const obj_end = std.mem.indexOfScalarPos(u8, json, obj_start, '}') orelse break;
const obj = json[obj_start .. obj_end + 1];
const id = extractField(obj, "\"id\"") orelse {
pos = obj_end + 1;
continue;
};
const url = extractField(obj, "\"url\"") orelse "";
const title = extractField(obj, "\"title\"") orelse "";
const ws_url = extractField(obj, "\"ws_url\"") orelse "";
try self.putTab(.{
.id = id,
.url = url,
.title = title,
.ws_url = ws_url,
.created_at = std.time.timestamp(),
.last_accessed = std.time.timestamp(),
});
count += 1;
pos = obj_end + 1;
}
return count;
}
fn extractField(json: []const u8, field: []const u8) ?[]const u8 {
const field_pos = std.mem.indexOf(u8, json, field) orelse return null;
const colon = std.mem.indexOfScalarPos(u8, json, field_pos + field.len, ':') orelse return null;
var i = colon + 1;
while (i < json.len and (json[i] == ' ' or json[i] == '"')) : (i += 1) {}
if (i >= json.len) return null;
const val_start = i;
const val_end = std.mem.indexOfScalarPos(u8, json, val_start, '"') orelse return null;
return json[val_start..val_end];
}
/// Get or create a HAR recorder for a tab.
/// Returns a stable heap-allocated pointer that survives HashMap resizes.
pub fn getHarRecorder(self: *Bridge, tab_id: []const u8) ?*HarRecorder {
self.mu.lock();
defer self.mu.unlock();
if (self.har_recorders.get(tab_id)) |rec| {
return rec;
}
const rec = self.allocator.create(HarRecorder) catch return null;
rec.* = HarRecorder.init(self.allocator);
self.har_recorders.put(tab_id, rec) catch {
self.allocator.destroy(rec);
return null;
};
return rec;
}
pub fn cloneSnapshot(self: *Bridge, snapshot: []const A11yNode) ![]A11yNode {
const copy = try self.allocator.alloc(A11yNode, snapshot.len);
errdefer self.allocator.free(copy);
var initialized: usize = 0;
errdefer {
for (copy[0..initialized]) |node| {
self.allocator.free(node.ref);
self.allocator.free(node.role);
self.allocator.free(node.name);
self.allocator.free(node.value);
}
}
for (snapshot, 0..) |node, i| {
copy[i] = .{
.ref = try self.allocator.dupe(u8, node.ref),
.role = try self.allocator.dupe(u8, node.role),
.name = try self.allocator.dupe(u8, node.name),
.value = try self.allocator.dupe(u8, node.value),
.backend_node_id = node.backend_node_id,
.depth = node.depth,
};
initialized += 1;
}
return copy;
}
};
fn freeSnapshot(allocator: std.mem.Allocator, snapshot: []const A11yNode) void {
for (snapshot) |node| {
allocator.free(node.ref);
allocator.free(node.role);
allocator.free(node.name);
allocator.free(node.value);
}
allocator.free(snapshot);
}
test "bridge init/deinit" {
var bridge = Bridge.init(std.testing.allocator);
defer bridge.deinit();
try std.testing.expectEqual(@as(usize, 0), bridge.tabCount());
}
test "exportState empty bridge" {
var bridge = Bridge.init(std.testing.allocator);
defer bridge.deinit();
const json = try bridge.exportState(std.testing.allocator);
defer std.testing.allocator.free(json);
try std.testing.expectEqualStrings("[]", json);
}
test "exportState with one tab" {
var bridge = Bridge.init(std.testing.allocator);
defer bridge.deinit();
try bridge.putTab(.{
.id = "t1",
.url = "https://example.com",
.title = "Example",
.ws_url = "ws://localhost:9222/t1",
.created_at = 1000,
.last_accessed = 1000,
});
const json = try bridge.exportState(std.testing.allocator);
defer std.testing.allocator.free(json);
try std.testing.expect(std.mem.indexOf(u8, json, "https://example.com") != null);
try std.testing.expect(std.mem.indexOf(u8, json, "\"id\":\"t1\"") != null);
}
test "importState round-trip" {
var bridge = Bridge.init(std.testing.allocator);
defer bridge.deinit();
const input = "[{\"id\":\"a1\",\"url\":\"https://a.com\",\"title\":\"A\",\"ws_url\":\"ws://x\"},{\"id\":\"b2\",\"url\":\"https://b.com\",\"title\":\"B\",\"ws_url\":\"\"}]";
const count = try bridge.importState(input, std.testing.allocator);
try std.testing.expectEqual(@as(usize, 2), count);
try std.testing.expectEqual(@as(usize, 2), bridge.tabCount());
const tab = bridge.getTab("a1");
try std.testing.expect(tab != null);
try std.testing.expectEqualStrings("https://a.com", tab.?.url);
}
test "bridge tab CRUD" {
var bridge = Bridge.init(std.testing.allocator);
defer bridge.deinit();
const entry = TabEntry{
.id = "tab-1",
.url = "https://example.com",
.title = "Example",
.ws_url = "",
.created_at = 1000,
.last_accessed = 1000,
};
try bridge.putTab(entry);
try std.testing.expectEqual(@as(usize, 1), bridge.tabCount());
const got = bridge.getTab("tab-1");
try std.testing.expect(got != null);
try std.testing.expectEqualStrings("https://example.com", got.?.url);
bridge.removeTab("tab-1");
try std.testing.expectEqual(@as(usize, 0), bridge.tabCount());
}