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	wg := sync.WaitGroup{}
54	for _, command := range commands {
55		wg.Add(1)
56		r.start <- runtimeInputs{
57			ctx:      ctx,
58			repoName: repoName,
59			kind:     kind,
60			plugins:  plugins,
61			command:  command,
62			close: func() {
63				wg.Done()
64			},
65		}
66	}
67	wg.Wait()
68	r.lockRuntime.Unlock()
69}
70
71func (r *runtimes) Conf(ctx context.Context, plugin Plugin) (*pluginLib.ConfPlugin, error) {
72	timerStop := r.log.Time(fmt.Sprintf("Timer conf plugin %s", plugin.Log()))
73	defer timerStop()
74	r.lockRuntime.Lock()
75	defer r.lockRuntime.Unlock()
76	return r.runtime.conf(ctx, plugin)
77}