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	"encoding/json"
10	"fmt"
11
12	"github.com/samber/oops"
13	"github.com/tetratelabs/wazero/api"
14	pluginLib "gitroot.dev/libs/golang/plugin/model"
15	"gitroot.dev/server/logger"
16)
17
18func (r *runtime) callPluginForConf(ctx context.Context, module api.Module, log *logger.Logger) (*pluginLib.ConfPlugin, error) {
19	defaultConf := &pluginLib.ConfPlugin{}
20
21	free := module.ExportedFunction("gitrootFree")
22	if free == nil {
23		free = module.ExportedFunction("free")
24	}
25	for name := range module.ExportedFunctionDefinitions() {
26		log.Info(fmt.Sprintf("plugin has %s function", name))
27	}
28	if pluginConf := module.ExportedFunction("pluginConf"); pluginConf != nil {
29		ptrSize, err := pluginConf.Call(ctx)
30		if err != nil {
31			return nil, oops.Wrapf(err, "pluginConf call")
32		}
33		pluginConfPtr := uint32(ptrSize[0] >> 32)
34		pluginConfSize := uint32(ptrSize[0])
35		if pluginConfPtr != 0 {
36			defer func() {
37				if free != nil && len(free.Definition().ParamTypes()) == 1 {
38					_, err := free.Call(ctx, uint64(pluginConfPtr))
39					if err != nil {
40						log.Error("can't free pluginConf", err)
41					}
42				} else if free != nil {
43					_, err := free.Call(ctx, uint64(pluginConfPtr), uint64(pluginConfSize))
44					if err != nil {
45						log.Error("can't free pluginConf", err)
46					}
47				}
48			}()
49		}
50		res, err := r.readString(module, "read memory conf", pluginConfPtr, pluginConfSize)
51		if err != nil {
52			return nil, oops.Wrapf(err, "can't read memory")
53		}
54		if res != "" {
55			log.Debug(fmt.Sprintf("res conf %s", res))
56			if err = json.Unmarshal([]byte(res), &defaultConf); err != nil {
57				log.Debug("Conf receive from guest tinygo", logger.NewLoggerPair("err", err.Error()), logger.NewLoggerPair("json", res))
58				conf, err := r.readASString(module, "read conf", uint32(ptrSize[0]))
59				if err != nil {
60					return nil, oops.Wrapf(err, "can't readASString Configuration")
61				}
62				log.Debug("Conf receive from guest AS", logger.NewLoggerPair("json", conf))
63				if err = json.Unmarshal([]byte(conf), &defaultConf); err != nil {
64					return nil, oops.Wrapf(err, "can't unmarshal Configuration")
65				}
66			}
67		}
68	} else {
69		log.Info("plugin has no pluginConf exported function")
70	}
71	for name := range module.ExportedFunctionDefinitions() {
72		log.Info(fmt.Sprintf("plugin has %s function", name))
73	}
74	return defaultConf, nil
75}