GitRoot

craft your forge, build your project, grow your community freely
 1// SPDX-FileCopyrightText: 2025 Romain Maneschi <romain@gitroot.dev>
 2//
 3// SPDX-License-Identifier: EUPL-1.2
 4
 5package plugin
 6
 7import (
 8	"context"
 9	"fmt"
10	"path/filepath"
11	"sync"
12
13	"github.com/tetratelabs/wazero"
14	"github.com/tetratelabs/wazero/api"
15	"github.com/tetratelabs/wazero/experimental"
16	pluginLib "gitroot.dev/libs/golang/plugin/model"
17	"gitroot.dev/server/logger"
18)
19
20type runtimes struct {
21	lockRuntime sync.Mutex
22	runtime     *runtime
23	log         *logger.Logger
24	start       chan runtimeInputs
25}
26
27func newRuntimes(manager *Manager, log *logger.Logger) *runtimes {
28	chanStart := make(chan runtimeInputs)
29	compileCache, _ := wazero.NewCompilationCacheWithDir(filepath.Join(manager.conf.PathCache(), "wazero"))
30	runtimeConfig := wazero.NewRuntimeConfig().WithCompilationCache(compileCache).WithCoreFeatures(api.CoreFeaturesV2 | experimental.CoreFeaturesThreads)
31	r, err := newRuntime(context.Background(), manager, log, runtimeConfig)
32	if err != nil {
33		log.Error("can't create runtime", err)
34	}
35	go func() {
36		r.listen(chanStart)
37	}()
38	return &runtimes{
39		runtime: r,
40		log:     log,
41		start:   chanStart,
42	}
43}
44
45func (r *runtimes) Compile(ctx context.Context, binary []byte) (wazero.CompiledModule, error) {
46	r.lockRuntime.Lock()
47	defer r.lockRuntime.Unlock()
48	return r.runtime.wazRun.CompileModule(ctx, binary)
49}
50
51func (r *runtimes) Start(ctx context.Context, repoName string, plugins []Plugin, kind runtimeInputsKind, commands []CommandForDiff) {
52	r.lockRuntime.Lock()
53	defer r.lockRuntime.Unlock()
54	r.start <- runtimeInputs{
55		ctx:      ctx,
56		repoName: repoName,
57		kind:     kind,
58		plugins:  plugins,
59		commands: commands,
60	}
61}
62
63func (r *runtimes) Conf(ctx context.Context, plugin Plugin) (*pluginLib.ConfPlugin, error) {
64	timerStop := r.log.Time(fmt.Sprintf("Timer conf plugin %s", plugin.Name))
65	defer timerStop()
66	r.lockRuntime.Lock()
67	defer r.lockRuntime.Unlock()
68	return r.runtime.conf(ctx, plugin)
69}