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
//! consume the firehose and fold it into a live view.
//!
//! the network's writes stream past as an event log; you keep a "materialized
//! view" — a running query — in sync by folding each event in. here: which
//! languages people are posting in right now.
//! https://atproto.com/articles/atproto-for-distsys-engineers
//!
//! run: zig build example-follow-the-firehose (Ctrl-C to stop)
const std = @import("std");
const zat = @import("zat");
// the view we maintain from the stream: a post count per language.
const tracked = [_][]const u8{ "en", "ja", "pt", "es", "de", "fr", "ko" };
const LangView = struct {
total: u64 = 0,
counts: [tracked.len]u64 = @splat(0),
other: u64 = 0,
pub fn onEvent(self: *LangView, event: zat.JetstreamEvent) void {
const commit = switch (event) {
.commit => |c| c,
else => return,
};
if (commit.operation != .create) return;
const record = commit.record orelse return;
self.total += 1;
// a post's declared languages, e.g. ["en"]. many posts omit it.
const langs = zat.json.getArray(record, "langs") orelse {
if (self.total % 500 == 0) self.report();
return;
};
if (langs.len > 0) {
switch (langs[0]) {
.string => |primary| {
for (tracked, 0..) |code, i| {
if (std.mem.eql(u8, code, primary)) {
self.counts[i] += 1;
break;
}
} else self.other += 1;
},
else => {},
}
}
if (self.total % 500 == 0) self.report();
}
fn report(self: *const LangView) void {
std.debug.print("\n{d} posts\n", .{self.total});
for (tracked, self.counts) |code, n| {
std.debug.print(" {s:<6}{d}\n", .{ code, n });
}
std.debug.print(" other {d}\n", .{self.other});
}
pub fn onError(_: *LangView, err: anyerror) void {
std.debug.print("stream error: {s}\n", .{@errorName(err)});
}
};
pub fn main(init: std.process.Init) !void {
const allocator = init.gpa;
var view = LangView{};
var client = zat.JetstreamClient.init(init.io, allocator, .{
.hosts = &.{"jetstream2.us-east.bsky.network"},
.wanted_collections = &.{"app.bsky.feed.post"},
});
defer client.deinit();
// subscribe blocks, folding each event into `view` until interrupted.
try client.subscribe(&view);
}