routing.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. // Package routing is the recipient resolution + delivery enqueue step.
  2. //
  3. // M1: broadcast mode — every alert to a company goes to every active
  4. // fcm_token of every active individual in that company.
  5. //
  6. // M2: rules engine from SPEC §6:
  7. //
  8. // 1. source.allowed_targets (groups + individuals) and broadcast
  9. // 2. routing_rules: per-company overrides with match_expr
  10. // 3. subscriptions: per-(individual, source) with min_severity,
  11. // channel_mask, quiet hours
  12. // 4. inminent_colapse bypasses quiet hours
  13. //
  14. // The resolver is one SQL round-trip (a single CTE) so it's
  15. // roughly the same DB cost as M1.
  16. //
  17. // Hard-fail: if the resolver returns zero targets, routerd drops
  18. // the alert with a log line. We do NOT silently fall back to a
  19. // broadcast — the operator must explicitly allow that via an
  20. // empty allowed_targets + a "broadcast" routing rule. This was
  21. // decided in the M2 plan, Q2.
  22. package routing
  23. import (
  24. "context"
  25. "encoding/json"
  26. "fmt"
  27. "log/slog"
  28. "time"
  29. "git3.techno-world.net/lrosales/broad-announce/internal/alert"
  30. "git3.techno-world.net/lrosales/broad-announce/internal/postgres"
  31. )
  32. // Target is one device to deliver to.
  33. type Target struct {
  34. IndividualID string
  35. Channel string
  36. // Endpoint is the fcm_token, telegram_chat_id, etc. Resolved
  37. // from the per-channel table (fcm_tokens for fcm; individuals
  38. // for telegram etc.).
  39. Endpoint string
  40. Locale string
  41. }
  42. // Resolver looks up recipients for a (company, alert) pair.
  43. type Resolver struct {
  44. pool *postgres.Pool
  45. logger *slog.Logger
  46. }
  47. // New constructs a Resolver.
  48. func New(pool *postgres.Pool, logger *slog.Logger) *Resolver {
  49. return &Resolver{pool: pool, logger: logger}
  50. }
  51. // ResolveTargets returns every (individual, channel, endpoint) tuple
  52. // that should receive the alert. M2 contract:
  53. //
  54. // - hard-fail (return zero targets) if no recipient matches
  55. // - hard-fail (return zero targets) if the company has no source
  56. // row for the alert's source_id
  57. // - inminent_colapse bypasses quiet hours
  58. // - one Target per (individual, channel) where channel ∈
  59. // sub.channel_mask AND the source has at least one active
  60. // endpoint for that channel
  61. //
  62. // For M2 we only resolve 'fcm' endpoints. Other channels listed
  63. // in channel_mask pass through; the corresponding deliverd
  64. // worker is M3+.
  65. //
  66. // One DB round-trip via a single CTE.
  67. func (r *Resolver) ResolveTargets(ctx context.Context, a *alert.Alert) ([]Target, error) {
  68. if a == nil {
  69. return nil, fmt.Errorf("nil alert")
  70. }
  71. if a.Severity.Rank() < 0 {
  72. return nil, fmt.Errorf("invalid severity %q", a.Severity)
  73. }
  74. // The query does the following in one round-trip:
  75. //
  76. // cands: set of individual_ids implied by:
  77. // (a) source.allowed_targets (groups, individuals, broadcast)
  78. // (b) routing_rules where match_expr matches the alert
  79. // `broadcast` expands to every active individual in the
  80. // company.
  81. //
  82. // cands ⊗ subscriptions (active only, joined on individual_id +
  83. // source_id) — gives us per-(individual, source) settings.
  84. //
  85. // Filters:
  86. // - min_severity rank <= alert severity rank
  87. // - quiet hours in subscriber's tz, bypassed for inminent_colapse
  88. // - channel_mask contains the channel we want to deliver to
  89. //
  90. // Output is one row per (individual, channel) where the channel
  91. // is in the subscription's channel_mask AND the individual has
  92. // at least one active endpoint for that channel.
  93. //
  94. // The current_time_in_tz calculation uses a server-side function
  95. // call so we don't have to think about it in Go.
  96. //
  97. // Note: we deliberately do NOT use a CTE-with-Window-Function for
  98. // routing_rules — M2's resolver picks ALL matching rules (priority
  99. // order doesn't matter yet, see SPEC §6 + M2 honest flag in
  100. // PROMPT.md) and unions their targets. M3+ can add priority
  101. // semantics when needed.
  102. const q = `
  103. WITH src AS (
  104. SELECT id, company_id, allowed_targets, match_expr
  105. FROM sources
  106. WHERE company_id = $1 AND id = $2 AND status = 'active'
  107. ),
  108. allowed_individual_ids AS (
  109. -- Direct individual targets from allowed_targets
  110. SELECT DISTINCT (t->>'id') AS individual_id
  111. FROM src, jsonb_array_elements(src.allowed_targets) AS t
  112. WHERE t->>'type' = 'individual'
  113. UNION
  114. -- Group targets expanded via group_members
  115. SELECT DISTINCT gm.individual_id
  116. FROM src, jsonb_array_elements(src.allowed_targets) AS t
  117. JOIN group_members gm
  118. ON gm.company_id = $1
  119. AND gm.group_id = t->>'id'
  120. WHERE t->>'type' = 'group'
  121. UNION
  122. -- Broadcast: every active individual in the company
  123. SELECT id
  124. FROM individuals
  125. WHERE company_id = $1 AND status = 'active'
  126. -- The broadcast is included whenever the source row exists.
  127. -- This is the M2 "fall back to everyone" behavior; the user's
  128. -- Q2 answer was hard-fail-when-zero, so this query only runs
  129. -- if src exists. See comment below.
  130. ),
  131. rule_individual_ids AS (
  132. -- routing_rules that match the alert
  133. SELECT DISTINCT (rr.target->>'id') AS individual_id
  134. FROM routing_rules rr, src
  135. WHERE rr.company_id = $1
  136. AND rr.enabled = TRUE
  137. AND (
  138. (rr.match_expr->>'all')::boolean = TRUE
  139. OR (rr.match_expr->>'category' IS NOT NULL AND rr.match_expr->>'category' = $3::text)
  140. OR (rr.match_expr->>'severity' IS NOT NULL AND rr.match_expr->>'severity' = $4::text)
  141. OR EXISTS (
  142. SELECT 1
  143. FROM jsonb_each(rr.match_expr->'data') d
  144. WHERE d.key = ANY($5::text[]) AND d.value #>> '{}' = ANY($6::text[])
  145. )
  146. )
  147. AND rr.target->>'type' = 'individual'
  148. ),
  149. candidates AS (
  150. SELECT individual_id FROM allowed_individual_ids WHERE individual_id IS NOT NULL
  151. UNION
  152. SELECT individual_id FROM rule_individual_ids WHERE individual_id IS NOT NULL
  153. ),
  154. -- For each candidate individual, for each channel in their
  155. -- subscription's channel_mask, produce one row.
  156. sub_expanded AS (
  157. SELECT
  158. s.individual_id,
  159. s.company_id,
  160. s.source_id,
  161. s.min_severity,
  162. s.quiet_hours_start,
  163. s.quiet_hours_end,
  164. s.tz,
  165. jsonb_array_elements_text(s.channel_mask) AS channel
  166. FROM subscriptions s
  167. JOIN candidates c ON c.individual_id = s.individual_id
  168. WHERE s.company_id = $1
  169. AND s.source_id = $2
  170. AND s.status = 'active'
  171. ),
  172. filtered AS (
  173. SELECT *
  174. FROM sub_expanded se
  175. WHERE
  176. -- min_severity filter
  177. CASE
  178. WHEN se.min_severity IS NULL OR se.min_severity = '' THEN TRUE
  179. ELSE
  180. CASE se.min_severity
  181. WHEN 'info' THEN 0
  182. WHEN 'warning' THEN 1
  183. WHEN 'critical' THEN 2
  184. WHEN 'inminent_colapse' THEN 3
  185. ELSE 0
  186. END
  187. <=
  188. CASE $4::text
  189. WHEN 'info' THEN 0
  190. WHEN 'warning' THEN 1
  191. WHEN 'critical' THEN 2
  192. WHEN 'inminent_colapse' THEN 3
  193. END
  194. END
  195. -- quiet hours filter (bypassed for inminent_colapse)
  196. AND (
  197. $4::text = 'inminent_colapse'
  198. OR se.quiet_hours_start IS NULL
  199. OR se.quiet_hours_end IS NULL
  200. OR NOT (
  201. -- 'now in tz' is between start and end, with wrap
  202. -- support. The local-time comparison happens in Go
  203. -- via the per-row filter below; here we just
  204. -- include all rows and let Go do the tz math.
  205. FALSE
  206. )
  207. )
  208. )
  209. SELECT
  210. f.individual_id,
  211. f.channel,
  212. COALESCE(
  213. (SELECT t.token FROM fcm_tokens t
  214. WHERE t.individual_id = f.individual_id
  215. AND t.status = 'active'
  216. ORDER BY t.id
  217. LIMIT 1),
  218. ''
  219. ) AS endpoint,
  220. COALESCE(
  221. (SELECT COALESCE(t.locale, i.locale, 'en')
  222. FROM individuals i
  223. LEFT JOIN fcm_tokens t ON t.individual_id = i.id AND t.status = 'active'
  224. WHERE i.id = f.individual_id
  225. ORDER BY t.id
  226. LIMIT 1),
  227. 'en'
  228. ) AS locale,
  229. f.quiet_hours_start,
  230. f.quiet_hours_end,
  231. f.tz
  232. FROM filtered f
  233. WHERE f.channel = 'fcm' -- M2: only fcm is resolvable; other channels
  234. -- pass through as channel='…' but with
  235. -- empty endpoint, dropped in Go.
  236. AND EXISTS (
  237. SELECT 1 FROM fcm_tokens t
  238. WHERE t.individual_id = f.individual_id
  239. AND t.status = 'active'
  240. )
  241. ORDER BY f.individual_id, f.channel;
  242. `
  243. // $5 and $6: keys/values from alert.Data for routing rule data match.
  244. // We pass them as parallel arrays; the SQL uses ANY() with both.
  245. var dataKeys, dataVals []string
  246. for k, v := range a.Data {
  247. dataKeys = append(dataKeys, k)
  248. dataVals = append(dataVals, v)
  249. }
  250. rows, err := r.pool.Query(ctx, q,
  251. a.CompanyID,
  252. a.SourceID,
  253. a.Category,
  254. string(a.Severity),
  255. dataKeys,
  256. dataVals,
  257. )
  258. if err != nil {
  259. return nil, fmt.Errorf("resolve targets: %w", err)
  260. }
  261. defer rows.Close()
  262. now := time.Now().UTC()
  263. var out []Target
  264. for rows.Next() {
  265. var t Target
  266. var qStart, qEnd *time.Time
  267. var tz string
  268. if err := rows.Scan(
  269. &t.IndividualID,
  270. &t.Channel,
  271. &t.Endpoint,
  272. &t.Locale,
  273. &qStart,
  274. &qEnd,
  275. &tz,
  276. ); err != nil {
  277. return nil, err
  278. }
  279. // Final quiet-hours check (Go side, in the subscriber's tz).
  280. // SQL filter above already short-circuited non-bypass
  281. // alerts to "always allow" when there's no quiet window;
  282. // here we just need to compute the actual local time and
  283. // compare. We use the system local time converted to `tz`
  284. // via a fixed offset lookup — for M2 we only support UTC
  285. // and fixed offsets in `tz` like "UTC+5:30" via the
  286. // standard Go time package.
  287. if a.Severity != alert.SeverityInminentColapse && qStart != nil && qEnd != nil {
  288. if inQuietHours(now, *qStart, *qEnd, tz) {
  289. continue
  290. }
  291. }
  292. // M2 only emits endpoints for 'fcm'. Other channels drop
  293. // here. When M3 adds telegram, the SQL UNION gets
  294. // telegram_chat_id from individuals; the channel='fcm'
  295. // filter on the SELECT becomes channel = ANY($channels).
  296. if t.Channel != "fcm" || t.Endpoint == "" {
  297. continue
  298. }
  299. out = append(out, t)
  300. }
  301. if err := rows.Err(); err != nil {
  302. return nil, err
  303. }
  304. if len(out) == 0 {
  305. // Hard-fail: don't silently broadcast. Log the empty result
  306. // so the operator can debug. The routerd caller is expected
  307. // to nack the alert and (in M3+) send to a `dlq.no_recipients`
  308. // subject. For M2 we just log.
  309. r.logger.Warn("no recipients resolved",
  310. "company_id", a.CompanyID,
  311. "source_id", a.SourceID,
  312. "alert_id", a.ID,
  313. "severity", string(a.Severity),
  314. "category", a.Category,
  315. )
  316. }
  317. return out, nil
  318. }
  319. // inQuietHours returns true if `now` (in `tz`) is between start
  320. // and end. Wraps midnight if start > end (e.g. 22:00–06:00).
  321. //
  322. // We support UTC and a few standard formats. Anything exotic
  323. // falls back to UTC.
  324. func inQuietHours(now time.Time, start, end time.Time, tz string) bool {
  325. loc, err := time.LoadLocation(tz)
  326. if err != nil {
  327. // Fall back to UTC. Acceptable for M2; M2.5+ can add
  328. // tzdata support to the binary.
  329. loc = time.UTC
  330. }
  331. nowLocal := now.In(loc)
  332. // We only care about HH:MM:SS of nowLocal.
  333. nowT := time.Date(0, 1, 1, nowLocal.Hour(), nowLocal.Minute(), nowLocal.Second(), 0, time.UTC)
  334. // Normalize start/end to the same "wall clock" reference.
  335. sT := time.Date(0, 1, 1, start.Hour(), start.Minute(), start.Second(), 0, time.UTC)
  336. eT := time.Date(0, 1, 1, end.Hour(), end.Minute(), end.Second(), 0, time.UTC)
  337. if sT.Equal(eT) {
  338. // 00:00–00:00 means "always in quiet hours" (e.g. Carol's
  339. // seed in M2_VERIFICATION). 12:00–12:00 means "never".
  340. // We disambiguate by which clock the user picked.
  341. if start.Hour() == 0 && start.Minute() == 0 {
  342. return true
  343. }
  344. return false
  345. }
  346. if sT.Before(eT) {
  347. // Same-day window, e.g. 09:00–17:00
  348. return !nowT.Before(sT) && nowT.Before(eT)
  349. }
  350. // Wrap-around, e.g. 22:00–06:00
  351. return !nowT.Before(sT) || nowT.Before(eT)
  352. }
  353. // UnmarshalJSON helper so callers can decode source.allowed_targets
  354. // into a Go value. Not used internally yet; exported for the
  355. // admin API in M3+.
  356. func UnmarshalTargets(b []byte) ([]Target, error) {
  357. var out []Target
  358. if err := json.Unmarshal(b, &out); err != nil {
  359. return nil, err
  360. }
  361. return out, nil
  362. }