Files
archie/modules/connectors/connectors.go
T

94 lines
2.9 KiB
Go

// Package connectors hosts connector extensions: one confined subprocess per
// accepted connector, speaking the connector contract (proto/connector/v1).
// Other modules reach a connector only through the Connector this package
// returns, which validates every payload against the connector's declared
// schemas and checks that only the judged action runs.
package connectors
import (
"context"
"fmt"
"log/slog"
goplugin "github.com/hashicorp/go-plugin"
"google.golang.org/grpc"
pb "github.com/samcharles93/archie-core/internal/contracts/connector/v1"
"github.com/samcharles93/archie-core/modules/connectors/internal/host"
)
// surface names the connector contract in the plugin handshake.
const surface = "connector"
// contractVersion is the connector contract this host speaks.
const contractVersion = "v1"
// Spec is one accepted connector to run.
type Spec struct {
Name string
// Path is the connector binary; SHA256 is the digest it must match.
Path string
SHA256 string
// Env names host environment variables the connector may see.
Env []string
// Egress is the accepted host list. A connector that touches targets
// declares it, and runs confined to those hosts.
Egress []string
Settings map[string]string
Secrets map[string]string
}
// Host owns the running connectors.
type Host struct {
procs *host.Host
}
// NewHost returns a host that logs plugin lifecycle to log.
func NewHost(log *slog.Logger) *Host {
return &Host{procs: host.NewHost(log)}
}
// Start launches spec, configures it and reads its declaration. A connector
// already running under the same name is replaced.
func (h *Host) Start(ctx context.Context, spec Spec) (*Connector, error) {
raw, err := h.procs.Start(ctx, host.Spec{
Name: spec.Name, Path: spec.Path, SHA256: spec.SHA256, Env: spec.Env, Egress: spec.Egress,
}, surface, &plugin{})
if err != nil {
return nil, err
}
client, ok := raw.(pb.ConnectorServiceClient)
if !ok {
h.procs.Stop(spec.Name)
return nil, fmt.Errorf("connector %q: plugin is not a connector", spec.Name)
}
c, err := open(ctx, spec.Name, client, spec.Settings, spec.Secrets)
if err != nil {
h.procs.Stop(spec.Name)
return nil, err
}
return c, nil
}
// Stop ends the named connector.
func (h *Host) Stop(name string) { h.procs.Stop(name) }
// Alive reports whether the named connector's process is running.
func (h *Host) Alive(name string) bool { return h.procs.Alive(name) }
// Close stops every connector.
func (h *Host) Close() { h.procs.Close() }
// plugin is the host side of the go-plugin handshake for the contract.
type plugin struct {
goplugin.NetRPCUnsupportedPlugin
}
func (*plugin) GRPCServer(*goplugin.GRPCBroker, *grpc.Server) error {
return fmt.Errorf("connectors are served by extensions, not by the host")
}
func (*plugin) GRPCClient(_ context.Context, _ *goplugin.GRPCBroker, conn *grpc.ClientConn) (any, error) {
return pb.NewConnectorServiceClient(conn), nil
}