Debian Codegraph @

internal/warpc/warpc.go

raw
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 // Workaround for data race, see https://github.com/wazero/wazero/issues/2532
586 var wazeroCacheMu sync.Mutex
587
588 func newDispatcher[Q, R any](opts Options) (*dispatcherPool[Q, R], error) {
589 if opts.Ctx == nil {
590 opts.Ctx = context.Background()
591 }
592
593 if opts.Infof == nil {
594 opts.Infof = func(format string, v ...any) {
595 // noop
596 }
597 }
598 if opts.Warnf == nil {
599 opts.Warnf = func(format string, v ...any) {
600 // noop
601 }
602 }
603
604 if opts.Memory <= 0 {
605 opts.Memory = 32 // 32 MiB
606 }
607
608 ctx := opts.Ctx
609
610 // Page size is 64KB.
611 numPages := opts.Memory * 1024 / 64
612 runtimeConfig := wazero.NewRuntimeConfig().WithMemoryLimitPages(uint32(numPages))
613 runtimeConfig = runtimeConfig.WithCoreFeatures(api.CoreFeaturesV2 | experimental.CoreFeaturesExceptionHandling | experimental.CoreFeaturesThreads)
614
615 if opts.CompilationCacheDir != "" {
616 wazeroCacheMu.Lock()
617 defer wazeroCacheMu.Unlock()
618 compilationCache, err := wazero.NewCompilationCacheWithDir(opts.CompilationCacheDir)
619 if err != nil {
620 return nil, err
621 }
622 runtimeConfig = runtimeConfig.WithCompilationCache(compilationCache)
623 }
624
625 // Create a new WebAssembly Runtime.
626 r := wazero.NewRuntimeWithConfig(opts.Ctx, runtimeConfig)
627
628 // Instantiate WASI, which implements system I/O such as console output.
629 if _, err := wasi_snapshot_preview1.Instantiate(ctx, r); err != nil {
630 return nil, err
631 }
632
633 dispatchers := make([]*dispatcher[Q, R], opts.PoolSize)
634
635 inOuts := make([]*inOut, opts.PoolSize)
636 for i := range opts.PoolSize {
637 var stdinPipe, stdoutBinary hugio.ReadWriteCloser
638 var stdout io.WriteCloser
639 var jsonr io.Reader
640
641 stdinPipe = hugio.NewPipeReadWriteCloser()
642 stdoutPipe := hugio.NewPipeReadWriteCloser()
643 stdout = stdoutPipe
644
645 var zero Q
646 if _, ok := any(zero).(DestinationProvider); ok {
647 stdoutBinary = hugio.NewPipeReadWriteCloser()
648 jsonr = stdoutPipe
649 stdout = textandbinarywriter.NewWriter(stdout, stdoutBinary)
650 } else {
651 jsonr = stdoutPipe
652 }
653
654 inOuts[i] = &inOut{
655 stdin: stdinPipe,
656 stdout: stdout,
657 stdoutBinary: stdoutBinary,
658 dec: json.NewDecoder(jsonr),
659 enc: json.NewEncoder(stdinPipe),
660 }
661 }
662
663 var (
664 runtimeModule wazero.CompiledModule
665 mainModule wazero.CompiledModule
666 err error
667 )
668
669 if opts.Runtime.Data != nil {
670 runtimeModule, err = r.CompileModule(experimental.WithCompilationWorkers(ctx, runtime.GOMAXPROCS(0)/4), opts.Runtime.Data)
671 if err != nil {
672 return nil, err
673 }
674 }
675
676 mainModule, err = r.CompileModule(experimental.WithCompilationWorkers(ctx, runtime.GOMAXPROCS(0)/4), opts.Main.Data)
677 if err != nil {
678 return nil, err
679 }
680
681 toErr := func(what string, errBuff bytes.Buffer, err error) error {
682 return fmt.Errorf("%s: %s: %w", what, errBuff.String(), err)
683 }
684
685 run := func() error {
686 g, ctx := errgroup.WithContext(ctx)
687 for _, c := range inOuts {
688 g.Go(func() error {
689 var errBuff bytes.Buffer
690 stderr := io.MultiWriter(&errBuff, os.Stderr)
691 ctx := context.WithoutCancel(ctx)
692 // WithStartFunctions allows us to call the _start function manually.
693 configBase := wazero.NewModuleConfig().WithStderr(stderr).WithStdout(c.stdout).WithStdin(c.stdin).WithStartFunctions()
694 if opts.Runtime.Data != nil {
695 // This needs to be anonymous, it will be resolved in the import resolver below.
696 runtimeInstance, err := r.InstantiateModule(ctx, runtimeModule, configBase.WithName(""))
697 if err != nil {
698 return toErr("quickjs", errBuff, err)
699 }
700 ctx = experimental.WithImportResolver(
701 ctx,
702 func(name string) api.Module {
703 if name == opts.Runtime.Name {
704 return runtimeInstance
705 }
706 return nil
707 },
708 )
709 }
710
711 mainInstance, err := r.InstantiateModule(ctx, mainModule, configBase.WithName(""))
712 if err != nil {
713 return toErr(opts.Main.Name, errBuff, err)
714 }
715 if _, err := mainInstance.ExportedFunction("_start").Call(ctx); err != nil {
716 return toErr(opts.Main.Name, errBuff, err)
717 }
718
719 // The console.log in the Javy/quickjs WebAssembly module will write to stderr.
720 // In non-error situations, write that to the provided infof logger.
721 if errBuff.Len() > 0 {
722 opts.Infof("%s", errBuff.String())
723 }
724
725 return nil
726 })
727 }
728 return g.Wait()
729 }
730
731 dp := &dispatcherPool[Q, R]{
732 dispatchers: dispatchers,
733 opts: opts,
734
735 errc: make(chan error, 10),
736 donec: make(chan struct{}),
737 }
738
739 go func() {
740 // This will block until stdin is closed or it encounters an error.
741 err := run()
742 dp.SendIfErr(err)
743 close(dp.donec)
744 }()
745
746 for i := range inOuts {
747 ing, _ := errgroup.WithContext(ctx)
748 d := &dispatcher[Q, R]{
749 pending: make(map[uint32]*call[Q, R]),
750 inOut: inOuts[i],
751 inGroup: ing,
752 }
753 d.inGroup.Go(func() error {
754 return d.inputJSON()
755 })
756
757 if d.inOut.stdoutBinary != nil {
758 d.inGroup.Go(func() error {
759 return d.inputBlobs()
760 })
761 }
762 dp.dispatchers[i] = d
763 }
764
765 dp.close = func() error {
766 for _, d := range dp.dispatchers {
767 d.closing = true
768 if err := d.inOut.Close(); err != nil {
769 return err
770 }
771 }
772
773 for _, d := range dp.dispatchers {
774 // ErrShutdown is expected here; since Go 1.27 (json/v2), Decode
775 // surfaces the read error from the pipes we just closed.
776 if err := d.inGroup.Wait(); err != nil && err != ErrShutdown {
777 return err
778 }
779 }
780
781 // We need to wait for the WebAssembly instances to finish executing before we can close the runtime.
782 <-dp.donec
783
784 if err := r.Close(ctx); err != nil {
785 return err
786 }
787
788 // Return potential late compilation errors.
789 return dp.Err()
790 }
791
792 return dp, dp.Err()
793 }
794
795 type lazyDispatcher[Q, R any] struct {
796 opts Options
797
798 dispatcher Dispatcher[Q, R]
799 startOnce sync.Once
800 started bool
801 startErr error
802 }
803
804 func (d *lazyDispatcher[Q, R]) start() (Dispatcher[Q, R], error) {
805 d.startOnce.Do(func() {
806 start := time.Now()
807 d.dispatcher, d.startErr = Start[Q, R](d.opts)
808 if d.startErr == nil {
809 d.started = true
810 d.opts.Infof("started dispatcher in %s", time.Since(start))
811 }
812 })
813 return d.dispatcher, d.startErr
814 }
815
816 // Dispatchers holds all the dispatchers for the warpc package.
817 type Dispatchers struct {
818 katex *lazyDispatcher[KatexInput, KatexOutput]
819 webp *lazyDispatcher[WebpInput, WebpOutput]
820 avif *lazyDispatcher[AvifInput, AvifOutput]
821 }
822
823 func (d *Dispatchers) Katex() (Dispatcher[KatexInput, KatexOutput], error) {
824 return d.katex.start()
825 }
826
827 func (d *Dispatchers) Webp() (Dispatcher[WebpInput, WebpOutput], error) {
828 return d.webp.start()
829 }
830
831 func (d *Dispatchers) Avif() (Dispatcher[AvifInput, AvifOutput], error) {
832 return d.avif.start()
833 }
834
835 func (d *Dispatchers) NewWepCodec() (*WebpCodec, error) {
836 return &WebpCodec{
837 d: d.Webp,
838 }, nil
839 }
840
841 func (d *Dispatchers) NewAvifCodec() (*AvifCodec, error) {
842 return &AvifCodec{
843 d: d.Avif,
844 }, nil
845 }
846
847 func (d *Dispatchers) Close() error {
848 var errs []error
849 if d.katex.started {
850 if err := d.katex.dispatcher.Close(); err != nil {
851 errs = append(errs, err)
852 }
853 }
854 if d.webp.started {
855 if err := d.webp.dispatcher.Close(); err != nil {
856 errs = append(errs, err)
857 }
858 }
859 if len(errs) == 0 {
860 return nil
861 }
862 return fmt.Errorf("%v", errs)
863 }
864
865 // AllDispatchers creates all the dispatchers for the warpc package.
866 // Note that the individual dispatchers are started lazily.
867 // Remember to call Close on the returned Dispatchers when done.
868 func AllDispatchers(katexOpts, webpOpts, avifOpts Options) *Dispatchers {
869 if err := katexOpts.init(); err != nil {
870 panic(err)
871 }
872 if err := webpOpts.init(); err != nil {
873 panic(err)
874 }
875 if katexOpts.Runtime.Data == nil {
876 katexOpts.Runtime = Binary{Name: "javy_quickjs_provider_v2", Data: quickjsWasm}
877 }
878 if katexOpts.Main.Data == nil {
879 katexOpts.Main = Binary{Name: "renderkatex", Data: katexWasm}
880 }
881
882 webpOpts.Main = Binary{Name: "webp", Data: webpWasm}
883 avifOpts.Main = Binary{Name: "avif", Data: avifWasm}
884
885 dispatchers := &Dispatchers{
886 katex: &lazyDispatcher[KatexInput, KatexOutput]{opts: katexOpts},
887 webp: &lazyDispatcher[WebpInput, WebpOutput]{opts: webpOpts},
888 avif: &lazyDispatcher[AvifInput, AvifOutput]{opts: avifOpts},
889 }
890
891 return dispatchers
892 }