Something went wrong. Try again.
a bluesky feed generator framework
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325// Package ingest consumes the Jetstream firehose, storing posts that match// feed patterns and applying likes to tracked posts.package ingest
import ( "context" "encoding/json" "errors" "fmt" "log/slog" "strings" "time"
"github.com/bluesky-social/jetstream"
"tangled.org/edavis.dev/updraft/internal/config" "tangled.org/edavis.dev/updraft/internal/matcher" "tangled.org/edavis.dev/updraft/internal/store")
const ( postCollection = "app.bsky.feed.post" likeCollection = "app.bsky.feed.like")
// defaultPurgeInterval is how often posts older than their feed's max_age are removed.const defaultPurgeInterval = 10 * time.Minute
// defaultStatusInterval is how often Run logs its cursor and lag.const defaultStatusInterval = time.Minute
// Ingester applies firehose events to the store. All of its state is owned by// the goroutine calling Run (or ProcessBatch and Purge), so it needs no locking.type Ingester struct { store *store.Store matcher *matcher.Matcher feeds map[string]config.Feed // gravityByFeed holds the gravity of each feed that tracks likes. gravityByFeed map[string]float64 // tracked holds the URIs of stored posts in feeds that track likes. tracked map[string]struct{}
// purgeInterval is how often Run purges expired posts. purgeInterval time.Duration lastPurge time.Time
// statusInterval is how often Run logs its cursor and lag. statusInterval time.Duration lastStatus time.Time // cursor and timeUS are the cursor and time_us of the last committed event. cursor uint64 timeUS int64
now func() time.Time log *slog.Logger}
// New builds an Ingester for feeds and loads the tracked post set from st.func New(ctx context.Context, st *store.Store, feeds []config.Feed, log *slog.Logger) (*Ingester, error) { m, err := matcher.New(feeds) if err != nil { return nil, err } i := &Ingester{ store: st, matcher: m, feeds: make(map[string]config.Feed, len(feeds)), gravityByFeed: make(map[string]float64), purgeInterval: defaultPurgeInterval, statusInterval: defaultStatusInterval, now: time.Now, log: log, } for _, feed := range feeds { i.feeds[feed.Name] = feed if feed.TrackLikes { i.gravityByFeed[feed.Name] = feed.Gravity } } if err := i.reloadTracked(ctx); err != nil { return nil, err } return i, nil}
// Run consumes host until ctx is cancelled or a fatal error occurs, resuming// from the stored cursor. Store failures are fatal so that no batch is skipped:// on restart, consumption resumes from the last committed cursor.func (i *Ingester) Run(ctx context.Context, host string) error { cursor, err := i.store.Cursor(ctx) if err != nil { return err }
opts := []jetstream.Option{ jetstream.WithCollections(i.collections()), jetstream.WithKinds([]jetstream.Kind{jetstream.KindCommit}), jetstream.WithLogger(i.log), } if cursor > 0 { opts = append(opts, jetstream.WithLiveCursor(cursor)) i.log.Info("resuming jetstream", "host", host, "cursor", cursor) } else { i.log.Info("starting jetstream from live tip", "host", host) }
client, err := jetstream.Subscribe(host, opts...) if err != nil { return fmt.Errorf("subscribing to %s: %w", host, err) } defer client.Close()
for batch, err := range client.Events(ctx) { if err != nil { if errors.Is(err, jetstream.ErrFatal) { return err } i.log.Warn("jetstream error", "err", err) continue } if err := i.ProcessBatch(ctx, batch.Events(), batch.LastCursor()); err != nil { return err } if i.now().Sub(i.lastPurge) >= i.purgeInterval { if err := i.Purge(ctx); err != nil { return err } } if i.cursor != 0 && i.now().Sub(i.lastStatus) >= i.statusInterval { i.logStatus() } } if err := ctx.Err(); err != nil { return err } return errors.New("jetstream stream ended unexpectedly")}
// collections returns the Jetstream collections Updraft needs.func (i *Ingester) collections() []string { if len(i.gravityByFeed) > 0 { return []string{postCollection, likeCollection} } return []string{postCollection}}
// ProcessBatch applies events and saves cursor in a single transaction.// A cursor of 0 (an empty batch) is not saved.func (i *Ingester) ProcessBatch(ctx context.Context, events []jetstream.Event, cursor uint64) error { err := i.store.WithTx(ctx, func(tx *store.Tx) error { for _, event := range events { if err := i.processEvent(ctx, tx, event); err != nil { return err } } if cursor == 0 { return nil } return tx.SaveCursor(ctx, cursor) }) if err != nil || cursor == 0 || len(events) == 0 { return err } i.cursor = cursor i.timeUS = events[len(events)-1].TimeUS return nil}
// logStatus logs the last committed cursor and how far its time_us trails now.func (i *Ingester) logStatus() { now := i.now() lag := now.Sub(time.UnixMicro(i.timeUS)).Round(time.Second) i.log.Info("ingest status", "cursor", i.cursor, "time_us", i.timeUS, "lag", lag) i.lastStatus = now}
func (i *Ingester) processEvent(ctx context.Context, tx *store.Tx, event jetstream.Event) error { commit := event.Commit if event.Kind != jetstream.KindCommit || commit == nil { return nil }
switch { case commit.Collection == postCollection && commit.Operation == jetstream.OpCreate: return i.processPostCreate(ctx, tx, event)
case commit.Collection == postCollection && commit.Operation == jetstream.OpDelete: uri := recordURI(event.DID, commit.Collection, commit.Rkey) delete(i.tracked, uri) return tx.DeletePost(ctx, uri)
case commit.Collection == likeCollection && commit.Operation == jetstream.OpCreate: uri, ok := likeSubjectURI(commit.Record) if !ok { return nil } if _, tracked := i.tracked[uri]; !tracked { return nil } return tx.ApplyLike(ctx, uri, event.TimeUS, i.gravityByFeed) } return nil}
func (i *Ingester) processPostCreate(ctx context.Context, tx *store.Tx, event jetstream.Event) error { uri := recordURI(event.DID, event.Commit.Collection, event.Commit.Rkey)
// A malformed event is skipped rather than halting ingestion. data, err := json.Marshal(event) if err != nil { i.log.Warn("skipping unencodable post", "uri", uri, "err", err) return nil } matches, err := i.matcher.Match(data) if err != nil { i.log.Warn("skipping unmatchable post", "uri", uri, "err", err) return nil }
// fields is the event decoded generically, so rule targets can be looked // up by dot path. It is decoded only when a matching rule has a target. var fields map[string]any for _, match := range matches { targetURI, targetCID := uri, event.Commit.CID if match.Target != "" { if fields == nil { if err := json.Unmarshal(data, &fields); err != nil { i.log.Warn("skipping undecodable post", "uri", uri, "err", err) return nil } } var ok bool targetURI, targetCID, ok = lookupStrongRef(fields, match.Target) if !ok || !isPostURI(targetURI) { i.log.Debug("skipping rule target that is not a post", "uri", uri, "feed", match.Feed, "target", match.Target) continue } } if err := tx.InsertPost(ctx, match.Feed, targetURI, targetCID, event.TimeUS); err != nil { return err } if i.feeds[match.Feed].TrackLikes { i.tracked[targetURI] = struct{}{} } } return nil}
// Purge deletes posts older than each feed's max_age and rebuilds the tracked post set.func (i *Ingester) Purge(ctx context.Context) error { now := i.now() var purged int64 for name, feed := range i.feeds { n, err := i.store.Purge(ctx, name, now.Add(-feed.MaxAge).UnixMicro()) if err != nil { return err } purged += n } if err := i.reloadTracked(ctx); err != nil { return err } i.lastPurge = now i.log.Info("purged expired posts", "purged", purged, "tracked", len(i.tracked)) return nil}
// reloadTracked replaces the tracked post set with the posts stored in feeds that track likes.func (i *Ingester) reloadTracked(ctx context.Context) error { feeds := make([]string, 0, len(i.gravityByFeed)) for name := range i.gravityByFeed { feeds = append(feeds, name) } uris, err := i.store.PostURIs(ctx, feeds) if err != nil { return err } i.tracked = make(map[string]struct{}, len(uris)) for _, uri := range uris { i.tracked[uri] = struct{}{} } return nil}
func recordURI(did, collection, rkey string) string { return fmt.Sprintf("at://%s/%s/%s", did, collection, rkey)}
// isPostURI reports whether uri is an at:// URI naming an app.bsky.feed.post// record by DID, the form used by firehose deletes.func isPostURI(uri string) bool { rest, ok := strings.CutPrefix(uri, "at://") if !ok { return false } parts := strings.Split(rest, "/") return len(parts) == 3 && strings.HasPrefix(parts[0], "did:") && parts[1] == postCollection && parts[2] != ""}
// likeSubjectURI extracts subject.uri from an app.bsky.feed.like record.func likeSubjectURI(record map[string]any) (string, bool) { uri, _, ok := lookupStrongRef(record, "subject") return uri, ok}
// lookupStrongRef follows the dot path through fields to a strongRef object// and returns its uri and cid. ok is false when the path or uri is missing.func lookupStrongRef(fields map[string]any, path string) (uri, cid string, ok bool) { var value any = fields for _, key := range strings.Split(path, ".") { object, isObject := value.(map[string]any) if !isObject { return "", "", false } value = object[key] } ref, isObject := value.(map[string]any) if !isObject { return "", "", false } uri, ok = ref["uri"].(string) cid, _ = ref["cid"].(string) return uri, cid, ok}