-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcache.go
More file actions
298 lines (260 loc) · 7.26 KB
/
cache.go
File metadata and controls
298 lines (260 loc) · 7.26 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
package server
import (
"encoding/json"
"fmt"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
)
type CacheEntry struct {
ID int64
Key string
Version string
Scope string
Size int64
Finalized bool
CreatedAt time.Time
}
// --- Twirp dispatcher ---
func (s *Server) handleCacheTwirp(w http.ResponseWriter, r *http.Request) {
if ct := r.Header.Get("Content-Type"); !strings.HasPrefix(ct, "application/json") {
writeTwirpError(w, http.StatusBadRequest, "invalid_argument", "Content-Type must be application/json")
return
}
if _, _, err := parseJWT(r.Header.Get("Authorization")); err != nil {
writeTwirpError(w, http.StatusUnauthorized, "unauthenticated", err.Error())
return
}
method := r.PathValue("method")
switch method {
case "CreateCacheEntry":
s.handleCreateCacheEntry(w, r)
case "FinalizeCacheEntryUpload":
s.handleFinalizeCacheEntry(w, r)
case "GetCacheEntryDownloadURL":
s.handleGetCacheEntryDownloadURL(w, r)
case "DeleteCacheEntry":
s.handleDeleteCacheEntry(w, r)
default:
writeTwirpError(w, http.StatusNotFound, "not_found", fmt.Sprintf("unknown method: %s", method))
}
}
// --- Request/Response types ---
type CacheMetadata struct {
RepositoryID string `json:"repository_id"`
Scope string `json:"scope"`
}
type CreateCacheEntryRequest struct {
Key string `json:"key"`
Version string `json:"version"`
Metadata *CacheMetadata `json:"metadata,omitempty"`
}
type CreateCacheEntryResponse struct {
Ok bool `json:"ok"`
SignedUploadURL string `json:"signed_upload_url"`
}
// FlexInt64 unmarshals from both JSON numbers and JSON strings.
// Protobuf's canonical JSON encoding represents int64 as strings.
type FlexInt64 int64
func (f *FlexInt64) UnmarshalJSON(data []byte) error {
var n int64
if err := json.Unmarshal(data, &n); err == nil {
*f = FlexInt64(n)
return nil
}
var s string
if err := json.Unmarshal(data, &s); err != nil {
return fmt.Errorf("FlexInt64: cannot unmarshal %s", string(data))
}
n, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return fmt.Errorf("FlexInt64: invalid int64 string %q: %w", s, err)
}
*f = FlexInt64(n)
return nil
}
type FinalizeCacheEntryRequest struct {
Key string `json:"key"`
Version string `json:"version"`
SizeBytes FlexInt64 `json:"size_bytes"`
}
type FinalizeCacheEntryResponse struct {
Ok bool `json:"ok"`
EntryID string `json:"entry_id"`
}
type GetCacheEntryDownloadURLRequest struct {
Metadata *CacheMetadata `json:"metadata,omitempty"`
Key string `json:"key"`
RestoreKeys []string `json:"restore_keys,omitempty"`
Version string `json:"version"`
}
type GetCacheEntryDownloadURLResponse struct {
Ok bool `json:"ok"`
SignedDownloadURL string `json:"signed_download_url"`
MatchedKey string `json:"matched_key"`
}
type DeleteCacheEntryRequest struct {
Key string `json:"key"`
Version string `json:"version"`
}
type DeleteCacheEntryResponse struct {
Ok bool `json:"ok"`
}
// --- RPC handlers ---
func (s *Server) handleCreateCacheEntry(w http.ResponseWriter, r *http.Request) {
var req CreateCacheEntryRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeTwirpError(w, http.StatusBadRequest, "invalid_argument", "invalid JSON")
return
}
if req.Key == "" || req.Version == "" {
writeTwirpError(w, http.StatusBadRequest, "invalid_argument", "key and version are required")
return
}
scope := ""
if req.Metadata != nil {
scope = req.Metadata.Scope
}
cacheKey := scope + "/" + req.Key + "/" + req.Version
s.mu.Lock()
// If entry already exists, overwrite (caches are mutable)
if existing, ok := s.caches[cacheKey]; ok {
delete(s.cacheByID, existing.ID)
delete(s.uploadMu, existing.ID)
}
id := s.nextID
s.nextID++
entry := &CacheEntry{
ID: id,
Key: req.Key,
Version: req.Version,
Scope: scope,
CreatedAt: time.Now(),
}
s.caches[cacheKey] = entry
s.cacheByID[id] = entry
s.uploadMu[id] = &sync.Mutex{}
s.mu.Unlock()
uploadURL := s.makeSignedURL("PUT", id)
writeJSON(w, http.StatusOK, CreateCacheEntryResponse{
Ok: true,
SignedUploadURL: uploadURL,
})
}
func (s *Server) handleFinalizeCacheEntry(w http.ResponseWriter, r *http.Request) {
var req FinalizeCacheEntryRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeTwirpError(w, http.StatusBadRequest, "invalid_argument", "invalid JSON")
return
}
s.mu.Lock()
var found *CacheEntry
for _, entry := range s.caches {
if entry.Key == req.Key && entry.Version == req.Version {
found = entry
break
}
}
if found == nil {
s.mu.Unlock()
writeTwirpError(w, http.StatusNotFound, "not_found", "cache entry not found")
return
}
found.Size = int64(req.SizeBytes)
found.Finalized = true
s.mu.Unlock()
writeJSON(w, http.StatusOK, FinalizeCacheEntryResponse{
Ok: true,
EntryID: strconv.FormatInt(found.ID, 10),
})
}
func (s *Server) handleGetCacheEntryDownloadURL(w http.ResponseWriter, r *http.Request) {
var req GetCacheEntryDownloadURLRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeTwirpError(w, http.StatusBadRequest, "invalid_argument", "invalid JSON")
return
}
scope := ""
if req.Metadata != nil {
scope = req.Metadata.Scope
}
type match struct {
id int64
key string
}
var found *match
s.mu.RLock()
// 1. Exact match: scope + key + version
exactKey := scope + "/" + req.Key + "/" + req.Version
if entry, ok := s.caches[exactKey]; ok && entry.Finalized {
found = &match{id: entry.ID, key: entry.Key}
}
// 2. Prefix match with restore_keys
if found == nil {
for _, rk := range req.RestoreKeys {
var best *CacheEntry
for _, entry := range s.caches {
if entry.Scope != scope || entry.Version != req.Version {
continue
}
if !entry.Finalized {
continue
}
if !strings.HasPrefix(entry.Key, rk) {
continue
}
if best == nil || entry.CreatedAt.After(best.CreatedAt) {
best = entry
}
}
if best != nil {
found = &match{id: best.ID, key: best.Key}
break
}
}
}
s.mu.RUnlock()
if found != nil {
downloadURL := s.makeSignedURL("GET", found.id)
writeJSON(w, http.StatusOK, GetCacheEntryDownloadURLResponse{
Ok: true,
SignedDownloadURL: downloadURL,
MatchedKey: found.key,
})
return
}
writeTwirpError(w, http.StatusNotFound, "not_found", "cache entry not found")
}
func (s *Server) handleDeleteCacheEntry(w http.ResponseWriter, r *http.Request) {
var req DeleteCacheEntryRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeTwirpError(w, http.StatusBadRequest, "invalid_argument", "invalid JSON")
return
}
s.mu.Lock()
var found *CacheEntry
var foundKey string
for k, entry := range s.caches {
if entry.Key == req.Key && entry.Version == req.Version {
found = entry
foundKey = k
break
}
}
if found == nil {
s.mu.Unlock()
writeTwirpError(w, http.StatusNotFound, "not_found", "cache entry not found")
return
}
delete(s.caches, foundKey)
delete(s.cacheByID, found.ID)
delete(s.uploadMu, found.ID)
s.mu.Unlock()
blobPath := filepath.Join(s.storageDir, fmt.Sprintf("%d.blob", found.ID))
os.Remove(blobPath)
writeJSON(w, http.StatusOK, DeleteCacheEntryResponse{Ok: true})
}