| 1 |
// Copyright 2024 The Hugo Authors. All rights reserved. |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package warpc |
| 15 |
|
| 16 |
import ( |
| 17 |
"bytes" |
| 18 |
"context" |
| 19 |
_ "embed" |
| 20 |
"encoding/json" |
| 21 |
"errors" |
| 22 |
"fmt" |
| 23 |
"io" |
| 24 |
"os" |
| 25 |
"runtime" |
| 26 |
"strings" |
| 27 |
"sync" |
| 28 |
"sync/atomic" |
| 29 |
"time" |
| 30 |
|
| 31 |
"github.com/bep/helpers/maphelpers" |
| 32 |
"github.com/bep/textandbinarywriter" |
| 33 |
|
| 34 |
"github.com/gohugoio/hugo/common/hstrings" |
| 35 |
"github.com/gohugoio/hugo/common/hugio" |
| 36 |
"golang.org/x/sync/errgroup" |
| 37 |
|
| 38 |
"github.com/tetratelabs/wazero" |
| 39 |
"github.com/tetratelabs/wazero/api" |
| 40 |
"github.com/tetratelabs/wazero/experimental" |
| 41 |
"github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1" |
| 42 |
) |
| 43 |
|
| 44 |
const ( |
| 45 |
MessageKindJSON string = "json" |
| 46 |
MessageKindBlob string = "blob" |
| 47 |
) |
| 48 |
|
| 49 |
const currentVersion = 1 |
| 50 |
|
| 51 |
// GetWASMDeps returns version information for the C libraries bundled as WASM. |
| 52 |
func GetWASMDeps() [][2]string { |
| 53 |
return [][2]string{ |
| 54 |
{"aomedia.googlesource.com/aom", aomVersion}, |
| 55 |
{"code.videolan.org/videolan/dav1d", dav1dVersion}, |
| 56 |
{"github.com/AOMediaCodec/libavif", libavifVersion}, |
| 57 |
{"github.com/KaTeX/KaTeX", katexVersion}, |
| 58 |
{"github.com/webmproject/libwebp", libwebpVersion}, |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
//go:embed wasm/quickjs.wasm |
| 63 |
var quickjsWasm []byte |
| 64 |
|
| 65 |
//go:embed wasm/webp.wasm |
| 66 |
var webpWasm []byte |
| 67 |
|
| 68 |
//go:embed wasm/avif.wasm |
| 69 |
var avifWasm []byte |
| 70 |
|
| 71 |
// Header is in both the request and response. |
| 72 |
type Header struct { |
| 73 |
// Major version of the protocol. |
| 74 |
Version uint16 `json:"version"` |
| 75 |
|
| 76 |
// Unique ID for the request. |
| 77 |
// Note that this only needs to be unique within the current request set time window. |
| 78 |
ID uint32 `json:"id"` |
| 79 |
|
| 80 |
// Command is the command to execute. |
| 81 |
Command string `json:"command"` |
| 82 |
|
| 83 |
// RequestKinds is a list of kinds in this RPC request, |
| 84 |
// e.g. {"json", "blob"}, or {"json"}. |
| 85 |
RequestKinds []string `json:"requestKinds"` |
| 86 |
// ResponseKinds is a list of kinds expected in the response, |
| 87 |
// e.g. {"json", "blob"}, or {"json"}. |
| 88 |
ResponseKinds []string `json:"responseKinds"` |
| 89 |
|
| 90 |
// Set in the response if there was an error. |
| 91 |
Err string `json:"err"` |
| 92 |
|
| 93 |
// Warnings is a list of warnings that may be returned in the response. |
| 94 |
Warnings []string `json:"warnings,omitempty"` |
| 95 |
} |
| 96 |
|
| 97 |
func (m *Header) init() error { |
| 98 |
if m.ID == 0 { |
| 99 |
return errors.New("ID must not be 0 (note that this must be unique within the current request set time window)") |
| 100 |
} |
| 101 |
if m.Version == 0 { |
| 102 |
m.Version = currentVersion |
| 103 |
} |
| 104 |
if len(m.RequestKinds) == 0 { |
| 105 |
m.RequestKinds = []string{string(MessageKindJSON)} |
| 106 |
} |
| 107 |
if len(m.ResponseKinds) == 0 { |
| 108 |
m.ResponseKinds = []string{string(MessageKindJSON)} |
| 109 |
} |
| 110 |
if m.Version != currentVersion { |
| 111 |
return fmt.Errorf("unsupported version: %d", m.Version) |
| 112 |
} |
| 113 |
for range 2 { |
| 114 |
if len(m.RequestKinds) > 2 { |
| 115 |
return fmt.Errorf("invalid number of request kinds: %d", len(m.RequestKinds)) |
| 116 |
} |
| 117 |
if len(m.ResponseKinds) > 2 { |
| 118 |
return fmt.Errorf("invalid number of response kinds: %d", len(m.ResponseKinds)) |
| 119 |
} |
| 120 |
m.RequestKinds = hstrings.UniqueStringsReuse(m.RequestKinds) |
| 121 |
m.ResponseKinds = hstrings.UniqueStringsReuse(m.ResponseKinds) |
| 122 |
|
| 123 |
} |
| 124 |
|
| 125 |
return nil |
| 126 |
} |
| 127 |
|
| 128 |
type Message[T any] struct { |
| 129 |
Header Header `json:"header"` |
| 130 |
Data T `json:"data"` |
| 131 |
} |
| 132 |
|
| 133 |
func (m Message[T]) GetID() uint32 { |
| 134 |
return m.Header.ID |
| 135 |
} |
| 136 |
|
| 137 |
func (m *Message[T]) init() error { |
| 138 |
return m.Header.init() |
| 139 |
} |
| 140 |
|
| 141 |
type SourceProvider interface { |
| 142 |
GetSource() hugio.SizeReader |
| 143 |
} |
| 144 |
|
| 145 |
type DestinationProvider interface { |
| 146 |
GetDestination() io.Writer |
| 147 |
} |
| 148 |
|
| 149 |
type Dispatcher[Q, R any] interface { |
| 150 |
Execute(ctx context.Context, q Message[Q]) (Message[R], error) |
| 151 |
Close() error |
| 152 |
} |
| 153 |
|
| 154 |
func (p *dispatcherPool[Q, R]) getDispatcher() *dispatcher[Q, R] { |
| 155 |
i := int(p.counter.Add(1)) % len(p.dispatchers) |
| 156 |
return p.dispatchers[i] |
| 157 |
} |
| 158 |
|
| 159 |
func (p *dispatcherPool[Q, R]) Close() error { |
| 160 |
return p.close() |
| 161 |
} |
| 162 |
|
| 163 |
type dispatcher[Q, R any] struct { |
| 164 |
zeroR Message[R] |
| 165 |
|
| 166 |
id atomic.Uint32 |
| 167 |
|
| 168 |
mu sync.Mutex |
| 169 |
encodeMu sync.Mutex |
| 170 |
|
| 171 |
pending map[uint32]*call[Q, R] |
| 172 |
|
| 173 |
inOut *inOut |
| 174 |
inGroup *errgroup.Group |
| 175 |
|
| 176 |
shutdown bool |
| 177 |
closing bool |
| 178 |
} |
| 179 |
|
| 180 |
type inOut struct { |
| 181 |
sync.Mutex |
| 182 |
stdin hugio.ReadWriteCloser |
| 183 |
stdout io.WriteCloser |
| 184 |
stdoutBinary hugio.ReadWriteCloser |
| 185 |
dec *json.Decoder |
| 186 |
enc *json.Encoder |
| 187 |
} |
| 188 |
|
| 189 |
func (p *inOut) Close() error { |
| 190 |
if err := p.stdin.Close(); err != nil { |
| 191 |
return err |
| 192 |
} |
| 193 |
|
| 194 |
// This will also close the underlying writers. |
| 195 |
if err := p.stdout.Close(); err != nil { |
| 196 |
return err |
| 197 |
} |
| 198 |
return nil |
| 199 |
} |
| 200 |
|
| 201 |
var ErrShutdown = fmt.Errorf("dispatcher is shutting down") |
| 202 |
|
| 203 |
var timerPool = sync.Pool{} |
| 204 |
|
| 205 |
func getTimer(d time.Duration) *time.Timer { |
| 206 |
if v := timerPool.Get(); v != nil { |
| 207 |
timer := v.(*time.Timer) |
| 208 |
timer.Reset(d) |
| 209 |
return timer |
| 210 |
} |
| 211 |
return time.NewTimer(d) |
| 212 |
} |
| 213 |
|
| 214 |
func putTimer(t *time.Timer) { |
| 215 |
if !t.Stop() { |
| 216 |
select { |
| 217 |
case <-t.C: |
| 218 |
default: |
| 219 |
} |
| 220 |
} |
| 221 |
timerPool.Put(t) |
| 222 |
} |
| 223 |
|
| 224 |
// Execute sends a request to the dispatcher and waits for the response. |
| 225 |
func (p *dispatcherPool[Q, R]) Execute(ctx context.Context, q Message[Q]) (Message[R], error) { |
| 226 |
d := p.getDispatcher() |
| 227 |
|
| 228 |
call, err := d.newCall(q) |
| 229 |
if err != nil { |
| 230 |
return d.zeroR, err |
| 231 |
} |
| 232 |
|
| 233 |
if err := d.send(call); err != nil { |
| 234 |
return d.zeroR, err |
| 235 |
} |
| 236 |
|
| 237 |
timer := getTimer(30 * time.Second) |
| 238 |
defer putTimer(timer) |
| 239 |
|
| 240 |
select { |
| 241 |
case call = <-call.donec: |
| 242 |
case <-p.donec: |
| 243 |
return d.zeroR, p.Err() |
| 244 |
case <-ctx.Done(): |
| 245 |
return d.zeroR, ctx.Err() |
| 246 |
case <-timer.C: |
| 247 |
return d.zeroR, errors.New("timeout") |
| 248 |
} |
| 249 |
|
| 250 |
if call.err != nil { |
| 251 |
return d.zeroR, call.err |
| 252 |
} |
| 253 |
|
| 254 |
resp, err := call.response, p.Err() |
| 255 |
|
| 256 |
if err == nil && resp.Header.Err != "" { |
| 257 |
err = errors.New(resp.Header.Err) |
| 258 |
} |
| 259 |
|
| 260 |
return resp, err |
| 261 |
} |
| 262 |
|
| 263 |
func (d *dispatcher[Q, R]) newCall(q Message[Q]) (*call[Q, R], error) { |
| 264 |
if q.Header.ID == 0 { |
| 265 |
q.Header.ID = d.id.Add(1) |
| 266 |
} |
| 267 |
if err := q.init(); err != nil { |
| 268 |
return nil, err |
| 269 |
} |
| 270 |
responseKinds := maphelpers.NewConcurrentMap[string, bool]() |
| 271 |
for _, rk := range q.Header.ResponseKinds { |
| 272 |
responseKinds.Set(rk, true) |
| 273 |
} |
| 274 |
call := &call[Q, R]{ |
| 275 |
donec: make(chan *call[Q, R], 1), |
| 276 |
request: q, |
| 277 |
responseKinds: responseKinds, |
| 278 |
} |
| 279 |
|
| 280 |
if d.shutdown || d.closing { |
| 281 |
call.err = ErrShutdown |
| 282 |
call.done() |
| 283 |
return call, nil |
| 284 |
} |
| 285 |
|
| 286 |
d.mu.Lock() |
| 287 |
d.pending[q.GetID()] = call |
| 288 |
d.mu.Unlock() |
| 289 |
|
| 290 |
return call, nil |
| 291 |
} |
| 292 |
|
| 293 |
func (d *dispatcher[Q, R]) send(call *call[Q, R]) error { |
| 294 |
d.mu.Lock() |
| 295 |
if d.closing || d.shutdown { |
| 296 |
d.mu.Unlock() |
| 297 |
return ErrShutdown |
| 298 |
} |
| 299 |
d.mu.Unlock() |
| 300 |
|
| 301 |
d.encodeMu.Lock() |
| 302 |
defer d.encodeMu.Unlock() |
| 303 |
err := d.inOut.enc.Encode(call.request) |
| 304 |
if err != nil { |
| 305 |
return err |
| 306 |
} |
| 307 |
if sp, ok := any(call.request.Data).(SourceProvider); ok { |
| 308 |
source := sp.GetSource() |
| 309 |
if source.Size() == 0 { |
| 310 |
return errors.New("source size must be greater than 0") |
| 311 |
} |
| 312 |
|
| 313 |
if err := textandbinarywriter.WriteBlobHeader(d.inOut.stdin, call.request.GetID(), uint32(source.Size())); err != nil { |
| 314 |
return err |
| 315 |
} |
| 316 |
_, err := io.Copy(d.inOut.stdin, source) |
| 317 |
if err != nil { |
| 318 |
return err |
| 319 |
} |
| 320 |
} |
| 321 |
return nil |
| 322 |
} |
| 323 |
|
| 324 |
func (d *dispatcher[Q, R]) inputBlobs() error { |
| 325 |
var inputErr error |
| 326 |
for { |
| 327 |
id, length, err := textandbinarywriter.ReadBlobHeader(d.inOut.stdoutBinary) |
| 328 |
if err != nil { |
| 329 |
inputErr = err |
| 330 |
break |
| 331 |
} |
| 332 |
|
| 333 |
lr := &io.LimitedReader{ |
| 334 |
R: d.inOut.stdoutBinary, |
| 335 |
N: int64(length), |
| 336 |
} |
| 337 |
|
| 338 |
call := d.pendingCall(id) |
| 339 |
|
| 340 |
if err := call.handleBlob(lr); err != nil { |
| 341 |
inputErr = err |
| 342 |
break |
| 343 |
} |
| 344 |
if lr.N != 0 { |
| 345 |
inputErr = fmt.Errorf("blob %d: expected to read %d more bytes", id, lr.N) |
| 346 |
break |
| 347 |
} |
| 348 |
if err := call.responseKinds.WithWriteLock( |
| 349 |
func(m map[string]bool) error { |
| 350 |
if _, ok := m[MessageKindBlob]; !ok { |
| 351 |
return fmt.Errorf("unexpected blob response for %q call ID %d", call.request.Header.Command, id) |
| 352 |
} |
| 353 |
delete(m, MessageKindBlob) |
| 354 |
if len(m) == 0 { |
| 355 |
// Message exchange is complete. |
| 356 |
d.mu.Lock() |
| 357 |
delete(d.pending, id) |
| 358 |
d.mu.Unlock() |
| 359 |
call.done() |
| 360 |
} |
| 361 |
return nil |
| 362 |
}, |
| 363 |
); err != nil { |
| 364 |
inputErr = err |
| 365 |
break |
| 366 |
} |
| 367 |
} |
| 368 |
|
| 369 |
return inputErr |
| 370 |
} |
| 371 |
|
| 372 |
func (d *dispatcher[Q, R]) inputJSON() error { |
| 373 |
var inputErr error |
| 374 |
|
| 375 |
for d.inOut.dec.More() { |
| 376 |
var r Message[R] |
| 377 |
if err := d.inOut.dec.Decode(&r); err != nil { |
| 378 |
inputErr = err |
| 379 |
break |
| 380 |
} |
| 381 |
|
| 382 |
call := d.pendingCall(r.GetID()) |
| 383 |
|
| 384 |
if err := call.responseKinds.WithWriteLock( |
| 385 |
func(m map[string]bool) error { |
| 386 |
call.response = r |
| 387 |
if _, ok := m[MessageKindJSON]; !ok { |
| 388 |
return fmt.Errorf("unexpected JSON response for call ID %d", r.GetID()) |
| 389 |
} |
| 390 |
delete(m, MessageKindJSON) |
| 391 |
if len(m) == 0 || r.Header.Err != "" { |
| 392 |
// Message exchange is complete. |
| 393 |
d.mu.Lock() |
| 394 |
delete(d.pending, r.GetID()) |
| 395 |
d.mu.Unlock() |
| 396 |
call.done() |
| 397 |
} |
| 398 |
return nil |
| 399 |
}, |
| 400 |
); err != nil { |
| 401 |
inputErr = err |
| 402 |
break |
| 403 |
} |
| 404 |
|
| 405 |
} |
| 406 |
|
| 407 |
// Terminate pending calls. |
| 408 |
d.shutdown = true |
| 409 |
if inputErr != nil { |
| 410 |
isEOF := inputErr == io.EOF || inputErr == io.ErrClosedPipe || strings.Contains(inputErr.Error(), "already closed") |
| 411 |
if isEOF { |
| 412 |
if d.closing { |
| 413 |
inputErr = ErrShutdown |
| 414 |
} else { |
| 415 |
inputErr = io.ErrUnexpectedEOF |
| 416 |
} |
| 417 |
} |
| 418 |
} |
| 419 |
|
| 420 |
d.mu.Lock() |
| 421 |
defer d.mu.Unlock() |
| 422 |
for _, call := range d.pending { |
| 423 |
call.err = inputErr |
| 424 |
call.done() |
| 425 |
} |
| 426 |
|
| 427 |
return inputErr |
| 428 |
} |
| 429 |
|
| 430 |
func (d *dispatcher[Q, R]) pendingCall(id uint32) *call[Q, R] { |
| 431 |
d.mu.Lock() |
| 432 |
defer d.mu.Unlock() |
| 433 |
c, ok := d.pending[id] |
| 434 |
if !ok { |
| 435 |
// The WASM module wrote a response for an ID we never sent. This means it |
| 436 |
// broke the RPC protocol, e.g. a corrupted stream after an error path that |
| 437 |
// failed to drain its input or write a response. This is a bug in the |
| 438 |
// module and should be reported. |
| 439 |
panic(fmt.Errorf("received response for unknown call ID %d: WASM module violated the RPC protocol", id)) |
| 440 |
} |
| 441 |
return c |
| 442 |
} |
| 443 |
|
| 444 |
type call[Q, R any] struct { |
| 445 |
request Message[Q] |
| 446 |
response Message[R] |
| 447 |
responseKinds *maphelpers.ConcurrentMap[string, bool] |
| 448 |
err error |
| 449 |
donec chan *call[Q, R] |
| 450 |
} |
| 451 |
|
| 452 |
func (c *call[Q, R]) handleBlob(r io.Reader) error { |
| 453 |
dest := any(c.request.Data).(DestinationProvider).GetDestination() |
| 454 |
if dest == nil { |
| 455 |
panic("blob destination is not set") |
| 456 |
} |
| 457 |
_, err := io.Copy(dest, r) |
| 458 |
return err |
| 459 |
} |
| 460 |
|
| 461 |
func (call *call[Q, R]) done() { |
| 462 |
select { |
| 463 |
case call.donec <- call: |
| 464 |
default: |
| 465 |
} |
| 466 |
} |
| 467 |
|
| 468 |
// Binary represents a WebAssembly binary. |
| 469 |
type Binary struct { |
| 470 |
// The name of the binary. |
| 471 |
// For quickjs, this must match the instance import name, "javy_quickjs_provider_v2". |
| 472 |
// For the main module, we only use this for caching. |
| 473 |
Name string |
| 474 |
|
| 475 |
// THe wasm binary. |
| 476 |
Data []byte |
| 477 |
} |
| 478 |
|
| 479 |
type ProtocolType int |
| 480 |
|
| 481 |
const ( |
| 482 |
ProtocolJSON ProtocolType = iota + 1 |
| 483 |
ProtocolJSONAndBinary = iota |
| 484 |
) |
| 485 |
|
| 486 |
type Options struct { |
| 487 |
Ctx context.Context |
| 488 |
|
| 489 |
Infof func(format string, v ...any) |
| 490 |
|
| 491 |
Warnf func(format string, v ...any) |
| 492 |
|
| 493 |
// E.g. quickjs wasm. May be omitted if not needed. |
| 494 |
Runtime Binary |
| 495 |
|
| 496 |
// The main module to instantiate. |
| 497 |
Main Binary |
| 498 |
|
| 499 |
CompilationCacheDir string |
| 500 |
PoolSize int |
| 501 |
|
| 502 |
// Memory limit in MiB. |
| 503 |
Memory int |
| 504 |
} |
| 505 |
|
| 506 |
func (o *Options) init() error { |
| 507 |
if o.Infof == nil { |
| 508 |
o.Infof = func(format string, v ...any) { |
| 509 |
} |
| 510 |
} |
| 511 |
if o.Warnf == nil { |
| 512 |
o.Warnf = func(format string, v ...any) { |
| 513 |
} |
| 514 |
} |
| 515 |
return nil |
| 516 |
} |
| 517 |
|
| 518 |
type CompileModuleContext struct { |
| 519 |
Opts Options |
| 520 |
Runtime wazero.Runtime |
| 521 |
} |
| 522 |
|
| 523 |
type CompiledModule struct { |
| 524 |
// Runtime (e.g. QuickJS) may be nil if not needed (e.g. embedded in Module). |
| 525 |
Runtime wazero.CompiledModule |
| 526 |
|
| 527 |
// If Runtime is not nil, this should be the name of the instance. |
| 528 |
RuntimeName string |
| 529 |
|
| 530 |
// The main module to instantiate. |
| 531 |
// This will be insantiated multiple times in a pool, |
| 532 |
// so it does not need a name. |
| 533 |
Module wazero.CompiledModule |
| 534 |
} |
| 535 |
|
| 536 |
// Start creates a new dispatcher pool. |
| 537 |
func Start[Q, R any](opts Options) (Dispatcher[Q, R], error) { |
| 538 |
if opts.Main.Data == nil { |
| 539 |
return nil, errors.New("Main.Data must be set") |
| 540 |
} |
| 541 |
if opts.Main.Name == "" { |
| 542 |
return nil, errors.New("Main.Name must be set") |
| 543 |
} |
| 544 |
|
| 545 |
if opts.Runtime.Data != nil && opts.Runtime.Name == "" { |
| 546 |
return nil, errors.New("Runtime.Name must be set") |
| 547 |
} |
| 548 |
|
| 549 |
if opts.PoolSize == 0 { |
| 550 |
opts.PoolSize = 1 |
| 551 |
} |
| 552 |
|
| 553 |
d, err := newDispatcher[Q, R](opts) |
| 554 |
if err != nil { |
| 555 |
return nil, err |
| 556 |
} |
| 557 |
return d, nil |
| 558 |
} |
| 559 |
|
| 560 |
type dispatcherPool[Q, R any] struct { |
| 561 |
counter atomic.Uint32 |
| 562 |
dispatchers []*dispatcher[Q, R] |
| 563 |
close func() error |
| 564 |
opts Options |
| 565 |
|
| 566 |
errc chan error |
| 567 |
donec chan struct{} |
| 568 |
} |
| 569 |
|
| 570 |
func (p *dispatcherPool[Q, R]) SendIfErr(err error) { |
| 571 |
if err != nil { |
| 572 |
p.errc <- err |
| 573 |
} |
| 574 |
} |
| 575 |
|
| 576 |
func (p *dispatcherPool[Q, R]) Err() error { |
| 577 |
select { |
| 578 |
case err := <-p.errc: |
| 579 |
return err |
| 580 |
default: |
| 581 |
return nil |
| 582 |
} |
| 583 |
} |
| 584 |
|
| 585 |
func newDispatcher[Q, R any](opts Options) (*dispatcherPool[Q, R], error) { |
| 586 |
if opts.Ctx == nil { |
| 587 |
opts.Ctx = context.Background() |
| 588 |
} |
| 589 |
|
| 590 |
if opts.Infof == nil { |
| 591 |
opts.Infof = func(format string, v ...any) { |
| 592 |
// noop |
| 593 |
} |
| 594 |
} |
| 595 |
if opts.Warnf == nil { |
| 596 |
opts.Warnf = func(format string, v ...any) { |
| 597 |
// noop |
| 598 |
} |
| 599 |
} |
| 600 |
|
| 601 |
if opts.Memory <= 0 { |
| 602 |
opts.Memory = 32 // 32 MiB |
| 603 |
} |
| 604 |
|
| 605 |
ctx := opts.Ctx |
| 606 |
|
| 607 |
// Page size is 64KB. |
| 608 |
numPages := opts.Memory * 1024 / 64 |
| 609 |
runtimeConfig := wazero.NewRuntimeConfig().WithMemoryLimitPages(uint32(numPages)) |
| 610 |
runtimeConfig = runtimeConfig.WithCoreFeatures(api.CoreFeaturesV2 | experimental.CoreFeaturesExceptionHandling | experimental.CoreFeaturesThreads) |
| 611 |
|
| 612 |
if opts.CompilationCacheDir != "" { |
| 613 |
compilationCache, err := wazero.NewCompilationCacheWithDir(opts.CompilationCacheDir) |
| 614 |
if err != nil { |
| 615 |
return nil, err |
| 616 |
} |
| 617 |
runtimeConfig = runtimeConfig.WithCompilationCache(compilationCache) |
| 618 |
} |
| 619 |
|
| 620 |
// Create a new WebAssembly Runtime. |
| 621 |
r := wazero.NewRuntimeWithConfig(opts.Ctx, runtimeConfig) |
| 622 |
|
| 623 |
// Instantiate WASI, which implements system I/O such as console output. |
| 624 |
if _, err := wasi_snapshot_preview1.Instantiate(ctx, r); err != nil { |
| 625 |
return nil, err |
| 626 |
} |
| 627 |
|
| 628 |
dispatchers := make([]*dispatcher[Q, R], opts.PoolSize) |
| 629 |
|
| 630 |
inOuts := make([]*inOut, opts.PoolSize) |
| 631 |
for i := range opts.PoolSize { |
| 632 |
var stdinPipe, stdoutBinary hugio.ReadWriteCloser |
| 633 |
var stdout io.WriteCloser |
| 634 |
var jsonr io.Reader |
| 635 |
|
| 636 |
stdinPipe = hugio.NewPipeReadWriteCloser() |
| 637 |
stdoutPipe := hugio.NewPipeReadWriteCloser() |
| 638 |
stdout = stdoutPipe |
| 639 |
|
| 640 |
var zero Q |
| 641 |
if _, ok := any(zero).(DestinationProvider); ok { |
| 642 |
stdoutBinary = hugio.NewPipeReadWriteCloser() |
| 643 |
jsonr = stdoutPipe |
| 644 |
stdout = textandbinarywriter.NewWriter(stdout, stdoutBinary) |
| 645 |
} else { |
| 646 |
jsonr = stdoutPipe |
| 647 |
} |
| 648 |
|
| 649 |
inOuts[i] = &inOut{ |
| 650 |
stdin: stdinPipe, |
| 651 |
stdout: stdout, |
| 652 |
stdoutBinary: stdoutBinary, |
| 653 |
dec: json.NewDecoder(jsonr), |
| 654 |
enc: json.NewEncoder(stdinPipe), |
| 655 |
} |
| 656 |
} |
| 657 |
|
| 658 |
var ( |
| 659 |
runtimeModule wazero.CompiledModule |
| 660 |
mainModule wazero.CompiledModule |
| 661 |
err error |
| 662 |
) |
| 663 |
|
| 664 |
if opts.Runtime.Data != nil { |
| 665 |
runtimeModule, err = r.CompileModule(experimental.WithCompilationWorkers(ctx, runtime.GOMAXPROCS(0)/4), opts.Runtime.Data) |
| 666 |
if err != nil { |
| 667 |
return nil, err |
| 668 |
} |
| 669 |
} |
| 670 |
|
| 671 |
mainModule, err = r.CompileModule(experimental.WithCompilationWorkers(ctx, runtime.GOMAXPROCS(0)/4), opts.Main.Data) |
| 672 |
if err != nil { |
| 673 |
return nil, err |
| 674 |
} |
| 675 |
|
| 676 |
toErr := func(what string, errBuff bytes.Buffer, err error) error { |
| 677 |
return fmt.Errorf("%s: %s: %w", what, errBuff.String(), err) |
| 678 |
} |
| 679 |
|
| 680 |
run := func() error { |
| 681 |
g, ctx := errgroup.WithContext(ctx) |
| 682 |
for _, c := range inOuts { |
| 683 |
g.Go(func() error { |
| 684 |
var errBuff bytes.Buffer |
| 685 |
stderr := io.MultiWriter(&errBuff, os.Stderr) |
| 686 |
ctx := context.WithoutCancel(ctx) |
| 687 |
// WithStartFunctions allows us to call the _start function manually. |
| 688 |
configBase := wazero.NewModuleConfig().WithStderr(stderr).WithStdout(c.stdout).WithStdin(c.stdin).WithStartFunctions() |
| 689 |
if opts.Runtime.Data != nil { |
| 690 |
// This needs to be anonymous, it will be resolved in the import resolver below. |
| 691 |
runtimeInstance, err := r.InstantiateModule(ctx, runtimeModule, configBase.WithName("")) |
| 692 |
if err != nil { |
| 693 |
return toErr("quickjs", errBuff, err) |
| 694 |
} |
| 695 |
ctx = experimental.WithImportResolver( |
| 696 |
ctx, |
| 697 |
func(name string) api.Module { |
| 698 |
if name == opts.Runtime.Name { |
| 699 |
return runtimeInstance |
| 700 |
} |
| 701 |
return nil |
| 702 |
}, |
| 703 |
) |
| 704 |
} |
| 705 |
|
| 706 |
mainInstance, err := r.InstantiateModule(ctx, mainModule, configBase.WithName("")) |
| 707 |
if err != nil { |
| 708 |
return toErr(opts.Main.Name, errBuff, err) |
| 709 |
} |
| 710 |
if _, err := mainInstance.ExportedFunction("_start").Call(ctx); err != nil { |
| 711 |
return toErr(opts.Main.Name, errBuff, err) |
| 712 |
} |
| 713 |
|
| 714 |
// The console.log in the Javy/quickjs WebAssembly module will write to stderr. |
| 715 |
// In non-error situations, write that to the provided infof logger. |
| 716 |
if errBuff.Len() > 0 { |
| 717 |
opts.Infof("%s", errBuff.String()) |
| 718 |
} |
| 719 |
|
| 720 |
return nil |
| 721 |
}) |
| 722 |
} |
| 723 |
return g.Wait() |
| 724 |
} |
| 725 |
|
| 726 |
dp := &dispatcherPool[Q, R]{ |
| 727 |
dispatchers: dispatchers, |
| 728 |
opts: opts, |
| 729 |
|
| 730 |
errc: make(chan error, 10), |
| 731 |
donec: make(chan struct{}), |
| 732 |
} |
| 733 |
|
| 734 |
go func() { |
| 735 |
// This will block until stdin is closed or it encounters an error. |
| 736 |
err := run() |
| 737 |
dp.SendIfErr(err) |
| 738 |
close(dp.donec) |
| 739 |
}() |
| 740 |
|
| 741 |
for i := range inOuts { |
| 742 |
ing, _ := errgroup.WithContext(ctx) |
| 743 |
d := &dispatcher[Q, R]{ |
| 744 |
pending: make(map[uint32]*call[Q, R]), |
| 745 |
inOut: inOuts[i], |
| 746 |
inGroup: ing, |
| 747 |
} |
| 748 |
d.inGroup.Go(func() error { |
| 749 |
return d.inputJSON() |
| 750 |
}) |
| 751 |
|
| 752 |
if d.inOut.stdoutBinary != nil { |
| 753 |
d.inGroup.Go(func() error { |
| 754 |
return d.inputBlobs() |
| 755 |
}) |
| 756 |
} |
| 757 |
dp.dispatchers[i] = d |
| 758 |
} |
| 759 |
|
| 760 |
dp.close = func() error { |
| 761 |
for _, d := range dp.dispatchers { |
| 762 |
d.closing = true |
| 763 |
if err := d.inOut.Close(); err != nil { |
| 764 |
return err |
| 765 |
} |
| 766 |
} |
| 767 |
|
| 768 |
for _, d := range dp.dispatchers { |
| 769 |
if err := d.inGroup.Wait(); err != nil { |
| 770 |
return err |
| 771 |
} |
| 772 |
} |
| 773 |
|
| 774 |
// We need to wait for the WebAssembly instances to finish executing before we can close the runtime. |
| 775 |
<-dp.donec |
| 776 |
|
| 777 |
if err := r.Close(ctx); err != nil { |
| 778 |
return err |
| 779 |
} |
| 780 |
|
| 781 |
// Return potential late compilation errors. |
| 782 |
return dp.Err() |
| 783 |
} |
| 784 |
|
| 785 |
return dp, dp.Err() |
| 786 |
} |
| 787 |
|
| 788 |
type lazyDispatcher[Q, R any] struct { |
| 789 |
opts Options |
| 790 |
|
| 791 |
dispatcher Dispatcher[Q, R] |
| 792 |
startOnce sync.Once |
| 793 |
started bool |
| 794 |
startErr error |
| 795 |
} |
| 796 |
|
| 797 |
func (d *lazyDispatcher[Q, R]) start() (Dispatcher[Q, R], error) { |
| 798 |
d.startOnce.Do(func() { |
| 799 |
start := time.Now() |
| 800 |
d.dispatcher, d.startErr = Start[Q, R](d.opts) |
| 801 |
if d.startErr == nil { |
| 802 |
d.started = true |
| 803 |
d.opts.Infof("started dispatcher in %s", time.Since(start)) |
| 804 |
} |
| 805 |
}) |
| 806 |
return d.dispatcher, d.startErr |
| 807 |
} |
| 808 |
|
| 809 |
// Dispatchers holds all the dispatchers for the warpc package. |
| 810 |
type Dispatchers struct { |
| 811 |
katex *lazyDispatcher[KatexInput, KatexOutput] |
| 812 |
webp *lazyDispatcher[WebpInput, WebpOutput] |
| 813 |
avif *lazyDispatcher[AvifInput, AvifOutput] |
| 814 |
} |
| 815 |
|
| 816 |
func (d *Dispatchers) Katex() (Dispatcher[KatexInput, KatexOutput], error) { |
| 817 |
return d.katex.start() |
| 818 |
} |
| 819 |
|
| 820 |
func (d *Dispatchers) Webp() (Dispatcher[WebpInput, WebpOutput], error) { |
| 821 |
return d.webp.start() |
| 822 |
} |
| 823 |
|
| 824 |
func (d *Dispatchers) Avif() (Dispatcher[AvifInput, AvifOutput], error) { |
| 825 |
return d.avif.start() |
| 826 |
} |
| 827 |
|
| 828 |
func (d *Dispatchers) NewWepCodec() (*WebpCodec, error) { |
| 829 |
return &WebpCodec{ |
| 830 |
d: d.Webp, |
| 831 |
}, nil |
| 832 |
} |
| 833 |
|
| 834 |
func (d *Dispatchers) NewAvifCodec() (*AvifCodec, error) { |
| 835 |
return &AvifCodec{ |
| 836 |
d: d.Avif, |
| 837 |
}, nil |
| 838 |
} |
| 839 |
|
| 840 |
func (d *Dispatchers) Close() error { |
| 841 |
var errs []error |
| 842 |
if d.katex.started { |
| 843 |
if err := d.katex.dispatcher.Close(); err != nil { |
| 844 |
errs = append(errs, err) |
| 845 |
} |
| 846 |
} |
| 847 |
if d.webp.started { |
| 848 |
if err := d.webp.dispatcher.Close(); err != nil { |
| 849 |
errs = append(errs, err) |
| 850 |
} |
| 851 |
} |
| 852 |
if len(errs) == 0 { |
| 853 |
return nil |
| 854 |
} |
| 855 |
return fmt.Errorf("%v", errs) |
| 856 |
} |
| 857 |
|
| 858 |
// AllDispatchers creates all the dispatchers for the warpc package. |
| 859 |
// Note that the individual dispatchers are started lazily. |
| 860 |
// Remember to call Close on the returned Dispatchers when done. |
| 861 |
func AllDispatchers(katexOpts, webpOpts, avifOpts Options) *Dispatchers { |
| 862 |
if err := katexOpts.init(); err != nil { |
| 863 |
panic(err) |
| 864 |
} |
| 865 |
if err := webpOpts.init(); err != nil { |
| 866 |
panic(err) |
| 867 |
} |
| 868 |
if katexOpts.Runtime.Data == nil { |
| 869 |
katexOpts.Runtime = Binary{Name: "javy_quickjs_provider_v2", Data: quickjsWasm} |
| 870 |
} |
| 871 |
if katexOpts.Main.Data == nil { |
| 872 |
katexOpts.Main = Binary{Name: "renderkatex", Data: katexWasm} |
| 873 |
} |
| 874 |
|
| 875 |
webpOpts.Main = Binary{Name: "webp", Data: webpWasm} |
| 876 |
avifOpts.Main = Binary{Name: "avif", Data: avifWasm} |
| 877 |
|
| 878 |
dispatchers := &Dispatchers{ |
| 879 |
katex: &lazyDispatcher[KatexInput, KatexOutput]{opts: katexOpts}, |
| 880 |
webp: &lazyDispatcher[WebpInput, WebpOutput]{opts: webpOpts}, |
| 881 |
avif: &lazyDispatcher[AvifInput, AvifOutput]{opts: avifOpts}, |
| 882 |
} |
| 883 |
|
| 884 |
return dispatchers |
| 885 |
} |