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

zat.dev/zat

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

0
0
121 lines · 4.3 KB Raw History

follow the firehose

The firehose is the network's event log — every write, streamed live. You consume it by folding events into a materialized view: a running query you keep in sync. This one tallies the languages people are posting in, right now.

The AT Protocol for distributed systems engineers article is the mental model here — the database turned inside-out, writes flowing through an event log into views you build yourself.

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);
}
500 posts
  en    161
  ja    61
  pt    2
  es    15
  de    27
  fr    10
  ko    10
  other 61

This is examples/04_follow_the_firehose.zig verbatim — copy it and zig build example-follow-the-firehose (Ctrl-C to stop).

This view is a cache, never canonical: the repos are the source of truth, so you can throw it away and rebuild it by replaying the stream. That is also why a durable consumer saves a cursor and advances it only after the write lands — a crash replays events instead of dropping them. Each event's record is freed after onEvent returns, so a persistent view copies out what it needs. Point wanted_collections at any lexicon (or leave it empty for the whole firehose) and fold it into whatever query you care about.

zat.JetstreamClient reads the JSON firehose — convenient, but the events carry no signatures, so you're trusting the relay that serves them. For the raw CBOR stream with signed commit blocks you can verify yourself, use zat.FirehoseClient with zat.verifyCommitDiff.

See also: the sync spec and firehose guide; Bluesky's Statusphere example app is the canonical "subscribe → build a view" tutorial. typeahead is a live actor-search service built on zat that indexes the firehose this way.

wiring zat into your own <code>build.zig</code>
const zat = b.dependency("zat", .{}).module("zat");
exe.root_module.addImport("zat", zat);

after zig fetch --save https://tangled.org/zat.dev/zat/archive/main.