Files
archie/internal/app/archiegateway/gateway.go
T

111 lines
4.8 KiB
Go

package archiegateway
import (
"context"
"fmt"
"net"
"google.golang.org/grpc"
"github.com/samcharles93/archie-core/internal/app/servicekit"
pb "github.com/samcharles93/archie-core/internal/contracts/gateway/v1"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc"
"github.com/samcharles93/archie-core/internal/infrastructure/rpcidentity"
"github.com/samcharles93/archie-core/internal/infrastructure/rpctls"
"github.com/samcharles93/archie-core/internal/plugin"
)
// serveGatewayListener is the serving tail of Run: the listener is
// bound, the process declares itself serving, and the chat contract answers
// until ctx ends.
func (b *server) serveGatewayListener(ctx context.Context, listener net.Listener, contract gateway.ChatContract, opts []grpc.ServerOption) error {
defer listener.Close()
b.log.Info("archie-gateway running", "addr", listener.Addr().String(), "tls", b.id != nil)
// Boot is over and this listener is about to accept: the same fact
// systemd's READY=1 asserts, so the announcement goes out here rather than
// from a second notion of "started". Not later: Serve
// begins accepting the moment it is called, and a unit whose
// TimeoutStartSec expires first would restart a healthy process.
b.announceReady()
taskTools := &taskToolsServer{gateway: b, authority: b.stateStore, configFor: b.taskToolsConfig, sessions: make(map[[32]byte]*taskToolSession)}
defer taskTools.Close(ctx)
return serveGateway(ctx, listener, contract, b.chatSessionStore, b.chatCatalog(), opts, taskTools)
}
func (b *server) startGatewayRuntime(ctx context.Context, actor gateway.ChatTaskActor) (gateway.ChatContract, error) {
b.bus = events.NewBus()
b.addCleanup(b.bus.Close)
b.capabilityHost = plugin.NewHost()
b.startRateLimiter(ctx, b.cfg.Chat.RateLimit)
// setupMemoryEngine must run before setupGatewayChat: setupGatewayChat
// constructs the turn runner, which captures b.memEngines at
// construction time.
if err := b.setupMemoryEngine(); err != nil { //nolint:contextcheck // setupMemoryEngine owns its own lifecycle context
return nil, err
}
contract, err := b.setupGatewayChat(ctx, actor)
if err != nil {
return nil, err
}
if err := b.registerTools(); err != nil {
return nil, err
}
b.registerStandaloneTools(ctx)
b.serveSkills(ctx)
b.addCleanup(shutdownCapabilityHost(ctx, b.capabilityHost, b.log))
if err := b.capabilityHost.Start(ctx); err != nil {
return nil, fmt.Errorf("start gateway tool providers: %w", err)
}
for _, skipped := range b.providerRegistry.Skipped() {
b.log.Warn("gateway tool provider unavailable", "provider", skipped.ID, "err", skipped.Err)
}
if err := b.startRuntimeWatches(ctx); err != nil {
return nil, fmt.Errorf("runtime resource watches: %w", err)
}
b.startModelCatalogRefresh(ctx)
if err := b.startCurators(ctx); err != nil {
return nil, err
}
return contract, nil
}
// inboundMessageHeadroomBytes leaves room for the protobuf framing and the
// rest of the request around an attachment at the messaging contract's
// ceiling, so the largest attachment a channel frontend may send is accepted
// rather than rejected as an oversized gRPC message.
const inboundMessageHeadroomBytes = 1 << 20
// gatewayServerOpts serves listen with id's credentials; every caller
// presents a service certificate.
//
// The receive limit is raised above gRPC's 4 MB default because an inbound
// request carries a channel attachment's bytes: the channel frontend
// downloads the file, and this process -- which runs the turn -- holds no
// platform credential to fetch it again.
func gatewayServerOpts(listen string, id *rpctls.Identity, principals access.PrincipalSource) ([]grpc.ServerOption, error) {
creds, err := id.ServerOption(listen, false)
if err != nil {
return nil, fmt.Errorf("gateway: %w", err)
}
callers := rpcidentity.Callers{Principals: principals}
return []grpc.ServerOption{
creds,
grpc.MaxRecvMsgSize(messaging.MaxInboundAttachmentBytes + inboundMessageHeadroomBytes),
grpc.ChainUnaryInterceptor(callers.Unary()),
grpc.ChainStreamInterceptor(callers.Stream()),
}, nil
}
func serveGateway(ctx context.Context, listener net.Listener, contract gateway.ChatContract, sessions gateway.SessionStore, catalog gatewayrpc.Catalog, opts []grpc.ServerOption, taskTools pb.TaskToolsServiceServer) error {
server := grpc.NewServer(append(servicekit.ServerLimits(), opts...)...)
gatewayrpc.RegisterServer(server, contract, sessions, catalog)
pb.RegisterTaskToolsServiceServer(server, taskTools)
// Serve's bounded drain returns before the session store and tools close.
return servicekit.Serve(ctx, server, listener)
}