Files
archie/internal/app/archiemessaging/run.go
T
sam af7577625f
deploy / plan (push) Successful in 11s
deploy / archied-image (push) Canceled after 0s
deploy / agent-image (push) Canceled after 0s
deploy / dist-zip (push) Canceled after 0s
deploy / gate (push) Canceled after 7m26s
refactor(messaging): store Telegram's connection in extension-settings (#1802)
2026-11-08 17:12:59 +11:00

149 lines
6.3 KiB
Go

package archiemessaging
import (
"context"
"fmt"
"log/slog"
"net"
"os"
"google.golang.org/grpc"
"github.com/samcharles93/archie-core/internal/app/servicekit"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/applystatus"
"github.com/samcharles93/archie-core/internal/domain/presence"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
"github.com/samcharles93/archie-core/internal/infrastructure/extension"
"github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc"
"github.com/samcharles93/archie-core/internal/infrastructure/messagingrpc"
"github.com/samcharles93/archie-core/internal/infrastructure/rpctls"
"github.com/samcharles93/archie-core/internal/infrastructure/secretengine"
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
"github.com/samcharles93/archie-core/internal/logging"
"github.com/samcharles93/archie-core/internal/secret"
)
// resolveTraced resolves the configuration and starts trace export from it.
func resolveLogged(ctx context.Context, o Options) (ResolvedConfig, *slog.Logger, *logging.Feed, func(), error) {
cfg, err := Resolve(o, slog.New(slog.NewJSONHandler(os.Stderr, nil)))
if err != nil {
return ResolvedConfig{}, nil, nil, nil, fmt.Errorf("resolve messaging options: %w", err)
}
logs, err := servicekit.Logging(ctx, cfg.Logging, "messaging")
if err != nil {
return ResolvedConfig{}, nil, nil, nil, err
}
return cfg, logs.Log.With("service", "archie-messaging"), logs.Feed, func() { _ = logs.Closer.Close() }, nil
}
// Run runs the standalone Messaging Service process until ctx is cancelled.
func Run(ctx context.Context, o Options) error {
cfg, log, feed, closeLogs, err := resolveLogged(ctx, o)
if err != nil {
return err
}
defer closeLogs()
chat, closeGateway, err := gatewayrpc.Dial(cfg.Options.Gateway.Target, cfg.Identity)
if err != nil {
return fmt.Errorf("dial gateway (%s): %w", cfg.Options.Gateway.Target, err)
}
defer closeGateway()
secrets := secret.NewRegistry()
health := newReadinessRegistry(cfg.Options, chat)
// channelStatusStore is the same client, held where compose can reach it: the
// channel report is published to the store this process already dials.
var channelStatusStore storecontract.ChannelStatusStore
// settingsSource and applyReporter are the live channel-settings path: the
// control-plane client to re-read the resource, and the record of what this
// process applied. Both stay nil without a State Store, which leaves the
// service with no live path.
var settingsSource chatSettingsSource
var applyReporter *applystatus.Reporter
var appliedVersion int64
var orgChannels *orgChannelDeps
var extensionChannels []*channelInstance
var extensionFactory *channelFactory
if cfg.Options.StateStore.Target != "" {
stateStore, closeClient, dialErr := staterpc.Dial(cfg.Options.StateStore.Target, presence.Messaging, cfg.Identity, staterpc.WaitForPeer)
if dialErr != nil {
return fmt.Errorf("dial state store control plane (%s): %w", cfg.Options.StateStore.Target, dialErr)
}
defer closeClient()
controlPlaneClient := controlplanerpc.NewRPCClient(stateStore.ControlPlane())
reporter := applystatus.New(applystatus.Messaging, stateStore, log)
extensions := extension.Source{Query: controlPlaneClient, Packages: stateStore}
defer superviseSecretEngines(ctx, extensions, secrets, reporter, log)()
chatSettings, channelVersion, settingsErr := controlPlaneClient.RuntimeChatConfig(ctx, config.ChatConfig{ShowToolCalls: cfg.ShowToolCalls})
if settingsErr != nil {
return fmt.Errorf("load channel settings: %w", settingsErr)
}
reporter.Report(ctx, controlplanerpc.ChannelSettingsKind, channelVersion, nil)
go reporter.Run(ctx)
go presence.Run(ctx, presence.Messaging, servicekit.Build(), stateStore, health, log)
cfg.ShowToolCalls = chatSettings.ShowToolCalls
extensionChannels, extensionFactory = openExtensionChannels(ctx, extensions, secrets, log, cfg.ShowToolCalls)
channelStatusStore = stateStore
settingsSource, applyReporter, appliedVersion, orgChannels = controlPlaneClient, reporter, channelVersion, &orgChannelDeps{Source: controlPlaneClient, Principals: stateStore}
}
srv, err := compose(ctx, deps{
Secrets: secrets,
ChannelStatus: channelStatusStore,
Config: cfg,
ExtensionChannels: extensionChannels,
ExtensionFactory: extensionFactory,
Log: log,
Chat: chat,
SettingsSource: settingsSource,
OrgChannels: orgChannels,
ApplyReporter: applyReporter,
AppliedVersion: appliedVersion,
})
if err != nil {
return err
}
return serve(ctx, cfg.Options.Listen, cfg.Identity, srv, log, feed)
}
// serve runs srv and serves MessagingService over it until ctx is cancelled.
func serve(ctx context.Context, listen string, id *rpctls.Identity, srv *Service, log *slog.Logger, feed *logging.Feed) error {
opts, err := messagingrpc.ServerOptions(listen, id)
if err != nil {
return err
}
listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", listen)
if err != nil {
return fmt.Errorf("listen messaging (%s): %w", listen, err)
}
server := grpc.NewServer(append(servicekit.ServerLimits(), opts...)...)
messagingrpc.RegisterServer(server, srv, feed)
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// A dead listener stops the channels too: the process exits and its
// supervisor restarts it, rather than it running on without Deliver.
serveErr := make(chan error, 1)
go func() {
serveErr <- servicekit.Serve(ctx, server, listener)
cancel()
}()
log.InfoContext(ctx, "messaging service listening", "listen", listen)
startErr := srv.Start(ctx)
cancel()
if err := <-serveErr; err != nil {
return fmt.Errorf("serve messaging: %w", err)
}
return startErr
}
// superviseSecretEngines runs the secret-engine extensions and reports their
// settings outcome; the returned function stops them.
func superviseSecretEngines(ctx context.Context, source extension.Source, secrets *secret.Registry, reporter *applystatus.Reporter, log *slog.Logger) func() {
return secretengine.Supervise(ctx, secrets, source, applystatus.Messaging, func(ctx context.Context, version int64, err error) {
reporter.Report(ctx, controlplanerpc.ExtensionSettingsKind, version, err)
}, log).Close
}