65 lines
2.5 KiB
Go
65 lines
2.5 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"git.a-wan.net/alan/pipelines/internal/protocol"
|
|
)
|
|
|
|
func validChatAutomationInfo(info protocol.ChatAutomationInfo, sessionID string) error {
|
|
if info.SessionID != "" && info.SessionID != sessionID {
|
|
return fmt.Errorf("provider returned automation metadata for another session")
|
|
}
|
|
if info.Status != protocol.ChatAutomationSupported && info.Status != protocol.ChatAutomationUnavailable {
|
|
return fmt.Errorf("provider returned an invalid automation status")
|
|
}
|
|
if info.ActiveCount != nil && *info.ActiveCount < 0 {
|
|
return fmt.Errorf("provider returned a negative automation count")
|
|
}
|
|
if info.Status == protocol.ChatAutomationUnavailable && info.ActiveCount != nil {
|
|
return fmt.Errorf("unavailable automation metadata must not include a count")
|
|
}
|
|
if info.Status == protocol.ChatAutomationSupported && info.ActiveCount == nil {
|
|
return fmt.Errorf("supported automation metadata is missing a count")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func handleChatAutomations(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry, write func(protocol.Message) error) {
|
|
if broker == nil {
|
|
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
|
|
return
|
|
}
|
|
query := request.ChatQuery
|
|
if query == nil || !validChatSessionID(query.SessionID) {
|
|
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid chat session id is required"})
|
|
return
|
|
}
|
|
if err := operatorChatSession(ctx, registry, query.SessionID); err != nil {
|
|
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
|
return
|
|
}
|
|
reader, ok := broker.(chatAutomationReader)
|
|
if !ok {
|
|
_ = write(protocol.Message{Type: protocol.ChatAutomations, ID: request.ID, ChatAutomations: &protocol.ChatAutomationInfo{
|
|
SessionID: query.SessionID, Status: protocol.ChatAutomationUnavailable,
|
|
Reason: "this chat provider has no authoritative scheduled-work read API",
|
|
}})
|
|
return
|
|
}
|
|
info, err := reader.Automations(ctx, query.SessionID)
|
|
if err != nil {
|
|
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: fmt.Sprintf("read chat automations: %v", err)})
|
|
return
|
|
}
|
|
if info.SessionID == "" {
|
|
info.SessionID = query.SessionID
|
|
}
|
|
if err := validChatAutomationInfo(info, query.SessionID); err != nil {
|
|
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "read chat automations: " + err.Error()})
|
|
return
|
|
}
|
|
_ = write(protocol.Message{Type: protocol.ChatAutomations, ID: request.ID, ChatAutomations: &info})
|
|
}
|