aboutsummaryrefslogtreecommitdiff
path: root/fetchers/jetstream.go
blob: 866533aa014605893306127457ef44f800d32650 (plain)
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package fetchers

import (
	"context"
	"encoding/json"
	"fmt"
	"llostre/general"
	"net/url"
	"time"

	"github.com/coder/websocket"
)

type jetstreamEvent struct {
	DID    string           `json:"did"`
	Kind   string           `json:"kind"`
	Commit *jetstreamCommit `json:"commit,omitempty"`
}

type jetstreamCommit struct {
	Operation  string          `json:"operation"`
	Collection string          `json:"collection"`
	RKey       string          `json:"rkey"`
	Record     json.RawMessage `json:"record,omitempty"`
}

var jetstreamCollections = []string{"app.bsky.feed.post", "app.bsky.actor.profile"}

// Meant to be run in its own goroutine; blocks forever, reconnecting on failure.
// Monitors the jetstream for changes in cached records
func StartJetstream(conf *Config) {
	if conf.JetstreamURL == "" {
		return
	}

	subscribeURL := buildJetstreamURL(conf.JetstreamURL)

	for {
		if err := consumeJetstream(conf, subscribeURL); err != nil {
			conf.Logger.Error("jetstream connection lost, reconnecting", "error", err)
		}
		time.Sleep(5 * time.Second)
	}
}

func buildJetstreamURL(base string) string {
	query := url.Values{}
	for _, collection := range jetstreamCollections {
		query.Add("wantedCollections", collection)
	}
	return fmt.Sprintf("%s?%s", base, query.Encode())
}

func consumeJetstream(conf *Config, subscribeURL string) error {
	ctx := context.Background()

	conn, _, err := websocket.Dial(ctx, subscribeURL, nil)
	if err != nil {
		return err
	}
	defer conn.CloseNow()
	conn.SetReadLimit(1 << 20) // 1MiB; default 32KiB is too tight for larger posts/profiles

	conf.Logger.Debug("jetstream connected", "url", subscribeURL)

	for {
		_, data, err := conn.Read(ctx)
		if err != nil {
			return err
		}

		var event jetstreamEvent
		if err := json.Unmarshal(data, &event); err != nil {
			conf.Logger.Warn("failed to parse jetstream event", "error", err)
			continue
		}

		if event.Kind != "commit" || event.Commit == nil {
			continue
		}

		handleJetstreamCommit(conf, event.DID, event.Commit)
	}
}

func handleJetstreamCommit(conf *Config, did string, commit *jetstreamCommit) {
	uri := fmt.Sprintf("at://%s/%s/%s", did, commit.Collection, commit.RKey)

	switch commit.Collection {
	case "app.bsky.feed.post":
		handleJetstreamPost(conf, did, uri, commit)
	case "app.bsky.actor.profile":
		handleJetstreamProfile(conf, did, commit)
	}
}

func handleJetstreamPost(conf *Config, did, uri string, commit *jetstreamCommit) {
	if commit.Operation == "delete" {
		if _, found := conf.Cache.Get(uri); found {
			conf.Cache.Delete(uri)
		}
		return
	}

	// only track posts from authors we already care about
	author, found := conf.Cache.readAuthor(did)
	if !found {
		return
	}

	rawRecord := &general.RawRecord{URI: uri, Value: commit.Record}

	// cache the result
	if _, err := parseAppBskyFeedPostRecord(rawRecord, author, conf); err != nil {
		conf.Logger.Warn("jetstream: failed to parse post", "uri", uri, "error", err)
	}
}

func handleJetstreamProfile(conf *Config, did string, commit *jetstreamCommit) {
	if commit.Operation == "delete" {
		if _, found := conf.Cache.readAuthor(did); found {
			conf.Cache.DeleteAuthor(did)
		}
		return
	}

	existing, found := conf.Cache.readAuthor(did)
	if !found {
		return
	}

	rawRecord := &general.RawRecord{URI: fmt.Sprintf("at://%s/app.bsky.actor.profile/self", did), Value: commit.Record}

	// cache the result
	if _, err := parseAppBskyActorProfile(did, existing.PDS, rawRecord, conf.Cache); err != nil {
		conf.Logger.Warn("jetstream: failed to parse updated profile", "did", did, "error", err)
	}
}