272 lines
9.1 KiB
Go
272 lines
9.1 KiB
Go
package gatewayrpc
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"sync"
|
|
"time"
|
|
|
|
"google.golang.org/grpc"
|
|
"google.golang.org/grpc/codes"
|
|
"google.golang.org/grpc/status"
|
|
|
|
pb "github.com/samcharles93/archie-core/internal/contracts/gateway/v1"
|
|
"github.com/samcharles93/archie-core/internal/domain/identity"
|
|
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
|
"github.com/samcharles93/archie-core/internal/domain/taskactions"
|
|
"github.com/samcharles93/archie-core/internal/infrastructure/publicnet"
|
|
"github.com/samcharles93/archie-core/internal/taskstate"
|
|
)
|
|
|
|
type server struct {
|
|
pb.UnimplementedChatServiceServer
|
|
chat messaging.ChatContract
|
|
sessions messaging.SessionStore
|
|
catalog Catalog
|
|
asks pendingAsks
|
|
// fetch reads the head of a URL-only attachment; it reaches public hosts only.
|
|
fetch *http.Client
|
|
}
|
|
|
|
// RegisterServer serves the Gateway chat contract. catalog supplies the
|
|
// process-owned runtime surfaces (skill catalogue, curator registry, channel
|
|
// reload) the dashboard reads over the same contract; a zero Catalog answers
|
|
// empty lists and an Unavailable reload.
|
|
func RegisterServer(registrar grpc.ServiceRegistrar, chat messaging.ChatContract, sessions messaging.SessionStore, catalog Catalog) {
|
|
pb.RegisterChatServiceServer(registrar, &server{chat: chat, sessions: sessions, catalog: catalog, fetch: publicnet.Client(10*time.Second, 15*time.Second)})
|
|
}
|
|
|
|
func (s *server) sessionStore() (messaging.SessionStore, error) {
|
|
if s.sessions == nil {
|
|
return nil, status.Error(codes.Unavailable, "session store unavailable")
|
|
}
|
|
return s.sessions, nil
|
|
}
|
|
|
|
func (s *server) Snapshot(ctx context.Context, _ *pb.SnapshotRequest) (*pb.SnapshotResponse, error) {
|
|
v, err := s.chat.Snapshot(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return snapshotProto(v), nil
|
|
}
|
|
|
|
func (s *server) GetSession(ctx context.Context, r *pb.GetSessionRequest) (*pb.GetSessionResponse, error) {
|
|
v, found, err := s.chat.GetSession(ctx, r.SessionId)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &pb.GetSessionResponse{Session: sessionProto(v), Found: found}, nil
|
|
}
|
|
|
|
func (s *server) RecentMessages(ctx context.Context, r *pb.RecentMessagesRequest) (*pb.RecentMessagesResponse, error) {
|
|
v, err := s.chat.RecentMessages(ctx, r.SessionId, int(r.Limit))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &pb.RecentMessagesResponse{Messages: mapValues(v, storedProto)}, nil
|
|
}
|
|
|
|
func (s *server) RecentTurns(ctx context.Context, r *pb.RecentTurnsRequest) (*pb.RecentTurnsResponse, error) {
|
|
v, err := s.chat.RecentTurns(ctx, r.SessionId, int(r.Limit))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &pb.RecentTurnsResponse{Turns: mapValues(v, turnProto)}, nil
|
|
}
|
|
|
|
func (s *server) Route(ctx context.Context, r *pb.RouteRequest) (*pb.RouteResponse, error) {
|
|
in := inboundValue(r.Message)
|
|
if err := checkInbound(ctx, s.fetch, in); err != nil {
|
|
return nil, err
|
|
}
|
|
v, err := s.chat.Route(ctx, in)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &pb.RouteResponse{Text: v.Text, SessionId: v.SessionID, RateLimited: v.RateLimited}, nil
|
|
}
|
|
|
|
func (s *server) Cancel(ctx context.Context, r *pb.CancelRequest) (*pb.CancelResponse, error) {
|
|
v, err := s.chat.Cancel(ctx, r.SessionId)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &pb.CancelResponse{Cancelled: v.Cancelled, Dropped: int64(v.Dropped)}, nil
|
|
}
|
|
|
|
func (s *server) StopTasks(ctx context.Context, r *pb.StopTasksRequest) (*pb.StopTasksResponse, error) {
|
|
stopped, err := s.chat.StopTasks(ctx, r.Origin, r.TaskId)
|
|
if err != nil && len(stopped) == 0 {
|
|
return nil, err
|
|
}
|
|
out := &pb.StopTasksResponse{Stopped: stopped}
|
|
if err != nil {
|
|
out.Error = err.Error()
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (s *server) ApplyTaskAction(ctx context.Context, r *pb.ApplyTaskActionRequest) (*pb.ApplyTaskActionResponse, error) {
|
|
v, err := s.chat.ApplyTaskAction(ctx, r.Identity, r.TaskId, taskstate.Action(r.Action), taskactions.ActionPayload{
|
|
Instructions: r.Instructions,
|
|
Findings: r.Findings,
|
|
})
|
|
if err != nil {
|
|
return nil, taskActionStatus(err)
|
|
}
|
|
return &pb.ApplyTaskActionResponse{TaskId: v.TaskID, Action: v.Action, Message: v.Message}, nil
|
|
}
|
|
|
|
func (s *server) ApplyOperatorTaskAction(ctx context.Context, r *pb.ApplyOperatorTaskActionRequest) (*pb.ApplyOperatorTaskActionResponse, error) {
|
|
actor := taskactions.Actor{
|
|
Identity: identity.IdentityID(r.ActorId),
|
|
Kind: identity.Kind(r.ActorKind),
|
|
Principal: identity.IdentityID(r.PrincipalId),
|
|
}
|
|
v, err := s.chat.ApplyOperatorTaskAction(ctx, actor, r.TaskId, taskstate.Action(r.Action), taskactions.ActionPayload{
|
|
Instructions: r.Instructions,
|
|
Findings: r.Findings,
|
|
RetryMode: taskstate.RetryMode(r.RetryMode),
|
|
ResumeFrom: r.ResumeFrom,
|
|
CurrentDefinition: r.CurrentDefinition,
|
|
})
|
|
if err != nil {
|
|
return nil, taskActionStatus(err)
|
|
}
|
|
return &pb.ApplyOperatorTaskActionResponse{TaskId: v.TaskID, Action: v.Action, Message: v.Message}, nil
|
|
}
|
|
|
|
func (s *server) GetSessionsByChannel(ctx context.Context, r *pb.GetSessionsByChannelRequest) (*pb.GetSessionsByChannelResponse, error) {
|
|
ss, e := s.sessionStore()
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
v, e := ss.GetByChannel(ctx, r.Platform, r.ChannelId)
|
|
return &pb.GetSessionsByChannelResponse{Sessions: mapValues(v, sessionProto)}, e
|
|
}
|
|
|
|
// storedMessages converts wire messages to canonical records, deriving
|
|
// roles from the owning session's bot identity (see
|
|
// messaging.RoleForSender). The wire carries no role; both sides derive from
|
|
// the same session, so they agree.
|
|
func (s *server) storedMessages(ctx context.Context, ss messaging.SessionStore, sessionID string, msgs []*pb.Message) ([]messaging.Message, error) {
|
|
var botUser string
|
|
if sc, err := ss.Get(ctx, sessionID); err != nil {
|
|
return nil, err
|
|
} else if sc != nil {
|
|
botUser = sc.Source.BotUser
|
|
}
|
|
out := make([]messaging.Message, 0, len(msgs))
|
|
for _, m := range msgs {
|
|
stored := storedValue(m)
|
|
stored.Role = messaging.RoleForSender(stored.Sender, botUser)
|
|
out = append(out, stored)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (s *server) SaveMessage(ctx context.Context, r *pb.SaveMessageRequest) (*pb.SaveMessageResponse, error) {
|
|
ss, e := s.sessionStore()
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
msgs, e := s.storedMessages(ctx, ss, r.SessionId, []*pb.Message{r.Message})
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
return &pb.SaveMessageResponse{}, ss.SaveMessage(ctx, r.SessionId, msgs[0])
|
|
}
|
|
|
|
func (s *server) Stream(r *pb.StreamRequest, out grpc.ServerStreamingServer[pb.StreamResponse]) error {
|
|
// An ask is sent from the turn's goroutine while this one sends events.
|
|
var sendMu sync.Mutex
|
|
send := func(v *pb.StreamResponse) error {
|
|
sendMu.Lock()
|
|
defer sendMu.Unlock()
|
|
return out.Send(v)
|
|
}
|
|
ctx := withAsks(out.Context(), r, remoteAsker{pending: &s.asks, send: send})
|
|
in := inboundValue(r.Message)
|
|
if err := checkInbound(ctx, s.fetch, in); err != nil {
|
|
return err
|
|
}
|
|
events, err := s.chat.Stream(ctx, in)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for {
|
|
select {
|
|
case <-out.Context().Done():
|
|
return out.Context().Err()
|
|
case event, ok := <-events:
|
|
if !ok {
|
|
return nil
|
|
}
|
|
if err := send(eventProto(event)); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func (s *server) Answer(_ context.Context, r *pb.AnswerRequest) (*pb.AnswerResponse, error) {
|
|
return &pb.AnswerResponse{Found: s.asks.answer(r.AskId, r.Answer)}, nil
|
|
}
|
|
|
|
// checkInbound refuses a self-contradicting attachment at the one seam every
|
|
// channel, in-tree or extension, crosses before the Gateway acts on it.
|
|
func checkInbound(ctx context.Context, fetch *http.Client, in messaging.Inbound) error {
|
|
for _, m := range in.Media {
|
|
m, err := withHead(ctx, fetch, m)
|
|
if err == nil {
|
|
err = messaging.ValidateInbound(m)
|
|
}
|
|
if err != nil {
|
|
return status.Error(codes.InvalidArgument, err.Error())
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// sniffBytes is enough to recognise an image or a clip container.
|
|
const sniffBytes = 512
|
|
|
|
// withHead gives a URL-only attachment of a sniffed type the first bytes of what
|
|
// its URL serves, so the type check sees the content rather than the claim. An
|
|
// unreadable URL is an error: the model provider would fetch it unchecked. The
|
|
// copy is for validation only; the attachment keeps no bytes.
|
|
func withHead(ctx context.Context, fetch *http.Client, m messaging.MediaAttachment) (messaging.MediaAttachment, error) {
|
|
switch m.Type {
|
|
case messaging.MediaTypeImage, messaging.MediaTypeAudio, messaging.MediaTypeVoice:
|
|
default:
|
|
return m, nil
|
|
}
|
|
if len(m.Data) > 0 || m.URL == "" {
|
|
return m, nil
|
|
}
|
|
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
|
defer cancel()
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, m.URL, nil)
|
|
if err != nil {
|
|
return m, fmt.Errorf("%s attachment URL: %w", m.Type, err)
|
|
}
|
|
req.Header.Set("Range", fmt.Sprintf("bytes=0-%d", sniffBytes-1))
|
|
resp, err := fetch.Do(req)
|
|
if err != nil {
|
|
return m, fmt.Errorf("%s attachment URL is unreadable: %w", m.Type, err)
|
|
}
|
|
defer func() { _ = resp.Body.Close() }()
|
|
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent {
|
|
return m, fmt.Errorf("%s attachment URL answered %s", m.Type, resp.Status)
|
|
}
|
|
head, err := io.ReadAll(io.LimitReader(resp.Body, sniffBytes))
|
|
if err != nil || len(head) == 0 {
|
|
return m, fmt.Errorf("%s attachment URL served no content", m.Type)
|
|
}
|
|
m.Data = head
|
|
return m, nil
|
|
}
|