~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/zat

atproto utils for zig · mirror of https://tangled.org/zat.dev/zat

0
0
77 lines · 2.5 KB Raw History
//! 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);
}