Documentation
¶
Overview ¶
Package jetstream is the official Go client for Jetstream v2, atproto's full-network archive and live-streaming service.
A single Client can follow the live firehose, replay full or filtered history, or return a point-in-time archive snapshot. A replay reads the sealed archive and then cuts over to the live tail without a gap. Events are delivered as decoded, JSON-shaped Go values through a range-over-func iterator:
client, err := jetstream.Subscribe("jetstream.us-west.bsky.network",
jetstream.WithCollections([]string{"app.bsky.feed.post"}),
jetstream.WithAfterSeq(0), // replay from the start of the archive
)
if err != nil {
// handle err
}
defer client.Close()
for batch, err := range client.Events(ctx) {
if err != nil {
continue // handle error; iteration continues unless ctx is done
}
if err := db.WriteBatch(batch.Events()); err != nil {
continue // handle error
}
if err := db.SaveCursor(batch.LastCursor()); err != nil {
continue // handle error
}
}
Subscribe(host) follows the current live tip. WithAfterSeq enables archive replay before v2 cutover; WithSnapshotOnly stops after sealed history, and WithBeforeSeq bounds that snapshot. Both sources yield the same Event type.
WithAPIKey authenticates planSnapshot, getSegment, and getBlock only. Dictionary requests and the live websocket remain public. Live compression defaults to dictionary-zstd; use WithZstdCompression(false) to opt out. Dictionary failures fall back to uncompressed streaming.
Delivery is at-least-once. Consumers must fold events idempotently: creates and updates apply; deletes, account deletions, and syncs remove records. Collection filters preserve DID-level markers unless kinds excludes them. The library delivers markers without folding or suppressing records.
If cutover falls behind the server's lookback window, the client replays from the last processed seq. Seqs increase but need not be contiguous: crash recovery may leave registered vacancies to prevent reuse of previously observed seqs. The client accepts these jumps and deduplicates by seq.
Transport, planning, download, and cutover implementations are private to this package.
Index ¶
- Variables
- func TypedEvents[T any, PT interface{ ... }](ctx context.Context, c *Client, collection string) iter.Seq2[*TypedBatch[T], error]
- type Account
- type Batch
- type Client
- type Commit
- type CursorMode
- type Event
- type Identity
- type Kind
- type Operation
- type Option
- func WithAPIKey(apiKey string) Option
- func WithAfterSeq(seq uint64) Option
- func WithBatchSize(n int) Option
- func WithBeforeSeq(seq uint64) Option
- func WithCollection(collection string) Option
- func WithCollections(collections []string) Option
- func WithCursorMode(m CursorMode) Option
- func WithDID(did string) Option
- func WithDIDs(dids []string) Option
- func WithDownloadConcurrency(n int) Option
- func WithFailoverHosts(hosts ...string) Option
- func WithFailoverRewind(d time.Duration) Option
- func WithHTTPClient(h *http.Client) Option
- func WithKinds(kinds []Kind) Option
- func WithLiveCursor(seq uint64) Option
- func WithLogger(l *slog.Logger) Option
- func WithMaxBatchDelay(d time.Duration) Option
- func WithMaxDownloadAttempts(n int) Option
- func WithRawRecordCIDs() Option
- func WithRawRecords() Option
- func WithRawRecordsCopied() Option
- func WithSegmentStripes(n int) Option
- func WithSnapshotOnly() Option
- func WithZstdCompression(enabled bool) Option
- type Stats
- type Sync
- type TypedBatch
- type TypedEvent
Constants ¶
This section is empty.
Variables ¶
var ErrCursorClamped = errors.New("jetstream: timestamp cursor clamped to server retention floor")
ErrCursorClamped is yielded (recoverable) under WithCursorMode(CursorTime) when a server reports that a witnessed-time resume started later than requested because the cursor predates its retention window: events between the cursor and the retention floor may have been missed.
var ErrFatal = errors.New("jetstream: fatal stream error")
ErrFatal marks a terminal stream failure: the engine has aborted and will deliver no further events. It distinguishes a doomed stream (plan rejection, a cutover guarantee broken) from a recoverable per-entry hiccup (a single bad segment, a transient live read error) that the stream continues past. Consumers test for it with errors.Is(err, ErrFatal) and should stop and surface a non-zero status rather than logging and continuing.
Functions ¶
func TypedEvents ¶
func TypedEvents[T any, PT interface { *T UnmarshalCBOR([]byte) error }](ctx context.Context, c *Client, collection string) iter.Seq2[*TypedBatch[T], error]
TypedEvents decodes a Client's records as T through PT.UnmarshalCBOR. T is a lexicon record type and PT its pointer. The client must use WithRawRecords or WithRawRecordsCopied so archive workers decode CBOR directly. Live JSON records are canonicalized before typed decoding.
collection must be a non-empty NSID matching T. Only its create/update records are decoded; all other events pass through with nil Record. A mismatched type can silently decode incorrect fields. Pair with WithCollections to limit server delivery.
Stream errors retain the ErrFatal contract and yield a nil batch. Per-record failures set TypedEvent.DecodeErr and do not stop iteration.
WithRawRecords may produce strings or bytes that alias the batch buffer and are valid only for the current iteration. Copy retained values or use WithRawRecordsCopied.
Types ¶
type Account ¶
type Account struct {
DID string `json:"did"`
Active bool `json:"active"`
// Status is the inactive reason (e.g. "deleted", "suspended",
// "takendown") when Active is false; empty when Active is true.
Status string `json:"status,omitempty"`
Seq int64 `json:"seq"`
Time string `json:"time"`
}
Account is a #account event: a change to an account's hosting status.
type Batch ¶
type Batch struct {
// contains filtered or unexported fields
}
Batch is a group of events delivered together by the Events iterator. It amortizes per-event overhead (notably cursor persistence): handle the whole batch, then save LastCursor to your database of choice once.
func (*Batch) Events ¶
Events returns the events in this batch. The slice is owned by the caller for the lifetime of the loop iteration; do not retain it past the next iteration without copying.
func (*Batch) LastCursor ¶
LastCursor returns the batch's resume point, suitable for persisting and passing back via WithLiveCursor (or WithAfterSeq in seq mode): the highest Seq, or under WithCursorMode(CursorTime) the highest WitnessedAtUS. Returns 0 for an empty batch.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a Jetstream replay consumer. Construct one with Subscribe. A Client drives at most one Events iteration at a time; create separate Clients for concurrent streams. Close releases its resources and is safe to call concurrently with a running Events (the natural way to stop a live tail) and to call more than once.
func Subscribe ¶
Subscribe creates a Client for the given Jetstream host. host may be a bare hostname ("jetstream.us-west.bsky.network"), a host:port, or a full http(s):// URL; the scheme defaults to https.
With no replay bound, the Client live-tails from the current tip or resumes from WithLiveCursor. WithAfterSeq starts by replaying sealed history and then cuts over to live. WithSnapshotOnly stops after the sealed range; WithBeforeSeq bounds that snapshot and requires WithSnapshotOnly.
func (*Client) Close ¶
Close releases the Client's resources. It is safe to call after Events returns, concurrently with a running Events (to stop a live tail), and more than once; the underlying engine is closed exactly once and every call returns that same result. Calling Events after Close yields an error.
func (*Client) Events ¶
Events streams event batches in delivery order until ctx is cancelled or a terminal error occurs. It is a Go range-over-func iterator:
for batch, err := range client.Events(ctx) {
...
}
A non-nil err is yielded for recoverable problems; iteration continues so the caller may log and move on. A terminal failure is yielded as an error satisfying errors.Is(err, ErrFatal), after which the stream aborts and the iterator returns no further events — callers should stop and surface a failure rather than treat it as recoverable. When ctx is done or the stream ends, the iterator returns. Events must not be called concurrently on the same Client.
type Commit ¶
type Commit struct {
// Operation is create, update, or delete.
Operation Operation `json:"operation"`
// Collection is the record's NSID, e.g. "app.bsky.feed.post".
Collection string `json:"collection"`
// Rkey is the record key within the collection.
Rkey string `json:"rkey"`
// Rev is the repo revision that produced this commit.
Rev string `json:"rev"`
// CID is the content identifier of the record. Empty for deletes.
CID string `json:"cid,omitempty"`
// Record is the decoded record as a generic atproto object. nil for
// deletes. Callers that want typed records can decode RecordCBOR with
// their own lexicon codegen.
Record map[string]any `json:"record,omitempty"`
// RecordCBOR is the record's canonical DAG-CBOR encoding. On the archive
// path it is the segment payload; on the live path the client reconstructs
// it from the atproto JSON record according to DRISL. nil for deletes.
// Marshals to base64 in JSON output.
RecordCBOR []byte `json:"record_cbor,omitempty"`
}
Commit describes a single record mutation. The JSON tags mirror the Jetstream wire shape so json.Marshal(Event) yields the familiar payload.
type CursorMode ¶ added in v0.2.5
type CursorMode int
CursorMode selects which of an event's two resume positions a Client treats as its cursor. See WithCursorMode.
const ( // CursorSeq (the default) resumes by Event.Seq. Seqs are exact and // gapless, but only meaningful on the instance that assigned them. CursorSeq CursorMode = iota // CursorTime resumes by Event.WitnessedAtUS, a unix-microsecond timestamp // every Jetstream instance can seek to, trading exactness for portability. CursorTime )
type Event ¶
type Event struct {
// DID is the repository (account) this event belongs to.
DID string `json:"did"`
// Seq is Jetstream's monotonic per-event sequence number (the cursor).
// Persist the last seen Seq (via Batch.LastCursor) to resume later.
Seq uint64 `json:"cursor"`
// TimeUS is the event's display timestamp, microseconds since the Unix
// epoch: the operator-imported indexed_at value if one was set, otherwise
// the witnessed_at time Jetstream first saw the event. It is not the
// record's client-supplied createdAt. Absent any timestamp import, this
// is simply the server's ingest (witnessed) time. Do not use it as a
// resume cursor; use WitnessedAtUS.
TimeUS int64 `json:"time_us"`
// WitnessedAtUS is when the serving Jetstream instance first saw the
// event, microseconds since the Unix epoch. It is never altered by
// timestamp imports and is monotonic with Seq on one instance, so it is
// the value a timestamp cursor resumes from (see WithCursorMode). Across
// instances it is approximate: each instance witnesses events on its own
// clock. Zero when the server predates the field.
WitnessedAtUS int64 `json:"witnessed_at_us,omitempty"`
// Kind selects which of the payload pointers below is populated.
Kind Kind `json:"kind"`
Commit *Commit `json:"commit,omitempty"`
Identity *Identity `json:"identity,omitempty"`
Account *Account `json:"account,omitempty"`
Sync *Sync `json:"sync,omitempty"`
}
Event is a single, decoded firehose event delivered to the caller. It is identical in shape regardless of whether it was replayed from the sealed archive or received from the live tail, so callers need not distinguish the transport that produced it.
Exactly one of Commit, Identity, Account, or Sync is non-nil, selected by Kind.
type Identity ¶
type Identity struct {
DID string `json:"did"`
Handle string `json:"handle,omitempty"` // empty if not present in the event
Seq int64 `json:"seq"` // upstream relay sequence number carried by the event
Time string `json:"time"` // RFC3339 timestamp from the upstream event
}
Identity is a #identity event: a change to an account's handle or DID document.
type Kind ¶
type Kind string
Kind discriminates the firehose event type carried by an Event. The string values match the Jetstream JSON wire format.
const ( // KindCommit is a record create, update, delete, or resync replacement. // Commit is non-nil. KindCommit Kind = "commit" // KindIdentity is a #identity event (handle/DID-doc change). Identity is non-nil. KindIdentity Kind = "identity" // KindAccount is a #account event (hosting-status change). Account is non-nil. KindAccount Kind = "account" // KindSync is a #sync event (repo divergence / resync). Sync is non-nil. // Sync events are delivered during archive replay and on the live tail. KindSync Kind = "sync" )
type Option ¶
type Option func(*config)
Option configures a Client. Options are applied in order by Subscribe.
func WithAPIKey ¶ added in v0.2.0
WithAPIKey authenticates archive negotiation and downloads with a bearer API key. Pass the raw key, without a "Bearer " prefix. The key is sent on planSnapshot, getSegment, and getBlock requests; it is not sent when fetching the public zstd dictionary or upgrading the public live WebSocket.
The value is a bearer secret. Use TLS when crossing an untrusted network, and avoid putting the API key in logs or process arguments.
func WithAfterSeq ¶
WithAfterSeq sets the exclusive lower sequence bound for a replay: only events with seq > afterSeq are delivered. Supplying it, including WithAfterSeq(0) for the whole archive, starts with sealed-history replay before the client cuts over to the live tail.
func WithBatchSize ¶
WithBatchSize sets the maximum number of events returned in a single Batch. Must be > 0; ignored otherwise. Default 64.
func WithBeforeSeq ¶
WithBeforeSeq sets the inclusive upper sequence bound for an archive snapshot: only events with seq <= beforeSeq are delivered.
It requires WithSnapshotOnly. On a replay that continues into the live tail, the same upper bound would silently drop every later live event, so Subscribe rejects WithBeforeSeq unless WithSnapshotOnly is also set.
func WithCollection ¶
WithCollection is shorthand for WithCollections with a single NSID.
func WithCollections ¶
WithCollections restricts delivery to the given collections. Each entry is either an exact NSID (e.g. "app.bsky.feed.post") or a namespace wildcard ending in ".*" (e.g. "app.bsky.feed.*"). Empty or unset means all collections.
A collection filter does NOT suppress DID-level events: Account, Identity, and Sync carry no collection but always bypass the collection filter (subject to WithDIDs), because they are a folding consumer's only signal to purge a deleted account's records — hiding them would create a permanently stale view. The client does not suppress deleted-account records during an archive replay; consumers fold those markers themselves. With no collection filter, Account and Identity events are likewise delivered, subject to WithDIDs. See issue #142.
func WithCursorMode ¶ added in v0.2.5
func WithCursorMode(m CursorMode) Option
WithCursorMode selects the resume-cursor style.
Under CursorTime, Batch.LastCursor returns the highest Event.WitnessedAtUS in the batch instead of the highest Seq; feed it back through WithLiveCursor to resume on any instance. The live tail keeps resuming by seq while it reconnects to the host that assigned that seq, and on any other host resumes from the last witnessed time minus WithFailoverRewind, re-delivering the overlap. Delivery is therefore at-least-once across a host change; consumers must be idempotent. It also enables WithFailoverHosts.
Timestamp resumes cover the server's live lookback window only: a cursor older than that (for example one saved mid-way through a deep archive replay) starts at the oldest retained event, and the client yields a recoverable ErrCursorClamped. Archive replay (WithAfterSeq) is always seq-addressed on the primary host.
func WithDIDs ¶
WithDIDs restricts delivery to the given DIDs. Empty or unset means all DIDs. The DID filter applies to every event kind, including Account and Identity: with a DID filter and no collection filter, you receive Account and Identity events for the matching DIDs only.
func WithDownloadConcurrency ¶
WithDownloadConcurrency sizes archive-replay parallelism: n bounds the block decode pool directly, and the block-mode getBlock fetch pool is derived from it (2n, capped at 64) so sparse (DID/collection-filtered) replays overlap network round trips instead of paying one RTT per block. Must be > 0; ignored otherwise.
Whole-segment downloads are prefetched ahead of decode one segment at a time, striped across parallel range requests; WithSegmentStripes (a separate, network-bound knob) controls that per-segment fan-out.
The default is auto-sized from the CPU count (GOMAXPROCS, clamped to [4, 32]), so a many-core host uses more of its cores without configuration while small/CPU-limited environments stay modest. Set this to override the auto-sizing — e.g. a higher value on a very large box, or a lower value to cap memory (each in-flight download holds roughly one segment-sized buffer).
func WithFailoverHosts ¶ added in v0.2.5
WithFailoverHosts adds live-tail fallback hosts, tried round-robin after the primary host passed to Subscribe when a connection attempt fails. Each entry accepts the same forms as Subscribe's host. Requires WithCursorMode(CursorTime): a seq cursor from one instance is meaningless on another. Archive replay always uses the primary host.
func WithFailoverRewind ¶ added in v0.2.5
WithFailoverRewind sets how far a CursorTime resume rewinds a witnessed-time cursor when the client cannot prove it is on the same instance (a host change, a server restart, or a caller-supplied WithLiveCursor timestamp). Larger values tolerate more cross-instance skew at the cost of more re-delivered events. Must be >= 0; default 5s.
func WithHTTPClient ¶
WithHTTPClient overrides the HTTP client used for XRPC negotiation, public dictionary fetches, bulk segment/block downloads, and live WebSocket upgrades. It is an override: when unset, the client builds its own gttp clients tuned per workload — xrpc.ATProtoOpts for the short XRPC calls (planSnapshot and getZstdDictionary) and xrpc.BulkDownloadOpts for streaming segment/block downloads, whose large transfers a short wall-clock timeout would prematurely kill. Supplying a client here replaces both tuned clients with the single client given; WithAPIKey still scopes authentication to archive requests and never mutates the supplied client.
func WithKinds ¶
WithKinds restricts delivery to the selected event kinds. Empty or unset means all kinds. KindCommit includes create, update, delete, and resync replacement records. Combine WithKinds([]Kind{KindCommit}) with WithCollections for a commits-only collection stream.
func WithLiveCursor ¶
WithLiveCursor resumes a pure live tail from a cursor. A value below 1e15 is a previously saved sequence cursor (typically Batch.LastCursor from a prior run); delivery resumes after it because the client deduplicates the server's inclusive replay. For compatibility with Jetstream v1, a value at or above 1e15 is a unix-microsecond timestamp: the server seeks to the first retained event witnessed at or after that time, and the client establishes its seq deduplication floor from the first event delivered.
Timestamp resumes are at-least-once. They may re-deliver an event at the boundary and must not be deduplicated by Event.TimeUS, which can be an imported display timestamp rather than the witnessed time used for seeking; save Event.WitnessedAtUS (Batch.LastCursor under CursorTime) instead. Under CursorTime a timestamp is rewound by WithFailoverRewind before dialing, since it may have been witnessed by a different instance. Ignored when an archive replay is requested, since that workflow computes its own live cutover cursor.
func WithLogger ¶
WithLogger sets a structured logger for diagnostics. The default discards all output.
func WithMaxBatchDelay ¶ added in v0.3.9
WithMaxBatchDelay caps how long the live tail holds a partially-filled batch before delivering it. The client already delivers a partial batch as soon as it has handled every frame the server has sent so far, so at the tip each burst arrives with no added wait and this delay only applies to a stream that never pauses between frames. Under a sustained backlog batches still fill to WithBatchSize. Archive replay fills batches by count and is unaffected. Must be > 0; ignored otherwise. Default 20ms.
func WithMaxDownloadAttempts ¶
WithMaxDownloadAttempts caps the total number of attempts (the initial request plus retries) each XRPC/download request makes before failing. n <= 0 is ignored (leaves the default retry policy). n == 1 disables retries entirely.
The default policy retries transient failures, which is right for production resilience but undesirable for tests and tools that must fail fast against a deliberately-broken or unavailable backend rather than wait out a long backoff schedule. Bounding attempts turns a permanent download failure into a prompt error instead of a slow retry loop.
func WithRawRecordCIDs ¶
func WithRawRecordCIDs() Option
WithRawRecordCIDs keeps computing Commit.CID (the record's content identifier, a sha256 + base32 of the payload) when raw-record mode is enabled. Without it, raw mode leaves Commit.CID empty to avoid the per-record hashing cost. No effect unless WithRawRecords or WithRawRecordsCopied is also set.
func WithRawRecords ¶
func WithRawRecords() Option
WithRawRecords skips the generic Commit.Record map and exposes archive RecordCBOR directly from segment bytes, reducing decode CPU and allocations. Live JSON records are converted to canonical DAG-CBOR. Deletes and non-commit events are unchanged, as are Operation, Collection, Rkey, and Rev. CID stays empty unless WithRawRecordCIDs is set.
Archive events reference the decompressed block directly: RecordCBOR and the DID, Collection, Rkey, and Rev strings (and marker fields) are views into a block buffer shared by thousands of events. They stay valid after the Batch, but retaining any one of them keeps the whole block in memory. Copy what you retain, or use WithRawRecordsCopied.
func WithRawRecordsCopied ¶
func WithRawRecordsCopied() Option
WithRawRecordsCopied is like WithRawRecords but archive events do not reference the decompressed block: Commit.RecordCBOR (and anything decoded from it) is a private copy of the record, and the event's strings live in a small per-block arena holding only identifiers. Retaining them costs that record plus at most the arena, as in the default (map) mode. It still skips the generic map build; the cost over WithRawRecords is one allocation and copy of the record per event. Use this when the consumer keeps records or identifiers around; use WithRawRecords for maximum throughput when events are processed within the iteration.
func WithSegmentStripes ¶
WithSegmentStripes sets how many parallel HTTP range requests fetch each whole sealed segment. Default 8: on typical internet paths, per-TCP-stream congestion control is the throughput bound, and striping lets a segment download claim multiple streams' worth of bandwidth. Must be > 0; ignored otherwise.
Set 1 for a single resumable stream. That can be the better choice on paths where parallel streams cannot claim additional bandwidth — in our lab measurements, a WireGuard tunnel (which encapsulates all TCP into one UDP flow) ran 20-40% faster single-stream, and on a fast LAN the modes were indistinguishable. Failed parts retry at part granularity either way, and the single-stream mode resumes mid-segment on transient failure.
func WithSnapshotOnly ¶
func WithSnapshotOnly() Option
WithSnapshotOnly turns a replay into a point-in-time archive snapshot: it downloads and delivers the matched sealed range, bounded by WithAfterSeq and/or WithBeforeSeq, and then ends without starting the live tail.
It requires a replay bound (WithAfterSeq and/or WithBeforeSeq); without one, Subscribe returns an error. Records in the active, unsealed segment (above the sealed tip) are only reachable via the live tail and are therefore not included in the snapshot.
func WithZstdCompression ¶
WithZstdCompression controls live-tail dictionary-zstd compression, which is enabled by default. The client fetches the server's current dictionary before the first live dial, negotiates zstdDictionary=<id>, and transparently decompresses binary frames. Fetch or rotation recovery failure degrades to an uncompressed tail rather than failing the stream. Pass false to opt out; archive segment compression is unaffected.
type Stats ¶
type Stats struct {
// Pages is the number of planSnapshot pages downloaded across the replay thus far.
Pages uint64
// SealedTip is the most recently learned sealed-archive tip (the pinned
// pagination goal of the current sweep).
SealedTip uint64
// PlannedThrough is the continuation cursor reached so far: the highest
// sealed seq accounted for. Equals SealedTip once a sweep completes.
PlannedThrough uint64
// ResidualGap is SealedTip - PlannedThrough: the sealed seqs still to
// download before cutover. Zero once the sweep has consumed the archive.
ResidualGap uint64
}
Stats is a point-in-time snapshot of replay-loop progress, returned by Client.Stats. The Jetstream client library has no metrics registry, so this accessor is how a caller observes how far a replay has progressed and the residual gap a sustained-ingest stream is still closing before cutover.
type Sync ¶
type Sync struct {
DID string `json:"did"`
Rev string `json:"rev"`
Seq int64 `json:"seq"`
Time string `json:"time"`
}
Sync is a #sync event: the upstream signaled a repo divergence requiring a resync. The authoritative replacement records follow as their own commit events.
type TypedBatch ¶
type TypedBatch[T any] struct { // contains filtered or unexported fields }
TypedBatch is a batch of TypedEvents, mirroring Batch.
func (*TypedBatch[T]) Events ¶
func (b *TypedBatch[T]) Events() []TypedEvent[T]
Events returns the typed events in this batch. The slice — and any non-nil Record in it — is owned by the caller for the lifetime of the loop iteration; do not retain past the next iteration without copying (see the aliasing note on TypedEvents).
func (*TypedBatch[T]) LastCursor ¶
func (b *TypedBatch[T]) LastCursor() uint64
LastCursor returns the batch's resume point, mirroring Batch.LastCursor.
type TypedEvent ¶
TypedEvent pairs a delivered Event with its record decoded into the caller's type T. It is produced by TypedEvents.
- For a create/update commit whose Collection matches the requested NSID and whose record decoded cleanly, Record is non-nil and DecodeErr is nil.
- For a commit whose record failed to decode into T, Record is nil and DecodeErr is set (the Event is still delivered; nothing is dropped).
- For a delete, a non-commit event (identity/account/sync), or a commit of a different collection, Record and DecodeErr are both nil — inspect Event.
Event always carries the full envelope (DID/Seq/TimeUS/Kind and, for commits, Operation/Collection/Rkey/Rev/CID/RecordCBOR). In the raw-record modes that TypedEvents requires, Event.Commit.Record (the generic map) is nil by design.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
api
|
|
|
cmd
|
|
|
client
command
Command client drives the jetstream Go client against a running server: it live-tails the firehose or runs a filtered backfill that cuts over to live, printing decoded events or throughput stats.
|
Command client drives the jetstream Go client against a running server: it live-tails the firehose or runs a filtered backfill that cuts over to live, printing decoded events or throughput stats. |
|
compare
command
Command compare checks Jetstream v2 /subscribe payload compatibility against Jetstream v1 with a warmup/sample/drain capture model.
|
Command compare checks Jetstream v2 /subscribe payload compatibility against Jetstream v1 with a warmup/sample/drain capture model. |
|
jetstream
command
Command jetstream is the entry point for the jetstream process.
|
Command jetstream is the entry point for the jetstream process. |
|
simulator
command
Command simulator is a development-only fake atproto network: PLC, a single PDS, and a relay (firehose) under one HTTP listener.
|
Command simulator is a development-only fake atproto network: PLC, a single PDS, and a relay (firehose) under one HTTP listener. |
|
storagebench
command
Command storagebench measures disaggregated storage (design §22) against real PostgreSQL and S3, normally the `just up` environment: `just storagebench write` drives the hot writer at production rates, `just storagebench footers` times a pod start over a pop1-sized synthetic catalog, `just storagebench bootstrap` drives a bootstrapping leader's writers and reports fenced transactions per second, `just storagebench retryscan` times the failed-repo retry pass's scan of metadata_kv, and `just storagebench compaction` measures the leader's tombstone rebuild and a compaction pass's block fetches.
|
Command storagebench measures disaggregated storage (design §22) against real PostgreSQL and S3, normally the `just up` environment: `just storagebench write` drives the hot writer at production rates, `just storagebench footers` times a pod start over a pop1-sized synthetic catalog, `just storagebench bootstrap` drives a bootstrapping leader's writers and reports fenced transactions per second, `just storagebench retryscan` times the failed-repo retry pass's scan of metadata_kv, and `just storagebench compaction` measures the leader's tombstone rebuild and a compaction pass's block fetches. |
|
examples
|
|
|
full-replay
command
Performs a full network replay with basic options, printing some sample events as it goes.
|
Performs a full network replay with basic options, printing some sample events as it goes. |
|
live-tail
command
Connects to the live tip websocket and prints out all events as JSON.
|
Connects to the live tip websocket and prints out all events as JSON. |
|
statusphere
command
Performs a full replay of all the emojis from the statusphere example app.
|
Performs a full replay of all the emojis from the statusphere example app. |
|
internal
|
|
|
catalog
Package catalog is the storage-neutral description of the archive: which segments exist in each namespace, and where each durable block's bytes live (design §11.2, §19.1).
|
Package catalog is the storage-neutral description of the archive: which segments exist in each namespace, and where each durable block's bytes live (design §11.2, §19.1). |
|
catalog/catalogtest
Package catalogtest is the catalog.Tx primitive contract suite (plan D1, layer 4).
|
Package catalogtest is the catalog.Tx primitive contract suite (plan D1, layer 4). |
|
catalog/follower
Package follower keeps a disaggregated pod's in-memory mirror of the PostgreSQL catalog current and serves reads from it (design §11).
|
Package follower keeps a disaggregated pod's in-memory mirror of the PostgreSQL catalog current and serves reads from it (design §11). |
|
catalog/local
Package local is the catalog over a local data directory: each namespace is a directory of segment files, a sealed segment's metadata is its header and footer, and an active segment's durable blocks come from the ingest writer that owns it (catalog.ActiveSource).
|
Package local is the catalog over a local data directory: each namespace is a directory of segment files, a sealed segment's metadata is its header and footer, and an active segment's durable blocks come from the ingest writer that owns it (catalog.ActiveSource). |
|
crashpoint
Package crashpoint defines named test-only crash checkpoints at durable lifecycle boundaries.
|
Package crashpoint defines named test-only crash checkpoints at durable lifecycle boundaries. |
|
datamodel
Package datamodel checks upstream record bytes against the atproto data model at the ingest gate (docs/README.md §4.4).
|
Package datamodel checks upstream record bytes against the atproto data model at the ingest gate (docs/README.md §4.4). |
|
format
Package format provides shared human-readable formatters used by the CLI renderers, the load-test client, and the web status page.
|
Package format provides shared human-readable formatters used by the CLI renderers, the load-test client, and the web status page. |
|
identity
Package identity caches atmos identity resolutions in a best-effort KV under sync/identity/<did>; in local mode that is meta.pebble.
|
Package identity caches atmos identity resolutions in a best-effort KV under sync/identity/<did>; in local mode that is meta.pebble. |
|
ingest
Package ingest owns Jetstream's active-segment writer.
|
Package ingest owns Jetstream's active-segment writer. |
|
ingest/backfill
Package backfill drives Jetstream's direct-PDS initial network backfill (docs/README.md §4.1).
|
Package backfill drives Jetstream's direct-PDS initial network backfill (docs/README.md §4.1). |
|
ingest/live
package live: consumer.go owns Consumer, the firehose-to- segments pump.
|
package live: consumer.go owns Consumer, the firehose-to- segments pump. |
|
ingest/maintainer
Package maintainer folds hot mode's closed blocks into active blocks and seals the active segment into a generation (design §10.7, §10.8).
|
Package maintainer folds hot mode's closed blocks into active blocks and seals the active segment into a generation (design §10.7, §10.8). |
|
ingest/orchestrator
Package orchestrator manages bootstrap, merge, and steady-state ingestion (docs/README.md §4).
|
Package orchestrator manages bootstrap, merge, and steady-state ingestion (docs/README.md §4). |
|
ingest/syncstate
Package syncstate persists verifier chain and hosting state in the metadata store under sync/chain/<did> and sync/host/<did>.
|
Package syncstate persists verifier chain and hosting state in the metadata store under sync/chain/<did> and sync/host/<did>. |
|
jetstreamd
Package jetstreamd builds and runs the jetstream service graph used by cmd/jetstream and integration tests.
|
Package jetstreamd builds and runs the jetstream service graph used by cmd/jetstream and integration tests. |
|
jetstreamd/jetstreamdtest
Package jetstreamdtest builds in-memory storage backends for tests that run a disaggregated jetstreamd.Runtime: storagefake for the catalog database and lease, memblob for the object store.
|
Package jetstreamdtest builds in-memory storage backends for tests that run a disaggregated jetstreamd.Runtime: storagefake for the catalog database and lease, memblob for the object store. |
|
leader
Package leader runs Jetstream's writer election loop (design §6.3).
|
Package leader runs Jetstream's writer election loop (design §6.3). |
|
leader/lockertest
Package lockertest is the leader.Locker contract suite (plan S2.3, audit finding 6).
|
Package lockertest is the leader.Locker contract suite (plan S2.3, audit finding 6). |
|
lifecycle
Package lifecycle stores phase and related timing metadata in the metadata store.
|
Package lifecycle stores phase and related timing metadata in the metadata store. |
|
manifest
Package manifest indexes sealed segment metadata in memory for archive planning and cursor lookup.
|
Package manifest indexes sealed segment metadata in memory for archive planning and cursor lookup. |
|
metastore
Package metastore is the backend-neutral metadata key/value interface (design §14.1).
|
Package metastore is the backend-neutral metadata key/value interface (design §14.1). |
|
metastore/memstore
Package memstore is an in-memory metastore.Store for unit tests.
|
Package memstore is an in-memory metastore.Store for unit tests. |
|
metastore/pebblestore
Package pebblestore is the local-mode metastore.Store: the Pebble database at <data-dir>/meta.pebble (docs/README.md §3.5), opened through internal/store so the jetstream_store_op_duration_seconds metrics keep their meaning.
|
Package pebblestore is the local-mode metastore.Store: the Pebble database at <data-dir>/meta.pebble (docs/README.md §3.5), opened through internal/store so the jetstream_store_op_duration_seconds metrics keep their meaning. |
|
metastore/pg
Package pg is the metastore.Store over PostgreSQL's metadata_kv table (design §14.2).
|
Package pg is the metastore.Store over PostgreSQL's metadata_kv table (design §14.2). |
|
metastore/storetest
Package storetest is the metastore.Store contract suite.
|
Package storetest is the metastore.Store contract suite. |
|
migrate
Package migrate moves a running local-mode archive to disaggregated storage without stopping it (specs/notes/2026-10-09-local-to-disagg- migration.md).
|
Package migrate moves a running local-mode archive to disaggregated storage without stopping it (specs/notes/2026-10-09-local-to-disagg- migration.md). |
|
objstore
Package objstore defines the object storage seams for disaggregated mode.
|
Package objstore defines the object storage seams for disaggregated mode. |
|
objstore/blobtest
Package blobtest is the contract suite every objstore.Blob implementation must pass.
|
Package blobtest is the contract suite every objstore.Blob implementation must pass. |
|
objstore/memblob
Package memblob is an in-memory objstore.Blob for tests and the layer 3 storage fake.
|
Package memblob is an in-memory objstore.Blob for tests and the layer 3 storage fake. |
|
objstore/objcache
Package objcache is the compressed object cache (design §17): an LRU of verified object bytes keyed by SHA-256, bounded by a byte budget.
|
Package objcache is the compressed object cache (design §17): an LRU of verified object bytes keyed by SHA-256, bounded by a byte budget. |
|
objstore/protocol
Package protocol is the design §7 object protocol over an objstore.Blob and the catalog.
|
Package protocol is the design §7 object protocol over an objstore.Blob and the catalog. |
|
objstore/s3
Package s3 is the objstore.Blob for S3-compatible object stores (AWS S3, MinIO, SeaweedFS) on aws-sdk-go-v2.
|
Package s3 is the objstore.Blob for S3-compatible object stores (AWS S3, MinIO, SeaweedFS) on aws-sdk-go-v2. |
|
objstore/s3/s3test
Package s3test holds test helpers for the S3 Blob.
|
Package s3test holds test helpers for the S3 Blob. |
|
obs
Span and Span2 name traces after their caller using gt.Caller.
|
Span and Span2 name traces after their caller using gt.Caller. |
|
obs/observe_innertest
Package observe_innertest exists solely to provide an obs.Span call site in a different package from internal/obs's own tests, so the tracer-scoping test can exercise cross-package behavior.
|
Package observe_innertest exists solely to provide an obs.Span call site in a different package from internal/obs's own tests, so the tracer-scoping test can exercise cross-package behavior. |
|
oracle
Package oracle runs Jetstream against a simulated atproto network and compares durable output and public replay against independent expectations.
|
Package oracle runs Jetstream against a simulated atproto network and compares durable output and public replay against independent expectations. |
|
pgstore
Package pgstore is the PostgreSQL catalog backend (design §8, §9): the connection pool, the embedded schema migration, the schema and format version check, the writer lease (§6.2), and catalog.DB over SQL.
|
Package pgstore is the PostgreSQL catalog backend (design §8, §9): the connection pool, the embedded schema migration, the schema and format version check, the writer lease (§6.2), and catalog.DB over SQL. |
|
pgstore/pgfixture
Package pgfixture is the PostgreSQL scaffolding cmd/storagebench needs outside a test: scratch databases and the server's WAL position.
|
Package pgfixture is the PostgreSQL scaffolding cmd/storagebench needs outside a test: scratch databases and the server's WAL position. |
|
pgstore/pgtest
Package pgtest is the PostgreSQL test harness for `just test-storage` (design §20 layer 4).
|
Package pgtest is the PostgreSQL test harness for `just test-storage` (design §20 layer 4). |
|
repoexport
Package repoexport reconstructs local atproto repo snapshots from Jetstream's segment archive.
|
Package repoexport reconstructs local atproto repo snapshots from Jetstream's segment archive. |
|
seqspace
Package seqspace owns the shared Jetstream sequence-number namespace and the immutable set of durable, explicitly-authorized sequence vacancies.
|
Package seqspace owns the shared Jetstream sequence-number namespace and the immutable set of durable, explicitly-authorized sequence vacancies. |
|
server
Package server owns the HTTP listeners for the jetstream process.
|
Package server owns the HTTP listeners for the jetstream process. |
|
simulator
Package simulator documents the local atproto network used by development runs and oracle tests.
|
Package simulator documents the local atproto network used by development runs and oracle tests. |
|
simulator/fanout
Package fanout owns the in-memory pub/sub that the simulator's traffic generator broadcasts to and the websocket subscribeRepos handler reads from.
|
Package fanout owns the in-memory pub/sub that the simulator's traffic generator broadcasts to and the websocket subscribeRepos handler reads from. |
|
simulator/http
Package http hosts the simulator's HTTP surface: PLC, PDS, and relay endpoints under a single mux at production paths.
|
Package http hosts the simulator's HTTP surface: PLC, PDS, and relay endpoints under a single mux at production paths. |
|
simulator/world
Package world owns the simulator's on-disk state: the pebble db, the global RNG, the deterministic account roster, and the live commit generator.
|
Package world owns the simulator's on-disk state: the pebble db, the global RNG, the deterministic account roster, and the live commit generator. |
|
status
Package status gathers the data shown by the public /status page.
|
Package status gathers the data shown by the public /status page. |
|
storagefake
Package storagefake is the in-memory PostgreSQL catalog used by unit tests and the layer 3 oracle (plan D3: the only PostgreSQL fake).
|
Package storagefake is the in-memory PostgreSQL catalog used by unit tests and the layer 3 oracle (plan D3: the only PostgreSQL fake). |
|
store
Package store opens the pebble database at <data-dir>/meta.pebble (docs/README.md §3.5) and instruments Get, Set, Delete, and Commit with duration metrics.
|
Package store opens the pebble database at <data-dir>/meta.pebble (docs/README.md §3.5) and instruments Get, Set, Delete, and Commit with duration metrics. |
|
subscribe
Package subscribe serves /subscribe (legacy v1) and /xrpc/network.bsky.jetstream.subscribeEvents (v2, atproto proposal 0015).
|
Package subscribe serves /subscribe (legacy v1) and /xrpc/network.bsky.jetstream.subscribeEvents (v2, atproto proposal 0015). |
|
tombstone
Package tombstone maintains the live in-memory delete/update tombstone set consumed by the delete compactor.
|
Package tombstone maintains the live in-memory delete/update tombstone set consumed by the delete compactor. |
|
version
Package version exposes link-time build metadata.
|
Package version exposes link-time build metadata. |
|
web
Package web renders the public /status page from a status.Snapshot.
|
Package web renders the public /status page from a status.Snapshot. |
|
xrpcapi
Package xrpcapi exposes jetstream's sealed segment files over XRPC (atproto's HTTP RPC framework).
|
Package xrpcapi exposes jetstream's sealed segment files over XRPC (atproto's HTTP RPC framework). |
|
zstddict
Package zstddict parses the header of a structured zstd dictionary (RFC 8878 §5).
|
Package zstddict parses the header of a structured zstd dictionary (RFC 8878 §5). |
|
Package segment implements the jetstream segment file format: a columnar, zstd-compressed, length-prefixed binary log of atproto firehose events.
|
Package segment implements the jetstream segment file format: a columnar, zstd-compressed, length-prefixed binary log of atproto firehose events. |
|
testing
|
|
|
dicttrain
command
Command dicttrain retrains the subscribeEvents zstd dictionary from live firehose traffic.
|
Command dicttrain retrains the subscribeEvents zstd dictionary from live firehose traffic. |
|
mutation/gate
command
Command gate enforces the oracle mutation campaign baseline (#108).
|
Command gate enforces the oracle mutation campaign baseline (#108). |