@@ -2,75 +2,176 @@ const std = @import("std");
22const Allocator = std .mem .Allocator ;
33const ArenAallocator = std .heap .ArenaAllocator ;
44
5- const Event = @import ("telemetry.zig" ).Event ;
5+ const Loop = @import ("jsruntime" ).Loop ;
6+ const Client = @import ("asyncio" ).Client ;
7+
68const log = std .log .scoped (.telemetry );
79
8- const URL = "https://lightpanda.io/browser-stats " ;
10+ const URL = "https://stats. lightpanda.io" ;
911
10- pub const Lightpanda = struct {
12+ pub const LightPanda = struct {
1113 uri : std.Uri ,
12- arena : ArenAallocator ,
13- client : std.http.Client ,
14- headers : [1 ]std.http.Header ,
14+ io : Client.IO ,
15+ client : Client ,
16+ allocator : Allocator ,
17+ sending_pool : std .heap .MemoryPool (Sending ),
18+ client_context_pool : std .heap .MemoryPool (Client .Ctx ),
1519
16- pub fn init (allocator : Allocator ) ! Lightpanda {
20+ pub fn init (allocator : Allocator , loop : * Loop ) ! LightPanda {
1721 return .{
22+ .allocator = allocator ,
23+ .io = Client .IO .init (loop ),
1824 .client = .{ .allocator = allocator },
19- .arena = std .heap .ArenaAllocator .init (allocator ),
2025 .uri = std .Uri .parse (URL ) catch unreachable ,
21- .headers = [1 ]std.http.Header {
22- .{ .name = "Content-Type" , .value = "application/json" },
23- },
26+ .sending_pool = std .heap .MemoryPool (Sending ).init (allocator ),
27+ .client_context_pool = std .heap .MemoryPool (Client .Ctx ).init (allocator ),
2428 };
2529 }
2630
27- pub fn deinit (self : * Lightpanda ) void {
28- self .arena .deinit ();
31+ pub fn deinit (self : * LightPanda ) void {
2932 self .client .deinit ();
33+ self .sending_pool .deinit ();
34+ self .client_context_pool .deinit ();
3035 }
3136
32- pub fn send (self : * Lightpanda , iid : ? []const u8 , eid : []const u8 , events : []Event ) ! void {
33- _ = self ;
34- _ = iid ;
35- _ = eid ;
36- _ = events ;
37- // defer _ = self.arena.reset(.{ .retain_capacity = {} });
38- // const body = try std.json.stringifyAlloc(self.arena.allocator(), PlausibleEvent{ .event = event }, .{});
39-
40- // var server_headers: [2048]u8 = undefined;
41- // var req = try self.client.open(.POST, self.uri, .{
42- // .redirect_behavior = .not_allowed,
43- // .extra_headers = &self.headers,
44- // .server_header_buffer = &server_headers,
45- // });
46- // req.transfer_encoding = .{ .content_length = body.len };
47- // try req.send();
48-
49- // try req.writeAll(body);
50- // try req.finish();
51- // try req.wait();
52-
53- // const status = req.response.status;
54- // if (status != .accepted) {
55- // log.warn("telemetry '{s}' event error: {d}", .{ @tagName(event), @intFromEnum(status) });
56- // } else {
57- // log.warn("telemetry '{s}' sent", .{@tagName(event)});
58- // }
37+ pub fn send (self : * LightPanda , iid : ? []const u8 , eid : []const u8 , event : anytype ) ! void {
38+ var arena = std .heap .ArenaAllocator .init (self .allocator );
39+ errdefer arena .deinit ();
40+
41+ const resp_header_buffer = try arena .allocator ().alloc (u8 , 4096 );
42+ const body = try std .json .stringifyAlloc (arena .allocator (), .{
43+ .iid = iid ,
44+ .eid = eid ,
45+ .event = event ,
46+ }, .{});
47+
48+ const sending = try self .sending_pool .create ();
49+ errdefer self .sending_pool .destroy (sending );
50+
51+ sending .* = .{
52+ .body = body ,
53+ .arena = arena ,
54+ .lightpanda = self ,
55+ .request = try self .client .create (.POST , self .uri , .{
56+ .server_header_buffer = resp_header_buffer ,
57+ }),
58+ };
59+ errdefer sending .request .deinit ();
60+
61+ const ctx = try self .client_context_pool .create ();
62+ errdefer self .client_context_pool .destroy (ctx );
63+
64+ ctx .* = try Client .Ctx .init (& self .io , & sending .request );
65+ ctx .userData = sending ;
66+
67+ try self .client .async_open (
68+ .POST ,
69+ self .uri ,
70+ .{ .server_header_buffer = resp_header_buffer },
71+ ctx ,
72+ onRequestConnect ,
73+ );
74+ }
75+
76+ fn handleError (self : * LightPanda , ctx : * Client.Ctx , err : anyerror ) anyerror ! void {
77+ ctx .deinit ();
78+ self .client_context_pool .destroy (ctx );
79+
80+ var sending : * Sending = @ptrCast (@alignCast (ctx .userData ));
81+ sending .deinit ();
82+ self .sending_pool .destroy (sending );
83+ log .info ("request failure: {}" , .{err });
84+ }
85+
86+ fn onRequestConnect (ctx : * Client.Ctx , res : anyerror ! void ) anyerror ! void {
87+ var sending : * Sending = @ptrCast (@alignCast (ctx .userData ));
88+ res catch | err | return sending .lightpanda .handleError (ctx , err );
89+
90+ ctx .req .transfer_encoding = .{ .content_length = sending .body .len };
91+ return ctx .req .async_send (ctx , onRequestSend ) catch | err | {
92+ return sending .lightpanda .handleError (ctx , err );
93+ };
94+ }
95+
96+ fn onRequestSend (ctx : * Client.Ctx , res : anyerror ! void ) anyerror ! void {
97+ var sending : * Sending = @ptrCast (@alignCast (ctx .userData ));
98+ res catch | err | return sending .lightpanda .handleError (ctx , err );
99+
100+ return ctx .req .async_writeAll (sending .body , ctx , onRequestWrite ) catch | err | {
101+ return sending .lightpanda .handleError (ctx , err );
102+ };
103+ }
104+
105+ fn onRequestWrite (ctx : * Client.Ctx , res : anyerror ! void ) anyerror ! void {
106+ var sending : * Sending = @ptrCast (@alignCast (ctx .userData ));
107+ res catch | err | return sending .lightpanda .handleError (ctx , err );
108+ return ctx .req .async_finish (ctx , onRequestFinish ) catch | err | {
109+ return sending .lightpanda .handleError (ctx , err );
110+ };
111+ }
112+
113+ fn onRequestFinish (ctx : * Client.Ctx , res : anyerror ! void ) anyerror ! void {
114+ var sending : * Sending = @ptrCast (@alignCast (ctx .userData ));
115+ res catch | err | return sending .lightpanda .handleError (ctx , err );
116+ return ctx .req .async_wait (ctx , onRequestWait ) catch | err | {
117+ return sending .lightpanda .handleError (ctx , err );
118+ };
119+ }
120+
121+ fn onRequestWait (ctx : * Client.Ctx , res : anyerror ! void ) anyerror ! void {
122+ var sending : * Sending = @ptrCast (@alignCast (ctx .userData ));
123+ res catch | err | return sending .lightpanda .handleError (ctx , err );
124+
125+ const lightpanda = sending .lightpanda ;
126+
127+ defer {
128+ ctx .deinit ();
129+ lightpanda .client_context_pool .destroy (ctx );
130+
131+ sending .deinit ();
132+ lightpanda .sending_pool .destroy (sending );
133+ }
134+
135+ var buffer : [2048 ]u8 = undefined ;
136+ const reader = ctx .req .reader ();
137+ while (true ) {
138+ const n = reader .read (& buffer ) catch 0 ;
139+ if (n == 0 ) {
140+ break ;
141+ }
142+ }
143+ if (ctx .req .response .status != .ok ) {
144+ log .info ("invalid response: {d}" , .{@intFromEnum (ctx .req .response .status )});
145+ }
146+ }
147+ };
148+
149+ const Sending = struct {
150+ body : []const u8 ,
151+ request : Client.Request ,
152+ lightpanda : * LightPanda ,
153+ arena : std.heap.ArenaAllocator ,
154+
155+ pub fn deinit (self : * Sending ) void {
156+ self .arena .deinit ();
157+ self .request .deinit ();
59158 }
60159};
61160
62- // wraps a telemetry event so that we can serialize it to plausible's event endpoint
63- // const PlausibleEvent = struct {
64- // event: Event,
161+ // // wraps a telemetry event so that we can serialize it to plausible's event endpoint
162+ // const EventWrap = struct {
163+ // iid: ?[]const u8,
164+ // eid: []const u8,
165+ // event: *const Event,
65166
66- // pub fn jsonStringify(self: PlausibleEvent , jws: anytype) !void {
167+ // pub fn jsonStringify(self: *const EventWrap , jws: anytype) !void {
67168// try jws.beginObject();
68- // try jws.objectField("name ");
69- // try jws.write(@tagName( self.event) );
70- // try jws.objectField("url ");
71- // try jws.write(EVENT_URL );
72- // try jws.objectField("domain ");
73- // try jws.write(DOMAIN_KEY );
169+ // try jws.objectField("iid ");
170+ // try jws.write(self.iid );
171+ // try jws.objectField("eid ");
172+ // try jws.write(self.eid );
173+ // try jws.objectField("event ");
174+ // try jws.write(@tagName(self.event.*) );
74175// try jws.objectField("props");
75176// switch (self.event) {
76177// inline else => |props| try jws.write(props),
@@ -80,11 +181,15 @@ pub const Lightpanda = struct {
80181// };
81182
82183// const testing = std.testing;
83- // test "plausible: json event" {
84- // const json = try std.json.stringifyAlloc(testing.allocator, PlausibleEvent{ .event = .{ .run = .{ .mode = .serve, .version = "over 9000!" } } }, .{});
184+ // test "telemetry: lightpanda json event" {
185+ // const json = try std.json.stringifyAlloc(testing.allocator, EventWrap{
186+ // .iid = "1234",
187+ // .eid = "abc!",
188+ // .event = .{ .run = .{ .mode = .serve, .version = "over 9000!" } }
189+ // }, .{});
85190// defer testing.allocator.free(json);
86191
87192// try testing.expectEqualStrings(
88- // \\{"name ":"run","url":"https://lightpanda.io/browser-stats ","domain ":"localhost ","props":{"version":"over 9000!","mode":"serve"}}
193+ // \\{"event ":"run","iid""1234 ","eid ":"abc! ","props":{"version":"over 9000!","mode":"serve"}}
89194// , json);
90195// }
0 commit comments