Skip to content

Commit 17d3d62

Browse files
Merge pull request #478 from lightpanda-io/global_http_client
Share the HTTP client globally
2 parents 9fe1074 + 705603a commit 17d3d62

File tree

8 files changed

+81
-59
lines changed

8 files changed

+81
-59
lines changed

src/app.zig

Lines changed: 26 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,54 +2,66 @@ const std = @import("std");
22

33
const Loop = @import("jsruntime").Loop;
44
const Allocator = std.mem.Allocator;
5+
const HttpClient = @import("http/Client.zig");
56
const Telemetry = @import("telemetry/telemetry.zig").Telemetry;
67

78
const log = std.log.scoped(.app);
89

9-
pub const RunMode = enum {
10-
serve,
11-
fetch,
12-
};
13-
1410
// Container for global state / objects that various parts of the system
1511
// might need.
1612
pub const App = struct {
1713
loop: *Loop,
18-
app_dir_path: ?[]const u8,
1914
allocator: Allocator,
2015
telemetry: Telemetry,
16+
http_client: HttpClient,
17+
app_dir_path: ?[]const u8,
18+
19+
pub const RunMode = enum {
20+
serve,
21+
fetch,
22+
};
23+
24+
pub fn init(allocator: Allocator, run_mode: RunMode) !*App {
25+
const app = try allocator.create(App);
26+
errdefer allocator.destroy(app);
2127

22-
pub fn init(allocator: Allocator, run_mode: RunMode) !App {
2328
const loop = try allocator.create(Loop);
2429
errdefer allocator.destroy(loop);
2530

2631
loop.* = try Loop.init(allocator);
2732
errdefer loop.deinit();
2833

2934
const app_dir_path = getAndMakeAppDir(allocator);
30-
const telemetry = Telemetry.init(allocator, run_mode, app_dir_path);
31-
errdefer telemetry.deinit();
3235

33-
return .{
36+
app.* = .{
3437
.loop = loop,
3538
.allocator = allocator,
36-
.telemetry = telemetry,
39+
.telemetry = undefined,
3740
.app_dir_path = app_dir_path,
41+
.http_client = .{ .allocator = allocator },
3842
};
43+
app.telemetry = Telemetry.init(app, run_mode);
44+
45+
return app;
3946
}
4047

4148
pub fn deinit(self: *App) void {
49+
const allocator = self.allocator;
4250
if (self.app_dir_path) |app_dir_path| {
43-
self.allocator.free(app_dir_path);
51+
allocator.free(app_dir_path);
4452
}
45-
4653
self.telemetry.deinit();
4754
self.loop.deinit();
48-
self.allocator.destroy(self.loop);
55+
allocator.destroy(self.loop);
56+
self.http_client.deinit();
57+
allocator.destroy(self);
4958
}
5059
};
5160

5261
fn getAndMakeAppDir(allocator: Allocator) ?[]const u8 {
62+
if (@import("builtin").is_test) {
63+
return allocator.dupe(u8, "/tmp") catch unreachable;
64+
}
5365
const app_dir_path = std.fs.getAppDataDir(allocator, "lightpanda") catch |err| {
5466
log.warn("failed to get lightpanda data dir: {}", .{err});
5567
return null;

src/browser/browser.zig

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ pub const Browser = struct {
6363
app: *App,
6464
session: ?*Session,
6565
allocator: Allocator,
66-
http_client: HttpClient,
66+
http_client: *HttpClient,
6767
session_pool: SessionPool,
6868
page_arena: std.heap.ArenaAllocator,
6969

@@ -75,15 +75,14 @@ pub const Browser = struct {
7575
.app = app,
7676
.session = null,
7777
.allocator = allocator,
78-
.http_client = .{ .allocator = allocator },
78+
.http_client = @ptrCast(&app.http_client),
7979
.session_pool = SessionPool.init(allocator),
8080
.page_arena = std.heap.ArenaAllocator.init(allocator),
8181
};
8282
}
8383

8484
pub fn deinit(self: *Browser) void {
8585
self.closeSession();
86-
self.http_client.deinit();
8786
self.session_pool.deinit();
8887
self.page_arena.deinit();
8988
}
@@ -454,7 +453,7 @@ pub const Page = struct {
454453
// replace the user context document with the new one.
455454
try session.env.setUserContext(.{
456455
.document = html_doc,
457-
.httpClient = &self.session.browser.http_client,
456+
.httpClient = self.session.browser.http_client,
458457
});
459458

460459
// browse the DOM tree to retrieve scripts

src/cdp/testing.zig

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ const TestCDP = main.CDPT(struct {
118118
});
119119

120120
const TestContext = struct {
121-
app: App,
121+
app: *App,
122122
client: ?Client = null,
123123
cdp_: ?TestCDP = null,
124124
arena: std.heap.ArenaAllocator,
@@ -136,7 +136,7 @@ const TestContext = struct {
136136
self.client = Client.init(self.arena.allocator());
137137
// Don't use the arena here. We want to detect leaks in CDP.
138138
// The arena is only for test-specific stuff
139-
self.cdp_ = TestCDP.init(&self.app, &self.client.?);
139+
self.cdp_ = TestCDP.init(self.app, &self.client.?);
140140
}
141141
return &self.cdp_.?;
142142
}

src/main.zig

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ pub fn main() !void {
7575
app.telemetry.record(.{ .run = {} });
7676

7777
const timeout = std.time.ns_per_s * @as(u64, opts.timeout);
78-
server.run(&app, address, timeout) catch |err| {
78+
server.run(app, address, timeout) catch |err| {
7979
log.err("Server error", .{});
8080
return err;
8181
};
@@ -92,7 +92,7 @@ pub fn main() !void {
9292
defer vm.deinit();
9393

9494
// browser
95-
var browser = Browser.init(&app);
95+
var browser = Browser.init(app);
9696
defer browser.deinit();
9797

9898
var session = try browser.newSession({});

src/telemetry/lightpanda.zig

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ const build_info = @import("build_info");
55
const Thread = std.Thread;
66
const Allocator = std.mem.Allocator;
77

8+
const App = @import("../app.zig").App;
89
const telemetry = @import("telemetry.zig");
9-
const RunMode = @import("../app.zig").RunMode;
1010

1111
const log = std.log.scoped(.telemetry);
1212
const URL = "https://telemetry.lightpanda.io";
@@ -19,18 +19,21 @@ pub const LightPanda = struct {
1919
allocator: Allocator,
2020
mutex: std.Thread.Mutex,
2121
cond: Thread.Condition,
22+
client: *std.http.Client,
2223
node_pool: std.heap.MemoryPool(List.Node),
2324

2425
const List = std.DoublyLinkedList(LightPandaEvent);
2526

26-
pub fn init(allocator: Allocator) !LightPanda {
27+
pub fn init(app: *App) !LightPanda {
28+
const allocator = app.allocator;
2729
return .{
2830
.cond = .{},
2931
.mutex = .{},
3032
.pending = .{},
3133
.thread = null,
3234
.running = true,
3335
.allocator = allocator,
36+
.client = @ptrCast(&app.http_client),
3437
.uri = std.Uri.parse(URL) catch unreachable,
3538
.node_pool = std.heap.MemoryPool(List.Node).init(allocator),
3639
};
@@ -47,7 +50,7 @@ pub const LightPanda = struct {
4750
self.node_pool.deinit();
4851
}
4952

50-
pub fn send(self: *LightPanda, iid: ?[]const u8, run_mode: RunMode, raw_event: telemetry.Event) !void {
53+
pub fn send(self: *LightPanda, iid: ?[]const u8, run_mode: App.RunMode, raw_event: telemetry.Event) !void {
5154
const event = LightPandaEvent{
5255
.iid = iid,
5356
.mode = run_mode,
@@ -68,19 +71,16 @@ pub const LightPanda = struct {
6871
}
6972

7073
fn run(self: *LightPanda) void {
74+
const client = self.client;
7175
var arr: std.ArrayListUnmanaged(u8) = .{};
72-
var client = std.http.Client{ .allocator = self.allocator };
7376

74-
defer {
75-
arr.deinit(self.allocator);
76-
client.deinit();
77-
}
77+
defer arr.deinit(self.allocator);
7878

7979
self.mutex.lock();
8080
while (true) {
8181
while (self.pending.popFirst()) |node| {
8282
self.mutex.unlock();
83-
self.postEvent(&node.data, &client, &arr) catch |err| {
83+
self.postEvent(&node.data, client, &arr) catch |err| {
8484
log.warn("Telementry reporting error: {}", .{err});
8585
};
8686
self.mutex.lock();
@@ -113,7 +113,7 @@ pub const LightPanda = struct {
113113

114114
const LightPandaEvent = struct {
115115
iid: ?[]const u8,
116-
mode: RunMode,
116+
mode: App.RunMode,
117117
event: telemetry.Event,
118118

119119
pub fn jsonStringify(self: *const LightPandaEvent, writer: anytype) !void {

src/telemetry/telemetry.zig

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@ const builtin = @import("builtin");
33

44
const Allocator = std.mem.Allocator;
55

6+
const App = @import("../app.zig").App;
67
const Loop = @import("jsruntime").Loop;
78
const uuidv4 = @import("../id.zig").uuidv4;
8-
const RunMode = @import("../app.zig").RunMode;
99

1010
const log = std.log.scoped(.telemetry);
1111
const IID_FILE = "iid";
@@ -25,11 +25,11 @@ fn TelemetryT(comptime P: type) type {
2525

2626
disabled: bool,
2727

28-
run_mode: RunMode,
28+
run_mode: App.RunMode,
2929

3030
const Self = @This();
3131

32-
pub fn init(allocator: Allocator, run_mode: RunMode, app_dir_path: ?[]const u8) Self {
32+
pub fn init(app: *App, run_mode: App.RunMode) Self {
3333
const disabled = std.process.hasEnvVarConstant("LIGHTPANDA_DISABLE_TELEMETRY");
3434
if (builtin.mode != .Debug and builtin.is_test == false) {
3535
log.info("telemetry {s}", .{if (disabled) "disabled" else "enabled"});
@@ -38,8 +38,8 @@ fn TelemetryT(comptime P: type) type {
3838
return .{
3939
.disabled = disabled,
4040
.run_mode = run_mode,
41-
.provider = try P.init(allocator),
42-
.iid = if (disabled) null else getOrCreateId(app_dir_path),
41+
.provider = try P.init(app),
42+
.iid = if (disabled) null else getOrCreateId(app.app_dir_path),
4343
};
4444
}
4545

@@ -104,32 +104,32 @@ pub const Event = union(enum) {
104104
};
105105

106106
const NoopProvider = struct {
107-
fn init(_: Allocator) !NoopProvider {
107+
fn init(_: *App) !NoopProvider {
108108
return .{};
109109
}
110110
fn deinit(_: NoopProvider) void {}
111-
pub fn send(_: NoopProvider, _: ?[]const u8, _: RunMode, _: Event) !void {}
111+
pub fn send(_: NoopProvider, _: ?[]const u8, _: App.RunMode, _: Event) !void {}
112112
};
113113

114114
extern fn setenv(name: [*:0]u8, value: [*:0]u8, override: c_int) c_int;
115115
extern fn unsetenv(name: [*:0]u8) c_int;
116116

117-
const testing = std.testing;
117+
const testing = @import("../testing.zig");
118118
test "telemetry: disabled by environment" {
119119
_ = setenv(@constCast("LIGHTPANDA_DISABLE_TELEMETRY"), @constCast(""), 0);
120120
defer _ = unsetenv(@constCast("LIGHTPANDA_DISABLE_TELEMETRY"));
121121

122122
const FailingProvider = struct {
123-
fn init(_: Allocator) !@This() {
123+
fn init(_: *App) !@This() {
124124
return .{};
125125
}
126126
fn deinit(_: @This()) void {}
127-
pub fn send(_: @This(), _: ?[]const u8, _: RunMode, _: Event) !void {
127+
pub fn send(_: @This(), _: ?[]const u8, _: App.RunMode, _: Event) !void {
128128
unreachable;
129129
}
130130
};
131131

132-
var telemetry = TelemetryT(FailingProvider).init(testing.allocator, .serve, null);
132+
var telemetry = TelemetryT(FailingProvider).init(undefined, .serve);
133133
defer telemetry.deinit();
134134
telemetry.record(.{ .run = {} });
135135
}
@@ -141,15 +141,18 @@ test "telemetry: getOrCreateId" {
141141

142142
const id1 = getOrCreateId("/tmp/").?;
143143
const id2 = getOrCreateId("/tmp/").?;
144-
try testing.expectEqualStrings(&id1, &id2);
144+
try testing.expectEqual(&id1, &id2);
145145

146146
std.fs.cwd().deleteFile("/tmp/" ++ IID_FILE) catch {};
147147
const id3 = getOrCreateId("/tmp/").?;
148148
try testing.expectEqual(false, std.mem.eql(u8, &id1, &id3));
149149
}
150150

151151
test "telemetry: sends event to provider" {
152-
var telemetry = TelemetryT(MockProvider).init(testing.allocator, .serve, "/tmp/");
152+
var app = testing.app(.{});
153+
defer app.deinit();
154+
155+
var telemetry = TelemetryT(MockProvider).init(app, .serve);
153156
defer telemetry.deinit();
154157
const mock = &telemetry.provider;
155158

@@ -165,28 +168,28 @@ test "telemetry: sends event to provider" {
165168

166169
const MockProvider = struct {
167170
iid: ?[]const u8,
168-
run_mode: ?RunMode,
171+
run_mode: ?App.RunMode,
169172
allocator: Allocator,
170173
events: std.ArrayListUnmanaged(Event),
171174

172-
fn init(allocator: Allocator) !@This() {
175+
fn init(app: *App) !@This() {
173176
return .{
174177
.iid = null,
175178
.run_mode = null,
176179
.events = .{},
177-
.allocator = allocator,
180+
.allocator = app.allocator,
178181
};
179182
}
180183
fn deinit(self: *MockProvider) void {
181184
self.events.deinit(self.allocator);
182185
}
183-
pub fn send(self: *MockProvider, iid: ?[]const u8, run_mode: RunMode, events: Event) !void {
186+
pub fn send(self: *MockProvider, iid: ?[]const u8, run_mode: App.RunMode, events: Event) !void {
184187
if (self.iid == null) {
185188
try testing.expectEqual(null, self.run_mode);
186189
self.iid = iid.?;
187190
self.run_mode = run_mode;
188191
} else {
189-
try testing.expectEqualStrings(self.iid.?, iid.?);
192+
try testing.expectEqual(self.iid.?, iid.?);
190193
try testing.expectEqual(self.run_mode.?, run_mode);
191194
}
192195
try self.events.append(self.allocator, events);

0 commit comments

Comments
 (0)