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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
package atproto
import (
"cmp"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
const (
DefaultPLCURL = "https://plc.directory"
defaultHTTPTimeout = 15 * time.Second
)
type StrongRef struct {
URI string `json:"uri"`
CID string `json:"cid"`
}
type Record struct {
URI string
CID string
Value map[string]any
}
var ErrRecordNotFound = errors.New("record not found")
type StatusError struct {
Code int
Body string
}
func (e *StatusError) Error() string {
return fmt.Sprintf("status %d: %s", e.Code, e.Body)
}
func (e *StatusError) recordNotFound() bool {
if e.Code == http.StatusNotFound {
return true
}
var body struct {
Error string `json:"error"`
}
return e.Code == http.StatusBadRequest && json.Unmarshal([]byte(e.Body), &body) == nil && body.Error == "RecordNotFound"
}
type Client struct {
HTTP *http.Client
PLCURL string
Timeout time.Duration
}
func NewClient() *Client {
return &Client{
HTTP: &http.Client{Timeout: defaultHTTPTimeout},
PLCURL: DefaultPLCURL,
Timeout: defaultHTTPTimeout,
}
}
func SplitURI(uri string) (repo, collection, rkey string) {
trimmed := strings.TrimPrefix(strings.TrimSpace(uri), "at://")
parts := strings.SplitN(trimmed, "/", 3)
if len(parts) > 0 {
repo = parts[0]
}
if len(parts) > 1 {
collection = parts[1]
}
if len(parts) > 2 {
rkey = parts[2]
}
return repo, collection, rkey
}
func RepoFromURI(uri string) string {
repo, _, _ := SplitURI(uri)
return repo
}
func (c *Client) ResolvePDS(ctx context.Context, did string) (string, error) {
did = strings.TrimSpace(did)
if did == "" {
return "", fmt.Errorf("did is empty")
}
var docURL string
if after, ok := strings.CutPrefix(did, "did:web:"); ok {
host := after
host = strings.ReplaceAll(host, ":", "/")
docURL = "https://" + host + "/did.json"
} else {
base := c.PLCURL
base = cmp.Or(base, DefaultPLCURL)
docURL = strings.TrimSuffix(base, "/") + "/" + url.PathEscape(did)
}
var doc struct {
Service []struct {
ID string `json:"id"`
Type string `json:"type"`
ServiceEndpoint json.RawMessage `json:"serviceEndpoint"`
} `json:"service"`
}
if err := c.getJSON(ctx, docURL, &doc); err != nil {
return "", fmt.Errorf("resolve did %s: %w", did, err)
}
for _, service := range doc.Service {
if service.Type != "AtprotoPersonalDataServer" && service.ID != "#atproto_pds" && !strings.HasSuffix(service.ID, "#atproto_pds") {
continue
}
endpoint := decodeEndpoint(service.ServiceEndpoint)
if endpoint != "" {
return strings.TrimSuffix(endpoint, "/"), nil
}
}
return "", fmt.Errorf("did %s has no atproto pds service", did)
}
func decodeEndpoint(raw json.RawMessage) string {
var value string
if err := json.Unmarshal(raw, &value); err == nil {
return value
}
var object map[string]any
if err := json.Unmarshal(raw, &object); err == nil {
if endpoint, ok := object["endpoint"].(string); ok {
return endpoint
}
}
return ""
}
func (c *Client) GetRecord(ctx context.Context, ref StrongRef) (map[string]any, error) {
record, err := c.GetRecordAt(ctx, ref)
if err != nil {
return nil, err
}
return record.Value, nil
}
func (c *Client) GetRecordAt(ctx context.Context, ref StrongRef) (Record, error) {
repo, collection, rkey := SplitURI(ref.URI)
if repo == "" || collection == "" || rkey == "" {
return Record{}, fmt.Errorf("invalid at uri %q", ref.URI)
}
pds, err := c.ResolvePDS(ctx, repo)
if err != nil {
return Record{}, err
}
endpoint := pds + "/xrpc/com.atproto.repo.getRecord"
query := url.Values{}
query.Set("repo", repo)
query.Set("collection", collection)
query.Set("rkey", rkey)
var response struct {
URI string `json:"uri"`
CID string `json:"cid"`
Value map[string]any `json:"value"`
}
if err := c.getJSON(ctx, endpoint+"?"+query.Encode(), &response); err != nil {
var status *StatusError
if errors.As(err, &status) && status.recordNotFound() {
return Record{}, fmt.Errorf("getRecord %s: %w", ref.URI, ErrRecordNotFound)
}
return Record{}, fmt.Errorf("getRecord %s: %w", ref.URI, err)
}
if response.Value == nil {
response.Value = map[string]any{}
}
return Record{URI: response.URI, CID: response.CID, Value: response.Value}, nil
}
func (c *Client) getJSON(ctx context.Context, endpoint string, target any) error {
client := c.HTTP
if client == nil {
client = &http.Client{Timeout: c.timeout()}
}
request, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return err
}
request.Header.Set("Accept", "application/json")
response, err := client.Do(request)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode < 200 || response.StatusCode >= 300 {
body, _ := io.ReadAll(io.LimitReader(response.Body, 2048))
return &StatusError{Code: response.StatusCode, Body: strings.TrimSpace(string(body))}
}
decoder := json.NewDecoder(io.LimitReader(response.Body, 8<<20))
return decoder.Decode(target)
}
func (c *Client) timeout() time.Duration {
if c.Timeout > 0 {
return c.Timeout
}
return defaultHTTPTimeout
}