Repository navigation
Expand file tree
/
Copy pathcache.go
More file actions
330 lines (316 loc) · 7.48 KB
/
Copy pathcache.go
File metadata and controls
330 lines (316 loc) · 7.48 KB
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
package pubengine
import (
"context"
"database/sql"
"slices"
"sort"
"strings"
"sync"
"time"
)
var ErrNotFound = sql.ErrNoRows
const maxCachedBodies = 128
const maxBodyBytes = 16 << 20
type postSnapshot struct {
posts []BlogPost
tags []string
slugs map[string]int
byTag map[string][]int
fetched time.Time
}
// PostCache stores summaries and a bounded set of article bodies.
type PostCache struct {
mu sync.RWMutex
snapshot *postSnapshot
bodies map[string]BlogPost
bodyOrder []string
bodyBytes int
generation uint64
loading chan struct{}
lastErr error
retryAt time.Time
ttl time.Duration
store *Store
}
func NewPostCache(s *Store, ttl time.Duration) *PostCache { return &PostCache{store: s, ttl: ttl} }
func (c *PostCache) valid() bool { return c.snapshot != nil && time.Since(c.snapshot.fetched) < c.ttl }
func (c *PostCache) Invalidate() {
c.mu.Lock()
defer c.mu.Unlock()
c.generation++
c.snapshot = nil
c.bodies = nil
c.bodyOrder = nil
c.bodyBytes = 0
c.lastErr = nil
c.retryAt = time.Time{}
}
func (c *PostCache) snapshotContext(ctx context.Context) (*postSnapshot, error) {
for {
if err := ctx.Err(); err != nil {
return nil, err
}
c.mu.Lock()
if c.valid() {
snapshot := c.snapshot
c.mu.Unlock()
return snapshot, nil
}
if c.loading != nil {
done := c.loading
c.mu.Unlock()
select {
case <-done:
continue
case <-ctx.Done():
return nil, ctx.Err()
}
}
if c.lastErr != nil && time.Now().Before(c.retryAt) {
err := c.lastErr
c.mu.Unlock()
return nil, err
}
generation := c.generation
done := make(chan struct{})
c.loading = done
c.mu.Unlock()
posts, err := c.store.ListSummariesContext(ctx)
snapshot := &postSnapshot{posts: posts, slugs: map[string]int{}, byTag: map[string][]int{}, fetched: time.Now()}
if err == nil {
for i, p := range posts {
snapshot.slugs[p.Slug] = i
for _, tag := range p.Tags {
snapshot.byTag[tag] = append(snapshot.byTag[tag], i)
}
}
for tag := range snapshot.byTag {
snapshot.tags = append(snapshot.tags, tag)
}
sort.Strings(snapshot.tags)
}
c.mu.Lock()
c.loading = nil
current := generation == c.generation
if current {
if err == nil {
c.snapshot = snapshot
c.bodies = map[string]BlogPost{}
c.bodyOrder = nil
c.bodyBytes = 0
c.lastErr = nil
} else if ctx.Err() == nil {
c.lastErr = err
c.retryAt = time.Now().Add(100 * time.Millisecond)
}
}
close(done)
c.mu.Unlock()
if !current {
continue
}
return snapshot, err
}
}
// ListPosts preserves the full-content API. Prefer ListPageContext for lists.
func (c *PostCache) ListPosts(tag string) ([]BlogPost, error) {
return c.ListPostsContext(context.Background(), tag)
}
func (c *PostCache) ListPostsContext(ctx context.Context, tag string) ([]BlogPost, error) {
for {
snapshot, err := c.snapshotContext(ctx)
if err != nil {
return nil, err
}
indices := snapshot.byTag[normalizeTag(tag)]
count := len(indices)
if tag == "" {
count = len(snapshot.posts)
}
posts := make([]BlogPost, count)
complete := true
c.mu.RLock()
for i := range posts {
index := i
if tag != "" {
index = indices[i]
}
summary := snapshot.posts[index]
p, ok := c.bodies[summary.Slug]
if ok {
posts[i] = clonePost(p)
} else {
posts[i] = summary
complete = false
}
}
current := snapshot == c.snapshot
c.mu.RUnlock()
if !current {
continue
}
if complete {
return posts, nil
}
loaded, err := c.store.ListPostsContext(ctx, tag)
if err != nil {
return nil, err
}
bySlug := make(map[string]BlogPost, len(loaded))
for _, p := range loaded {
bySlug[p.Slug] = p
}
c.mu.Lock()
if snapshot != c.snapshot {
c.mu.Unlock()
continue
}
for i, p := range posts {
full, ok := bySlug[p.Slug]
if !ok {
c.mu.Unlock()
return nil, ErrNotFound
}
posts[i] = full
if i < maxCachedBodies {
c.rememberBody(full)
}
}
c.mu.Unlock()
return posts, nil
}
}
// ListPageContext returns summaries and whether another page exists; zero limit means all.
func (c *PostCache) ListPageContext(ctx context.Context, tag string, offset, limit int) ([]BlogPost, bool, error) {
snapshot, err := c.snapshotContext(ctx)
if err != nil {
return nil, false, err
}
if offset < 0 {
offset = 0
}
var indices []int
if tag != "" {
indices = snapshot.byTag[normalizeTag(tag)]
}
count := len(snapshot.posts)
if tag != "" {
count = len(indices)
}
if offset > count {
offset = count
}
end := count
if limit > 0 && limit < count-offset {
end = offset + limit
}
posts := make([]BlogPost, 0, end-offset)
for i := offset; i < end; i++ {
index := i
if tag != "" {
index = indices[i]
}
posts = append(posts, clonePost(snapshot.posts[index]))
}
return posts, end < count, nil
}
func (c *PostCache) ListTags() ([]string, error) { return c.ListTagsContext(context.Background()) }
func (c *PostCache) ListTagsContext(ctx context.Context) ([]string, error) {
snapshot, err := c.snapshotContext(ctx)
if err != nil {
return nil, err
}
return slices.Clone(snapshot.tags), nil
}
func (c *PostCache) GetPost(slug string) (BlogPost, error) {
return c.GetPostContext(context.Background(), slug)
}
func (c *PostCache) GetPostContext(ctx context.Context, slug string) (BlogPost, error) {
for {
snapshot, err := c.snapshotContext(ctx)
if err != nil {
return BlogPost{}, err
}
if _, ok := snapshot.slugs[slug]; !ok {
return BlogPost{}, ErrNotFound
}
c.mu.RLock()
p, ok := c.bodies[slug]
current := snapshot == c.snapshot
c.mu.RUnlock()
if !current {
continue
}
if ok {
return clonePost(p), nil
}
p, err = c.store.GetPostContext(ctx, slug)
if err != nil {
return BlogPost{}, err
}
c.mu.Lock()
if snapshot != c.snapshot {
c.mu.Unlock()
continue
}
c.rememberBody(p)
c.mu.Unlock()
return clonePost(p), nil
}
}
// rememberBody requires the cache lock.
func (c *PostCache) rememberBody(p BlogPost) {
if _, ok := c.bodies[p.Slug]; ok || len(p.Content) > maxBodyBytes {
return
}
for len(c.bodies) >= maxCachedBodies || c.bodyBytes+len(p.Content) > maxBodyBytes {
slug := c.bodyOrder[0]
c.bodyOrder[0] = ""
c.bodyOrder = c.bodyOrder[1:]
c.bodyBytes -= len(c.bodies[slug].Content)
delete(c.bodies, slug)
}
c.bodies[p.Slug] = clonePost(p)
c.bodyOrder = append(c.bodyOrder, p.Slug)
c.bodyBytes += len(p.Content)
}
func (c *PostCache) RelatedContext(ctx context.Context, p BlogPost, limit int) ([]BlogPost, error) {
snapshot, err := c.snapshotContext(ctx)
if err != nil {
return nil, err
}
lists := make([][]int, 0, len(p.Tags))
for _, tag := range p.Tags {
lists = append(lists, snapshot.byTag[normalizeTag(tag)])
}
var result []BlogPost
for limit <= 0 || len(result) < limit {
next := len(snapshot.posts)
for _, list := range lists {
if len(list) > 0 && list[0] < next {
next = list[0]
}
}
if next == len(snapshot.posts) {
break
}
for i, list := range lists {
if len(list) > 0 && list[0] == next {
lists[i] = list[1:]
}
}
if snapshot.posts[next].Slug != p.Slug {
result = append(result, clonePost(snapshot.posts[next]))
}
}
return result, nil
}
func normalizeTag(t string) string { return strings.ToLower(strings.TrimSpace(t)) }
func clonePost(p BlogPost) BlogPost { p.Tags = slices.Clone(p.Tags); return p }
func clonePosts(posts []BlogPost) []BlogPost {
result := make([]BlogPost, len(posts))
for i, p := range posts {
result[i] = clonePost(p)
}
return result
}