From be4fd100896138979fa1f0b5f642146262b14e3b Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Tue, 27 Oct 2026 10:36:55 +1100 Subject: [PATCH] fix(orgs): layer only the fields an org document sets, retry alerts on a failed lookup, and key chat sessions by org --- internal/app/archied/alerts.go | 50 ++++++++++---- internal/app/archied/alerts_settle_test.go | 34 +++++++++ internal/gateway/gateway.go | 8 +-- internal/gateway/session_commands.go | 69 +++++++++++-------- internal/gateway/session_delete.go | 2 +- internal/gateway/session_titles.go | 2 +- internal/gateway/session_tools.go | 2 +- internal/gateway/session_tracker_org_test.go | 67 ++++++++++++++++++ .../infrastructure/alertwebhook/public.go | 23 ++++++- .../alertwebhook/public_test.go | 3 + .../controlplanestore/runtime_config.go | 38 +++++++--- .../scheduling_layer_test.go | 43 ++++++++++++ 12 files changed, 279 insertions(+), 62 deletions(-) create mode 100644 internal/app/archied/alerts_settle_test.go create mode 100644 internal/gateway/session_tracker_org_test.go create mode 100644 internal/infrastructure/controlplanestore/scheduling_layer_test.go diff --git a/internal/app/archied/alerts.go b/internal/app/archied/alerts.go index 3a73658c9..3c0665ba1 100644 --- a/internal/app/archied/alerts.go +++ b/internal/app/archied/alerts.go @@ -316,28 +316,48 @@ func (b *boot) deliverAlerts(store alert.Deliverer) func(context.Context) { b.log.WarnContext(ctx, "alert deliveries not claimed", "err", err) return } - notifies := map[org.OrgID]config.Notify{} - for _, d := range due { - notify, ok := notifies[d.Alert.Org] - outcome := alert.Outcome{DeliveryID: d.ID} - 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) + outcomes := settleDeliveries(due, func(owner org.OrgID) (config.Notify, error) { + notify, err := b.alertNotify(ctx, owner) + if err != nil { + b.log.WarnContext(ctx, "alert notification settings unavailable", "org", owner, "err", err) } + 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 { - 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 // 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 { diff --git a/internal/app/archied/alerts_settle_test.go b/internal/app/archied/alerts_settle_test.go new file mode 100644 index 000000000..b4ffd9b6a --- /dev/null +++ b/internal/app/archied/alerts_settle_test.go @@ -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) + } + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 76186064e..fede657ef 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -912,7 +912,7 @@ func (r *Router) handleSessions(ctx context.Context, msg messaging.Message) (str } active := "" 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 } @@ -1029,12 +1029,12 @@ func (r *Router) handleResume(ctx context.Context, msg messaging.Message, arg st case match == 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 { - 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) } diff --git a/internal/gateway/session_commands.go b/internal/gateway/session_commands.go index 5a85510b4..c0e603784 100644 --- a/internal/gateway/session_commands.go +++ b/internal/gateway/session_commands.go @@ -12,6 +12,7 @@ import ( "github.com/google/uuid" "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 @@ -48,7 +49,7 @@ func newSessionTracker(sessions SessionStore) *sessionTracker { // resolve returns the session ID for a message, creating one if needed. // ThreadID may be empty for flat chats. 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() id, ok := t.active[key] 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. - id = sessionKeyFromFields(channelID, threadID) + id = sessionKeyFromFields(ctx, channelID, threadID) if winner, won := t.claimActive(key, id); !won { return winner, nil } @@ -156,37 +157,46 @@ func (t *sessionTracker) cacheActive(key, sessionID string) string { return sessionID } -func sessionKeyFromFields(channelID, threadID string) string { - if threadID == "" { - return channelID +// sessionKeyFromFields derives a new session's ID from its chat. A chat id is +// only unique within its org's channel, so another org's session carries the +// 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 // 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. if sessionID == "" { return } t.mu.Lock() 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, // in one critical section. -func (t *sessionTracker) flattenTopic(channelID, threadID string) { +func (t *sessionTracker) flattenTopic(ctx context.Context, channelID, threadID string) { t.mu.Lock() defer t.mu.Unlock() - current, ok := t.active[sessionTrackerKey(channelID, threadID)] + current, ok := t.active[sessionTrackerKey(ctx, channelID, threadID)] if !ok || current == "" { // Nothing to carry over. The next message resolves from the store, // which is the correct answer anyway. return } - t.active[sessionTrackerKey(channelID, "")] = current + t.active[sessionTrackerKey(ctx, channelID, "")] = current } // 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. -func (t *sessionTracker) getActive(channelID, threadID string) string { +func (t *sessionTracker) getActive(ctx context.Context, channelID, threadID string) string { t.mu.RLock() 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 @@ -217,11 +227,14 @@ func parsePositiveInt(s string) (int, bool) { return int(n), err == nil && n > 0 } -func sessionTrackerKey(channelID, threadID string) string { - if threadID == "" { - return channelID +// sessionTrackerKey names a chat in the active-session cache. The cache is +// shared by every org, so a non-system org's key carries the org. +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 @@ -239,7 +252,7 @@ func (r *Router) sessionPlatform(in Inbound) string { func (r *Router) ResolveSessionKey(ctx context.Context, in Inbound) (string, error) { conv := in.Message.ConversationID 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) } @@ -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 { 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 != "" { 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 { 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 case "help": return topicHelpText(), nil @@ -314,7 +327,7 @@ func topicHelpText() string { } 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) if err != nil { 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 } 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", 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 } - sessionID := r.sessionTracker.getActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID) + sessionID := r.sessionTracker.getActive(ctx, msg.ConversationID.ChannelID, msg.ConversationID.ThreadID) if sessionID == "" { 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 } - sessionID := r.sessionTracker.getActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID) + sessionID := r.sessionTracker.getActive(ctx, msg.ConversationID.ChannelID, msg.ConversationID.ThreadID) if sessionID == "" { 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 } - sessionID := r.sessionTracker.getActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID) + sessionID := r.sessionTracker.getActive(ctx, msg.ConversationID.ChannelID, msg.ConversationID.ThreadID) if sessionID == "" { 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 threadID := msg.ConversationID.ThreadID - parentID := r.sessionTracker.getActive(channelID, threadID) + parentID := r.sessionTracker.getActive(ctx, channelID, threadID) if parentID == "" { // Channels that call Route directly can reach this with no session. 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 != "" { 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 } - sessionID := r.sessionTracker.getActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID) + sessionID := r.sessionTracker.getActive(ctx, msg.ConversationID.ChannelID, msg.ConversationID.ThreadID) if sessionID == "" { return "No active session. Send a message first.", nil } diff --git a/internal/gateway/session_delete.go b/internal/gateway/session_delete.go index 67747d10e..3406b08f8 100644 --- a/internal/gateway/session_delete.go +++ b/internal/gateway/session_delete.go @@ -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. active := "" 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 { diff --git a/internal/gateway/session_titles.go b/internal/gateway/session_titles.go index 6f43fa5be..0ee897e6d 100644 --- a/internal/gateway/session_titles.go +++ b/internal/gateway/session_titles.go @@ -41,7 +41,7 @@ func (r *Router) maybeAutoTitle(ctx context.Context, msg messaging.Message) { if r.Titles == nil || r.sessionTracker == nil { 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) { return } diff --git a/internal/gateway/session_tools.go b/internal/gateway/session_tools.go index 4d8f27f32..e728574ef 100644 --- a/internal/gateway/session_tools.go +++ b/internal/gateway/session_tools.go @@ -176,7 +176,7 @@ func sessionResumeTool(store SessionStore, tracker *sessionTracker, platform, ch // The channel+thread are the ones this tool was built for, never // input. Tracker presence is guaranteed: SessionTools omits the // 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{ SessionID: match.SessionID, Title: sessionDisplayTitle(*match), diff --git a/internal/gateway/session_tracker_org_test.go b/internal/gateway/session_tracker_org_test.go new file mode 100644 index 000000000..d6d163238 --- /dev/null +++ b/internal/gateway/session_tracker_org_test.go @@ -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) + } + }) + } +} diff --git a/internal/infrastructure/alertwebhook/public.go b/internal/infrastructure/alertwebhook/public.go index e01e16838..f8d758dd8 100644 --- a/internal/infrastructure/alertwebhook/public.go +++ b/internal/infrastructure/alertwebhook/public.go @@ -42,6 +42,25 @@ func public(ip net.IP) bool { ip.IsInterfaceLocalMulticast(), ip.IsMulticast(): return false } - v4 := ip.To4() - return v4 == nil || v4[0] != 100 || v4[1] < 64 || v4[1] > 127 + for _, block := range reserved { + 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 } diff --git a/internal/infrastructure/alertwebhook/public_test.go b/internal/infrastructure/alertwebhook/public_test.go index d26051313..3b5630b6a 100644 --- a/internal/infrastructure/alertwebhook/public_test.go +++ b/internal/infrastructure/alertwebhook/public_test.go @@ -19,6 +19,9 @@ func TestPublicRefusesInstanceNetworks(t *testing.T) { {"169.254.169.254", false}, {"100.64.0.1", 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 { t.Run(tt.ip, func(t *testing.T) { diff --git a/internal/infrastructure/controlplanestore/runtime_config.go b/internal/infrastructure/controlplanestore/runtime_config.go index 45443b62b..696aa0858 100644 --- a/internal/infrastructure/controlplanestore/runtime_config.go +++ b/internal/infrastructure/controlplanestore/runtime_config.go @@ -111,22 +111,40 @@ func runtimeConfigFrom(ctx context.Context, reader controlplanerpc.ResourceReade } out.Chat, versions[ChannelSettingsKind] = chat, chatVersion if err := layerResource(ctx, reader, versions, SchedulingPolicyKind, func(policy schedulingPolicy) error { - interval, err := time.ParseDuration(policy.PollInterval) - 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 + return layerScheduling(&out, policy) }); err != nil { return config.Config{}, nil, err } 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) { policy := taskPolicyOf(out) if err := layerResourceJSON(ctx, reader, versions, TaskPolicyKind, &policy); err != nil { diff --git a/internal/infrastructure/controlplanestore/scheduling_layer_test.go b/internal/infrastructure/controlplanestore/scheduling_layer_test.go new file mode 100644 index 000000000..903a68c53 --- /dev/null +++ b/internal/infrastructure/controlplanestore/scheduling_layer_test.go @@ -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) + } + }) + } +}