fix(orgs): layer only the fields an org document sets, retry alerts on a failed lookup, and key chat sessions by org
This commit is contained in:
12 files changed
+279
-62
No files matched your search
@@ -316,28 +316,48 @@ func (b *boot) deliverAlerts(store alert.Deliverer) func(context.Context) {
|
|||||||
b.log.WarnContext(ctx, "alert deliveries not claimed", "err", err)
|
b.log.WarnContext(ctx, "alert deliveries not claimed", "err", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
notifies := map[org.OrgID]config.Notify{}
|
outcomes := settleDeliveries(due, func(owner org.OrgID) (config.Notify, error) {
|
||||||
for _, d := range due {
|
notify, err := b.alertNotify(ctx, owner)
|
||||||
notify, ok := notifies[d.Alert.Org]
|
if err != nil {
|
||||||
outcome := alert.Outcome{DeliveryID: d.ID}
|
b.log.WarnContext(ctx, "alert notification settings unavailable", "org", owner, "err", err)
|
||||||
if !ok {
|
|
||||||
notify, err = b.alertNotify(ctx, d.Alert.Org)
|
|
||||||
if err != nil {
|
|
||||||
b.log.WarnContext(ctx, "alert notification settings unavailable", "org", d.Alert.Org, "err", err)
|
|
||||||
outcome.Error = "notification settings unavailable"
|
|
||||||
}
|
|
||||||
notifies[d.Alert.Org] = notify
|
|
||||||
}
|
|
||||||
if outcome.Error == "" {
|
|
||||||
outcome = b.sendAlert(ctx, clientFor(d.Alert.Org), notify, d)
|
|
||||||
}
|
}
|
||||||
|
return notify, err
|
||||||
|
}, func(d alert.Due, notify config.Notify) alert.Outcome {
|
||||||
|
return b.sendAlert(ctx, clientFor(d.Alert.Org), notify, d)
|
||||||
|
})
|
||||||
|
for _, outcome := range outcomes {
|
||||||
if err := store.RecordAlertAttempt(ctx, outcome); err != nil {
|
if err := store.RecordAlertAttempt(ctx, outcome); err != nil {
|
||||||
b.log.WarnContext(ctx, "alert delivery not recorded", "delivery", d.ID, "err", err)
|
b.log.WarnContext(ctx, "alert delivery not recorded", "delivery", outcome.DeliveryID, "err", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// settleDeliveries decides each due delivery's outcome. Each org's settings
|
||||||
|
// are looked up once per batch.
|
||||||
|
func settleDeliveries(due []alert.Due, notifyFor func(org.OrgID) (config.Notify, error), send func(alert.Due, config.Notify) alert.Outcome) []alert.Outcome {
|
||||||
|
type lookup struct {
|
||||||
|
notify config.Notify
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
lookups := map[org.OrgID]lookup{}
|
||||||
|
outcomes := make([]alert.Outcome, 0, len(due))
|
||||||
|
for _, d := range due {
|
||||||
|
found, ok := lookups[d.Alert.Org]
|
||||||
|
if !ok {
|
||||||
|
found.notify, found.err = notifyFor(d.Alert.Org)
|
||||||
|
lookups[d.Alert.Org] = found
|
||||||
|
}
|
||||||
|
notify, err := found.notify, found.err
|
||||||
|
if err != nil {
|
||||||
|
outcomes = append(outcomes, alert.Outcome{DeliveryID: d.ID, Error: "notification settings unavailable"})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
outcomes = append(outcomes, send(d, notify))
|
||||||
|
}
|
||||||
|
return outcomes
|
||||||
|
}
|
||||||
|
|
||||||
// sendAlert posts one delivery to notify's webhook, or closes it as skipped
|
// sendAlert posts one delivery to notify's webhook, or closes it as skipped
|
||||||
// when there is none or the alert is below its severity threshold.
|
// when there is none or the alert is below its severity threshold.
|
||||||
func (b *boot) sendAlert(ctx context.Context, client *http.Client, notify config.Notify, d alert.Due) alert.Outcome {
|
func (b *boot) sendAlert(ctx context.Context, client *http.Client, notify config.Notify, d alert.Due) alert.Outcome {
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package archied
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/samcharles93/archie-core/internal/config"
|
||||||
|
"github.com/samcharles93/archie-core/internal/domain/alert"
|
||||||
|
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSettleDeliveriesRetriesWhenSettingsAreUnavailable(t *testing.T) {
|
||||||
|
due := []alert.Due{
|
||||||
|
{ID: 1, Alert: alert.Alert{Key: alert.Key{Org: "acme"}}},
|
||||||
|
{ID: 2, Alert: alert.Alert{Key: alert.Key{Org: "acme"}}},
|
||||||
|
{ID: 3, Alert: alert.Alert{Key: alert.Key{Org: "beta"}}},
|
||||||
|
}
|
||||||
|
notifyFor := func(owner org.OrgID) (config.Notify, error) {
|
||||||
|
if owner == "acme" {
|
||||||
|
return config.Notify{}, errors.New("control plane unavailable")
|
||||||
|
}
|
||||||
|
return config.Notify{Webhook: "https://example.com"}, nil
|
||||||
|
}
|
||||||
|
send := func(d alert.Due, notify config.Notify) alert.Outcome {
|
||||||
|
return alert.Outcome{DeliveryID: d.ID, Skipped: notify.Webhook == ""}
|
||||||
|
}
|
||||||
|
outcomes := settleDeliveries(due, notifyFor, send)
|
||||||
|
for i, outcome := range outcomes {
|
||||||
|
failed := due[i].Alert.Org == "acme"
|
||||||
|
if outcome.Skipped || (outcome.Error != "") != failed {
|
||||||
|
t.Fatalf("delivery %d: outcome %+v, want a retryable failure only for acme", outcome.DeliveryID, outcome)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -912,7 +912,7 @@ func (r *Router) handleSessions(ctx context.Context, msg messaging.Message) (str
|
|||||||
}
|
}
|
||||||
active := ""
|
active := ""
|
||||||
if r.sessionTracker != nil {
|
if r.sessionTracker != nil {
|
||||||
active = r.sessionTracker.getActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
active = r.sessionTracker.getActive(ctx, msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
||||||
}
|
}
|
||||||
return renderSessionList(sessions, active, time.Now()), nil
|
return renderSessionList(sessions, active, time.Now()), nil
|
||||||
}
|
}
|
||||||
@@ -1029,12 +1029,12 @@ func (r *Router) handleResume(ctx context.Context, msg messaging.Message, arg st
|
|||||||
case match == nil:
|
case match == nil:
|
||||||
return fmt.Sprintf("No session matching %q.", arg), nil
|
return fmt.Sprintf("No session matching %q.", arg), nil
|
||||||
}
|
}
|
||||||
return r.resumeSession(msg, *match), nil
|
return r.resumeSession(ctx, msg, *match), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Router) resumeSession(msg messaging.Message, s SessionContext) string {
|
func (r *Router) resumeSession(ctx context.Context, msg messaging.Message, s SessionContext) string {
|
||||||
if r.sessionTracker != nil {
|
if r.sessionTracker != nil {
|
||||||
r.sessionTracker.setActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID, s.SessionID)
|
r.sessionTracker.setActive(ctx, msg.ConversationID.ChannelID, msg.ConversationID.ThreadID, s.SessionID)
|
||||||
}
|
}
|
||||||
return fmt.Sprintf("Resumed session %s.", s.SessionID)
|
return fmt.Sprintf("Resumed session %s.", s.SessionID)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import (
|
|||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
|
|
||||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||||
|
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||||
)
|
)
|
||||||
|
|
||||||
// sessionTracker maps (channelID, threadID) pairs to the currently active
|
// sessionTracker maps (channelID, threadID) pairs to the currently active
|
||||||
@@ -48,7 +49,7 @@ func newSessionTracker(sessions SessionStore) *sessionTracker {
|
|||||||
// resolve returns the session ID for a message, creating one if needed.
|
// resolve returns the session ID for a message, creating one if needed.
|
||||||
// ThreadID may be empty for flat chats.
|
// ThreadID may be empty for flat chats.
|
||||||
func (t *sessionTracker) resolve(ctx context.Context, platform, botUser, channelID, threadID string) (string, error) {
|
func (t *sessionTracker) resolve(ctx context.Context, platform, botUser, channelID, threadID string) (string, error) {
|
||||||
key := sessionTrackerKey(channelID, threadID)
|
key := sessionTrackerKey(ctx, channelID, threadID)
|
||||||
t.mu.RLock()
|
t.mu.RLock()
|
||||||
id, ok := t.active[key]
|
id, ok := t.active[key]
|
||||||
t.mu.RUnlock()
|
t.mu.RUnlock()
|
||||||
@@ -86,7 +87,7 @@ func (t *sessionTracker) resolve(ctx context.Context, platform, botUser, channel
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Claim the cache slot before saving, so only the winner of a race writes.
|
// Claim the cache slot before saving, so only the winner of a race writes.
|
||||||
id = sessionKeyFromFields(channelID, threadID)
|
id = sessionKeyFromFields(ctx, channelID, threadID)
|
||||||
if winner, won := t.claimActive(key, id); !won {
|
if winner, won := t.claimActive(key, id); !won {
|
||||||
return winner, nil
|
return winner, nil
|
||||||
}
|
}
|
||||||
@@ -156,37 +157,46 @@ func (t *sessionTracker) cacheActive(key, sessionID string) string {
|
|||||||
return sessionID
|
return sessionID
|
||||||
}
|
}
|
||||||
|
|
||||||
func sessionKeyFromFields(channelID, threadID string) string {
|
// sessionKeyFromFields derives a new session's ID from its chat. A chat id is
|
||||||
if threadID == "" {
|
// only unique within its org's channel, so another org's session carries the
|
||||||
return channelID
|
// org in front; the system org's ids are unchanged so existing sessions keep
|
||||||
|
// resolving.
|
||||||
|
func sessionKeyFromFields(ctx context.Context, channelID, threadID string) string {
|
||||||
|
return sessionTrackerKey(ctx, channelID, threadID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// orgPrefix is empty for the system org.
|
||||||
|
func orgPrefix(ctx context.Context) string {
|
||||||
|
if owner := org.OrgFromContext(ctx); owner != org.DefaultOrgID {
|
||||||
|
return "@" + string(owner) + ":"
|
||||||
}
|
}
|
||||||
return channelID + ":" + threadID
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// setActive sets the current session for a channel+thread, overriding any
|
// setActive sets the current session for a channel+thread, overriding any
|
||||||
// previously resolved session (used by /new, /branch and /topic).
|
// previously resolved session (used by /new, /branch and /topic).
|
||||||
func (t *sessionTracker) setActive(channelID, threadID, sessionID string) {
|
func (t *sessionTracker) setActive(ctx context.Context, channelID, threadID, sessionID string) {
|
||||||
// Never cache an empty session ID.
|
// Never cache an empty session ID.
|
||||||
if sessionID == "" {
|
if sessionID == "" {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
t.mu.Lock()
|
t.mu.Lock()
|
||||||
defer t.mu.Unlock()
|
defer t.mu.Unlock()
|
||||||
t.active[sessionTrackerKey(channelID, threadID)] = sessionID
|
t.active[sessionTrackerKey(ctx, channelID, threadID)] = sessionID
|
||||||
}
|
}
|
||||||
|
|
||||||
// flattenTopic points a channel's flat key at its thread's current session,
|
// flattenTopic points a channel's flat key at its thread's current session,
|
||||||
// in one critical section.
|
// in one critical section.
|
||||||
func (t *sessionTracker) flattenTopic(channelID, threadID string) {
|
func (t *sessionTracker) flattenTopic(ctx context.Context, channelID, threadID string) {
|
||||||
t.mu.Lock()
|
t.mu.Lock()
|
||||||
defer t.mu.Unlock()
|
defer t.mu.Unlock()
|
||||||
current, ok := t.active[sessionTrackerKey(channelID, threadID)]
|
current, ok := t.active[sessionTrackerKey(ctx, channelID, threadID)]
|
||||||
if !ok || current == "" {
|
if !ok || current == "" {
|
||||||
// Nothing to carry over. The next message resolves from the store,
|
// Nothing to carry over. The next message resolves from the store,
|
||||||
// which is the correct answer anyway.
|
// which is the correct answer anyway.
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
t.active[sessionTrackerKey(channelID, "")] = current
|
t.active[sessionTrackerKey(ctx, channelID, "")] = current
|
||||||
}
|
}
|
||||||
|
|
||||||
// forget drops every cached key whose active session is sessionID.
|
// forget drops every cached key whose active session is sessionID.
|
||||||
@@ -202,10 +212,10 @@ func (t *sessionTracker) forget(sessionID string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// getActive returns the current session ID for a channel+thread.
|
// getActive returns the current session ID for a channel+thread.
|
||||||
func (t *sessionTracker) getActive(channelID, threadID string) string {
|
func (t *sessionTracker) getActive(ctx context.Context, channelID, threadID string) string {
|
||||||
t.mu.RLock()
|
t.mu.RLock()
|
||||||
defer t.mu.RUnlock()
|
defer t.mu.RUnlock()
|
||||||
return t.active[sessionTrackerKey(channelID, threadID)]
|
return t.active[sessionTrackerKey(ctx, channelID, threadID)]
|
||||||
}
|
}
|
||||||
|
|
||||||
// parsePositiveInt is a nilerr-safe wrapper: it returns (n, true) on
|
// parsePositiveInt is a nilerr-safe wrapper: it returns (n, true) on
|
||||||
@@ -217,11 +227,14 @@ func parsePositiveInt(s string) (int, bool) {
|
|||||||
return int(n), err == nil && n > 0
|
return int(n), err == nil && n > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func sessionTrackerKey(channelID, threadID string) string {
|
// sessionTrackerKey names a chat in the active-session cache. The cache is
|
||||||
if threadID == "" {
|
// shared by every org, so a non-system org's key carries the org.
|
||||||
return channelID
|
func sessionTrackerKey(ctx context.Context, channelID, threadID string) string {
|
||||||
|
key := channelID
|
||||||
|
if threadID != "" {
|
||||||
|
key += ":" + threadID
|
||||||
}
|
}
|
||||||
return channelID + ":" + threadID
|
return orgPrefix(ctx) + key
|
||||||
}
|
}
|
||||||
|
|
||||||
// sessionPlatform returns the channel that carried the message, else the
|
// sessionPlatform returns the channel that carried the message, else the
|
||||||
@@ -239,7 +252,7 @@ func (r *Router) sessionPlatform(in Inbound) string {
|
|||||||
func (r *Router) ResolveSessionKey(ctx context.Context, in Inbound) (string, error) {
|
func (r *Router) ResolveSessionKey(ctx context.Context, in Inbound) (string, error) {
|
||||||
conv := in.Message.ConversationID
|
conv := in.Message.ConversationID
|
||||||
if r.sessionTracker == nil {
|
if r.sessionTracker == nil {
|
||||||
return sessionKeyFromFields(conv.ChannelID, conv.ThreadID), nil
|
return sessionKeyFromFields(ctx, conv.ChannelID, conv.ThreadID), nil
|
||||||
}
|
}
|
||||||
return r.sessionTracker.resolve(ctx, r.sessionPlatform(in), r.Identity, conv.ChannelID, conv.ThreadID)
|
return r.sessionTracker.resolve(ctx, r.sessionPlatform(in), r.Identity, conv.ChannelID, conv.ThreadID)
|
||||||
}
|
}
|
||||||
@@ -277,7 +290,7 @@ func (r *Router) handleNew(ctx context.Context, msg messaging.Message, platform,
|
|||||||
if err := r.sessionTracker.sessions.Save(ctx, sc); err != nil {
|
if err := r.sessionTracker.sessions.Save(ctx, sc); err != nil {
|
||||||
return "", fmt.Errorf("create session: %w", err)
|
return "", fmt.Errorf("create session: %w", err)
|
||||||
}
|
}
|
||||||
r.sessionTracker.setActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID, id)
|
r.sessionTracker.setActive(ctx, msg.ConversationID.ChannelID, msg.ConversationID.ThreadID, id)
|
||||||
|
|
||||||
if title != "" {
|
if title != "" {
|
||||||
return fmt.Sprintf("New session created: %s (%s)", title, shortSessionID(id)), nil
|
return fmt.Sprintf("New session created: %s (%s)", title, shortSessionID(id)), nil
|
||||||
@@ -295,7 +308,7 @@ func (r *Router) handleTopic(ctx context.Context, msg messaging.Message, platfor
|
|||||||
|
|
||||||
switch rest {
|
switch rest {
|
||||||
case "off":
|
case "off":
|
||||||
r.sessionTracker.flattenTopic(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
r.sessionTracker.flattenTopic(ctx, msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
||||||
return "Topic routing disabled. Messages will use the General topic.", nil
|
return "Topic routing disabled. Messages will use the General topic.", nil
|
||||||
case "help":
|
case "help":
|
||||||
return topicHelpText(), nil
|
return topicHelpText(), nil
|
||||||
@@ -314,7 +327,7 @@ func topicHelpText() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *Router) topicListSessions(ctx context.Context, msg messaging.Message, platform string) (string, error) {
|
func (r *Router) topicListSessions(ctx context.Context, msg messaging.Message, platform string) (string, error) {
|
||||||
active := r.sessionTracker.getActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
active := r.sessionTracker.getActive(ctx, msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
||||||
sessions, err := r.sessionTracker.sessions.GetByChannel(ctx, platform, msg.ConversationID.ChannelID)
|
sessions, err := r.sessionTracker.sessions.GetByChannel(ctx, platform, msg.ConversationID.ChannelID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("list sessions: %w", err)
|
return "", fmt.Errorf("list sessions: %w", err)
|
||||||
@@ -346,7 +359,7 @@ func (r *Router) topicSwitchSession(ctx context.Context, msg messaging.Message,
|
|||||||
return fmt.Sprintf("Multiple sessions match %q. Use more of the session ID.", rest), nil
|
return fmt.Sprintf("Multiple sessions match %q. Use more of the session ID.", rest), nil
|
||||||
}
|
}
|
||||||
if match != nil {
|
if match != nil {
|
||||||
r.sessionTracker.setActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID, match.SessionID)
|
r.sessionTracker.setActive(ctx, msg.ConversationID.ChannelID, msg.ConversationID.ThreadID, match.SessionID)
|
||||||
return fmt.Sprintf("Switched to session %s: %s",
|
return fmt.Sprintf("Switched to session %s: %s",
|
||||||
shortSessionID(match.SessionID), sessionDisplayTitle(*match)), nil
|
shortSessionID(match.SessionID), sessionDisplayTitle(*match)), nil
|
||||||
}
|
}
|
||||||
@@ -360,7 +373,7 @@ func (r *Router) handleRetry(ctx context.Context, msg messaging.Message) (string
|
|||||||
return "Session management is not configured.", nil
|
return "Session management is not configured.", nil
|
||||||
}
|
}
|
||||||
|
|
||||||
sessionID := r.sessionTracker.getActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
sessionID := r.sessionTracker.getActive(ctx, msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
||||||
if sessionID == "" {
|
if sessionID == "" {
|
||||||
return "No active session. Send a message first.", nil
|
return "No active session. Send a message first.", nil
|
||||||
}
|
}
|
||||||
@@ -403,7 +416,7 @@ func (r *Router) handleUndo(ctx context.Context, msg messaging.Message, rest str
|
|||||||
return "Session management is not configured.", nil
|
return "Session management is not configured.", nil
|
||||||
}
|
}
|
||||||
|
|
||||||
sessionID := r.sessionTracker.getActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
sessionID := r.sessionTracker.getActive(ctx, msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
||||||
if sessionID == "" {
|
if sessionID == "" {
|
||||||
return "No active session. Send a message first.", nil
|
return "No active session. Send a message first.", nil
|
||||||
}
|
}
|
||||||
@@ -437,7 +450,7 @@ func (r *Router) handleTitle(ctx context.Context, msg messaging.Message, rest st
|
|||||||
return "Session management is not configured.", nil
|
return "Session management is not configured.", nil
|
||||||
}
|
}
|
||||||
|
|
||||||
sessionID := r.sessionTracker.getActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
sessionID := r.sessionTracker.getActive(ctx, msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
||||||
if sessionID == "" {
|
if sessionID == "" {
|
||||||
return "No active session. Send a message first.", nil
|
return "No active session. Send a message first.", nil
|
||||||
}
|
}
|
||||||
@@ -478,7 +491,7 @@ func (r *Router) handleBranch(ctx context.Context, msg messaging.Message, platfo
|
|||||||
|
|
||||||
channelID := msg.ConversationID.ChannelID
|
channelID := msg.ConversationID.ChannelID
|
||||||
threadID := msg.ConversationID.ThreadID
|
threadID := msg.ConversationID.ThreadID
|
||||||
parentID := r.sessionTracker.getActive(channelID, threadID)
|
parentID := r.sessionTracker.getActive(ctx, channelID, threadID)
|
||||||
if parentID == "" {
|
if parentID == "" {
|
||||||
// Channels that call Route directly can reach this with no session.
|
// Channels that call Route directly can reach this with no session.
|
||||||
return "No active session to branch from. Send a message first.", nil
|
return "No active session to branch from. Send a message first.", nil
|
||||||
@@ -537,7 +550,7 @@ func (r *Router) handleBranch(ctx context.Context, msg messaging.Message, platfo
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
r.sessionTracker.setActive(channelID, threadID, id)
|
r.sessionTracker.setActive(ctx, channelID, threadID, id)
|
||||||
|
|
||||||
if branchName != "" {
|
if branchName != "" {
|
||||||
return fmt.Sprintf("Branched to \"%s\" (%s) with %d inherited messages.", branchName, shortSessionID(id), len(msgs)), nil
|
return fmt.Sprintf("Branched to \"%s\" (%s) with %d inherited messages.", branchName, shortSessionID(id), len(msgs)), nil
|
||||||
@@ -552,7 +565,7 @@ func (r *Router) handleCompress(ctx context.Context, msg messaging.Message, rest
|
|||||||
return "Session management is not configured.", nil
|
return "Session management is not configured.", nil
|
||||||
}
|
}
|
||||||
|
|
||||||
sessionID := r.sessionTracker.getActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
sessionID := r.sessionTracker.getActive(ctx, msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
||||||
if sessionID == "" {
|
if sessionID == "" {
|
||||||
return "No active session. Send a message first.", nil
|
return "No active session. Send a message first.", nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ func (r *Router) handleDelete(ctx context.Context, msg messaging.Message, rest s
|
|||||||
// whether the operator just ended the conversation they are in.
|
// whether the operator just ended the conversation they are in.
|
||||||
active := ""
|
active := ""
|
||||||
if r.sessionTracker != nil {
|
if r.sessionTracker != nil {
|
||||||
active = r.sessionTracker.getActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
active = r.sessionTracker.getActive(ctx, msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := r.Sessions.Delete(ctx, target.SessionID); err != nil {
|
if err := r.Sessions.Delete(ctx, target.SessionID); err != nil {
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ func (r *Router) maybeAutoTitle(ctx context.Context, msg messaging.Message) {
|
|||||||
if r.Titles == nil || r.sessionTracker == nil {
|
if r.Titles == nil || r.sessionTracker == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
sessionID := r.sessionTracker.getActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
sessionID := r.sessionTracker.getActive(ctx, msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
||||||
if sessionID == "" || !r.claimTitleInFlight(sessionID) {
|
if sessionID == "" || !r.claimTitleInFlight(sessionID) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -176,7 +176,7 @@ func sessionResumeTool(store SessionStore, tracker *sessionTracker, platform, ch
|
|||||||
// The channel+thread are the ones this tool was built for, never
|
// The channel+thread are the ones this tool was built for, never
|
||||||
// input. Tracker presence is guaranteed: SessionTools omits the
|
// input. Tracker presence is guaranteed: SessionTools omits the
|
||||||
// tool when no tracker is wired.
|
// tool when no tracker is wired.
|
||||||
tracker.setActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID, match.SessionID)
|
tracker.setActive(ctx, msg.ConversationID.ChannelID, msg.ConversationID.ThreadID, match.SessionID)
|
||||||
return SessionResumeResult{
|
return SessionResumeResult{
|
||||||
SessionID: match.SessionID,
|
SessionID: match.SessionID,
|
||||||
Title: sessionDisplayTitle(*match),
|
Title: sessionDisplayTitle(*match),
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package gateway
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||||
|
)
|
||||||
|
|
||||||
|
// orgSessions stores sessions the way the real store does: a session id
|
||||||
|
// belongs to the org that first wrote it, and listings are per org.
|
||||||
|
type orgSessions struct {
|
||||||
|
SessionStore
|
||||||
|
owner map[string]org.OrgID
|
||||||
|
byID map[string]SessionContext
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *orgSessions) Save(ctx context.Context, sc SessionContext) error {
|
||||||
|
caller := org.OrgFromContext(ctx)
|
||||||
|
if owner, taken := s.owner[sc.SessionID]; taken && owner != caller {
|
||||||
|
return errors.New("session owned by another org")
|
||||||
|
}
|
||||||
|
s.owner[sc.SessionID], s.byID[sc.SessionID] = caller, sc
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *orgSessions) GetByChannel(ctx context.Context, _, channelID string) ([]SessionContext, error) {
|
||||||
|
var out []SessionContext
|
||||||
|
for id, sc := range s.byID {
|
||||||
|
if s.owner[id] == org.OrgFromContext(ctx) && sc.Source.ChannelID == channelID {
|
||||||
|
out = append(out, sc)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *orgSessions) Touch(context.Context, string) error { return nil }
|
||||||
|
|
||||||
|
func TestTrackerKeepsOrgsChatsApart(t *testing.T) {
|
||||||
|
store := &orgSessions{owner: map[string]org.OrgID{}, byID: map[string]SessionContext{}}
|
||||||
|
tracker := newSessionTracker(store)
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
owner org.OrgID
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"the system org keeps the bare chat id", org.DefaultOrgID, "42"},
|
||||||
|
{"another org gets its own session for the same chat", "acme", "@acme:42"},
|
||||||
|
{"a third org does too", "beta", "@beta:42"},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
ctx := org.WithOrg(t.Context(), tt.owner)
|
||||||
|
got, err := tracker.resolve(ctx, "telegram", "bot", "42", "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("resolve() error = %v", err)
|
||||||
|
}
|
||||||
|
if got != tt.want {
|
||||||
|
t.Fatalf("resolve() = %q, want %q", got, tt.want)
|
||||||
|
}
|
||||||
|
if again, _ := tracker.resolve(ctx, "telegram", "bot", "42", ""); again != got {
|
||||||
|
t.Fatalf("second resolve() = %q, want the cached %q", again, got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -42,6 +42,25 @@ func public(ip net.IP) bool {
|
|||||||
ip.IsInterfaceLocalMulticast(), ip.IsMulticast():
|
ip.IsInterfaceLocalMulticast(), ip.IsMulticast():
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
v4 := ip.To4()
|
for _, block := range reserved {
|
||||||
return v4 == nil || v4[0] != 100 || v4[1] < 64 || v4[1] > 127
|
if block.Contains(ip) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// reserved are ranges that are not the public internet: carrier-grade NAT,
|
||||||
|
// benchmarking, IETF protocol assignments and the NAT64 prefix, which can map
|
||||||
|
// to private IPv4 hosts.
|
||||||
|
var reserved = []*net.IPNet{
|
||||||
|
mustCIDR("100.64.0.0/10"), mustCIDR("198.18.0.0/15"), mustCIDR("192.0.0.0/24"), mustCIDR("64:ff9b::/96"),
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustCIDR(text string) *net.IPNet {
|
||||||
|
_, block, err := net.ParseCIDR(text)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return block
|
||||||
}
|
}
|
||||||
@@ -19,6 +19,9 @@ func TestPublicRefusesInstanceNetworks(t *testing.T) {
|
|||||||
{"169.254.169.254", false},
|
{"169.254.169.254", false},
|
||||||
{"100.64.0.1", false},
|
{"100.64.0.1", false},
|
||||||
{"0.0.0.0", false},
|
{"0.0.0.0", false},
|
||||||
|
{"198.19.0.1", false},
|
||||||
|
{"192.0.0.8", false},
|
||||||
|
{"64:ff9b::a00:1", false},
|
||||||
}
|
}
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.ip, func(t *testing.T) {
|
t.Run(tt.ip, func(t *testing.T) {
|
||||||
|
|||||||
@@ -111,22 +111,40 @@ func runtimeConfigFrom(ctx context.Context, reader controlplanerpc.ResourceReade
|
|||||||
}
|
}
|
||||||
out.Chat, versions[ChannelSettingsKind] = chat, chatVersion
|
out.Chat, versions[ChannelSettingsKind] = chat, chatVersion
|
||||||
if err := layerResource(ctx, reader, versions, SchedulingPolicyKind, func(policy schedulingPolicy) error {
|
if err := layerResource(ctx, reader, versions, SchedulingPolicyKind, func(policy schedulingPolicy) error {
|
||||||
interval, err := time.ParseDuration(policy.PollInterval)
|
return layerScheduling(&out, policy)
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
out.PollInterval, out.MaxRetries, out.Dispatch = config.Duration(interval), policy.MaxRetries, policy.Dispatch
|
|
||||||
// A stored label replaces the file's.
|
|
||||||
if policy.Label != nil {
|
|
||||||
out.Label = *policy.Label
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
return config.Config{}, nil, err
|
return config.Config{}, nil, err
|
||||||
}
|
}
|
||||||
return runtimeToolConfigFrom(ctx, reader, versions, out)
|
return runtimeToolConfigFrom(ctx, reader, versions, out)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// layerScheduling applies a stored scheduling policy over out. A field the
|
||||||
|
// document leaves unset keeps the value out already holds, which is how a
|
||||||
|
// document that carries only an org's discovery rule layers.
|
||||||
|
func layerScheduling(out *config.Config, policy schedulingPolicy) error {
|
||||||
|
if policy.PollInterval != "" {
|
||||||
|
interval, err := time.ParseDuration(policy.PollInterval)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
out.PollInterval = config.Duration(interval)
|
||||||
|
}
|
||||||
|
if policy.MaxRetries != 0 {
|
||||||
|
out.MaxRetries = policy.MaxRetries
|
||||||
|
}
|
||||||
|
if policy.Dispatch.Trigger != "" {
|
||||||
|
out.Dispatch.Trigger = policy.Dispatch.Trigger
|
||||||
|
}
|
||||||
|
if policy.Dispatch.AckReaction != "" {
|
||||||
|
out.Dispatch.AckReaction = policy.Dispatch.AckReaction
|
||||||
|
}
|
||||||
|
// A stored label replaces the file's.
|
||||||
|
if policy.Label != nil {
|
||||||
|
out.Label = *policy.Label
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func runtimeToolConfigFrom(ctx context.Context, reader controlplanerpc.ResourceReader, versions map[string]int64, out config.Config) (config.Config, map[string]int64, error) {
|
func runtimeToolConfigFrom(ctx context.Context, reader controlplanerpc.ResourceReader, versions map[string]int64, out config.Config) (config.Config, map[string]int64, error) {
|
||||||
policy := taskPolicyOf(out)
|
policy := taskPolicyOf(out)
|
||||||
if err := layerResourceJSON(ctx, reader, versions, TaskPolicyKind, &policy); err != nil {
|
if err := layerResourceJSON(ctx, reader, versions, TaskPolicyKind, &policy); err != nil {
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package controlplanestore
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/samcharles93/archie-core/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
// onlyScheduling serves one scheduling-policy document and nothing else.
|
||||||
|
type onlyScheduling string
|
||||||
|
|
||||||
|
func (r onlyScheduling) Query(_ context.Context, kind string, decode func([]byte) error) (int64, bool, error) {
|
||||||
|
if kind != SchedulingPolicyKind {
|
||||||
|
return 0, false, nil
|
||||||
|
}
|
||||||
|
return 1, true, decode([]byte(r))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRuntimeConfigLayersSchedulingFromAnyOrgsDocument(t *testing.T) {
|
||||||
|
base := config.Config{PollInterval: config.Duration(time.Minute), MaxRetries: 3, Label: "archie", Dispatch: config.Dispatch{Trigger: "assignee", AckReaction: "eyes"}}
|
||||||
|
tests := []struct {
|
||||||
|
name, doc string
|
||||||
|
poll time.Duration
|
||||||
|
retries int
|
||||||
|
trigger string
|
||||||
|
}{
|
||||||
|
{"system org document replaces the instance values", `{"poll_interval":"30s","max_retries":5,"dispatch":{"trigger":"label"},"label":"go"}`, 30 * time.Second, 5, "label"},
|
||||||
|
{"another org's unset document keeps the instance values", orgEmptyDocuments[SchedulingPolicyKind], time.Minute, 3, "assignee"},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
got, _, err := runtimeConfigFrom(t.Context(), onlyScheduling(tt.doc), base)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("runtimeConfigFrom() error = %v", err)
|
||||||
|
}
|
||||||
|
if got.PollInterval.Std() != tt.poll || got.MaxRetries != tt.retries || got.Dispatch.Trigger != tt.trigger {
|
||||||
|
t.Fatalf("got poll %v retries %d trigger %q, want %v %d %q", got.PollInterval.Std(), got.MaxRetries, got.Dispatch.Trigger, tt.poll, tt.retries, tt.trigger)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user