-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.go
More file actions
266 lines (228 loc) · 6.47 KB
/
cache.go
File metadata and controls
266 lines (228 loc) · 6.47 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
package worker
import (
"encoding/json"
"fmt"
v8 "github.com/tommie/v8go"
)
// cacheJS defines the Cache and CacheStorage classes available to workers.
const cacheJS = `
(function() {
class Cache {
constructor(name) {
this._name = name;
}
match(request, options) {
var url;
if (typeof request === 'string') {
url = request;
} else if (request && request.url) {
url = request.url;
} else {
return Promise.resolve(undefined);
}
var result = __cache_match(this._name, url);
if (result === 'null' || result === null || result === undefined) {
return Promise.resolve(undefined);
}
try {
var parsed = JSON.parse(result);
var hdrs = new Headers(parsed.headers || {});
var resp = new Response(parsed.body, {
status: parsed.status,
headers: hdrs,
});
return Promise.resolve(resp);
} catch(e) {
return Promise.resolve(undefined);
}
}
put(request, response) {
var url;
if (typeof request === 'string') {
url = request;
} else if (request && request.url) {
url = request.url;
} else {
return Promise.reject(new Error('Cache.put requires a request'));
}
if (!response) {
return Promise.reject(new Error('Cache.put requires a response'));
}
// Extract Cache-Control max-age for TTL.
var ttl = -1;
var cc = '';
if (response.headers && typeof response.headers.get === 'function') {
cc = response.headers.get('Cache-Control') || '';
}
if (cc) {
var match = cc.match(/max-age=(\d+)/);
if (match) {
ttl = parseInt(match[1], 10);
}
}
// Serialize headers.
var hdrs = {};
if (response.headers) {
if (typeof response.headers.forEach === 'function') {
response.headers.forEach(function(v, k) { hdrs[k] = v; });
} else if (response.headers._map) {
var m = response.headers._map;
for (var k in m) { if (m.hasOwnProperty(k)) hdrs[k] = String(m[k]); }
}
}
var body = '';
if (response._body !== null && response._body !== undefined) {
body = String(response._body);
}
__cache_put(
this._name,
url,
response.status || 200,
JSON.stringify(hdrs),
body,
ttl
);
return Promise.resolve(undefined);
}
delete(request, options) {
var url;
if (typeof request === 'string') {
url = request;
} else if (request && request.url) {
url = request.url;
} else {
return Promise.resolve(false);
}
var result = __cache_delete(this._name, url);
return Promise.resolve(result === 'true' || result === true);
}
}
class CacheStorage {
constructor() {
this._caches = {};
this.default = new Cache('default');
}
open(name) {
if (!this._caches[name]) {
this._caches[name] = new Cache(name);
}
return Promise.resolve(this._caches[name]);
}
}
globalThis.caches = new CacheStorage();
})();
`
// setupCache registers the Cache API JS classes and Go-backed functions.
func setupCache(iso *v8.Isolate, ctx *v8.Context, _ *eventLoop) error {
// We need a reference to the CacheStore from the request state.
// The cache store is read per-call from the env.
// __cache_match(cacheName, url) -> JSON string or "null"
matchFn := v8.NewFunctionTemplate(iso, func(info *v8.FunctionCallbackInfo) *v8.Value {
args := info.Args()
if len(args) < 2 {
val, _ := v8.NewValue(iso, "null")
return val
}
cacheName := args[0].String()
url := args[1].String()
store := getCacheStore(info.Context())
if store == nil {
val, _ := v8.NewValue(iso, "null")
return val
}
entry, err := store.Match(cacheName, url)
if err != nil || entry == nil {
val, _ := v8.NewValue(iso, "null")
return val
}
var headers map[string]string
if entry.Headers != "" {
_ = json.Unmarshal([]byte(entry.Headers), &headers)
}
if headers == nil {
headers = make(map[string]string)
}
result := map[string]interface{}{
"status": entry.Status,
"headers": headers,
"body": string(entry.Body),
}
data, _ := json.Marshal(result)
val, _ := v8.NewValue(iso, string(data))
return val
})
if err := ctx.Global().Set("__cache_match", matchFn.GetFunction(ctx)); err != nil {
return fmt.Errorf("setting __cache_match: %w", err)
}
// __cache_put(cacheName, url, status, headersJSON, body, ttl)
putFn := v8.NewFunctionTemplate(iso, func(info *v8.FunctionCallbackInfo) *v8.Value {
args := info.Args()
if len(args) < 6 {
return v8.Undefined(iso)
}
cacheName := args[0].String()
url := args[1].String()
status := int(args[2].Int32())
headersJSON := args[3].String()
body := args[4].String()
ttlVal := int(args[5].Int32())
store := getCacheStore(info.Context())
if store == nil {
return v8.Undefined(iso)
}
var ttl *int
if ttlVal > 0 {
ttl = &ttlVal
}
_ = store.Put(cacheName, url, status, headersJSON, []byte(body), ttl)
return v8.Undefined(iso)
})
if err := ctx.Global().Set("__cache_put", putFn.GetFunction(ctx)); err != nil {
return fmt.Errorf("setting __cache_put: %w", err)
}
// __cache_delete(cacheName, url) -> "true" or "false"
deleteFn := v8.NewFunctionTemplate(iso, func(info *v8.FunctionCallbackInfo) *v8.Value {
args := info.Args()
if len(args) < 2 {
val, _ := v8.NewValue(iso, "false")
return val
}
cacheName := args[0].String()
url := args[1].String()
store := getCacheStore(info.Context())
if store == nil {
val, _ := v8.NewValue(iso, "false")
return val
}
deleted, err := store.Delete(cacheName, url)
if err != nil || !deleted {
val, _ := v8.NewValue(iso, "false")
return val
}
val, _ := v8.NewValue(iso, "true")
return val
})
if err := ctx.Global().Set("__cache_delete", deleteFn.GetFunction(ctx)); err != nil {
return fmt.Errorf("setting __cache_delete: %w", err)
}
// Evaluate JS classes.
if _, err := ctx.RunScript(cacheJS, "cache.js"); err != nil {
return fmt.Errorf("evaluating cache.js: %w", err)
}
return nil
}
// getCacheStore retrieves the CacheStore from the current request state.
// The CacheStore is stored in the per-request Env.
func getCacheStore(ctx *v8.Context) CacheStore {
reqIDVal, err := ctx.Global().Get("__requestID")
if err != nil || reqIDVal.IsUndefined() {
return nil
}
var reqID uint64
_, _ = fmt.Sscanf(reqIDVal.String(), "%d", &reqID)
state := getRequestState(reqID)
if state == nil || state.env == nil || state.env.Cache == nil {
return nil
}
return state.env.Cache
}