Repository navigation
Expand file tree
/
Copy pathwasm_backends.go
More file actions
452 lines (391 loc) · 16.6 KB
/
Copy pathwasm_backends.go
File metadata and controls
452 lines (391 loc) · 16.6 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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//go:build wasip1
package plugin
import (
"encoding/json"
"fmt"
"time"
"unsafe"
)
// ── Memory management ─────────────────────────────────────────────────────────
// mallocBuffer is a pre-allocated buffer for host-managed memory allocations:
// the host writes request data and host-function results into it. Results the
// plugin returns are not placed here (see packWASMResult), so this only has to
// hold what the host sends in, not what the plugin sends back. wasm_exports.go
// resets the allocator between reading the request and handling it. Sized to
// match services/api's DefaultResourceLimits.MaxRequestBodyBytes
// (paca/services/api/internal/platform/plugin/runtime.go) — the host already
// rejects any payload larger than that before ever attempting to write it
// here, so this only needs to cover the same ceiling, not more. This buffer
// is a fixed array (not a growable slice) because mallocBase below caches its
// linear-memory address once; a slice that reallocates on growth would go
// stale and corrupt every pointer handed to the host afterward. Keep this in
// sync with MaxRequestBodyBytes if either changes.
var mallocBuffer [1 * 1024 * 1024]byte
// mallocOffset tracks the next free position in mallocBuffer.
var mallocOffset int32
// mallocBase is the absolute linear-memory offset of mallocBuffer[0].
var mallocBase int32
// wasmMalloc allocates space in mallocBuffer and returns the offset.
func wasmMalloc(size int32) int32 {
if size <= 0 {
return 0
}
if mallocBase == 0 {
mallocBase = int32(uintptr(unsafe.Pointer(&mallocBuffer[0])))
}
bufOffset := mallocOffset
if bufOffset+size > int32(len(mallocBuffer)) {
return 0
}
mallocOffset += size
ptr := mallocBase + bufOffset
return ptr
}
// wasmResetAllocator resets the malloc offset to allow reuse of the buffer.
// This should be called after the host has copied out the response data.
// SAFETY: The host MUST copy out all allocated data before calling this.
func wasmResetAllocator() {
mallocOffset = 0
}
// ── WASM DB backend ───────────────────────────────────────────────────────────
type wasmDBBackend struct{}
func newWASMDBBackend() DBBackend { return &wasmDBBackend{} }
func (b *wasmDBBackend) Query(sql string, params []any) (*DBQueryResult, error) {
sqlBytes := []byte(sql)
paramsJSON, err := json.Marshal(params)
if err != nil {
return nil, err
}
// 16 bytes: [0:4]=resultPtr [4:8]=resultLen [8:12]=errPtr [12:16]=errLen.
// db_query2 (unlike the deprecated db_query) reports execution errors
// back through errPtr/errLen instead of silently returning a zero-length
// result indistinguishable from a genuine zero-row success.
outputBuf := make([]byte, 16)
hostDBQuery2(
int64(ptrOf(sqlBytes)), int64(len(sqlBytes)),
int64(ptrOf(paramsJSON)), int64(len(paramsJSON)),
int64(ptrOf(outputBuf)), int64(ptrOf(outputBuf[4:])),
int64(ptrOf(outputBuf[8:])), int64(ptrOf(outputBuf[12:])),
)
resPtr, resLen, errPtr, errLen := decodeQuery2Output(outputBuf)
if errLen > 0 {
msg := string(wasmSlice(errPtr, errLen))
wasmResetAllocator()
return nil, &hostError{msg}
}
if resLen == 0 {
return &DBQueryResult{}, nil
}
var result DBQueryResult
err = json.Unmarshal(wasmSlice(resPtr, resLen), &result)
// Unmarshal copies what it keeps, so release the host allocation now;
// otherwise results accumulate in the shared arena across calls.
wasmResetAllocator()
if err != nil {
return nil, err
}
return &result, nil
}
func (b *wasmDBBackend) Exec(sql string, params []any) (int64, error) {
sqlBytes := []byte(sql)
paramsJSON, err := json.Marshal(params)
if err != nil {
return 0, err
}
outputBuf := make([]byte, 16)
hostDBExec(
int64(ptrOf(sqlBytes)), int64(len(sqlBytes)),
int64(ptrOf(paramsJSON)), int64(len(paramsJSON)),
int64(ptrOf(outputBuf)), int64(ptrOf(outputBuf[8:])), int64(ptrOf(outputBuf[12:])),
)
rowsAffected := int64(uint64(outputBuf[0]) | uint64(outputBuf[1])<<8 | uint64(outputBuf[2])<<16 | uint64(outputBuf[3])<<24 | uint64(outputBuf[4])<<32 | uint64(outputBuf[5])<<40 | uint64(outputBuf[6])<<48 | uint64(outputBuf[7])<<56)
errPtr := int32(uint32(outputBuf[8]) | uint32(outputBuf[9])<<8 | uint32(outputBuf[10])<<16 | uint32(outputBuf[11])<<24)
errLen := int32(uint32(outputBuf[12]) | uint32(outputBuf[13])<<8 | uint32(outputBuf[14])<<16 | uint32(outputBuf[15])<<24)
if errLen > 0 {
msg := string(wasmSlice(errPtr, errLen))
wasmResetAllocator()
return 0, &hostError{msg}
}
return rowsAffected, nil
}
// ── WASM KV backend ───────────────────────────────────────────────────────────
type wasmKVBackend struct{}
func newWASMKVBackend() KVBackend { return &wasmKVBackend{} }
func (b *wasmKVBackend) Get(key string) (string, bool) {
keyBytes := []byte(key)
outputBuf := make([]byte, 8)
hostStorageGet(
int64(ptrOf(keyBytes)), int64(len(keyBytes)),
int64(ptrOf(outputBuf)), int64(ptrOf(outputBuf[4:])),
)
valPtr := int32(uint32(outputBuf[0]) | uint32(outputBuf[1])<<8 | uint32(outputBuf[2])<<16 | uint32(outputBuf[3])<<24)
valLen := int32(uint32(outputBuf[4]) | uint32(outputBuf[5])<<8 | uint32(outputBuf[6])<<16 | uint32(outputBuf[7])<<24)
if valLen == 0 {
return "", false
}
val := string(wasmSlice(valPtr, valLen))
wasmResetAllocator()
return val, true
}
func (b *wasmKVBackend) Set(key, value string) {
keyBytes := []byte(key)
valBytes := []byte(value)
hostStorageSet(int64(ptrOf(keyBytes)), int64(len(keyBytes)), int64(ptrOf(valBytes)), int64(len(valBytes)))
}
func (b *wasmKVBackend) Delete(key string) {
keyBytes := []byte(key)
hostStorageDelete(int64(ptrOf(keyBytes)), int64(len(keyBytes)))
}
// ── WASM Cache backend ────────────────────────────────────────────────────────
type wasmCacheBackend struct{}
func newWASMCacheBackend() CacheBackend { return &wasmCacheBackend{} }
func (b *wasmCacheBackend) Get(key string) (string, bool) {
keyBytes := []byte(key)
outputBuf := make([]byte, 8)
hostCacheGet(
int64(ptrOf(keyBytes)), int64(len(keyBytes)),
int64(ptrOf(outputBuf)), int64(ptrOf(outputBuf[4:])),
)
valPtr := int32(uint32(outputBuf[0]) | uint32(outputBuf[1])<<8 | uint32(outputBuf[2])<<16 | uint32(outputBuf[3])<<24)
valLen := int32(uint32(outputBuf[4]) | uint32(outputBuf[5])<<8 | uint32(outputBuf[6])<<16 | uint32(outputBuf[7])<<24)
if valLen == 0 {
return "", false
}
val := string(wasmSlice(valPtr, valLen))
wasmResetAllocator()
return val, true
}
func (b *wasmCacheBackend) Set(key, value string, ttl time.Duration) {
keyBytes := []byte(key)
valBytes := []byte(value)
hostCacheSet(int64(ptrOf(keyBytes)), int64(len(keyBytes)), int64(ptrOf(valBytes)), int64(len(valBytes)), ttlToSeconds(ttl))
}
func (b *wasmCacheBackend) Delete(key string) {
keyBytes := []byte(key)
hostCacheDelete(int64(ptrOf(keyBytes)), int64(len(keyBytes)))
}
// ── WASM log backend ──────────────────────────────────────────────────────────
type wasmLogBackend struct{}
func newWASMLogBackend() LogBackend { return &wasmLogBackend{} }
func (b *wasmLogBackend) Log(level int, msg string) {
msgBytes := []byte(msg)
if len(msgBytes) == 0 {
return
}
hostLog(int32(level), int64(ptrOf(msgBytes)), int64(len(msgBytes)))
}
// ── WASM config backend ───────────────────────────────────────────────────────
type wasmConfigBackend struct{}
func newWASMConfigBackend() ConfigBackend { return &wasmConfigBackend{} }
func (b *wasmConfigBackend) Get(key string) (string, bool) {
keyBytes := []byte(key)
outputBuf := make([]byte, 8)
hostConfigGet(
int64(ptrOf(keyBytes)), int64(len(keyBytes)),
int64(ptrOf(outputBuf)), int64(ptrOf(outputBuf[4:])),
)
valPtr := int32(uint32(outputBuf[0]) | uint32(outputBuf[1])<<8 | uint32(outputBuf[2])<<16 | uint32(outputBuf[3])<<24)
valLen := int32(uint32(outputBuf[4]) | uint32(outputBuf[5])<<8 | uint32(outputBuf[6])<<16 | uint32(outputBuf[7])<<24)
if valLen == 0 {
return "", false
}
val := string(wasmSlice(valPtr, valLen))
wasmResetAllocator()
return val, true
}
// ── WASM Permission backend ───────────────────────────────────────────────────
type wasmPermissionBackend struct{}
func newWASMPermissionBackend() PermissionBackend { return &wasmPermissionBackend{} }
func (b *wasmPermissionBackend) Check(permission string) bool {
permBytes := []byte(permission)
if len(permBytes) == 0 {
return false
}
return hostPermissionCheck(int64(ptrOf(permBytes)), int64(len(permBytes))) != 0
}
// ── EmitEvent ─────────────────────────────────────────────────────────────────
// EmitEvent publishes an event to the paca event bus from WASM.
func EmitEvent(topic string, payload any) {
topicBytes := []byte(topic)
payloadBytes, _ := json.Marshal(payload)
hostEventEmit(
int64(ptrOf(topicBytes)), int64(len(topicBytes)),
int64(ptrOf(payloadBytes)), int64(len(payloadBytes)),
)
}
// ── RecordActivity ────────────────────────────────────────────────────────────
// activityInput is the JSON shape sent to the paca.activity_record host function.
type activityInput struct {
TaskID string `json:"task_id"`
ProjectID string `json:"project_id"`
ActorID string `json:"actor_id,omitempty"`
ActivityType string `json:"activity_type"`
Content any `json:"content"`
}
// RecordActivity appends a task-activity event to the paca activity stream so
// that it is persisted to PostgreSQL by the ActivityConsumer worker.
// actorUserID should be req.Caller.UserID (the authenticated user's UUID).
// content must be JSON-encodable and match the expected shape for activityType.
func RecordActivity(taskID, projectID, actorUserID, activityType string, content any) {
inp := activityInput{
TaskID: taskID,
ProjectID: projectID,
ActorID: actorUserID,
ActivityType: activityType,
Content: content,
}
payloadBytes, _ := json.Marshal(inp)
hostActivityRecord(int64(ptrOf(payloadBytes)), int64(len(payloadBytes)))
}
// ── Fetch ─────────────────────────────────────────────────────────────────────
// FetchResponse is the result of a Fetch call.
type FetchResponse struct {
Status int `json:"status"`
Body string `json:"body"`
Headers map[string]string `json:"headers"`
Error string `json:"error"`
// Code is a machine-readable error classification set by newer hosts
// (e.g. "response_too_large"). Fetch maps it to a typed error.
Code string `json:"code,omitempty"`
}
// Fetch makes an outbound HTTP request via the paca.fetch host function.
// The URL's domain must be listed in the plugin manifest's allowedOutboundDomains.
func Fetch(method, rawURL string, headers map[string]string, body string) (*FetchResponse, error) {
req := struct {
Method string `json:"method"`
URL string `json:"url"`
Headers map[string]string `json:"headers"`
Body string `json:"body"`
// Chunked tells the host it may return a body_handle (read via
// readBodyChunks) instead of response_too_large.
Chunked bool `json:"chunked"`
}{
Method: method,
URL: rawURL,
Headers: headers,
Body: body,
Chunked: true,
}
reqJSON, err := json.Marshal(req)
if err != nil {
return nil, err
}
resBytes, err := callFetchHost(reqJSON)
if err != nil {
return nil, err
}
var env fetchEnvelope
if err := json.Unmarshal(resBytes, &env); err != nil {
return nil, fmt.Errorf("plugin: fetch: decode response: %w", err)
}
if env.Error != "" {
return nil, hostResultError("fetch", env.Error, env.Code)
}
if env.BodyHandle != "" {
// Too big for one envelope: the host parked the body; pull it in pieces.
body, err := readBodyChunks(env.BodyHandle, env.BodySize, readFetchChunk)
if err != nil {
return nil, err
}
env.Body = body
}
return &env.FetchResponse, nil
}
// callFetchHost sends one request to paca.fetch and returns the response
// bytes, copied out of the host arena (which is then released).
func callFetchHost(reqJSON []byte) ([]byte, error) {
outputBuf := make([]byte, 8)
hostFetch(
int64(ptrOf(reqJSON)), int64(len(reqJSON)),
int64(ptrOf(outputBuf)), int64(ptrOf(outputBuf[4:])),
)
resPtr := int32(uint32(outputBuf[0]) | uint32(outputBuf[1])<<8 | uint32(outputBuf[2])<<16 | uint32(outputBuf[3])<<24)
resLen := int32(uint32(outputBuf[4]) | uint32(outputBuf[5])<<8 | uint32(outputBuf[6])<<16 | uint32(outputBuf[7])<<24)
if resLen == 0 {
return nil, errEmptyHostResponse("fetch")
}
resBytes := append([]byte(nil), wasmSlice(resPtr, resLen)...)
wasmResetAllocator()
return resBytes, nil
}
// readFetchChunk reads one piece of a body the host parked for handle.
func readFetchChunk(handle string, offset, limit int) (*fetchChunk, error) {
reqJSON, err := json.Marshal(map[string]any{"body_handle": handle, "offset": offset, "limit": limit})
if err != nil {
return nil, err
}
resBytes, err := callFetchHost(reqJSON)
if err != nil {
return nil, err
}
var c fetchChunk
if err := json.Unmarshal(resBytes, &c); err != nil {
return nil, fmt.Errorf("plugin: fetch: decode body chunk: %w", err)
}
if c.Error != "" {
return nil, hostResultError("fetch", c.Error, c.Code)
}
return &c, nil
}
// ── GetBranding ───────────────────────────────────────────────────────────────
// BrandingInfo mirrors the workspace's public branding (GET /branding).
// Empty fields mean the admin has not customized that value — plugins
// should fall back to their own defaults in that case.
type BrandingInfo struct {
LogoURL string `json:"logo_url"`
BrandName string `json:"brand_name"`
PrimaryColorLight string `json:"primary_color_light"`
PrimaryColorDark string `json:"primary_color_dark"`
}
type brandingResult struct {
BrandingInfo
Error string `json:"error"`
Code string `json:"code"`
}
// GetBranding reads the workspace's current branding (logo, brand name,
// primary colors) via the paca.settings_get host function. Call this at
// send/render time rather than caching the result, so that an admin's
// branding change is reflected immediately in anything rendered afterward.
func GetBranding() (*BrandingInfo, error) {
outputBuf := make([]byte, 8)
hostSettingsGet(int64(ptrOf(outputBuf)), int64(ptrOf(outputBuf[4:])))
resPtr := int32(uint32(outputBuf[0]) | uint32(outputBuf[1])<<8 | uint32(outputBuf[2])<<16 | uint32(outputBuf[3])<<24)
resLen := int32(uint32(outputBuf[4]) | uint32(outputBuf[5])<<8 | uint32(outputBuf[6])<<16 | uint32(outputBuf[7])<<24)
if resLen == 0 {
return nil, errEmptyHostResponse("settings_get")
}
resBytes := append([]byte(nil), wasmSlice(resPtr, resLen)...)
wasmResetAllocator()
var res brandingResult
if err := json.Unmarshal(resBytes, &res); err != nil {
return nil, fmt.Errorf("plugin: settings_get: decode response: %w", err)
}
if res.Error != "" {
return nil, hostResultError("settings_get", res.Error, res.Code)
}
return &res.BrandingInfo, nil
}
// ── Helpers ───────────────────────────────────────────────────────────────────
//go:nocheckptr
func wasmSlice(ptr, length int32) []byte {
if length == 0 || ptr == 0 {
return nil
}
if mallocBase == 0 {
mallocBase = int32(uintptr(unsafe.Pointer(&mallocBuffer[0])))
}
start := ptr - mallocBase
if start < 0 || start+length > int32(len(mallocBuffer)) {
return nil
}
return mallocBuffer[start : start+length]
}
func ptrOf(b []byte) int32 {
if len(b) == 0 {
return 0
}
// Return absolute linear-memory pointer expected by host imports.
return int32(uintptr(unsafe.Pointer(&b[0])))
}
type hostError struct{ msg string }
func (e *hostError) Error() string { return e.msg }