Compare commits

..
Author SHA1 Message Date
james.maesandClaude Opus 5.5 a65b019ffa ci: rebuild on the released QQQ 4.1.0-RC.6
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 07:15:35 -05:00
james.maesandClaude Opus 5.5 2692f8b1dc feat(api): alerts UI routes as spec'd extension endpoints; webhook to /qqq/hooks; follow via collaboration
#13: the six inbox and record-panel routes move from the raw
AlertsRouteProvider onto a MiddlewareSpecExtension "alerts" (prefix
/alerts). Paths are unchanged. The committed fragment
openapi/qqq-v1/alerts.yaml is checked by a contract test, and the server
tests run in strict mode. Additive fields let Next stop hard-coding
alerts names: the summary has inboxHref, and inbox items and panel
alerts have actions with process names and hrefs.

#14: the Alertmanager webhook moves to POST /qqq/hooks/alerts/alertmanager.
The old /qqq/v1 path is an opt-in deprecated alias (legacyAlertmanagerPath,
default off; it needs non-strict mode). The alias sends Deprecation and
Sunset headers and logs a warning per call.

#16: POST /alerts/record-panel/watch is removed; collaboration owns
following a record. The record panel reports follow.available when the
collaboration extension is registered. Existing record-scoped watch
subscriptions stay readable and are deprecated. Follower fan-out waits for
core RecordFollowersProviderInterface (STAND-IN(core=QRun-IO/qqq#1164,
removeBy=4.1.0-RC.7)).

The checkstyle header template now matches the short Apache header that
the sources already use. The core baseline becomes 4.1.0-RC.6.

Closes #13, closes #14, closes #16 (architecture review QRun-IO/qqq#1150,
F2, F7, F12, F20).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 20:18:36 -05:00
james.maes 3044f15fbc Merge pull request #17 from QRun-IO/feature/arch-rc5-standins
refactor(alerts): core QAlerts and WebhookSigner on QQQ RC.5 (#15 part 1)
2026-10-13 19:36:43 -05:00
james.maesandClaude Opus 5.5 cb3d206e0f refactor(alerts): use core QAlerts and WebhookSigner from QQQ 4.1.0-RC.5
Bump the core baseline to 4.1.0-RC.5 and delete the alert-side copies in
the spi package. The qbit now registers its sink in core's
AlertsInstanceMetaData, so core QAlerts.raise/resolve/heartbeat from any
host qbit reaches it. The alertsQBitStandIn name is gone.

The notification types (NotificationSignal and friends) and
AlertsRuntime.sink().notify stay, binary compatible, for the released
qbit-easypost-tracking. They are tagged
STAND-IN(core=QRun-IO/qqq#1125, removeBy=4.1.0-RC.6).

StandardWebhookSigner delegates to core WebhookSigner. The wire format is
unchanged. Legacy secrets shorter than core's 16-byte minimum are
zero-padded, which gives an identical HMAC-SHA256.

Refs #15 (architecture review QRun-IO/qqq#1150, F3 and F11).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 19:31:16 -05:00
james.maes 110f15d866 Merge pull request #12 from QRun-IO/feature/release-rc-automation
ci: automate RC releases; hotfix/* pushes no longer publish
2026-10-13 14:43:10 -05:00
james.maesandClaude Opus 5.5 f50b3c1e18 ci: automate RC releases; hotfix/* pushes no longer publish
Removes publish_hotfix_release: a hotfix/* branch push published a GA
release to Maven Central with no tag or review (QRun-IO/qbit-cdn#12,
QRun-IO/qqq#1121). hotfix/* branches now run test_only; a hotfix
release publishes from a reviewed vX.Y.Z tag through publish_release.
Adds .github/workflows/release-rc.yml (reusable QRun-IO/.github
qbit-release-rc): a manual dispatch, or merging a develop PR labelled
release:rc, merges develop into the release line and the release/* push
runs the existing CircleCI RC publish.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:37:13 -05:00
james.maes 758b68a6a9 Merge pull request #11 from QRun-IO/feature/notifications-de
feat(notifications): security, share and release notices, email digests; harden links (phases d, e)
2026-10-13 10:21:19 -05:00
james.maesandClaude Opus 5.5 020d38e810 fix(api): notificationsHref is the Next UI route /app/notifications
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 10:15:52 -05:00
james.maes 784bf0026c Merge pull request #10 from QRun-IO/feature/notifications-c-jobs
feat(notifications): notify people of their failed and partial jobs (phase c)
2026-10-13 10:15:26 -05:00
james.maesandClaude Opus 5.5 65fa558ed5 feat(notifications): security, share and release notices, email digests, home line; harden links (phases d, e)
- AlertsNotices: newSignIn, apiKeyCreated, apiKeyExpiring (deduped per
  key), permissionChanged, shared, release.
- NotificationEmailer: opt-in email per user and category, IMMEDIATE (at
  or above a minimum severity) or DAILY_DIGEST at the user's digest hour
  and time zone; inert without a messaging provider; ALERT not emailed
  here; SECURITY emails carry no body. Runs in the delivery job.
- Alerts home: a link-only Notifications line for authors.
- safeLink refuses backslashes, whitespace, control characters, a second
  leading slash, and anything but https with a host (open-redirect fix
  from security review); the table customizer uses it on save.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 10:15:05 -05:00
james.maes e68bdb9db2 Merge pull request #9 from QRun-IO/feature/notifications-a-tables
feat(notifications): user notifications, recipients, audiences and the bell API (phase a)
2026-10-13 10:09:01 -05:00
james.maesandClaude Opus 5.5 1e8f9aac25 test(demo): seed user notifications for the bell, page and admin screens
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 10:08:51 -05:00
james.maesandClaude Opus 5.5 62dfa5f350 feat(notifications): notify people of their failed and partial jobs (phase c)
The process lifecycle listener now also sends a JOB notification to the
person who started a run that fails, or that completes with ERROR summary
lines (a partial run). System runs and the qbit's own processes are
skipped; a repeat of the same run updates one notification (sourceKey
process:<uuid>). It links to jobRunLinkPattern or the process's table.
Monitor heartbeats stay limited to watched processes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 10:06:30 -05:00
james.maesandClaude Opus 5.5 81407f88c0 chore: license headers on the new notification classes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 10:06:28 -05:00
james.maesandClaude Opus 5.5 4a94a23314 feat(notifications): user notifications, recipients, audiences and the bell API (phase a)
- alerts_notification (user notifications), alerts_notification_recipient
  (one row per user, read/dismissed) and alerts_notification_preference
  (per-category mute and email settings), with entities, changelog and
  test DDL.
- The delivery log becomes alerts_delivery and alerts_inbox_item is
  retired (guarded changesets 16-17); in-app alert delivery writes ALERT
  notifications and recipient rows.
- Audiences resolved at send time (all users, roles, permission, users)
  through a pluggable user directory; record actions Preview audience,
  Send now, Schedule and Retract; scheduled sends and retention purge in
  the delivery job.
- Bell API: summary with banners, a paged page endpoint with filters,
  read, unread and dismiss; alerts_recipient security key and
  alerts.notification.admin.
- NotificationSignal / NotificationAudience in the SPI stand-in, and the
  sink's notify.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 10:03:47 -05:00
james.maes cd06fff114 Merge pull request #8 from QRun-IO/feature/notifications-spec
docs: user notifications design (owner decisions 2026-10-13)
2026-10-13 10:03:46 -05:00
james.maesandClaude Opus 5.5 1a6bb6096e docs: user notifications design (owner decisions 2026-10-13)
Extends the alerts model with admin-authored and producer-emitted user
notifications, per-user recipient rows, dynamic audiences, the Next UI
notification center, and QAlerts.notify in the core SPI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 09:45:34 -05:00
james.maes b673032d6b Merge pull request #7 from QRun-IO/feature/sink-stop-drains-in-flight
fix(sink): stop() waits for in-flight signals before returning
2026-10-12 17:50:51 -05:00
james.maesandClaude Opus 5.5 23054f54f1 fix(sink): stop() waits for in-flight signals before returning
The drain thread could take a signal off the queue and still be writing
it when stop() flushed (an empty queue) and returned; the interrupt could
also land mid-write. A resolve submitted just before shutdown could be
lost. That is what failed SinkAndScheduleTest on the release/0.1 build.

stop() now ends the drain loop with a flag, joins the thread (up to 10 s,
interrupting only if it does not finish), then flushes what is left. The
drain poll is 200 ms so stop() returns promptly. New regression test fails
on the old code (3 of 4 runs) and passes on the fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 17:48:46 -05:00
james.maes 5039c4b837 Merge pull request #5 from QRun-IO/feature/alerts-external-channels-p4
feat: external channels and Alertmanager ingest (P4)
2026-10-12 17:27:12 -05:00
james.maesandClaude Opus 5.5 050c141c6b feat: external channels (Slack, Teams, signed webhook, PagerDuty, Alertmanager) and Alertmanager ingest (P4)
- SLACK (Incoming Webhook, Block Kit), TEAMS (Workflows webhook, Adaptive
  Card), WEBHOOK (Standard Webhooks signature via a stand-in for core's
  WebhookSigner, QRun-IO/qqq#1109), PAGERDUTY (Events API v2 trigger /
  acknowledge / resolve, dedup_key = type:key), ALERTMANAGER sink
  (/api/v2/alerts, qqq_* labels, qqq_origin guard, endsAt on resolve)
- shared HTTP rules: https only unless allowInsecureHttp, 10 s timeout,
  2xx sent, 408/425/429/5xx retry, other 4xx permanent; URLs (secrets for
  Slack and Teams) never appear in errors
- AlertMessage carries one structured, redacted entry per alert
- POST /qqq/v1/alerts/ingest/alertmanager: bearer token by secret
  reference (off without one), firing/resolved to raise/resolve, EXTERNAL
  prometheus.* types with notifications off, loop guard

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 17:23:03 -05:00
james.maes d821a0ad30 Merge pull request #4 from QRun-IO/feature/alerts-core-p1-p3
feat: alerts tables, engine, monitors, in-app and email, Alerts home and bell API (P1-P3)
2026-10-12 17:16:47 -05:00
james.maesandClaude Opus 5.5 fed79bd753 feat: spec table labels, record-label titles, readable heartbeat titles, local demo server
- table labels follow the design (Alerts, Monitors, Alert Types, ...)
- per-record monitor alerts are titled with the record's label field
- heartbeat titles read "for 46 h" instead of minutes; short group names
  are upper-cased (CDN)
- AlertsDemoServer (test scope, not shipped): H2 + mock admin + 30 days of
  history produced through the engine, for screenshots and manual checks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 17:14:41 -05:00
james.maesandClaude Opus 5.5 45c7b4fb8f feat: alerts tables, engine, monitors, in-app and email delivery, Alerts home and bell API (P1-P3)
Implements phases P1 to P3 of the Alerts design (QRun-IO/qqq#1090):
- 15 alerts_* tables with the Liquibase changelog, record security
  (alerts_user / alerts_permission / alerts_readable_table keys) and a
  write guard so alerts change only through the engine and record actions
- the state machine: dedup, refresh, severity changes, snooze, resolve,
  reopen window, flapping, quiet-period auto-resolve, maintenance windows
- monitors: TABLE_QUERY, AGGREGATE, HEARTBEAT, PROCESS_FAILED, CODE, with
  the full-state diff, forMinutes, timeouts, CHECK_FAILED meta-alert and
  seeded monitors
- routing with scopes, teams, the bootstrap rule, recipient visibility and
  logged suppression reasons; in-app, email and email-list channels; a
  channel SPI; retries to DEAD and channel health; redaction
- record actions as streamed ETL processes; hidden scheduled processes
- the Alerts app home, AlertSummaryLoader, and /qqq/v1/alerts routes for
  the Next UI bell and record panel

The core producer SPI (QRun-IO/qqq#1108) is not released yet, so its types
are a stand-in in the spi package, marked for replacement.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 16:57:39 -05:00
james.maes a41f8b8ecb Merge pull request #3 from QRun-IO/feature/ga-only-release-tags
ci: publish only GA tags (vX.Y.Z), never RC tags
2026-10-12 16:01:48 -05:00
james.maesandClaude Opus 5.5 9962e4ba57 ci: publish only GA tags (vX.Y.Z), never RC tags
An RC tag matched /v.*/ and the orb republished it as the next RC.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 15:59:03 -05:00
124 changed files with 32804 additions and 133 deletions

No files matched your search

+57 -11
View File
@@ -1,14 +1,60 @@
version: 2.1
setup: true
orbs:
qqq-orb: kingsrook/qqq-orb@0.8
qqq-orb: kingsrook/qqq-orb@0.6.8
commands:
configure-package-install:
steps:
- run:
name: Keep package installation unattended
command: |
# These build machines are discarded after the job.
sudo install -d /etc/needrestart/conf.d
printf '%s\n' '$nrconf{restart} = "l";' | sudo tee /etc/needrestart/conf.d/99-qqq-ci.conf >/dev/null
workflows:
setup:
jobs:
- qqq-orb/generate_pipeline:
orb_version: '0.8'
filters:
branches:
ignore: automation/qbit-rc-pending
tags:
only: /v.*/
test_only:
jobs:
- qqq-orb/mvn_test_only:
pre-steps:
- configure-package-install
context: [qqq-maven-registry-credentials]
filters:
branches:
ignore: /(develop|release\/.*)/
publish_snapshot:
jobs:
- qqq-orb/mvn_publish:
pre-steps:
- configure-package-install
context: [qqq-maven-registry-credentials]
branch_type: snapshot
filters:
branches:
only: [develop]
publish_release_candidate:
jobs:
- qqq-orb/mvn_publish:
pre-steps:
- configure-package-install
context: [qqq-maven-registry-credentials]
branch_type: release_candidate
filters:
branches:
only: [/release\/.*/]
publish_release:
jobs:
- qqq-orb/mvn_publish:
pre-steps:
- configure-package-install
context: [qqq-maven-registry-credentials]
branch_type: release
filters:
branches:
ignore: /.*/
tags:
only: [/^v\d+\.\d+\.\d+$/]
-25
View File
@@ -1,25 +0,0 @@
# Standard QRun release caller (v2, thin contract): every push and manual dispatch delegates to the protected qrun-release-v1 channel. Do not edit per repository.
name: qrun-release
on:
push: {}
workflow_dispatch: {}
permissions:
contents: read
actions: read
jobs:
release:
uses: self:KofTwentyTwo/platform-ci/.gitea/workflows/java-docker.yaml@qrun-release-v1
with:
runner: linux-small
docker-runner: container-build
browsers: true
browser-runner: browser-build
postpublish:
if: ${{ needs.release.outputs.capture == 'true' }}
needs: release
permissions:
contents: write
actions: write
uses: self:KofTwentyTwo/platform-ci/.gitea/workflows/qrun-source-version.yaml@qrun-release-v1
with:
runner: linux-small
-23
View File
@@ -1,23 +0,0 @@
name: CodeQL
'on':
push:
branches:
- main
- develop
- release/**
- hotfix/**
pull_request: {}
schedule:
- cron: 41 16 * * 0
workflow_dispatch: {}
permissions:
contents: read
actions: read
security-events: write
packages: read
concurrency:
group: codeql-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
analyze:
uses: QRun-IO/qqq-orb/.github/workflows/qbit-codeql.yml@c288a8864fe9054f68410e1d78f5863aea4c4d22
+25
View File
@@ -0,0 +1,25 @@
# Cut the next release candidate (QRun-IO/qqq docs/QRUN-QBIT-REPO-STANDARD.md, C6):
# run this workflow by hand, or merge a develop PR labelled `release:rc`. It merges develop into
# the release line and the release/* push runs CircleCI publish_release_candidate.
name: Release candidate
on:
workflow_dispatch:
inputs:
dry_run:
description: Print the plan without merging or creating branches
type: boolean
default: false
pull_request:
types: [closed]
branches: [develop]
permissions:
contents: write
jobs:
release-rc:
if: github.event_name == 'workflow_dispatch' || (github.event.pull_request.merged == true && contains(github.event.pull_request.labels.*.name, 'release:rc'))
uses: QRun-IO/.github/.github/workflows/qbit-release-rc.yml@main
with:
dry_run: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }}
-16
View File
@@ -1,16 +0,0 @@
profile: qbit
orb_version: '0.8'
default_branch: develop
java_version: '21'
browsers: true
api_checks: false
docs_only: false
release_on_main: false
release_tag_policy: v-prefix
test_branch_policy: non-release-no-hotfix
publish:
snapshot: true
release_candidate: true
release: true
hotfix: true
asciidoc: false
+12 -3
View File
@@ -4,7 +4,7 @@ This file provides guidance to Codex when working with code in this repository.
## Project Overview
**QBit Alerts**: QQQ QBit: alerts and manage-by-exception (monitors, alerts, subscriptions, channels and notifications as standard QQQ tables). Design: [QRun-IO/qqq#1090](https://github.com/QRun-IO/qqq/pull/1090). Implementation in progress.
**QBit Alerts**: QQQ QBit: alerts and manage-by-exception (monitors, alerts, subscriptions, channels and notifications as standard QQQ tables). Design: [QRun-IO/qqq#1090](https://github.com/QRun-IO/qqq/pull/1090). Phases P1 to P3 are implemented; see README.md for the remaining phases and the notification compatibility types in `spi/`.
## Build Commands
@@ -16,7 +16,16 @@ This file provides guidance to Codex when working with code in this repository.
## Architecture
**Entry point:** `AlertsQBitProducer implements QBitMetaDataProducer<AlertsQBitConfig>` in `com.kingsrook.qbits.alerts`. Component producers in this package (and below) are found by package scanning.
**Entry point:** `AlertsQBitProducer implements QBitMetaDataProducer<AlertsQBitConfig>` in `com.kingsrook.qbits.alerts`. Component producers are found by package scanning, in the `metadata` package only (the `api` package needs the optional Javalin dependency).
Packages:
- `model`: entities, generated from one schema together with the changelog and the test DDL. If you change a table, change all three.
- `engine`: the state machine (`AlertsEngine`), routing (`AlertRouter`), monitors (`MonitorEvaluator`), type sync, the sink and the process listener.
- `delivery`: channels, rendering, redaction and the delivery worker.
- `processes`: the record actions (`AlertsAction`, `AlertsActionSteps`) and the scheduled steps.
- `home`: the Alerts home and `AlertSummaryLoader`.
- `api`: the bell and record-panel routes.
- `spi`: notification types and their AlertLink dependency retained for binary compatibility until core RC.6; alerts use core RC.5.
## Naming (owner rule)
@@ -35,7 +44,7 @@ This file provides guidance to Codex when working with code in this repository.
## Dependencies
- Java 21.
- Parent `com.kingsrook:qbit-build-parent:2.0.0` (qqq 4.0.0). The default-active `qqq-snapshot` profile imports `qqq-bom-pom:4.1.0-RC.4` ahead of it, as in qbit-quick-search (ADR-0007). Remove that activation when the parent moves to 4.1.
- Parent `com.kingsrook:qbit-build-parent:2.0.0` (qqq 4.0.0). The default-active `qqq-snapshot` profile imports `qqq-bom-pom:4.1.0-RC.5` ahead of it, as in qbit-quick-search (ADR-0007). Remove that activation when the parent moves to 4.1.
- Tests: JUnit 5, AssertJ.
## Release
+50
View File
@@ -4,5 +4,55 @@ All notable changes to this project are documented here. The format follows Keep
## [0.1.0] - Unreleased
### Changed
- Target QQQ `4.1.0-RC.6` for the UI extension API; local verification uses a command-line version override only.
- Register six JSON UI specs as extension `alerts` at the established `/alerts` prefix, preserving methods, paths and existing payload fields. Publish the OpenAPI fragment with a regeneration/contract test and strict server coverage (#13, F2).
- Add summary `inboxHref`, notification operation actions, alert process actions with complete hrefs, and record-panel `follow.available` (#13, F20). Follow discovery reads core extension metadata without a collaboration dependency or URL.
- Remove the record-panel watch route and handler. Existing RECORD subscriptions and the deprecated `watching` response remain readable without a migration; new panel follows belong to collaboration. Follower fan-out waits for core #1164 (#16, F12).
- Move Alertmanager ingest to `/qqq/hooks/alerts/alertmanager`. The old path is an opt-in alias (`legacyAlertmanagerPath`, default false) for one minor release, incompatible with strict raw-route mode. Each alias call carries deprecation/sunset headers and logs a warning; authentication is shared (#14, F7).
- Run Checkstyle 14.3.0 in Maven validate (including tests); align the license template with this repository's existing headers and correct pre-existing switch/import formatting so the style check passes.
- Alert types and sink registration use core's alerts SPI (introduced in QQQ 4.1.0-RC.5); host `QAlerts.raise/resolve/heartbeat` calls reach the installed qbit through core instance metadata (qbit-alerts#15, F3).
- Removed alert SPI copies. Retained `spi.NotificationSignal`, `NotificationAudience`, `NotificationCategory`, `NotificationSeverity`, `AlertLink`, and the binary-compatible `AlertsRuntime.sink().notify(...)` entry point for qbit-easypost-tracking 0.1.x until QRun-IO/qqq#1125 ships in RC.6.
- Webhook signing delegates to core `WebhookSigner`/`WebhookSecret` (qbit-alerts#15, F11). Headers, `v1,` signatures and `whsec_` encoding are unchanged. A thin adapter preserves legacy keys shorter than core's 16-byte minimum using equivalent HMAC zero-padding.
### Added
- Optional external channels:
- Slack (an Incoming Webhook, Block Kit)
- Microsoft Teams (a Workflows webhook, an Adaptive Card)
- a generic webhook, signed with Standard Webhooks headers through core's `WebhookSigner` (QRun-IO/qqq#1109)
- PagerDuty (Events API v2: trigger, acknowledge and resolve)
- an Alertmanager sink (`/api/v2/alerts`, with the qqq labels and the origin guard)
- Prometheus Alertmanager ingest at `POST /qqq/hooks/alerts/alertmanager`. It takes a bearer token, creates EXTERNAL types with notifications off, and keeps a loop guard.
- Tables (`alerts_*`), with the Liquibase changelog `db/liquibase/qbit-alerts/alerts.changelog.sql`:
- alerts, their timeline and records
- types, groups and monitors
- subscriptions, user settings, teams and members
- channels, mutes and maintenance windows
- the notification log, inbox items and heartbeats
- An engine with dedup, refresh, severity changes, snooze, resolve, a reopen window, flapping, quiet-period auto-resolve and maintenance windows.
- Monitors: `TABLE_QUERY`, `AGGREGATE`, `HEARTBEAT`, `PROCESS_FAILED` and `CODE`. They have:
- a full-state diff, so a clean check resolves the monitor's open alerts
- `forMinutes`
- timeouts
- `CHECK_FAILED`, which raises the meta-alert `alerts.monitor.failing`
- seeded default monitors
- Routing:
- subscriptions by scope, team expansion, the bootstrap rule and a recipient visibility check
- suppression reasons logged on the notification
- in-app (inbox), email and email-list channels
- a pluggable channel SPI
- retries with backoff to DEAD, and channel health
- a redactor and detail levels for every external message
- Record actions, each a streamed ETL process:
- on alerts: acknowledge, snooze, resolve, reopen, assign, comment and mute
- on types, groups and monitors: subscribe and mute
- on monitors: run check now, enable and disable
- on types: create monitor
- on channels: send test notification
- on notifications: retry delivery
- Two hidden scheduled processes, for evaluation and delivery.
- The top-level Alerts app and its home dashboard, plus `AlertSummaryLoader` for link-only summaries.
- `/qqq/v1/alerts` routes for the Next UI bell and record panel.
- Record security, through three key types (`alerts_user`, `alerts_permission`, `alerts_readable_table`).
- Core alert producer SPI integration (QRun-IO/qqq#1108), plus temporary notification SPI compatibility until RC.6 (QRun-IO/qqq#1125).
- Repository scaffold: `AlertsQBitConfig` and `AlertsQBitProducer` (table prefix `alerts_`, permissions `alerts.*`), build, CI and repository standard files.
+11 -2
View File
@@ -4,7 +4,7 @@ This file provides guidance to Claude Code when working with code in this reposi
## Project Overview
**QBit Alerts**: QQQ QBit: alerts and manage-by-exception (monitors, alerts, subscriptions, channels and notifications as standard QQQ tables). Design: [QRun-IO/qqq#1090](https://github.com/QRun-IO/qqq/pull/1090). Implementation in progress.
**QBit Alerts**: QQQ QBit: alerts and manage-by-exception (monitors, alerts, subscriptions, channels and notifications as standard QQQ tables). Design: [QRun-IO/qqq#1090](https://github.com/QRun-IO/qqq/pull/1090). Phases P1 to P3 are implemented; see README.md for the remaining phases and the core SPI stand-in in `spi/`.
## Build Commands
@@ -16,7 +16,16 @@ This file provides guidance to Claude Code when working with code in this reposi
## Architecture
**Entry point:** `AlertsQBitProducer implements QBitMetaDataProducer<AlertsQBitConfig>` in `com.kingsrook.qbits.alerts`. Component producers in this package (and below) are found by package scanning.
**Entry point:** `AlertsQBitProducer implements QBitMetaDataProducer<AlertsQBitConfig>` in `com.kingsrook.qbits.alerts`. Component producers are found by package scanning, in the `metadata` package only (the `api` package needs the optional Javalin dependency).
Packages:
- `model`: entities, generated from one schema together with the changelog and the test DDL. If you change a table, change all three.
- `engine`: the state machine (`AlertsEngine`), routing (`AlertRouter`), monitors (`MonitorEvaluator`), type sync, the sink and the process listener.
- `delivery`: channels, rendering, redaction and the delivery worker.
- `processes`: the record actions (`AlertsAction`, `AlertsActionSteps`) and the scheduled steps.
- `home`: the Alerts home and `AlertSummaryLoader`.
- `api`: the bell and record-panel routes.
- `spi`: the stand-in for the core producer SPI.
## Naming (owner rule)
+133 -9
View File
@@ -5,30 +5,154 @@
> QQQ QBit: alerts and manage-by-exception (monitors, alerts, subscriptions, channels and notifications as standard QQQ tables).
**Status:** design: [QRun-IO/qqq#1090](https://github.com/QRun-IO/qqq/pull/1090); implementation in progress. Nothing is published yet.
**Status:** design: [QRun-IO/qqq#1090](https://github.com/QRun-IO/qqq/pull/1090). Phases P1 to P3 of the design are implemented: tables, engine, monitors, in-app and email channels, the Alerts app home, and the bell and record-panel API. Not yet published.
## What it does
Any qbit or app reports exceptional conditions ("a person should do something"). The qbit:
- **Records them** as alerts, keyed by `(type, dedupKey)`. Repeats update the open alert; they never duplicate it.
- **Runs the alert lifecycle:** acknowledge, snooze, assign, comment and resolve, with a reopen window, flapping detection and auto-resolve (by the producer, the monitor, or a quiet period).
- **Evaluates monitors**, which are plain data an admin can edit:
- `TABLE_QUERY` and `AGGREGATE`
- `HEARTBEAT`, on a key, a process or a table's newest row
- `PROCESS_FAILED`
- `CODE`, through `AlertCheckInterface`
- **Notifies subscribers** (users, teams or channels) through in-app (the bell), email and email lists. These optional channels are also built in:
- Slack (an Incoming Webhook)
- Microsoft Teams (a Workflows webhook)
- a generic signed webhook
- PagerDuty (Events API v2)
- Prometheus Alertmanager, as a sink
Any channel another qbit registers works too. Every suppressed notification is logged with its reason.
- **Ingests Prometheus Alertmanager** at `POST /qqq/hooks/alerts/alertmanager`, with notifications off for those types, so infrastructure alerts are triaged in one place.
- **Owns the Alerts home:** open alerts by severity, my alerts, needs action, by group, a 30-day trend, the noisiest types, delivery health and recently resolved. Other pages get link-only summaries from `AlertSummaryLoader`.
All data is in standard QQQ tables named `alerts_*`. People change alerts through record actions, never by editing rows.
## User notifications
The qbit also carries ordinary notifications for people (design: [docs/NOTIFICATIONS.md](docs/NOTIFICATIONS.md)):
- **Admins** with `alerts.notification.admin` write notifications in the Notifications table (title, markdown body, severity, category, link, audience, publish and expire times, a sticky banner flag), then use the record actions Preview audience, Send now, Schedule and Retract. Edits after sending show at once; retracting hides it.
- **Audiences** are resolved when sent: all users, roles or groups, holders of a permission, or named users. Each user gets one `alerts_notification_recipient` row, so read, unread and dismissed are per user. Roles need a user directory (`AlertsQBitConfig.withUserDirectory`, an `AlertsUserDirectoryInterface`); without one, "all users" means everyone who has used Alerts.
- **Producers** send with `AlertsRuntime.get(qInstance).sink().notify(new NotificationSignal(...))` (core: `QAlerts.notify`). Alerts a user subscribes to arrive in the bell as ALERT notifications.
- **Ready-made notices** in `AlertsNotices`: `newSignIn`, `apiKeyCreated`, `apiKeyExpiring`, `permissionChanged` (SECURITY), `shared` (SHARE) and `release` (RELEASE, all users). Core has no sign-in or API key events yet, so hosts call these from their authentication customizer and API key screens.
- **Email** is opt-in per user and category (IMMEDIATE, or DAILY_DIGEST at the digest hour in My Alert Settings), through the configured messaging provider; without one it is off. ALERT notifications are not emailed here (alert subscriptions already do), and SECURITY emails carry only the title and link.
- **Failed and partial jobs** notify the person who started them (`notifyFailedJobs`, `jobRunLinkPattern`).
- **Links** must be app paths with one leading slash, or https URLs; backslashes, whitespace and control characters are refused.
- **People** see them in the Next UI bell and notifications page, and choose per-category settings in My Notification Settings (security notices can't be muted).
Grant `getNotificationAdminPermissionNames()` to authors. Viewers' permissions include their own recipient rows and settings.
**Upgrading from 0.1.0-RC.1:** changeset 16 renames the delivery log `alerts_notification` to `alerts_delivery`, and changeset 17 drops `alerts_inbox_item` (bell state only). Both are guarded, so a fresh schema and an RC.1 schema both end up the same.
The UI routes are published as the `alerts` extension (`1.0.0`, established prefix `/alerts`), with
[the OpenAPI fragment](src/main/resources/openapi/qqq-v1/alerts.yaml) and a contract test.
See [UI API and webhook migration](docs/UI-API.md) for operation IDs and the complete Next handoff.
Summary `inboxHref`, item/alert `actions`, and panel `follow.available` are additive. Existing
hrefs, `notificationsHref`, `alertsHref`, `canManage` and deprecated `watching` remain.
Record following belongs to collaboration: `POST /alerts/record-panel/watch` is removed. Old
RECORD subscriptions remain readable without migration. The panel creates no subscriptions;
Next uses its collaboration module when `follow.available` is true. Follower fan-out waits
for core QRun-IO/qqq#1164.
The old Alertmanager path is available for one minor release only via
`withLegacyAlertmanagerPath(true)` (default false). It requires non-strict UI route mode,
returns `Deprecation: true` and `Sunset: Tue, 13 Apr 2027 00:00:00 GMT` on every call, and logs
a warning. Both paths use the same bearer-token check. Strict hosts use the canonical hook.
## Requirements
- Java 21.
- QQQ 4.1 (built against `4.1.0-RC.4`).
- QQQ 4.1 (targets `4.1.0-RC.6`; release pending).
- An RDBMS backend.
- A scheduler, for monitors and email delivery.
- A messaging provider, for email.
- `qqq-middleware-javalin`, for the `/qqq/v1/alerts` routes (optional).
## Install
Not yet published. Once released, add `com.kingsrook.qbits:qbit-alerts` and produce the qbit into your `QInstance`:
```java
new AlertsQBitProducer()
.withQBitConfig(new AlertsQBitConfig().withBackendName("rdbms"))
.withQBitConfig(new AlertsQBitConfig()
.withBackendName("rdbms")
.withSchedulerName("quartz")
.withMessagingProviderName("smtp")
.withFromAddress("alerts@example.com")
.withPublicBaseUrl("https://admin.example.com"))
.produce(qInstance);
```
## Naming
1. **Run the schema.** Include the bundled Liquibase changelog from the host's master changelog. The qbit never runs DDL.
Tables are `alerts_<name>` (lowercase snake_case, backend name equal to the table name). Permissions are `alerts.<action>`.
```yaml
- include: { file: db/liquibase/qbit-alerts/alerts.changelog.sql }
```
## Adopting in another app
2. **Add the security keys to sessions.** Call `AlertsSecurity.applyToSession(qInstance, session)` from your authentication customizer, after the user and permissions are set. The qbit's own home, bell and panel endpoints also add the keys when they are missing.
Follow the QQQ [adoption checklist](https://github.com/QRun-IO/qqq/blob/develop/docs/migration/adoption-checklist.adoc) once the first release is published.
3. **Map roles to permissions.** `AlertsQBitConfig.getViewerPermissionNames()`, `getManagerPermissionNames()` and `getAdminPermissionNames()` list what to grant: `alerts.view`, `alerts.manage` and `alerts.admin`, plus the standard per-table permissions. Nothing is granted by default.
4. **Optional: ESB and Quick Search.** `AlertsIntegrations` names the main tables and searchable fields for the host's ESB and Quick Search configuration.
## Raising alerts
Use the producer SPI from `com.kingsrook.qqq.backend.core.alerts`, released in QQQ 4.1.0-RC.5 ([QRun-IO/qqq#1108](https://github.com/QRun-IO/qqq/pull/1108)). `AlertsQBitProducer` registers the qbit's sink through core's `AlertsInstanceMetaData`, so host producers need only core:
```java
QAlerts.raise(new AlertSignal("cdn.purge.dead")
.withDedupKey("provider:" + providerId)
.withTitle("3 CDN purges failed after retries") // external-safe: no personal data
.withRecordRefs(AlertRecordRef.of("cdn_purge_request", ids)));
```
`QAlerts.resolve(...)` and `QAlerts.heartbeat(...)` reach the same sink. Declare types with core's `QAlertTypeMetaData`. Calls through `QAlerts.raise/resolve` defer to transaction commit when a transaction is present; without this qbit installed, core uses its logging sink.
User notifications remain on `AlertsRuntime.get(qInstance).sink().notify(...)`: core's notification API ([QRun-IO/qqq#1125](https://github.com/QRun-IO/qqq/pull/1125)) ships in RC.6; wiring the retained notification adapter to that API is a separate migration. The four `spi.Notification*` types and `spi.AlertLink` retain their binary signatures for released qbit-easypost-tracking 0.1.x. Use core `AlertLink` for alert signals and `spi.AlertLink` for notification signals until that migration.
## Endpoints (for the Next UI)
| Method | Path | What |
|---|---|---|
| GET | `/qqq/v1/alerts/inbox/summary` | Unread count, highest unread severity, the latest 10 notifications and sticky banners (the bell) |
| GET | `/qqq/v1/alerts/inbox` | The notifications page: `status` (all, unread), `category`, `severity`, `offset`, `limit` |
| POST | `/qqq/v1/alerts/inbox/read` | `{"id": n}`, `{"ids": [..]}`, `{"all": true}`, or `{"alertId": n}` |
| POST | `/qqq/v1/alerts/inbox/unread` | `{"id": n}` or `{"ids": [..]}` |
| POST | `/qqq/v1/alerts/inbox/dismiss` | `{"id": n}`, `{"ids": [..]}` or `{"all": true}` |
| GET | `/qqq/v1/alerts/record-panel?tableName=t&recordId=id` | The "Open alerts" panel for a record (`visible: false` when there is nothing to show) |
| POST | `/qqq/hooks/alerts/alertmanager` | Alertmanager's webhook receiver (version 4). It takes a bearer token whose reference is set by `withAlertmanagerIngestTokenSecretRef`, and is off without one. |
## External channels
Each external channel is an `alerts_channel` row that an admin creates. Its secret is a reference (`secretRef`, an environment variable name or a `${...}` expression), never the value. The minimum detail level is MINIMAL by default.
| Type | Secret | Settings |
|---|---|---|
| `SLACK` | The Incoming Webhook URL | none |
| `TEAMS` | The Workflows "when a webhook request is received" URL | none |
| `WEBHOOK` | The signing key (`whsec_...`) | `{"url": "https://receiver"}` |
| `PAGERDUTY` | The Events API v2 routing key | optional `url`, `source` |
| `ALERTMANAGER` | An optional bearer token | `{"url": "https://alertmanager:9093"}` |
How each one sends:
- **Webhook** bodies are `{type, subject, severity, link, alerts: [...]}`, signed by core's `WebhookSigner` with the Standard Webhooks headers (`webhook-id`, `webhook-timestamp`, `webhook-signature: v1,<base64 HMAC-SHA256 of id.timestamp.body>`). Both raw UTF-8 and `whsec_` base64 secrets keep the same wire format. Core's `WebhookSecret` requires 16 key bytes; a thin adapter zero-pads legacy shorter keys to 16 bytes, which is HMAC-SHA256-equivalent and preserves their signatures. New secrets should use `WebhookSecret.generate()`.
- **PagerDuty** gets one event per alert: `trigger`, `acknowledge` or `resolve`, with `dedup_key` set to the type and key.
- **Alertmanager** alerts carry the labels `qqq_type`, `qqq_group`, `qqq_key` and `qqq_origin="qbit-alerts"`. Ingest ignores alerts with that origin, so nothing loops.
- **Responses:** 2xx is sent. 408, 425, 429, 5xx and network errors are retried. Any other 4xx fails permanently.
- **URLs** must be https, unless the channel's settings say `"allowInsecureHttp": true`, which is meant for local receivers.
## Known limits (v1)
- **Claims are best-effort.** Delivery and monitor claims use a lease, not an atomic conditional update. With several scheduler nodes, run the two scheduled processes on one node, or accept at-least-once delivery.
- **Email threading headers.** `Message-ID` and `In-Reply-To` need core messaging support for custom headers, so they are not set.
- **Recipient visibility.** It is checked through `createAutomatedSessionForUser`. If a host's authentication module can't build a session with permissions for a user, email goes out only for alerts that have no visibility permission and no subject table. In-app delivery is always filtered by the record locks.
- **Outbound HTTP** blocks plain http, but has no full SSRF guard. Channels are admin-only. Core's `SafeHttpClient` (QRun-IO/qqq#1109) replaces the client when it is released.
- **Alertmanager sink:** open alerts are sent with an `endsAt` a week out, not re-posted.
- **Not built yet:** digests, quiet hours, reminders, Micrometer metrics, ROLE and IdP-group team resolvers, escalation, mirrored lock columns and a configurable table namespace. These are the rest of design phases P4 to P6.
## Build
+1 -1
View File
@@ -240,7 +240,7 @@
<module name="Header">
<property name="headerFile" value="checkstyle/license.txt"/>
<property name="fileExtensions" value="java"/>
<property name="ignoreLines" value="3"/>
<property name="ignoreLines" value="2"/>
</module>
<module name="SuppressWarningsFilter"/>
</module>
+2 -6
View File
@@ -1,15 +1,11 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
+12 -1
View File
@@ -1,3 +1,14 @@
# QBit Alerts: design
The design for this qbit is tracked in [QRun-IO/qqq#1090](https://github.com/QRun-IO/qqq/pull/1090). This repository implements it; the implementation is in progress.
The design for this qbit is tracked in [QRun-IO/qqq#1090](https://github.com/QRun-IO/qqq/pull/1090). This repository implements it. Phases P1 to P3 are built (see README.md); P4 to P6 remain.
Deviations from the design, and why:
- **UI API and record following:** the RC.6 alerts extension, collaboration ownership of follow, and machine webhook migration are specified in [UI-API.md](UI-API.md). Existing RECORD watch subscriptions remain readable without migration.
- **Alerts use core's RC.5 SPI** (QRun-IO/qqq#1108), including sink registration in core instance metadata. Only notification types and their `AlertLink` signature dependency remain in `spi/`, preserving released producers until QRun-IO/qqq#1125 ships in RC.6.
- **Visibility checks 1 to 3 (section 7.2)** are enforced by record security locks on session keys (`alerts_permission`, `alerts_readable_table`), not by a pre-query customizer. QQQ has no pre-query customizer, and locks also apply to counts, exports and the API.
- **Heartbeats** are stored in an extra table, `alerts_heartbeat`.
- **Claims** are leases, not atomic conditional updates (see README.md, Known limits).
- **Email threading headers** wait for core messaging support.
- **The delivery log is `alerts_delivery`** (the design calls it `alerts_notification`), and **`alerts_inbox_item` is retired**: user notifications took those roles (NOTIFICATIONS.md section 2).
User notifications (announcements, job failures, shares, security notices, releases and marketing), the recipient model and the Next UI notification center are designed in [NOTIFICATIONS.md](NOTIFICATIONS.md), with the owner decisions of 2026-10-13.
+259
View File
@@ -0,0 +1,259 @@
# QBit Alerts: user notifications (design)
**Status:** approved design, built in phases (section 11). It extends the alerts model in
[QRun-IO/qqq#1090](https://github.com/QRun-IO/qqq/pull/1090) (`docs/specs/2026-10-12-qbit-alerts-design.md`); it does not add a parallel system.
## 0. Summary
The Alerts qbit also carries ordinary user notifications: announcements an admin writes, a user's own
failed jobs, alerts they subscribe to, things shared or assigned to them, security notices, and release or
marketing messages. Every notification is a row in a standard QQQ table, and every person it reaches gets
one recipient row. The Next UI bell, which today shows only alerts, becomes a notification center: an
unread badge, a popover, mark read, dismiss, a "View all" page with filters, and a banner for sticky
critical items. Admins create, edit, schedule, send, retract and delete notifications in the admin
through standard record screens and record actions.
**Owner requirement (verbatim, 2026-10-13):** "the alerts qbit should work for normal notifications etc
too. and if installed and working, the next UI should support it via the 'bell' in the top nav. it should
show you notifications, allow you to mark them as read etc. in the admin system, the system admins should
be able to create notifications, edit, remove, etc. we should be able to send notifications to all users in
a smart way, or just some etc. and a users own alerts or errors or warnings should work through that
system as well"
## 1. Owner decisions (2026-10-13)
1. **Channels.** In-app (the bell and the notifications page) always. Email is opt-in per user, by
severity or as a daily digest. Slack stays a group or monitor channel only, never per user.
2. **Audience.** Dynamic audiences: all users, groups or roles, holders of a permission, or named users.
The audience is resolved at send time and materialized as one recipient row per user, so read,
unread and dismissed are tracked per user.
3. **Automatic sources into a user's bell:**
- their failed or partial jobs (processes, ETL, imports and exports they started), linked to the run;
- alerts they subscribe to;
- things assigned or shared to them (a notebook share, a record lock, a pending approval);
- security notices (new sign-in, API key created or expiring, permission change);
- application releases and marketing notifications (authored by admins or emitted by apps, such as
"new version released" or a marketing-qbit campaign), sent to an audience.
**Owner decisions (2026-10-12): all recommendations accepted.** Every open question below (section 12)
is decided as recommended.
## 2. How it fits the alerts model
| Before (0.1.0-RC.1) | After |
|---|---|
| `alerts_notification` = the delivery log (one row per send attempt per channel) | Renamed `alerts_delivery` ("Delivery Log"). Same columns, same role. |
| `alerts_inbox_item` = one alert in one user's bell | Retired. In-app alert delivery writes an `alerts_notification` (category ALERT, linked to the alert) and a recipient row. |
| The bell shows alerts only | The bell shows every notification category, alerts included. |
| `alerts_user_preference` (quiet hours, digest hour, time zone) | Kept. Notification email settings per category live in `alerts_notification_preference`, and reuse its time zone and digest hour. |
| Producer SPI: `QAlerts.raise/resolve/heartbeat` | Plus `QAlerts.notify(NotificationSignal)` (section 6). |
The rename and the retirement break the changelog's additive-only rule once, before GA. Nobody runs
0.1.0-RC.1 in production. Changeset 16 renames the table, its key and its indexes, and changeset 17 drops
`alerts_inbox_item` (it holds only bell state). Both are guarded by preconditions, so they are safe on a
fresh schema and on an RC.1 schema.
## 3. Tables
All are standard QQQ tables with record screens, the API, audit and ESB events, secured by permissions
and record locks, never hidden.
### 3.1 `alerts_notification` (Notifications)
| Field | Type | Notes |
|---|---|---|
| `title` | string(200), required | Plain text |
| `body` | text | Markdown, rendered safely (no raw HTML) |
| `severity` | INFO / SUCCESS / WARNING / ERROR / CRITICAL | Default INFO |
| `category` | SYSTEM / JOB / SECURITY / RELEASE / MARKETING / SHARE / ALERT | Default SYSTEM |
| `sourceName` | string | Who emitted it: `admin`, `qbit-alerts`, a qbit or app name |
| `sourceKey` | string | Dedup key from producers (for example `process:<uuid>`). A second notify with the same key and audience updates the first. |
| `sourceTableName`, `sourceRecordId` | string | The record it is about (an alert, a run, a share) |
| `linkUrl`, `linkLabel` | string | A deep link (a record, a table filter, a run, or an https URL) |
| `audienceType` | ALL_USERS / ROLES / PERMISSION / USERS | |
| `audienceValue` | text | Comma-separated role names, one permission, or user ids |
| `publishAt`, `expireAt` | timestamp | Not shown before publishAt; hidden and purged after expireAt |
| `sticky` | boolean | A top banner until the user dismisses it (meant for CRITICAL) |
| `status` | DRAFT / SCHEDULED / SENT / RETRACTED | Default DRAFT |
| `authorUserId` | string | Set on insert |
| `sentAt`, `retractedAt`, `recipientCount`, `readCount` | | Kept by the qbit |
Record screen: identity (title, severity, category, status), Message (body, link), Audience, Schedule,
the Recipients child list, and System.
Edits after sending change what recipients see (the bell reads the notification). Retracting hides it
everywhere. Deleting it deletes its recipient rows.
### 3.2 `alerts_notification_recipient` (Notification Recipients)
A child of the notification: one row per user, unique (`notificationId`, `userId`).
`notificationId`, `userId`, `deliveredAt`, `readAt`, `dismissedAt`, `emailedAt`, `emailStatus`
(NONE / PENDING / SENT / DIGESTED / SKIPPED / FAILED).
Users see and change only their own rows (owner lock on `userId`). Only `readAt` and `dismissedAt` are
editable; inserts and deletes are the qbit's.
### 3.3 `alerts_notification_preference` (My Notification Settings)
One row per user and category, unique (`userId`, `category`); a missing row means the defaults.
`userId`, `category`, `inAppMuted` (boolean; refused for SECURITY), `emailMode` (OFF / IMMEDIATE /
DAILY_DIGEST, default OFF), `emailMinSeverity` (default WARNING). It is owner-locked on `userId`. The
digest hour and time zone come from `alerts_user_preference`.
## 4. Audiences
`AlertsAudienceResolver` resolves an audience to user ids at send time:
| Audience | Resolved to |
|---|---|
| ALL_USERS | Every active user in the directory |
| ROLES | Directory users with any of the named roles or groups |
| PERMISSION | Directory users whose session holds the permission (`createAutomatedSessionForUser`) |
| USERS | The named user ids, as given |
**The user directory** is an SPI, `AlertsUserDirectoryInterface` (`listUsers()` returning id, label,
email and roles), set with `AlertsQBitConfig.withUserDirectory(QCodeReference)`. Without one, the directory
is every user who has used Alerts (a row in `alerts_user_preference`, created the first time a user opens
the bell). That is "all users who sign in", with no host code.
Resolution is capped by `maxAudienceSize` (default 50,000). Recipient rows are inserted in batches of 500.
## 5. Admin
The Notifications table is a main nav entry in the Alerts app (it needs `alerts.notification.admin`).
Admins use the standard create, edit and delete screens. Record actions are streamed-ETL processes with the
standard Review and Result summary lines, never nav entries:
| Action | On | Review, then Result |
|---|---|---|
| **Preview audience** | DRAFT or SCHEDULED (one) | "Would reach 42 users", plus up to 10 sample names. Writes nothing. |
| **Send now** | DRAFT or SCHEDULED (bulk) | "Will send 2 notifications to 57 recipients (1 already sent, skipped)", then "Sent" |
| **Schedule** | DRAFT (bulk), needing a future `publishAt` | Sets SCHEDULED. The delivery job sends it when `publishAt` passes. |
| **Retract** | SENT (bulk) | Sets RETRACTED, which hides it from every bell |
The Alerts home gets one link-only line, "Notifications: 3 scheduled, 12 sent this week", for
notification admins. The home stays the only Alerts dashboard.
## 6. Producer SPI
The notification API below is planned in [QRun-IO/qqq#1125](https://github.com/QRun-IO/qqq/pull/1125)
for 4.1.0-RC.6. This branch now targets 4.1.0-RC.6 for the UI extension API. The retained qbit notification
adapter still needs a separate migration to core `QAlerts.notify`; the following remains the
target integration shape:
```java
QAlerts.notify(new NotificationSignal("Your export failed")
.withBody("**Orders export** stopped after 1,200 rows: the file server refused the upload.")
.withSeverity(NotificationSeverity.ERROR)
.withCategory(NotificationCategory.JOB)
.withSourceKey("process:" + processUUID)
.withLink(AlertLink.toUrl("/app/orders", "Orders"))
.withAudience(NotificationAudience.user(userId)));
```
- `AlertSinkInterface` gets a default method, `notify(NotificationSignal)`, that logs; existing sinks keep
working. `LoggingAlertSink` logs at INFO. The qbit's sink queues the signal like an alert signal.
- The guarantees match `raise`: it never throws or blocks, it waits for the commit when a transaction is
open, and bad input is counted.
- `NotificationAudience`: `allUsers()`, `roles(...)`, `permission(p)`, `users(...)`, `user(id)`.
- Until RC.6 ships, the qbit keeps `spi.NotificationSignal`, `NotificationAudience`,
`NotificationCategory`, `NotificationSeverity` and `AlertLink`, and hosts call
`AlertsRuntime.get(qInstance).sink().notify(...)`. Their binary signatures remain unchanged for
released qbit-easypost-tracking 0.1.x. The return type of `sink()` remains `QbitAlertsSink`;
there is no local sink interface. This direct notification path queues immediately; the
transaction-aware `QAlerts.notify` guarantees above describe the planned core API.
### 6.1 Automatic sources
| Source | How | Category |
|---|---|---|
| Failed or partial jobs | The qbit's process lifecycle listener: a run that fails, or completes with error summary lines, notifies the user who started it (the session user; system runs are skipped). The link is the run's table, or `jobRunLinkPattern` with `{processName}` and `{processUUID}`. Turn it off with `notifyFailedJobs(false)`. | JOB |
| Alerts they subscribe to | The router's in-app channel writes an ALERT notification per alert (sourceKey `alert:<id>`) and a recipient row per routed user. A repeat or reopen marks it unread again. | ALERT |
| Shares, record locks, approvals | Producers call `QAlerts.notify(... user(id))`. The first wiring is the SQL Workbench notebook share in kof22. | SHARE |
| Security notices | `AlertsSecurityNotices` (new sign-in, API key created, API key expiring, permission change). Core has no authentication events today, so hosts call it from their authentication customizer. A core hook is follow-up work (section 12, Q5). Security is never mutable in-app. | SECURITY |
| Releases and marketing | Admin-authored notifications, or producers with an audience | RELEASE, MARKETING |
## 7. Delivery
- **In-app:** recipient rows. The bell shows rows that are not dismissed, of SENT notifications whose
`publishAt` has passed and whose `expireAt` has not.
- **Email** (phase e): through the QQQ messaging provider when configured; otherwise inert. IMMEDIATE
sends from the delivery job. DAILY_DIGEST sends one email per user at their digest hour, listing their
unread notifications since the last digest. A muted category is skipped. Email never includes a body
for SECURITY beyond the title and a link.
- **Slack** stays a channel for alert groups and monitors only.
## 8. Next UI bell and page
Gating is unchanged from #85: no bell and zero requests unless `metaData.apps.alerts` is present.
- **Badge:** the unread count (99+), red when an unread item is CRITICAL. The poller is tiny and lives in the
main bundle. It polls every `pollSeconds` (60), backs off to 5 minutes on errors, and pauses while the tab
is hidden. QQQ has no SSE today.
- **Popover** (lazy chunk): newest first, a severity icon, the title, the source, a relative time, and a
link. You can mark one read or unread, or dismiss it, and the footer has "Mark all read" and "View all".
- **Page** `/app/notifications` (lazy route): filters (All or Unread, category, severity), paging, a markdown
body, and the same actions.
- **Banner:** sticky, undismissed, unexpired items show above the page content until dismissed.
- **Budget:** total JS 1100 KB. The badge adds well under 1 KB to first load; the popover and the page are
lazy chunks with their own `lazyChunks` budget entry.
### 8.1 API (`/qqq/v1/alerts`, session-authenticated, `alerts.view`)
| Method | Path | Body or query | Returns |
|---|---|---|---|
| GET | `/inbox/summary` | | `{unreadCount, highestUnreadSeverity, items[≤10], banners[], pollSeconds, notificationsHref}` |
| GET | `/inbox` | `?status=all\|unread&category=&severity=&offset=0&limit=25` | `{items[], total, offset, limit}` |
| POST | `/inbox/read` | `{id}` or `{ids:[..]}` or `{all:true}` (`{alertId}` still works) | `{updated}` |
| POST | `/inbox/unread` | `{id}` | `{updated}` |
| POST | `/inbox/dismiss` | `{id}` or `{ids:[..]}` or `{all:true}` | `{updated}` |
An item is `{id, notificationId, title, body, severity, category, source, href, linkLabel,
deliveredAt, age, unread, sticky}`. `id` is the recipient row id. `body` appears only in `/inbox` and in
banners. `highestUnreadSeverity` is one of the five severities. Every call works in the caller's
session, so the record locks apply.
## 9. Security
- `alerts.notification.admin`: author, send, schedule, retract and delete notifications, and read every
recipient row (the `alerts_user` all-access key).
- `alerts.view`: the bell, the page, their own recipient rows (read and edit) and their own notification
settings.
- Recipient and preference rows are owner-locked on `userId`. Notification bodies reach a user only
through their own recipient rows.
- Markdown is rendered without raw HTML. Links must be relative app paths or https.
## 10. Retention
`expireAt` hides a notification at once. The delivery job's purge step deletes notifications (and their
recipients) whose `expireAt` is more than 7 days past, plus SENT or RETRACTED notifications older than
`notificationRetentionDays` (default 180).
## 11. Phases
| Phase | Scope |
|---|---|
| a | Tables, the rename and retirement, admin screens and actions, audiences and recipients, the bell API, ALERT notifications |
| b | Next UI: badge, popover, page, banner |
| c | Producer SPI (core PR plus the stand-in), job failures |
| d | Security notices, shares, release and marketing producers |
| e | Email: immediate and daily digest |
## 12. Questions, with the recommendations the owner accepted
1. Rename the delivery log rather than pick another name? **Yes**, before GA.
2. Copy notification content per recipient? **No**: recipients read the notification, so edits and
retractions apply at once.
3. Users added after a send? **They don't get it.** Resolution happens at send time, per decision 2.
4. Default email? **Off** for every category until the user opts in.
5. Core authentication events? **Later.** Hosts call `AlertsSecurityNotices` from their authentication
customizer until core offers a sign-in event.
6. Server-sent events? **Later.** Polling with backoff is enough at 60 s.
## UI contract
The implemented UI routes and additive action/follow metadata are specified in [UI-API.md](UI-API.md),
with the generated fragment at `src/main/resources/openapi/qqq-v1/alerts.yaml`. Record following
belongs to collaboration; the old alerts panel watch route is removed.
+108
View File
@@ -0,0 +1,108 @@
# Alerts UI API and webhook migration
The qbit targets QQQ **4.1.0-RC.6** (pending release). `AlertsQBitProducer` registers the
`alerts` `MiddlewareSpecExtension`, version `1.0.0`, with the established `/alerts` prefix.
`withRegisterRoutes(false)` opts out of both the extension and webhook registration.
The six JSON specs extend `AbstractJsonEndpointSpec`; existing `AlertsApi` logic continues
to enforce caller permissions, recipient ownership and alert visibility.
The deterministic fragment is `src/main/resources/openapi/qqq-v1/alerts.yaml`. Next should
vendor it. The live `/qqq/v1/openapi.yaml` includes these operations, and `/qqq/v1/version`
discovers the `alerts` extension so clients need not infer installation from an app name.
| Method | Path | operationId |
| --- | --- | --- |
| GET | `/qqq/v1/alerts/inbox/summary` | `alertsInboxSummary` |
| GET | `/qqq/v1/alerts/inbox` | `alertsInbox` |
| POST | `/qqq/v1/alerts/inbox/read` | `alertsInboxRead` |
| POST | `/qqq/v1/alerts/inbox/unread` | `alertsInboxUnread` |
| POST | `/qqq/v1/alerts/inbox/dismiss` | `alertsInboxDismiss` |
| GET | `/qqq/v1/alerts/record-panel` | `alertsRecordPanel` |
All existing query parameters, selector precedence, paging defaults and clamps, status
codes, JSON content-type requirements, and response keys remain. IDs refer to recipient
rows for inbox operations; legacy `alertId` selectors remain accepted. `all:true` applies
only to read/dismiss. Items in a summary omit `body`; page items and banners include it.
Nullable fields remain serialized as JSON null.
## Next handoff: additive payload fields
- Summary adds `inboxHref`, currently `/app/notifications`. Retain and honor the existing
`notificationsHref` and `alertsHref` fields for older clients.
- Every inbox item (including banners) adds `actions`: `name`, `label`, `operationId`.
An unread item offers `read` (`alertsInboxRead`); a read item offers `unread`
(`alertsInboxUnread`); both offer `dismiss` (`alertsInboxDismiss`). Invoke the operation
from the fragment with `{ "id": item.id }`. Existing item `href` semantics are unchanged.
- Every record-panel alert adds `actions`: `name`, `label`, `processName`, `href`.
Managers see `acknowledge` for OPEN alerts and `snooze` for panel alerts; viewers get an
empty list. The href is complete, including the process, alert id and table arguments:
`/app/alertsAcknowledge?recordsParam=recordIds&recordIds=9&tableName=alerts_alert`.
Clients follow the provided href without constructing a process or table name. Server
process authorization still applies when an action executes.
- Panel adds `follow: { "available": boolean }`, true exactly when core supplemental
`MiddlewareSpecExtensionsMetaData` contains an extension named `collaboration`. No
collaboration dependency or URL is embedded here. Next uses its collaboration module
to determine the follow endpoint and current follow state.
The provided Next `main` checkout had no alerts client at implementation time. The reviewed
client was `feature/notification-center:src/lib/api/alerts.ts` and its
`src/components/alerts/*` components. Its current process href and watch assumptions are
covered by the migration above.
## Removed watch operation
`POST /qqq/v1/alerts/record-panel/watch` and `AlertsApi.watchRecord` are removed. No panel
request creates a RECORD subscription. `alerts_subscription` continues to handle alert-type
and scope subscriptions; existing record-scoped watch rows are deprecated and remain readable
(and retain their existing routing behavior). No rows are migrated or deleted. The panel's
`watching` boolean is retained for compatibility and reports only those legacy rows; it must
not be used as collaboration follow state.
There is no follower fan-out yet. `AlertRouter.destinations` contains
`STAND-IN(core=QRun-IO/qqq#1164, removeBy=4.1.0-RC.7)` at the point where follower destinations
will join the existing recipient visibility and suppression pipeline.
## Alertmanager machine webhook
Canonical operation: **POST `/qqq/hooks/alerts/alertmanager`**. This is a raw machine route
outside the UI API and has no UI operationId. It preserves the bearer token, secret reference,
JSON request and `{raised, resolved, ignored}` response. No QQQ user session is required.
The previous **POST `/qqq/v1/alerts/ingest/alertmanager`** is an opt-in raw alias:
```java
new AlertsQBitConfig()
.withLegacyAlertmanagerPath(true)
.withAlertmanagerIngestTokenSecretRef("ALERTMANAGER_TOKEN");
```
`legacyAlertmanagerPath` defaults to false. Core `UiApiRouteAuditor` compares every raw v1
route against specs and offers no machine-webhook exemption. Therefore enabling the alias
requires non-strict UI route mode; strict startup rejects it. It is intentionally absent
from the UI fragment. Default hosts and all application-server tests run strict successfully.
The migration-only raw provider is tested separately, including strict-auditor rejection.
Both paths call the same handler and authenticate against the same secret. Every alias call,
including rejected authentication, logs a warning and carries:
```http
Deprecation: true
Sunset: Tue, 13 Apr 2027 00:00:00 GMT
```
The alias is supported for the 0.1 minor line only and scheduled for removal in 0.2; the
published calendar sunset is 13 April 2027. Move receivers before either retirement boundary.
No automatic runtime cutoff is applied by these informational headers.
## Verification
Use the Maven wrapper. The committed BOM version is RC.6; while it is unreleased, verify with
an already installed local core build:
```sh
./mvnw -B verify -Dqqq.snapshot.version=4.1.0-ARCHRC6-SNAPSHOT
```
Regenerate intentionally with `-Dtest=AlertsApiContractTest -Dalerts.openapi.update=true test`
(and the same local version override). Normal tests compare the fragment without rewriting it.
Checkstyle uses `checkstyle/config.xml` and the repository's existing short Apache headers.
+48 -2
View File
@@ -72,6 +72,26 @@
<artifactId>qqq-backend-core</artifactId>
</dependency>
<!-- The /qqq/v1/alerts routes (bell, record panel). Hosts that serve QQQ -->
<!-- through Javalin already have it; the qbit works without it. -->
<dependency>
<groupId>com.kingsrook.qqq</groupId>
<artifactId>qqq-middleware-javalin</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.kingsrook.qqq</groupId>
<artifactId>qqq-backend-module-rdbms</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.2.220</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
@@ -87,6 +107,32 @@
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.6.0</version>
<dependencies>
<dependency>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
<version>14.3.0</version>
</dependency>
</dependencies>
<configuration>
<configLocation>checkstyle/config.xml</configLocation>
<includeTestSourceDirectory>true</includeTestSourceDirectory>
<violationSeverity>warning</violationSeverity>
</configuration>
<executions>
<execution>
<id>checkstyle</id>
<phase>validate</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
@@ -138,14 +184,14 @@
<profiles>
<!-- Built against qqq 4.1 (QBitMetaDataProducer). Until qbit-build-parent -->
<!-- imports the released 4.1 BOM, this profile is active by default and -->
<!-- imports qqq-bom-pom 4.1.0-RC.4 ahead of the parent's 4.0.0 BOM. -->
<!-- imports qqq-bom-pom 4.1.0-RC.6 ahead of the parent's 4.0.0 BOM. -->
<profile>
<id>qqq-snapshot</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<qqq.snapshot.version>4.1.0-RC.4</qqq.snapshot.version>
<qqq.snapshot.version>4.1.0-RC.6</qqq.snapshot.version>
</properties>
<dependencyManagement>
<dependencies>
@@ -0,0 +1,106 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.kingsrook.qbits.alerts.model.AlertsAlert;
import com.kingsrook.qbits.alerts.model.AlertsMonitor;
import com.kingsrook.qbits.alerts.model.AlertsType;
/*******************************************************************************
** Opt-in hooks for wiring the main Alerts tables into a host's ESB and
** Quick Search without the qbit depending on either module: the host passes
** these names and field lists to its own qqq-esb (EsbTableMetaData
** publications) and qbit-quick-search (SearchableTableConfig) configuration.
**
** The main tables are Alerts, Monitors and Alert Types. What leaves the
** database: an alert event carries the alert row (title, summary, details,
** status, severity, ...); search hits are re-read through the tables'
** record locks, so a user only finds alerts they could open.
*******************************************************************************/
public final class AlertsIntegrations
{
/*******************************************************************************
** A table for Quick Search: field weights (most important first), the
** field basepull compares, and how a hit is labelled.
**
** @param tableName the table
** @param fieldWeights searchable fields and weights
** @param basepullTimestamp the field that moves when a row changes
** @param recordLabelFormat the hit label format
** @param recordLabelFields fields for the format
*******************************************************************************/
public record SearchableTable(String tableName, Map<String, Integer> fieldWeights, String basepullTimestamp, String recordLabelFormat, List<String> recordLabelFields)
{
}
/*******************************************************************************
** Hooks only.
*******************************************************************************/
private AlertsIntegrations()
{
}
/*******************************************************************************
** The tables whose insert / update / delete events a host may publish to
** its ESB.
*******************************************************************************/
public static List<String> esbTableNames()
{
return (List.of(AlertsAlert.TABLE_NAME, AlertsMonitor.TABLE_NAME, AlertsType.TABLE_NAME));
}
/*******************************************************************************
** The main tables as Quick Search tables.
*******************************************************************************/
public static List<SearchableTable> quickSearchTables()
{
Map<String, Integer> alert = new LinkedHashMap<>();
alert.put("title", 10);
alert.put("summary", 5);
alert.put("alertTypeName", 4);
alert.put("dedupKey", 3);
alert.put("sourceName", 1);
Map<String, Integer> monitor = new LinkedHashMap<>();
monitor.put("name", 10);
monitor.put("description", 4);
monitor.put("sourceName", 1);
Map<String, Integer> type = new LinkedHashMap<>();
type.put("label", 10);
type.put("name", 8);
type.put("description", 4);
type.put("sourceName", 1);
return (List.of(
new SearchableTable(AlertsAlert.TABLE_NAME, alert, "modifyDate", "%s", List.of("title")),
new SearchableTable(AlertsMonitor.TABLE_NAME, monitor, "modifyDate", "Monitor: %s", List.of("name")),
new SearchableTable(AlertsType.TABLE_NAME, type, "modifyDate", "Alert type: %s", List.of("label"))));
}
}
@@ -0,0 +1,112 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts;
import java.util.Map;
import com.kingsrook.qqq.backend.core.actions.permissions.AvailablePermission;
import com.kingsrook.qqq.backend.core.actions.permissions.CustomPermissionChecker;
import com.kingsrook.qqq.backend.core.actions.permissions.PermissionSubType;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QPermissionDeniedException;
import com.kingsrook.qqq.backend.core.model.actions.AbstractActionInput;
import com.kingsrook.qqq.backend.core.model.metadata.code.InitializableViaCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReferenceWithProperties;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.MetaDataWithName;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.MetaDataWithPermissionRules;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.PermissionLevel;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.QPermissionRules;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import com.kingsrook.qqq.backend.core.utils.ValueUtils;
/*******************************************************************************
** Gates the Alerts app, widgets and processes on one exact permission name
** (alerts.view, alerts.manage or alerts.admin), and lists that name among
** the instance's available permissions so hosts can grant it.
*******************************************************************************/
public class AlertsPermissionChecker implements CustomPermissionChecker, InitializableViaCodeReference
{
public static final String PERMISSION_PROPERTY = "permissionName";
private String permissionName;
/*******************************************************************************
** Permission rules requiring the named permission.
*******************************************************************************/
public static QPermissionRules rules(String permissionName)
{
return (new QPermissionRules()
.withLevel(PermissionLevel.HAS_ACCESS_PERMISSION)
.withCustomPermissionChecker(new QCodeReferenceWithProperties(AlertsPermissionChecker.class, Map.of(PERMISSION_PROPERTY, permissionName))));
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public void initialize(QCodeReference codeReference)
{
if(codeReference instanceof QCodeReferenceWithProperties withProperties)
{
this.permissionName = ValueUtils.getValueAsString(withProperties.getProperties().get(PERMISSION_PROPERTY));
}
}
/*******************************************************************************
** Deny unless the session holds the permission (fail closed).
*******************************************************************************/
@Override
public void checkPermissionsThrowing(AbstractActionInput actionInput, MetaDataWithPermissionRules metaDataWithPermissionRules) throws QPermissionDeniedException
{
QSession session = QContext.getQSession();
if(permissionName == null || session == null || !session.hasPermission(permissionName))
{
throw (new QPermissionDeniedException("Permission denied."));
}
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public boolean handlesBuildAvailablePermission()
{
return (true);
}
/*******************************************************************************
** The exact permission name.
*******************************************************************************/
@Override
public AvailablePermission buildAvailablePermission(QPermissionRules rules, PermissionSubType permissionSubType, String baseName, MetaDataWithName metaDataWithName, String objectType)
{
AvailablePermission permission = buildBaseAvailablePermission(rules, permissionSubType, metaDataWithName, objectType);
return (permission == null || permissionName == null ? null : permission.withName(permissionName));
}
}
@@ -0,0 +1,113 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import com.kingsrook.qbits.alerts.engine.AlertsDb;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.ChannelType;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.DeliveryMode;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.ScopeType;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.SubscriberType;
import com.kingsrook.qbits.alerts.model.AlertsSubscription;
import com.kingsrook.qbits.alerts.model.AlertsUserPreference;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.session.QSession;
/*******************************************************************************
** First visit set-up for a user (the home, the bell or the record panel):
** - My Alert Settings is created with defaults (in-app on; email on once
** they add an address);
** - the bootstrap rule (design 5.4): an alerts.admin holder with no
** subscriptions gets one in-app subscription to everything at the
** configured minimum severity (ERROR by default). With no subscriptions
** otherwise, a fresh install notifies nobody.
*******************************************************************************/
public final class AlertsPreferences
{
private static final Set<String> ENSURED = ConcurrentHashMap.newKeySet();
/*******************************************************************************
** Set-up only.
*******************************************************************************/
private AlertsPreferences()
{
}
/*******************************************************************************
** Make sure the session's user has settings (and, for admins, the
** bootstrap subscription). Cheap after the first call per user.
*******************************************************************************/
public static void ensure(AlertsRuntime runtime, QSession session) throws QException
{
String userId = AlertsSecurity.userId(session);
if(userId == null || !session.hasPermission(AlertsQBitConfig.PERMISSION_VIEW) || ENSURED.contains(userId))
{
return;
}
boolean admin = session.hasPermission(AlertsQBitConfig.PERMISSION_ADMIN);
String fullName = session.getUser() == null ? null : session.getUser().getFullName();
runtime.asSystem(() ->
{
if(AlertsDb.first(AlertsUserPreference.TABLE_NAME, AlertsDb.eq("userId", userId)) == null)
{
AlertsDb.insert(AlertsUserPreference.TABLE_NAME, new QRecord()
.withValue("userId", userId)
.withValue("userLabel", fullName == null ? userId : fullName)
.withValue("inAppEnabled", true)
.withValue("emailEnabled", true)
.withValue("quietBypassSeverity", "CRITICAL")
.withValue("digestHour", 8));
}
if(admin && runtime.getConfig().getBootstrapMinSeverity() != null && AlertsDb.first(AlertsSubscription.TABLE_NAME, AlertsDb.eq("userId", userId)) == null)
{
QRecord inApp = runtime.getChannels().defaultChannel(ChannelType.IN_APP);
AlertsDb.insert(AlertsSubscription.TABLE_NAME, new QRecord()
.withValue("subscriberType", SubscriberType.USER.name())
.withValue("userId", userId)
.withValue("scopeType", ScopeType.ALL.name())
.withValue("minSeverity", runtime.getConfig().getBootstrapMinSeverity().name())
.withValue("events", "RAISED,ESCALATED,REMINDER,RESOLVED")
.withValue("deliveryMode", DeliveryMode.IMMEDIATE.name())
.withValue("channelOverrideIds", String.valueOf(inApp.getValue("id")))
.withValue("enabled", true)
.withValue("createdByUserId", "alerts (bootstrap rule)"));
}
return (null);
});
ENSURED.add(userId);
}
/*******************************************************************************
** Forget who was set up (tests).
*******************************************************************************/
public static void reset()
{
ENSURED.clear();
}
}
@@ -17,34 +17,122 @@
package com.kingsrook.qbits.alerts;
import java.util.ArrayList;
import java.util.List;
import com.kingsrook.qbits.alerts.model.AlertsAlert;
import com.kingsrook.qbits.alerts.model.AlertsChannel;
import com.kingsrook.qbits.alerts.model.AlertsDelivery;
import com.kingsrook.qbits.alerts.model.AlertsEvent;
import com.kingsrook.qbits.alerts.model.AlertsGroup;
import com.kingsrook.qbits.alerts.model.AlertsHeartbeat;
import com.kingsrook.qbits.alerts.model.AlertsMonitor;
import com.kingsrook.qbits.alerts.model.AlertsMute;
import com.kingsrook.qbits.alerts.model.AlertsNotification;
import com.kingsrook.qbits.alerts.model.AlertsNotificationPreference;
import com.kingsrook.qbits.alerts.model.AlertsNotificationRecipient;
import com.kingsrook.qbits.alerts.model.AlertsRecordRef;
import com.kingsrook.qbits.alerts.model.AlertsSubscription;
import com.kingsrook.qbits.alerts.model.AlertsTeam;
import com.kingsrook.qbits.alerts.model.AlertsTeamMember;
import com.kingsrook.qbits.alerts.model.AlertsType;
import com.kingsrook.qbits.alerts.model.AlertsUserPreference;
import com.kingsrook.qqq.backend.core.alerts.AlertSeverity;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitConfig;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
/*******************************************************************************
** Host-facing configuration for the Alerts QBit.
** Host-facing configuration for the Alerts QBit (design section 8).
**
** Tables are named alerts_<name> (lowercase snake_case, backend name equal
** to the table name); permissions are alerts.<action>.
** Tables are named alerts_(name) (lowercase snake_case; the backend table and
** column names are the snake_case forms, matching the bundled Liquibase
** changelog). Permissions:
** - alerts.view: the Alerts app, home and bell; read the alerts the user may
** see; comment; subscribe themselves; their own settings and inbox.
** - alerts.manage: acknowledge, snooze, resolve, reopen, assign, mute.
** - alerts.admin: monitors, types, groups, teams, channels, every
** subscription, the delivery log, retries.
** - alerts.notification.admin: write, send, schedule, retract and delete
** user notifications (docs/NOTIFICATIONS.md).
** Each table also has QQQ's standard per-table permissions
** (alerts_alert.read, ...); getViewerPermissionNames,
** getManagerPermissionNames and getAdminPermissionNames list what to grant
** per role. Nothing is granted by default.
*******************************************************************************/
public class AlertsQBitConfig implements QBitConfig
{
public static final String TABLE_NAME_PREFIX = "alerts_";
public static final String PERMISSION_BASE_NAME = "alerts";
public static final String PERMISSION_VIEW = "alerts.view";
public static final String PERMISSION_MANAGE = "alerts.manage";
public static final String PERMISSION_ADMIN = "alerts.admin";
public static final String PERMISSION_NOTIFICATION_ADMIN = "alerts.notification.admin";
public static final String APP_NAME = "alerts";
private Boolean legacyAlertmanagerPath = false;
private String backendName;
private String schedulerName;
private String messagingProviderName;
private String fromAddress;
private String publicBaseUrl;
private Integer reopenWindowMinutes = 30;
private Integer flapThreshold = 5;
private Integer flapWindowMinutes = 60;
private Integer maxOpenPerMonitor = 50;
private Integer monitorTimeoutSeconds = 15;
private AlertSeverity bootstrapMinSeverity = AlertSeverity.ERROR;
private Integer evaluateEverySeconds = 30;
private Integer deliverEverySeconds = 15;
private List<QCodeReference> channelTypes = new ArrayList<>();
private String alertmanagerIngestTokenSecretRef;
private Boolean registerRoutes = true;
private Boolean synchronousSink = false;
private QCodeReference userDirectory;
private Integer maxAudienceSize = 50_000;
private Integer notificationRetentionDays = 180;
private Boolean notifyFailedJobs = true;
private String jobRunLinkPattern;
private transient AlertsRuntime runtime;
/*******************************************************************************
** The backend must be named.
** The backend must be named and exist; numbers must be positive.
*******************************************************************************/
@Override
public void validate(QInstance qInstance, List<String> errors)
{
assertCondition(StringUtils.hasContent(backendName), "backendName is required for the Alerts QBit", errors);
if(assertCondition(StringUtils.hasContent(backendName), "backendName is required for the Alerts QBit", errors))
{
assertCondition(qInstance.getBackend(backendName) != null, "Alerts QBit backend not found: " + backendName, errors);
}
if(StringUtils.hasContent(schedulerName))
{
assertCondition(qInstance.getScheduler(schedulerName) != null, "Alerts QBit scheduler not found: " + schedulerName, errors);
}
if(StringUtils.hasContent(messagingProviderName))
{
assertCondition(qInstance.getMessagingProvider(messagingProviderName) != null, "Alerts QBit messaging provider not found: " + messagingProviderName, errors);
}
for(Integer value : new Integer[] {reopenWindowMinutes, flapThreshold, flapWindowMinutes, maxOpenPerMonitor, monitorTimeoutSeconds, evaluateEverySeconds, deliverEverySeconds,
maxAudienceSize, notificationRetentionDays})
{
assertCondition(value != null && value > 0, "Alerts QBit timing and limit settings must be positive", errors);
}
}
@@ -60,6 +148,99 @@ public class AlertsQBitConfig implements QBitConfig
/*******************************************************************************
** Every table the qbit defines.
*******************************************************************************/
public static List<String> allTableNames()
{
return (List.of(AlertsAlert.TABLE_NAME, AlertsMonitor.TABLE_NAME, AlertsType.TABLE_NAME, AlertsGroup.TABLE_NAME, AlertsSubscription.TABLE_NAME,
AlertsUserPreference.TABLE_NAME, AlertsTeam.TABLE_NAME, AlertsTeamMember.TABLE_NAME, AlertsChannel.TABLE_NAME, AlertsMute.TABLE_NAME,
AlertsDelivery.TABLE_NAME, AlertsEvent.TABLE_NAME, AlertsRecordRef.TABLE_NAME, AlertsHeartbeat.TABLE_NAME, AlertsNotification.TABLE_NAME,
AlertsNotificationRecipient.TABLE_NAME, AlertsNotificationPreference.TABLE_NAME));
}
/*******************************************************************************
** What an ordinary alerts user needs: alerts.view, read on the alert,
** timeline, record, type, group, monitor, team and mute tables, and full
** access to their own subscriptions, settings and inbox (record locks keep
** those to their own rows).
*******************************************************************************/
public List<String> getViewerPermissionNames()
{
List<String> names = new ArrayList<>();
names.add(PERMISSION_VIEW);
for(String table : List.of(AlertsAlert.TABLE_NAME, AlertsEvent.TABLE_NAME, AlertsRecordRef.TABLE_NAME, AlertsType.TABLE_NAME, AlertsGroup.TABLE_NAME,
AlertsMonitor.TABLE_NAME, AlertsTeam.TABLE_NAME, AlertsTeamMember.TABLE_NAME, AlertsMute.TABLE_NAME))
{
names.add(table + ".read");
}
for(String table : List.of(AlertsSubscription.TABLE_NAME, AlertsUserPreference.TABLE_NAME, AlertsNotificationPreference.TABLE_NAME))
{
names.add(table + ".read");
names.add(table + ".insert");
names.add(table + ".edit");
names.add(table + ".delete");
}
names.add(AlertsNotificationRecipient.TABLE_NAME + ".read");
names.add(AlertsNotificationRecipient.TABLE_NAME + ".edit");
return (names);
}
/*******************************************************************************
** A viewer's permissions plus alerts.manage and mute editing.
*******************************************************************************/
public List<String> getManagerPermissionNames()
{
List<String> names = new ArrayList<>(getViewerPermissionNames());
names.add(PERMISSION_MANAGE);
names.add(AlertsMute.TABLE_NAME + ".insert");
names.add(AlertsMute.TABLE_NAME + ".edit");
names.add(AlertsMute.TABLE_NAME + ".delete");
return (names);
}
/*******************************************************************************
** Everything: all three alerts permissions and every table permission.
*******************************************************************************/
public List<String> getAdminPermissionNames()
{
List<String> names = new ArrayList<>(List.of(PERMISSION_VIEW, PERMISSION_MANAGE, PERMISSION_ADMIN, PERMISSION_NOTIFICATION_ADMIN));
for(String table : allTableNames())
{
for(String suffix : List.of("read", "insert", "edit", "delete"))
{
names.add(table + "." + suffix);
}
}
return (names);
}
/*******************************************************************************
** What a notification author needs on top of a viewer's permissions:
** alerts.notification.admin and full access to the notifications table
** (they read every recipient row through the alerts_user all-access key).
*******************************************************************************/
public List<String> getNotificationAdminPermissionNames()
{
List<String> names = new ArrayList<>(getViewerPermissionNames());
names.add(PERMISSION_NOTIFICATION_ADMIN);
for(String suffix : List.of("read", "insert", "edit", "delete"))
{
names.add(AlertsNotification.TABLE_NAME + "." + suffix);
}
return (names);
}
/*******************************************************************************
** Getter for backendName
*******************************************************************************/
@@ -81,7 +262,7 @@ public class AlertsQBitConfig implements QBitConfig
/*******************************************************************************
** Fluent setter for backendName
** Fluent setter for backendName (required: the RDBMS backend for all tables)
*******************************************************************************/
public AlertsQBitConfig withBackendName(String backendName)
{
@@ -89,4 +270,551 @@ public class AlertsQBitConfig implements QBitConfig
return (this);
}
/*******************************************************************************
** Getter for schedulerName
*******************************************************************************/
public String getSchedulerName()
{
return (this.schedulerName);
}
/*******************************************************************************
** Fluent setter for schedulerName. Without it, producer signals still work,
** but monitors and delivery do not run on their own (the home says so).
*******************************************************************************/
public AlertsQBitConfig withSchedulerName(String schedulerName)
{
this.schedulerName = schedulerName;
return (this);
}
/*******************************************************************************
** Getter for messagingProviderName
*******************************************************************************/
public String getMessagingProviderName()
{
return (this.messagingProviderName);
}
/*******************************************************************************
** Fluent setter for messagingProviderName (a QMessagingProviderMetaData for
** email; without it, email channels are disabled with an explanation).
*******************************************************************************/
public AlertsQBitConfig withMessagingProviderName(String messagingProviderName)
{
this.messagingProviderName = messagingProviderName;
return (this);
}
/*******************************************************************************
** Getter for fromAddress
*******************************************************************************/
public String getFromAddress()
{
return (this.fromAddress);
}
/*******************************************************************************
** Fluent setter for fromAddress (the From of alert emails)
*******************************************************************************/
public AlertsQBitConfig withFromAddress(String fromAddress)
{
this.fromAddress = fromAddress;
return (this);
}
/*******************************************************************************
** Getter for publicBaseUrl
*******************************************************************************/
public String getPublicBaseUrl()
{
return (this.publicBaseUrl);
}
/*******************************************************************************
** Fluent setter for publicBaseUrl (the base for links in messages, e.g.
** https://admin.example.com)
*******************************************************************************/
public AlertsQBitConfig withPublicBaseUrl(String publicBaseUrl)
{
this.publicBaseUrl = publicBaseUrl;
return (this);
}
/*******************************************************************************
** Getter for reopenWindowMinutes
*******************************************************************************/
public Integer getReopenWindowMinutes()
{
return (this.reopenWindowMinutes);
}
/*******************************************************************************
** Fluent setter for reopenWindowMinutes (a raise this soon after a resolve
** reopens the same alert; default 30)
*******************************************************************************/
public AlertsQBitConfig withReopenWindowMinutes(Integer reopenWindowMinutes)
{
this.reopenWindowMinutes = reopenWindowMinutes;
return (this);
}
/*******************************************************************************
** Getter for flapThreshold
*******************************************************************************/
public Integer getFlapThreshold()
{
return (this.flapThreshold);
}
/*******************************************************************************
** Fluent setter for flapThreshold (open/resolve changes within the flap
** window that mark an alert flapping; default 5)
*******************************************************************************/
public AlertsQBitConfig withFlapThreshold(Integer flapThreshold)
{
this.flapThreshold = flapThreshold;
return (this);
}
/*******************************************************************************
** Getter for flapWindowMinutes
*******************************************************************************/
public Integer getFlapWindowMinutes()
{
return (this.flapWindowMinutes);
}
/*******************************************************************************
** Fluent setter for flapWindowMinutes (default 60)
*******************************************************************************/
public AlertsQBitConfig withFlapWindowMinutes(Integer flapWindowMinutes)
{
this.flapWindowMinutes = flapWindowMinutes;
return (this);
}
/*******************************************************************************
** Getter for maxOpenPerMonitor
*******************************************************************************/
public Integer getMaxOpenPerMonitor()
{
return (this.maxOpenPerMonitor);
}
/*******************************************************************************
** Fluent setter for maxOpenPerMonitor (the per-record cap; beyond it a
** monitor raises one aggregate alert instead; default 50)
*******************************************************************************/
public AlertsQBitConfig withMaxOpenPerMonitor(Integer maxOpenPerMonitor)
{
this.maxOpenPerMonitor = maxOpenPerMonitor;
return (this);
}
/*******************************************************************************
** Getter for monitorTimeoutSeconds
*******************************************************************************/
public Integer getMonitorTimeoutSeconds()
{
return (this.monitorTimeoutSeconds);
}
/*******************************************************************************
** Fluent setter for monitorTimeoutSeconds (default 15)
*******************************************************************************/
public AlertsQBitConfig withMonitorTimeoutSeconds(Integer monitorTimeoutSeconds)
{
this.monitorTimeoutSeconds = monitorTimeoutSeconds;
return (this);
}
/*******************************************************************************
** Getter for bootstrapMinSeverity
*******************************************************************************/
public AlertSeverity getBootstrapMinSeverity()
{
return (this.bootstrapMinSeverity);
}
/*******************************************************************************
** Fluent setter for bootstrapMinSeverity: the minimum severity of the
** in-app subscription given to alerts.admin holders who have none (default
** ERROR; null turns the bootstrap rule off).
*******************************************************************************/
public AlertsQBitConfig withBootstrapMinSeverity(AlertSeverity bootstrapMinSeverity)
{
this.bootstrapMinSeverity = bootstrapMinSeverity;
return (this);
}
/*******************************************************************************
** Getter for evaluateEverySeconds
*******************************************************************************/
public Integer getEvaluateEverySeconds()
{
return (this.evaluateEverySeconds);
}
/*******************************************************************************
** Fluent setter for evaluateEverySeconds (the monitor evaluator's tick;
** default 30)
*******************************************************************************/
public AlertsQBitConfig withEvaluateEverySeconds(Integer evaluateEverySeconds)
{
this.evaluateEverySeconds = evaluateEverySeconds;
return (this);
}
/*******************************************************************************
** Getter for deliverEverySeconds
*******************************************************************************/
public Integer getDeliverEverySeconds()
{
return (this.deliverEverySeconds);
}
/*******************************************************************************
** Fluent setter for deliverEverySeconds (the delivery worker's tick;
** default 15)
*******************************************************************************/
public AlertsQBitConfig withDeliverEverySeconds(Integer deliverEverySeconds)
{
this.deliverEverySeconds = deliverEverySeconds;
return (this);
}
/*******************************************************************************
** Getter for channelTypes
*******************************************************************************/
public List<QCodeReference> getChannelTypes()
{
return (this.channelTypes);
}
/*******************************************************************************
** Add a channel type (an AlertChannelInterface), beyond the built-ins.
*******************************************************************************/
public AlertsQBitConfig withChannelType(QCodeReference channelType)
{
this.channelTypes.add(channelType);
return (this);
}
/*******************************************************************************
** Getter for registerRoutes
*******************************************************************************/
public Boolean getRegisterRoutes()
{
return (this.registerRoutes);
}
/*******************************************************************************
** Fluent setter for registerRoutes (the /qqq/v1/alerts routes for the bell
** and record panel, when qqq-middleware-javalin is present; default true)
*******************************************************************************/
public AlertsQBitConfig withRegisterRoutes(Boolean registerRoutes)
{
this.registerRoutes = registerRoutes;
return (this);
}
/*******************************************************************************
** Getter for synchronousSink
*******************************************************************************/
public Boolean getSynchronousSink()
{
return (this.synchronousSink);
}
/*******************************************************************************
** Fluent setter for synchronousSink: process signals on the caller's
** thread instead of the background queue (tests; default false).
*******************************************************************************/
public AlertsQBitConfig withSynchronousSink(Boolean synchronousSink)
{
this.synchronousSink = synchronousSink;
return (this);
}
/*******************************************************************************
** Getter for alertmanagerIngestTokenSecretRef
*******************************************************************************/
public String getAlertmanagerIngestTokenSecretRef()
{
return (this.alertmanagerIngestTokenSecretRef);
}
/*******************************************************************************
** Fluent setter for alertmanagerIngestTokenSecretRef: the reference (an
** environment variable name or ${...} expression, never the value) of the
** bearer token Alertmanager sends to POST /qqq/hooks/alerts/alertmanager.
** Null (the default) turns ingest off.
*******************************************************************************/
public AlertsQBitConfig withAlertmanagerIngestTokenSecretRef(String alertmanagerIngestTokenSecretRef)
{
this.alertmanagerIngestTokenSecretRef = alertmanagerIngestTokenSecretRef;
return (this);
}
/*******************************************************************************
** Getter for runtime (built by the producer)
*******************************************************************************/
public AlertsRuntime getRuntime()
{
return (this.runtime);
}
/*******************************************************************************
** Setter for runtime
*******************************************************************************/
public void setRuntime(AlertsRuntime runtime)
{
this.runtime = runtime;
}
/*******************************************************************************
** Getter for userDirectory
*******************************************************************************/
public QCodeReference getUserDirectory()
{
return (this.userDirectory);
}
/*******************************************************************************
** Setter for userDirectory
*******************************************************************************/
public void setUserDirectory(QCodeReference userDirectory)
{
this.userDirectory = userDirectory;
}
/*******************************************************************************
** Fluent setter for userDirectory: the host's user directory (AlertsUserDirectoryInterface) for notification audiences; default: everyone who has used Alerts
*******************************************************************************/
public AlertsQBitConfig withUserDirectory(QCodeReference userDirectory)
{
this.userDirectory = userDirectory;
return (this);
}
/*******************************************************************************
** Getter for maxAudienceSize
*******************************************************************************/
public Integer getMaxAudienceSize()
{
return (this.maxAudienceSize);
}
/*******************************************************************************
** Setter for maxAudienceSize
*******************************************************************************/
public void setMaxAudienceSize(Integer maxAudienceSize)
{
this.maxAudienceSize = maxAudienceSize;
}
/*******************************************************************************
** Fluent setter for maxAudienceSize: the most users one notification reaches (default 50,000)
*******************************************************************************/
public AlertsQBitConfig withMaxAudienceSize(Integer maxAudienceSize)
{
this.maxAudienceSize = maxAudienceSize;
return (this);
}
/*******************************************************************************
** Getter for notificationRetentionDays
*******************************************************************************/
public Integer getNotificationRetentionDays()
{
return (this.notificationRetentionDays);
}
/*******************************************************************************
** Setter for notificationRetentionDays
*******************************************************************************/
public void setNotificationRetentionDays(Integer notificationRetentionDays)
{
this.notificationRetentionDays = notificationRetentionDays;
}
/*******************************************************************************
** Fluent setter for notificationRetentionDays: how long sent and retracted notifications are kept (default 180)
*******************************************************************************/
public AlertsQBitConfig withNotificationRetentionDays(Integer notificationRetentionDays)
{
this.notificationRetentionDays = notificationRetentionDays;
return (this);
}
/*******************************************************************************
** Getter for notifyFailedJobs
*******************************************************************************/
public Boolean getNotifyFailedJobs()
{
return (this.notifyFailedJobs);
}
/*******************************************************************************
** Setter for notifyFailedJobs
*******************************************************************************/
public void setNotifyFailedJobs(Boolean notifyFailedJobs)
{
this.notifyFailedJobs = notifyFailedJobs;
}
/*******************************************************************************
** Fluent setter for notifyFailedJobs: notify a user when a process they started fails or completes with errors (default true)
*******************************************************************************/
public AlertsQBitConfig withNotifyFailedJobs(Boolean notifyFailedJobs)
{
this.notifyFailedJobs = notifyFailedJobs;
return (this);
}
/*******************************************************************************
** Getter for jobRunLinkPattern
*******************************************************************************/
public String getJobRunLinkPattern()
{
return (this.jobRunLinkPattern);
}
/*******************************************************************************
** Setter for jobRunLinkPattern
*******************************************************************************/
public void setJobRunLinkPattern(String jobRunLinkPattern)
{
this.jobRunLinkPattern = jobRunLinkPattern;
}
/*******************************************************************************
** Fluent setter for jobRunLinkPattern: where a job notification links, with {processName} and {processUUID} (default: the process's table)
*******************************************************************************/
public AlertsQBitConfig withJobRunLinkPattern(String jobRunLinkPattern)
{
this.jobRunLinkPattern = jobRunLinkPattern;
return (this);
}
/*******************************************************************************
** Whether to expose the deprecated UI-path webhook alias (default false).
** Requires non-strict UI route mode; remove after one minor release.
*******************************************************************************/
public Boolean getLegacyAlertmanagerPath()
{
return (this.legacyAlertmanagerPath);
}
/*******************************************************************************
** Opt in to the deprecated alias while migrating Alertmanager receivers.
*******************************************************************************/
public AlertsQBitConfig withLegacyAlertmanagerPath(Boolean legacyAlertmanagerPath)
{
this.legacyAlertmanagerPath = legacyAlertmanagerPath;
return (this);
}
}
@@ -17,22 +17,60 @@
package com.kingsrook.qbits.alerts;
import java.util.ArrayList;
import java.util.List;
import com.kingsrook.qbits.alerts.delivery.DeliveryWorker;
import com.kingsrook.qbits.alerts.engine.AlertsProcessListener;
import com.kingsrook.qbits.alerts.engine.AlertsSinkAdapter;
import com.kingsrook.qbits.alerts.engine.MonitorEvaluator;
import com.kingsrook.qbits.alerts.engine.QbitAlertsSink;
import com.kingsrook.qbits.alerts.metadata.AlertsTableMetaDataHelper;
import com.kingsrook.qbits.alerts.model.AlertsChannel;
import com.kingsrook.qbits.alerts.model.AlertsMonitor;
import com.kingsrook.qqq.backend.core.alerts.AlertSeverity;
import com.kingsrook.qqq.backend.core.alerts.AlertsInstanceMetaData;
import com.kingsrook.qqq.backend.core.alerts.DetailLevel;
import com.kingsrook.qqq.backend.core.alerts.QAlertTypeMetaData;
import com.kingsrook.qqq.backend.core.alerts.ResolveMode;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.metadata.MetaDataProducerMultiOutput;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitMetaDataProducer;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
/*******************************************************************************
** Produces the Alerts QBit. Component producers in this package are found by
** package scanning.
** Entry point of the Alerts QBit, a QQQ 4.1 QBitMetaDataProducer.
**
** produce() validates the config, runs the component producers in the
** metadata package (tables, joins, possible values, security keys, record
** actions, scheduled processes, home widgets, the Alerts app) and then
** postProduceActions: declares the qbit's own alert types, builds the
** runtime (engine, router, delivery, monitors, sink), registers the process
** listener that feeds PROCESS_FAILED and process heartbeat monitors, and,
** when qqq-middleware-javalin is present, the /qqq/v1/alerts routes.
**
** Host usage:
** new AlertsQBitProducer().withQBitConfig(new AlertsQBitConfig()
** .withBackendName("rdbms").withSchedulerName("quartz")
** .withMessagingProviderName("smtp").withFromAddress("alerts@example.com")
** .withPublicBaseUrl("https://admin.example.com")).produce(qInstance);
*******************************************************************************/
public class AlertsQBitProducer implements QBitMetaDataProducer<AlertsQBitConfig>
{
private static final QLogger LOG = QLogger.getLogger(AlertsQBitProducer.class);
public static final String GROUP_ID = "com.kingsrook.qbits";
public static final String ARTIFACT_ID = "qbit-alerts";
public static final String VERSION = "0.1.0";
private static final String JAVALIN_CLASS = "com.kingsrook.qqq.middleware.javalin.QJavalinMetaData";
private AlertsQBitConfig qBitConfig;
private String namespace;
private String namespace;
@@ -91,6 +129,18 @@ public class AlertsQBitProducer implements QBitMetaDataProducer<AlertsQBitConfig
/*******************************************************************************
** Component producers live in the metadata package only (the api package
** needs qqq-middleware-javalin, which is optional).
*******************************************************************************/
@Override
public String getPackageNameForFindingMetaDataProducers()
{
return (AlertsTableMetaDataHelper.class.getPackageName());
}
/*******************************************************************************
** Producers found by package scanning have no config: skip them.
*******************************************************************************/
@@ -100,4 +150,144 @@ public class AlertsQBitProducer implements QBitMetaDataProducer<AlertsQBitConfig
return (qBitConfig != null);
}
/*******************************************************************************
** Produce and add everything to the instance. Returns an empty output so a
** host that also calls addSelfToInstance on the result adds nothing twice.
*******************************************************************************/
@Override
public MetaDataProducerMultiOutput produce(QInstance qInstance) throws QException
{
if(qBitConfig == null)
{
throw (new QException("Alerts QBit configuration validation failed: no config was supplied (call withQBitConfig)"));
}
List<String> errors = new ArrayList<>();
qBitConfig.validate(qInstance, errors);
if(!errors.isEmpty())
{
throw (new QException("Alerts QBit configuration validation failed: " + String.join("; ", errors)));
}
MetaDataProducerMultiOutput output = QBitMetaDataProducer.super.produce(qInstance);
output.addSelfToInstance(qInstance);
return (new MetaDataProducerMultiOutput());
}
/*******************************************************************************
** Declare the qbit's own types, build the runtime, register the process
** listener and the routes.
*******************************************************************************/
@Override
public void postProduceActions(MetaDataProducerMultiOutput output, QInstance qInstance) throws QException
{
AlertsInstanceMetaData alertsMetaData = AlertsInstanceMetaData.ofOrWithNew(qInstance);
for(QAlertTypeMetaData type : ownAlertTypes())
{
if(alertsMetaData.getAlertType(type.getName()) == null)
{
alertsMetaData.withAlertType(type);
}
}
AlertsRuntime previous = qBitConfig.getRuntime();
if(previous != null)
{
previous.sink().stop();
}
AlertsRuntime runtime = new AlertsRuntime(qBitConfig, qInstance);
qBitConfig.setRuntime(runtime);
alertsMetaData.withSink(new QCodeReference(AlertsSinkAdapter.class));
String listener = AlertsProcessListener.class.getName();
if(qInstance.getProcessLifecycleListeners() == null || qInstance.getProcessLifecycleListeners().stream().noneMatch(ref -> ref != null && listener.equals(ref.getName())))
{
qInstance.withProcessLifecycleListener(new QCodeReference(AlertsProcessListener.class));
}
boolean routes = false;
if(Boolean.TRUE.equals(qBitConfig.getRegisterRoutes()) && isJavalinAvailable())
{
com.kingsrook.qbits.alerts.api.AlertsUiApi.register(qInstance);
com.kingsrook.qbits.alerts.api.AlertsRouteProvider.register(qInstance);
routes = true;
}
LOG.info("Alerts QBit produced", logPair("version", VERSION), logPair("backendName", qBitConfig.getBackendName()), logPair("scheduler", qBitConfig.getSchedulerName()),
logPair("routes", routes));
}
/*******************************************************************************
** The alert types the qbit raises about itself.
*******************************************************************************/
public static List<QAlertTypeMetaData> ownAlertTypes()
{
return (List.of(
new QAlertTypeMetaData()
.withName(MonitorEvaluator.MONITOR_FAILING_TYPE)
.withLabel("Monitor cannot run")
.withSourceName(ARTIFACT_ID)
.withGroupName("alerts")
.withDefaultSeverity(AlertSeverity.ERROR)
.withVisibilityPermission(AlertsQBitConfig.PERMISSION_ADMIN)
.withSubjectTableName(AlertsMonitor.TABLE_NAME)
.withResolveMode(ResolveMode.PRODUCER)
.withDescription("A monitor's check failed three times in a row, so the condition it watches is not being checked.")
.withHowToFix("Open the monitor, read Last Error, fix its definition (or what it checks), and choose Run check now."),
new QAlertTypeMetaData()
.withName(DeliveryWorker.CHANNEL_FAILING_TYPE)
.withLabel("Alert channel failing")
.withSourceName(ARTIFACT_ID)
.withGroupName("alerts")
.withDefaultSeverity(AlertSeverity.ERROR)
.withVisibilityPermission(AlertsQBitConfig.PERMISSION_ADMIN)
.withSubjectTableName(AlertsChannel.TABLE_NAME)
.withResolveMode(ResolveMode.PRODUCER)
.withExternalDetailCeiling(DetailLevel.MINIMAL)
.withDescription("Three deliveries in a row through a channel failed. This alert is only ever shown in-app, so a broken channel can't loop.")
.withHowToFix("Open the channel, check its settings and secret reference, then choose Send test notification and Retry delivery on the failed notifications."),
new QAlertTypeMetaData()
.withName(QbitAlertsSink.OVERFLOW_TYPE)
.withLabel("Alert signals dropped")
.withSourceName(ARTIFACT_ID)
.withGroupName("alerts")
.withDefaultSeverity(AlertSeverity.ERROR)
.withVisibilityPermission(AlertsQBitConfig.PERMISSION_ADMIN)
.withResolveMode(ResolveMode.MANUAL)
.withDescription("The in-memory queue of producer signals was full, so some signals were not recorded.")
.withHowToFix("Find the producer that floods (see Noisiest Alert Types), and check the database is keeping up. Resolve this alert when it has stopped."),
new QAlertTypeMetaData()
.withName(QbitAlertsSink.FLOOD_TYPE)
.withLabel("Producer flooding alerts")
.withSourceName(ARTIFACT_ID)
.withGroupName("alerts")
.withDefaultSeverity(AlertSeverity.WARNING)
.withVisibilityPermission(AlertsQBitConfig.PERMISSION_ADMIN)
.withQuietPeriod(java.time.Duration.ofHours(1))
.withDescription("More than 1,000 signals in a minute arrived for one alert type; the rest were counted, not stored.")
.withHowToFix("Fix the producer to raise once per condition (with a stable dedup key) instead of once per event.")));
}
/*******************************************************************************
**
*******************************************************************************/
static boolean isJavalinAvailable()
{
try
{
Class.forName(JAVALIN_CLASS, false, AlertsQBitProducer.class.getClassLoader());
return (true);
}
catch(ClassNotFoundException | LinkageError e)
{
return (false);
}
}
}
@@ -0,0 +1,287 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts;
import java.time.Clock;
import java.time.Instant;
import com.kingsrook.qbits.alerts.delivery.AlertChannels;
import com.kingsrook.qbits.alerts.delivery.DeliveryWorker;
import com.kingsrook.qbits.alerts.engine.AlertRouter;
import com.kingsrook.qbits.alerts.engine.AlertTypeSync;
import com.kingsrook.qbits.alerts.engine.AlertsEngine;
import com.kingsrook.qbits.alerts.engine.MonitorEvaluator;
import com.kingsrook.qbits.alerts.engine.QbitAlertsSink;
import com.kingsrook.qbits.alerts.notifications.NotificationService;
import com.kingsrook.qqq.backend.core.context.CapturedContext;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.exceptions.QNotFoundException;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitMetaData;
/*******************************************************************************
** One installed Alerts qbit at run time: its config and instance, the clock,
** and the engine parts (sink, engine, router, delivery worker, monitor
** evaluator, type sync). Built by the producer, kept on the config.
*******************************************************************************/
public class AlertsRuntime
{
private final AlertsQBitConfig config;
private final QInstance qInstance;
private Clock clock = Clock.systemUTC();
private final AlertTypeSync typeSync;
private final AlertsEngine engine;
private final AlertRouter router;
private final AlertChannels channels;
private final DeliveryWorker deliveryWorker;
private final MonitorEvaluator evaluator;
private final QbitAlertsSink sink;
private final NotificationService notifications;
/*******************************************************************************
** Something to run as the system user.
*******************************************************************************/
@FunctionalInterface
public interface SystemWork<R>
{
/***************************************************************************
**
***************************************************************************/
R run() throws QException;
}
/*******************************************************************************
** Constructor
*******************************************************************************/
public AlertsRuntime(AlertsQBitConfig config, QInstance qInstance)
{
this.config = config;
this.qInstance = qInstance;
this.typeSync = new AlertTypeSync(this);
this.router = new AlertRouter(this);
this.engine = new AlertsEngine(this);
this.channels = new AlertChannels(this);
this.deliveryWorker = new DeliveryWorker(this);
this.evaluator = new MonitorEvaluator(this);
this.sink = new QbitAlertsSink(this);
this.notifications = new NotificationService(this);
}
/*******************************************************************************
** The runtime of the Alerts qbit in the current context's instance.
*******************************************************************************/
public static AlertsRuntime get() throws QNotFoundException
{
return (get(QContext.getQInstance()));
}
/*******************************************************************************
** The runtime of the Alerts qbit installed in an instance.
*******************************************************************************/
public static AlertsRuntime get(QInstance qInstance) throws QNotFoundException
{
AlertsRuntime runtime = find(qInstance);
if(runtime == null)
{
throw (new QNotFoundException("The Alerts qbit is not installed in this instance."));
}
return (runtime);
}
/*******************************************************************************
** The runtime, or null when the qbit is not installed.
*******************************************************************************/
public static AlertsRuntime find(QInstance qInstance)
{
if(qInstance == null || qInstance.getQBits() == null)
{
return (null);
}
for(QBitMetaData qBit : qInstance.getQBits().values())
{
if(qBit.getConfig() instanceof AlertsQBitConfig alertsConfig && alertsConfig.getRuntime() != null)
{
return (alertsConfig.getRuntime());
}
}
return (null);
}
/*******************************************************************************
** Run work as the system user (the engine sees everything; what people are
** shown and sent is filtered separately).
*******************************************************************************/
public <R> R asSystem(SystemWork<R> work) throws QException
{
Object[] result = new Object[1];
QContext.withTemporaryContext(new CapturedContext(qInstance, AlertsSecurity.systemSession()), () ->
{
result[0] = work.run();
});
@SuppressWarnings("unchecked")
R typed = (R) result[0];
return (typed);
}
/*******************************************************************************
** Now, by the runtime's clock.
*******************************************************************************/
public Instant now()
{
return (clock.instant());
}
/*******************************************************************************
** Getter for config
*******************************************************************************/
public AlertsQBitConfig getConfig()
{
return (this.config);
}
/*******************************************************************************
** Getter for qInstance
*******************************************************************************/
public QInstance getQInstance()
{
return (this.qInstance);
}
/*******************************************************************************
** Getter for clock
*******************************************************************************/
public Clock getClock()
{
return (this.clock);
}
/*******************************************************************************
** Setter for clock (tests)
*******************************************************************************/
public void setClock(Clock clock)
{
this.clock = clock;
}
/*******************************************************************************
** Getter for typeSync
*******************************************************************************/
public AlertTypeSync getTypeSync()
{
return (this.typeSync);
}
/*******************************************************************************
** Getter for engine
*******************************************************************************/
public AlertsEngine getEngine()
{
return (this.engine);
}
/*******************************************************************************
** Getter for notifications (user notifications: send, retract, the bell)
*******************************************************************************/
public NotificationService getNotifications()
{
return (this.notifications);
}
/*******************************************************************************
** Getter for router
*******************************************************************************/
public AlertRouter getRouter()
{
return (this.router);
}
/*******************************************************************************
** Getter for channels
*******************************************************************************/
public AlertChannels getChannels()
{
return (this.channels);
}
/*******************************************************************************
** Getter for deliveryWorker
*******************************************************************************/
public DeliveryWorker getDeliveryWorker()
{
return (this.deliveryWorker);
}
/*******************************************************************************
** Getter for evaluator
*******************************************************************************/
public MonitorEvaluator getEvaluator()
{
return (this.evaluator);
}
/*******************************************************************************
** The runtime sink. Alert producers use core QAlerts; notification
** producers keep calling sink().notify(spi.NotificationSignal) until RC.6.
** STAND-IN(core=QRun-IO/qqq#1125, removeBy=4.1.0-RC.6)
*******************************************************************************/
public QbitAlertsSink sink()
{
return (this.sink);
}
}
@@ -0,0 +1,298 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.kingsrook.qqq.backend.core.actions.permissions.PermissionsHelper;
import com.kingsrook.qqq.backend.core.actions.permissions.TablePermissionSubType;
import com.kingsrook.qqq.backend.core.context.CapturedContext;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.model.actions.AbstractActionInput;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.security.MultiRecordSecurityLock;
import com.kingsrook.qqq.backend.core.model.metadata.security.QSecurityKeyType;
import com.kingsrook.qqq.backend.core.model.metadata.security.RecordSecurityLock;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import com.kingsrook.qqq.backend.core.model.session.QSystemUserSession;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
/*******************************************************************************
** The Alerts record-security keys (design section 7).
**
** Four security key types guard the qbit's tables:
** - alerts_user: the session's user id. Personal rows (subscriptions,
** settings, inbox items) are locked to it. alerts.admin holders get its
** all-access key.
** - alerts_permission: every permission the session holds. An alert whose
** type sets a visibility permission is only readable with it.
** - alerts_readable_table: every table the session can read. An alert about
** a subject table is only readable by users who can read that table.
** - alerts_recipient: the session's user id, for notification recipient
** rows. Notification authors (alerts.notification.admin) and alerts.admin
** holders get its all-access key.
** alerts_permission and alerts_readable_table follow the logged-in user, so counts, lists, the bell and
** the home are all filtered in the query. (The system user, which the
** engine runs as, holds every all-access key.)
**
** Hosts call applyToSession from their authentication customizer, after the
** session's user and permissions are set. The qbit's own endpoints and
** widgets also call ensureSessionKeys, so a host that forgets still gets
** correct (never wider) results there. Without the keys, gated alerts (with
** a visibility permission or a subject table) are hidden.
*******************************************************************************/
public final class AlertsSecurity
{
public static final String KEY_USER = "alerts_user";
public static final String KEY_USER_ALL_ACCESS = "alerts_user_all_access";
public static final String KEY_PERMISSION = "alerts_permission";
public static final String KEY_PERMISSION_ALL = "alerts_permission_all_access";
public static final String KEY_READABLE_TABLE = "alerts_readable_table";
public static final String KEY_READABLE_TABLE_ALL = "alerts_readable_table_all_access";
public static final String KEY_RECIPIENT = "alerts_recipient";
public static final String KEY_RECIPIENT_ALL = "alerts_recipient_all_access";
private static final String ALERT_TABLE = "alerts_alert";
/*******************************************************************************
** Keys only.
*******************************************************************************/
private AlertsSecurity()
{
}
/*******************************************************************************
** The three key types, for the producer.
*******************************************************************************/
public static List<QSecurityKeyType> buildSecurityKeyTypes()
{
return (List.of(
new QSecurityKeyType().withName(KEY_USER).withAllAccessKeyName(KEY_USER_ALL_ACCESS),
new QSecurityKeyType().withName(KEY_PERMISSION).withAllAccessKeyName(KEY_PERMISSION_ALL),
new QSecurityKeyType().withName(KEY_READABLE_TABLE).withAllAccessKeyName(KEY_READABLE_TABLE_ALL),
new QSecurityKeyType().withName(KEY_RECIPIENT).withAllAccessKeyName(KEY_RECIPIENT_ALL)));
}
/*******************************************************************************
** Owner lock: the session's alerts_user value must equal the field.
*******************************************************************************/
public static RecordSecurityLock ownerLock(String fieldName)
{
return (new RecordSecurityLock()
.withSecurityKeyType(KEY_USER)
.withFieldName(fieldName)
.withLockScope(RecordSecurityLock.LockScope.READ_AND_WRITE));
}
/*******************************************************************************
** Recipient lock: a notification recipient row is its user's (notification
** authors and alerts admins hold the all-access key).
*******************************************************************************/
public static RecordSecurityLock recipientLock(String fieldName)
{
return (new RecordSecurityLock()
.withSecurityKeyType(KEY_RECIPIENT)
.withFieldName(fieldName)
.withLockScope(RecordSecurityLock.LockScope.READ_AND_WRITE));
}
/*******************************************************************************
** Visibility lock on an alert (joinFromAlert null) or on a child of an
** alert (through that join): the session must hold the alert's
** visibilityPermission and be able to read its subjectTableName (each
** check passes when the alert has none).
*******************************************************************************/
public static MultiRecordSecurityLock visibilityLock(String joinFromAlert)
{
String prefix = joinFromAlert == null ? "" : ALERT_TABLE + ".";
RecordSecurityLock permission = new RecordSecurityLock()
.withSecurityKeyType(KEY_PERMISSION)
.withFieldName(prefix + "visibilityPermission")
.withNullValueBehavior(RecordSecurityLock.NullValueBehavior.ALLOW)
.withLockScope(RecordSecurityLock.LockScope.READ);
RecordSecurityLock table = new RecordSecurityLock()
.withSecurityKeyType(KEY_READABLE_TABLE)
.withFieldName(prefix + "subjectTableName")
.withNullValueBehavior(RecordSecurityLock.NullValueBehavior.ALLOW)
.withLockScope(RecordSecurityLock.LockScope.READ);
if(joinFromAlert != null)
{
permission.setJoinNameChain(List.of(joinFromAlert));
table.setJoinNameChain(List.of(joinFromAlert));
}
return (new MultiRecordSecurityLock()
.withOperator(MultiRecordSecurityLock.BooleanOperator.AND)
.withLock(permission)
.withLock(table));
}
/*******************************************************************************
** Put the alerts keys into a session: the user id (and, for alerts.admin,
** the all-access key), every permission it holds, and every table it can
** read. Idempotent: earlier alerts keys are replaced. A session without
** alerts.view gets none, so the locks deny.
*******************************************************************************/
public static void applyToSession(QInstance qInstance, QSession session)
{
if(session == null || session instanceof QSystemUserSession || qInstance == null)
{
return;
}
Map<String, List<Serializable>> keys = session.getSecurityKeyValues();
if(keys != null)
{
for(String key : List.of(KEY_USER, KEY_USER_ALL_ACCESS, KEY_PERMISSION, KEY_READABLE_TABLE, KEY_RECIPIENT, KEY_RECIPIENT_ALL))
{
keys.remove(key);
}
}
if(!session.hasPermission(AlertsQBitConfig.PERMISSION_VIEW))
{
return;
}
String userId = userId(session);
if(StringUtils.hasContent(userId))
{
session.withSecurityKeyValue(KEY_USER, userId);
session.withSecurityKeyValue(KEY_RECIPIENT, userId);
}
if(session.hasPermission(AlertsQBitConfig.PERMISSION_ADMIN) || session.hasPermission(AlertsQBitConfig.PERMISSION_NOTIFICATION_ADMIN))
{
session.withSecurityKeyValue(KEY_RECIPIENT_ALL, true);
}
if(session.hasPermission(AlertsQBitConfig.PERMISSION_ADMIN))
{
session.withSecurityKeyValue(KEY_USER_ALL_ACCESS, true);
}
Set<String> permissions = session.getPermissions();
if(permissions != null)
{
for(String permission : permissions)
{
session.withSecurityKeyValue(KEY_PERMISSION, permission);
}
}
for(String tableName : readableTables(qInstance, session))
{
session.withSecurityKeyValue(KEY_READABLE_TABLE, tableName);
}
}
/*******************************************************************************
** Apply the keys only if the session has none yet.
*******************************************************************************/
public static void ensureSessionKeys(QInstance qInstance, QSession session)
{
if(session == null || session instanceof QSystemUserSession)
{
return;
}
Map<String, List<Serializable>> keys = session.getSecurityKeyValues();
if(keys == null || !keys.containsKey(KEY_READABLE_TABLE))
{
applyToSession(qInstance, session);
}
}
/*******************************************************************************
** The tables the session may read (by its QQQ table permissions).
*******************************************************************************/
public static List<String> readableTables(QInstance qInstance, QSession session)
{
List<String> names = new ArrayList<>();
QContext.withTemporaryContext(new CapturedContext(qInstance, session), () ->
{
AbstractActionInput input = new AbstractActionInput();
for(QTableMetaData table : qInstance.getTables().values())
{
if(PermissionsHelper.hasTablePermission(input, table.getName(), TablePermissionSubType.READ))
{
names.add(table.getName());
}
}
});
return (names);
}
/*******************************************************************************
** The session's user id (null when there is none).
*******************************************************************************/
public static String userId(QSession session)
{
if(session == null || session.getUser() == null)
{
return (null);
}
return (session.getUser().getIdReference());
}
/*******************************************************************************
** A system-user session holding the alerts all-access keys (QQQ caches the
** system user's keys from whatever instance it saw first, so add ours
** explicitly).
*******************************************************************************/
public static QSystemUserSession systemSession()
{
QSystemUserSession session = new QSystemUserSession();
session.withSecurityKeyValue(KEY_USER_ALL_ACCESS, true);
session.withSecurityKeyValue(KEY_PERMISSION_ALL, true);
session.withSecurityKeyValue(KEY_READABLE_TABLE_ALL, true);
session.withSecurityKeyValue(KEY_RECIPIENT_ALL, true);
return (session);
}
/*******************************************************************************
** True when the current session is the system user.
*******************************************************************************/
public static boolean isSystemUser()
{
return (QContext.getQSession() instanceof QSystemUserSession);
}
}
@@ -0,0 +1,679 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.api;
import java.io.Serializable;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import com.kingsrook.qbits.alerts.AlertsPreferences;
import com.kingsrook.qbits.alerts.AlertsQBitConfig;
import com.kingsrook.qbits.alerts.AlertsRuntime;
import com.kingsrook.qbits.alerts.AlertsSecurity;
import com.kingsrook.qbits.alerts.delivery.AlertMessageRenderer;
import com.kingsrook.qbits.alerts.engine.AlertsDb;
import com.kingsrook.qbits.alerts.home.AlertsHome;
import com.kingsrook.qbits.alerts.model.AlertsAlert;
import com.kingsrook.qbits.alerts.model.AlertsGroup;
import com.kingsrook.qbits.alerts.model.AlertsNotification;
import com.kingsrook.qbits.alerts.model.AlertsNotificationRecipient;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.ScopeType;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.Status;
import com.kingsrook.qbits.alerts.model.AlertsRecordRef;
import com.kingsrook.qbits.alerts.model.AlertsSubscription;
import com.kingsrook.qbits.alerts.notifications.NotificationService;
import com.kingsrook.qbits.alerts.processes.AlertsAction;
import com.kingsrook.qbits.alerts.spi.NotificationCategory;
import com.kingsrook.qbits.alerts.spi.NotificationSeverity;
import com.kingsrook.qqq.backend.core.actions.permissions.PermissionsHelper;
import com.kingsrook.qqq.backend.core.actions.permissions.TablePermissionSubType;
import com.kingsrook.qqq.backend.core.actions.tables.UpdateAction;
import com.kingsrook.qqq.backend.core.alerts.AlertSeverity;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QBadRequestException;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.exceptions.QPermissionDeniedException;
import com.kingsrook.qqq.backend.core.model.actions.AbstractActionInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterOrderBy;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
import com.kingsrook.qqq.middleware.javalin.specs.extensions.MiddlewareSpecExtensionsMetaData;
/*******************************************************************************
** The bell, notifications page and record-panel endpoints' logic (design
** sections 6.3, 6.4; docs/NOTIFICATIONS.md 8.1),
** independent of the HTTP layer. Everything is read and written in the
** caller's session (record locks: their own recipient rows, alerts they can
** see); notification content is read for the rows they hold.
*******************************************************************************/
public class AlertsApi
{
static final int INBOX_ITEMS = 10;
static final int MAX_BANNERS = 3;
static final int SCAN_LIMIT = 1000;
static final int MAX_BATCH = 500;
static final int DEFAULT_PAGE = 25;
static final int MAX_PAGE = 100;
static final int POLL_SECONDS = 60;
public static final String NOTIFICATIONS_HREF = "/app/notifications";
static final int PANEL_ROWS = 5;
static final int RESOLVED_LOOKBACK = 30;
private final AlertsRuntime runtime;
/*******************************************************************************
** Constructor
*******************************************************************************/
public AlertsApi(AlertsRuntime runtime)
{
this.runtime = runtime;
}
/*******************************************************************************
** Check alerts.view and set up the session (keys, settings).
*******************************************************************************/
public String requireViewer() throws QException
{
QSession session = QContext.getQSession();
if(session == null || !session.hasPermission(AlertsQBitConfig.PERMISSION_VIEW))
{
throw (new QPermissionDeniedException("Alerts are not available to you."));
}
AlertsSecurity.ensureSessionKeys(runtime.getQInstance(), session);
AlertsPreferences.ensure(runtime, session);
return (AlertsSecurity.userId(session));
}
/*******************************************************************************
** The bell (docs/NOTIFICATIONS.md 8.1): the unread count, the highest
** unread severity, the latest items, and sticky banners.
*******************************************************************************/
public Map<String, Object> inboxSummary() throws QException
{
String userId = requireViewer();
Instant now = runtime.now();
List<Entry> entries = entries(userId, now);
int unread = 0;
NotificationSeverity highest = null;
List<Map<String, Object>> latest = new ArrayList<>();
List<Map<String, Object>> banners = new ArrayList<>();
for(Entry entry : entries)
{
if(entry.unread())
{
unread++;
NotificationSeverity severity = NotificationSeverity.fromName(entry.notification().getValueString("severity"), NotificationSeverity.INFO);
highest = highest == null || severity.compareTo(highest) > 0 ? severity : highest;
}
if(latest.size() < INBOX_ITEMS)
{
latest.add(item(entry, now, false));
}
if(Boolean.TRUE.equals(entry.notification().getValueBoolean("sticky")) && banners.size() < MAX_BANNERS)
{
banners.add(item(entry, now, true));
}
}
Map<String, Object> result = new LinkedHashMap<>();
result.put("unreadCount", unread);
result.put("highestUnreadSeverity", highest == null ? null : highest.name());
result.put("items", latest);
result.put("banners", banners);
result.put("notificationsHref", NOTIFICATIONS_HREF);
result.put("inboxHref", NOTIFICATIONS_HREF);
result.put("alertsHref", "/app/" + AlertsQBitConfig.APP_NAME);
result.put("pollSeconds", POLL_SECONDS);
return (result);
}
/*******************************************************************************
** The notifications page: the user's notifications (not dismissed),
** filtered by status (all or unread), category and severity, a page at a
** time, with bodies.
*******************************************************************************/
public Map<String, Object> inbox(Map<String, String> params) throws QException
{
String userId = requireViewer();
Instant now = runtime.now();
boolean onlyNew = "unread".equalsIgnoreCase(params.get("status"));
String category = StringUtils.hasContent(params.get("category")) ? params.get("category").toUpperCase(Locale.ROOT) : null;
String severity = StringUtils.hasContent(params.get("severity")) ? params.get("severity").toUpperCase(Locale.ROOT) : null;
int offset = Math.max(0, parseInt(params.get("offset"), 0));
int limit = Math.min(MAX_PAGE, Math.max(1, parseInt(params.get("limit"), DEFAULT_PAGE)));
List<Entry> matching = new ArrayList<>();
for(Entry entry : entries(userId, now))
{
if((!onlyNew || entry.unread())
&& (category == null || category.equals(entry.notification().getValueString("category")))
&& (severity == null || severity.equals(entry.notification().getValueString("severity"))))
{
matching.add(entry);
}
}
List<Map<String, Object>> items = new ArrayList<>();
for(Entry entry : matching.subList(Math.min(offset, matching.size()), Math.min(offset + limit, matching.size())))
{
items.add(item(entry, now, true));
}
Map<String, Object> result = new LinkedHashMap<>();
result.put("items", items);
result.put("total", matching.size());
result.put("offset", offset);
result.put("limit", limit);
return (result);
}
/*******************************************************************************
** Mark read: {"id": n}, {"ids": [..]}, {"all": true}, or (0.1 clients)
** {"alertId": n}.
*******************************************************************************/
public Map<String, Object> markRead(Map<String, Object> body) throws QException
{
String userId = requireViewer();
Instant now = runtime.now();
return (updateOwn(userId, target(userId, body, true), "readAt", now, record -> record.getValue("readAt") == null));
}
/*******************************************************************************
** Mark unread: {"id": n} or {"ids": [..]}.
*******************************************************************************/
public Map<String, Object> markUnread(Map<String, Object> body) throws QException
{
String userId = requireViewer();
return (updateOwn(userId, target(userId, body, false), "readAt", null, record -> record.getValue("readAt") != null));
}
/*******************************************************************************
** Dismiss (hide from the bell and the page; also marks read): {"id": n},
** {"ids": [..]} or {"all": true}.
*******************************************************************************/
public Map<String, Object> dismiss(Map<String, Object> body) throws QException
{
String userId = requireViewer();
Instant now = runtime.now();
return (updateOwn(userId, target(userId, body, true), "dismissedAt", now, record -> record.getValue("dismissedAt") == null));
}
/*******************************************************************************
** The open alerts in a user's bell (ALERT notifications not dismissed),
** for the Alerts home's "My alerts".
*******************************************************************************/
public static List<Integer> myAlertIds(String userId, int limit) throws QException
{
List<Integer> notificationIds = new ArrayList<>();
for(QRecord recipient : AlertsDb.query(AlertsNotificationRecipient.TABLE_NAME, AlertsDb.eq("userId", userId)
.withCriteria("dismissedAt", QCriteriaOperator.IS_BLANK).withLimit(limit)))
{
notificationIds.add(recipient.getValueInteger("notificationId"));
}
List<Integer> alertIds = new ArrayList<>();
if(notificationIds.isEmpty())
{
return (alertIds);
}
for(QRecord notification : AlertsRuntime.get().asSystem(() -> AlertsDb.query(AlertsNotification.TABLE_NAME, new QQueryFilter()
.withCriteria("id", QCriteriaOperator.IN, notificationIds)
.withCriteria("category", QCriteriaOperator.EQUALS, NotificationCategory.ALERT.name())
.withCriteria("status", QCriteriaOperator.EQUALS, NotificationService.STATUS_SENT))))
{
Integer alertId = parseInteger(notification.getValueString("sourceRecordId"));
if(alertId != null)
{
alertIds.add(alertId);
}
}
return (alertIds);
}
/*******************************************************************************
** One recipient row with its (live) notification.
*******************************************************************************/
record Entry(QRecord recipient, QRecord notification)
{
/***************************************************************************
**
***************************************************************************/
boolean unread()
{
return (recipient.getValue("readAt") == null);
}
}
/*******************************************************************************
** The user's bell: their recipient rows (the owner lock applies) that are
** not dismissed, joined with notifications that are SENT, published and
** not expired, newest first. ALERT notifications are kept only while the
** user can still see the alert.
*******************************************************************************/
private List<Entry> entries(String userId, Instant now) throws QException
{
if(userId == null)
{
return (List.of());
}
List<QRecord> recipients = AlertsDb.query(AlertsNotificationRecipient.TABLE_NAME, AlertsDb.eq("userId", userId)
.withCriteria("dismissedAt", QCriteriaOperator.IS_BLANK)
.withOrderBy(new QFilterOrderBy("deliveredAt", false))
.withOrderBy(new QFilterOrderBy("id", false))
.withLimit(SCAN_LIMIT));
if(recipients.isEmpty())
{
return (List.of());
}
List<Integer> ids = recipients.stream().map(recipient -> recipient.getValueInteger("notificationId")).distinct().toList();
Map<Integer, QRecord> notifications = new HashMap<>();
runtime.asSystem(() ->
{
for(QRecord notification : AlertsDb.query(AlertsNotification.TABLE_NAME, new QQueryFilter()
.withCriteria("id", QCriteriaOperator.IN, ids)
.withCriteria("status", QCriteriaOperator.EQUALS, NotificationService.STATUS_SENT)))
{
Instant publishAt = notification.getValueInstant("publishAt");
Instant expireAt = notification.getValueInstant("expireAt");
if((publishAt == null || !publishAt.isAfter(now)) && (expireAt == null || expireAt.isAfter(now)))
{
notifications.put(notification.getValueInteger("id"), notification);
}
}
return (null);
});
List<Integer> alertIds = new ArrayList<>();
for(QRecord notification : notifications.values())
{
if(NotificationCategory.ALERT.name().equals(notification.getValueString("category")) && parseInteger(notification.getValueString("sourceRecordId")) != null)
{
alertIds.add(parseInteger(notification.getValueString("sourceRecordId")));
}
}
Set<String> visibleAlerts = new HashSet<>();
if(!alertIds.isEmpty())
{
for(QRecord alert : AlertsDb.query(AlertsAlert.TABLE_NAME, new QQueryFilter().withCriteria("id", QCriteriaOperator.IN, alertIds)))
{
visibleAlerts.add(String.valueOf(alert.getValue("id")));
}
}
List<Entry> entries = new ArrayList<>();
for(QRecord recipient : recipients)
{
QRecord notification = notifications.get(recipient.getValueInteger("notificationId"));
if(notification != null && (!NotificationCategory.ALERT.name().equals(notification.getValueString("category")) || visibleAlerts.contains(notification.getValueString("sourceRecordId"))))
{
entries.add(new Entry(recipient, notification));
}
}
return (entries);
}
/*******************************************************************************
** One bell or page item.
*******************************************************************************/
private static Map<String, Object> item(Entry entry, Instant now, boolean withBody)
{
QRecord notification = entry.notification();
Instant deliveredAt = entry.recipient().getValueInstant("deliveredAt");
Map<String, Object> row = new LinkedHashMap<>();
row.put("id", entry.recipient().getValueInteger("id"));
row.put("notificationId", notification.getValueInteger("id"));
row.put("title", notification.getValueString("title"));
if(withBody)
{
row.put("body", notification.getValueString("body"));
}
row.put("severity", notification.getValueString("severity"));
row.put("category", notification.getValueString("category"));
row.put("source", notification.getValueString("sourceName"));
row.put("href", NotificationService.safeLink(notification.getValueString("linkUrl")));
row.put("linkLabel", notification.getValueString("linkLabel"));
row.put("deliveredAt", deliveredAt == null ? null : deliveredAt.toString());
row.put("age", AlertMessageRenderer.age(deliveredAt, now));
row.put("unread", entry.unread());
row.put("sticky", Boolean.TRUE.equals(notification.getValueBoolean("sticky")));
if(NotificationCategory.ALERT.name().equals(notification.getValueString("category")))
{
row.put("alertId", parseInteger(notification.getValueString("sourceRecordId")));
}
List<Map<String, Object>> actions = new ArrayList<>();
actions.add(Map.of("name", entry.unread() ? "read" : "unread", "label", entry.unread() ? "Mark read" : "Mark unread",
"operationId", entry.unread() ? InboxReadSpec.OPERATION_ID : InboxUnreadSpec.OPERATION_ID));
actions.add(Map.of("name", "dismiss", "label", "Dismiss", "operationId", InboxDismissSpec.OPERATION_ID));
row.put("actions", actions);
return (row);
}
/*******************************************************************************
** Which of the user's recipient rows a request names (null: all of them).
*******************************************************************************/
private List<Integer> target(String userId, Map<String, Object> body, boolean allowAll) throws QException
{
if(body != null && body.get("id") != null)
{
return (List.of(toInteger(body.get("id"))));
}
if(body != null && body.get("ids") instanceof List<?> list && !list.isEmpty())
{
List<Integer> ids = new ArrayList<>();
for(Object value : list.subList(0, Math.min(list.size(), MAX_BATCH)))
{
ids.add(toInteger(value));
}
return (ids);
}
if(body != null && body.get("alertId") != null)
{
Integer alertId = toInteger(body.get("alertId"));
QRecord notification = runtime.asSystem(() -> AlertsDb.first(AlertsNotification.TABLE_NAME, AlertsDb.eq("sourceKey", "alert:" + alertId)));
if(notification == null || userId == null)
{
return (List.of());
}
return (AlertsDb.query(AlertsNotificationRecipient.TABLE_NAME, AlertsDb.eq("userId", userId)
.withCriteria("notificationId", QCriteriaOperator.EQUALS, notification.getValue("id"))).stream().map(recipient -> recipient.getValueInteger("id")).toList());
}
if(allowAll && body != null && Boolean.TRUE.equals(body.get("all")))
{
return (null);
}
throw (new QBadRequestException(allowAll ? "Send id, ids, or all: true." : "Send id or ids."));
}
/*******************************************************************************
** Set one field on the user's own recipient rows (the named ones, or all
** not dismissed), where the row still needs it. Dismissing also marks
** read. Recounts the notifications' readers.
*******************************************************************************/
private Map<String, Object> updateOwn(String userId, List<Integer> ids, String field, Instant value, java.util.function.Predicate<QRecord> needs) throws QException
{
if(userId == null || (ids != null && ids.isEmpty()))
{
return (Map.of("updated", 0));
}
QQueryFilter filter = AlertsDb.eq("userId", userId).withLimit(SCAN_LIMIT);
if(ids != null)
{
filter.withCriteria("id", QCriteriaOperator.IN, ids);
}
else
{
filter.withCriteria("dismissedAt", QCriteriaOperator.IS_BLANK);
}
List<QRecord> updates = new ArrayList<>();
Set<Integer> affected = new HashSet<>();
for(QRecord recipient : AlertsDb.query(AlertsNotificationRecipient.TABLE_NAME, filter))
{
if(needs.test(recipient))
{
QRecord update = new QRecord().withValue("id", recipient.getValue("id")).withValue(field, value);
if("dismissedAt".equals(field) && recipient.getValue("readAt") == null)
{
update.setValue("readAt", value);
}
updates.add(update);
affected.add(recipient.getValueInteger("notificationId"));
}
}
if(!updates.isEmpty())
{
UpdateAction.executeForRecords(new UpdateInput(AlertsNotificationRecipient.TABLE_NAME).withRecords(updates));
runtime.getNotifications().recountRead(affected);
}
return (Map.of("updated", updates.size()));
}
/*******************************************************************************
**
*******************************************************************************/
private static Integer toInteger(Object value) throws QBadRequestException
{
Integer parsed = value == null ? null : parseInteger(String.valueOf(value));
if(parsed == null)
{
throw (new QBadRequestException("Ids must be numbers."));
}
return (parsed);
}
/*******************************************************************************
**
*******************************************************************************/
private static Integer parseInteger(String value)
{
try
{
return (value == null ? null : Integer.valueOf(value.trim().replaceAll("\\.0+$", "")));
}
catch(NumberFormatException e)
{
return (null);
}
}
/*******************************************************************************
**
*******************************************************************************/
private static int parseInt(String value, int fallback)
{
Integer parsed = parseInteger(value);
return (parsed == null ? fallback : parsed);
}
/*******************************************************************************
** The "Open alerts" panel for a record: visible open alerts that reference
** it (at most 5), how many were resolved in 30 days, and links. visible is
** false when there is nothing to show (the panel is then hidden).
*******************************************************************************/
public Map<String, Object> recordPanel(String tableName, String recordId) throws QException
{
requireViewer();
if(!StringUtils.hasContent(tableName) || !StringUtils.hasContent(recordId) || runtime.getQInstance().getTable(tableName) == null)
{
throw (new QBadRequestException("Send a table name and record id."));
}
if(!PermissionsHelper.hasTablePermission(new AbstractActionInput(), tableName, TablePermissionSubType.READ))
{
throw (new QPermissionDeniedException("You can't read that table."));
}
Instant now = runtime.now();
List<Integer> openIds = new ArrayList<>();
List<Integer> allIds = new ArrayList<>();
for(QRecord ref : AlertsDb.query(AlertsRecordRef.TABLE_NAME, AlertsDb.eq("tableName", tableName).withCriteria("recordId", QCriteriaOperator.EQUALS, recordId).withLimit(500)))
{
allIds.add(ref.getValueInteger("alertId"));
if(Boolean.TRUE.equals(ref.getValueBoolean("active")))
{
openIds.add(ref.getValueInteger("alertId"));
}
}
for(QRecord alert : AlertsDb.query(AlertsAlert.TABLE_NAME, AlertsDb.eq("subjectTableName", tableName).withCriteria("subjectRecordId", QCriteriaOperator.EQUALS, recordId).withLimit(500)))
{
allIds.add(alert.getValueInteger("id"));
openIds.add(alert.getValueInteger("id"));
}
List<QRecord> open = openIds.isEmpty() ? new ArrayList<>() : new ArrayList<>(AlertsDb.query(AlertsAlert.TABLE_NAME, new QQueryFilter()
.withCriteria("id", QCriteriaOperator.IN, openIds)
.withCriteria("status", QCriteriaOperator.IN, Status.openNames())));
open.sort((a, b) -> AlertSeverity.fromLabel(b.getValueString("severity"), AlertSeverity.INFO).compareTo(AlertSeverity.fromLabel(a.getValueString("severity"), AlertSeverity.INFO)));
int resolved = allIds.isEmpty() ? 0 : AlertsDb.count(AlertsAlert.TABLE_NAME, new QQueryFilter()
.withCriteria("id", QCriteriaOperator.IN, allIds)
.withCriteria("status", QCriteriaOperator.EQUALS, Status.RESOLVED.name())
.withCriteria("resolvedAt", QCriteriaOperator.GREATER_THAN_OR_EQUALS, now.minus(RESOLVED_LOOKBACK, ChronoUnit.DAYS)));
Map<Integer, String> groups = groupLabels();
List<Map<String, Object>> rows = new ArrayList<>();
for(QRecord alert : open.subList(0, Math.min(PANEL_ROWS, open.size())))
{
rows.add(alertRow(alert, groups, now));
}
QSession session = QContext.getQSession();
Map<String, Object> result = new LinkedHashMap<>();
result.put("visible", !open.isEmpty() || resolved > 0);
result.put("openCount", open.size());
result.put("open", rows);
result.put("resolvedLast30Days", resolved);
result.put("viewAllHref", allIds.isEmpty() ? null : AlertsHome.listUrl(new QQueryFilter().withCriteria("id", QCriteriaOperator.IN, dedupe(allIds))));
result.put("canManage", session.hasPermission(AlertsQBitConfig.PERMISSION_MANAGE));
result.put("watching", isWatching(tableName, recordId));
MiddlewareSpecExtensionsMetaData extensions = MiddlewareSpecExtensionsMetaData.of(runtime.getQInstance());
result.put("follow", Map.of("available", extensions != null && extensions.getExtensions().containsKey("collaboration")));
return (result);
}
/*******************************************************************************
** Whether the user already has a RECORD subscription for this record.
*******************************************************************************/
private boolean isWatching(String tableName, String recordId) throws QException
{
String userId = AlertsSecurity.userId(QContext.getQSession());
if(userId == null || !PermissionsHelper.hasTablePermission(new AbstractActionInput(), AlertsSubscription.TABLE_NAME, TablePermissionSubType.READ))
{
return (false);
}
return (AlertsDb.count(AlertsSubscription.TABLE_NAME, AlertsDb.eq("userId", userId)
.withCriteria("scopeType", QCriteriaOperator.EQUALS, ScopeType.RECORD.name())
.withCriteria("scopeValue", QCriteriaOperator.EQUALS, tableName)
.withCriteria("scopeRecordId", QCriteriaOperator.EQUALS, recordId)) > 0);
}
/*******************************************************************************
** One alert as the bell and panel show it.
*******************************************************************************/
private static Map<String, Object> alertRow(QRecord alert, Map<Integer, String> groups, Instant now)
{
Map<String, Object> row = new LinkedHashMap<>();
row.put("alertId", alert.getValueInteger("id"));
row.put("title", alert.getValueString("title"));
row.put("severity", alert.getValueString("severity"));
row.put("status", alert.getValueString("status"));
row.put("group", groups.get(alert.getValueInteger("groupId")));
row.put("age", AlertMessageRenderer.age(alert.getValueInstant("firstRaisedAt"), now));
row.put("raisedAt", alert.getValueInstant("firstRaisedAt") == null ? null : alert.getValueInstant("firstRaisedAt").toString());
row.put("href", "/app/" + AlertsAlert.TABLE_NAME + "/" + alert.getValue("id"));
List<Map<String, Object>> actions = new ArrayList<>();
if(QContext.getQSession().hasPermission(AlertsQBitConfig.PERMISSION_MANAGE))
{
if(Status.OPEN.name().equals(alert.getValueString("status")))
{
actions.add(processAction("acknowledge", AlertsAction.ACKNOWLEDGE, alert.getValueInteger("id")));
}
actions.add(processAction("snooze", AlertsAction.SNOOZE, alert.getValueInteger("id")));
}
row.put("actions", actions);
return (row);
}
/*******************************************************************************
** Complete navigation target so clients need no process or table conventions.
*******************************************************************************/
private static Map<String, Object> processAction(String name, AlertsAction action, Integer alertId)
{
return (Map.of("name", name, "label", action.getLabel(), "processName", action.getProcessName(),
"href", "/app/" + action.getProcessName() + "?recordsParam=recordIds&recordIds=" + alertId + "&tableName=" + AlertsAlert.TABLE_NAME));
}
/*******************************************************************************
** Group labels by id (empty without read permission).
*******************************************************************************/
private static Map<Integer, String> groupLabels() throws QException
{
Map<Integer, String> labels = new HashMap<>();
if(PermissionsHelper.hasTablePermission(new AbstractActionInput(), AlertsGroup.TABLE_NAME, TablePermissionSubType.READ))
{
for(QRecord group : AlertsDb.query(AlertsGroup.TABLE_NAME, new QQueryFilter()))
{
labels.put(group.getValueInteger("id"), group.getValueString("label"));
}
}
return (labels);
}
/*******************************************************************************
**
*******************************************************************************/
private static List<Serializable> dedupe(List<Integer> ids)
{
return (new ArrayList<>(new java.util.LinkedHashSet<>(ids)));
}
}
@@ -0,0 +1,97 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.api;
import java.util.List;
import com.kingsrook.qbits.alerts.AlertsRuntime;
import com.kingsrook.qqq.backend.core.exceptions.QBadRequestException;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.middleware.javalin.specs.BasicResponse;
import com.kingsrook.qqq.middleware.javalin.specs.extensions.AbstractJsonEndpointSpec;
import com.kingsrook.qqq.openapi.model.Method;
import io.javalin.http.Context;
import io.javalin.http.HttpStatus;
/*******************************************************************************
** Shared JSON transport; AlertsApi owns authorization and behavior.
*******************************************************************************/
abstract class AlertsJsonSpec extends AbstractJsonEndpointSpec
{
/*******************************************************************************
** The stable operation identifier exposed to clients.
*******************************************************************************/
protected abstract String operationId();
/*******************************************************************************
** Publish operation identifiers in both the fragment and served document.
*******************************************************************************/
@Override
public Method defineMethod()
{
return (super.defineMethod().withOperationId(operationId()));
}
/*******************************************************************************
** Keep the existing Content-Type requirement, including empty POST bodies.
*******************************************************************************/
@Override
public JsonInput buildInput(Context context) throws Exception
{
if(defineRequestBodySchema() != null && (context.contentType() == null || !context.contentType().toLowerCase(java.util.Locale.ROOT).startsWith("application/json")))
{
throw (new QBadRequestException("The request body must be JSON (Content-Type: application/json)."));
}
try
{
return (super.buildInput(context));
}
catch(QBadRequestException e)
{
throw (new QBadRequestException("The request body is not valid JSON."));
}
}
/*******************************************************************************
** Framework error responses retain their existing HTTP status mapping.
*******************************************************************************/
@Override
public List<BasicResponse> defineAdditionalBasicResponses()
{
return (List.of(new BasicResponse(HttpStatus.BAD_REQUEST, "Invalid input", "AlertsErrorV1"),
new BasicResponse(HttpStatus.UNAUTHORIZED, "Sign in required", "AlertsErrorV1"),
new BasicResponse(HttpStatus.FORBIDDEN, "Permission denied", "AlertsErrorV1"),
new BasicResponse(HttpStatus.NOT_FOUND, "Not found", "AlertsErrorV1")));
}
/*******************************************************************************
** Resolve the runtime in the authenticated caller context.
*******************************************************************************/
protected AlertsApi api() throws QException
{
return (new AlertsApi(AlertsRuntime.get()));
}
}
@@ -0,0 +1,160 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.api;
import java.util.Map;
import com.kingsrook.qbits.alerts.AlertsRuntime;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QBadRequestException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.utils.CollectionUtils;
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
import com.kingsrook.qqq.middleware.javalin.QJavalinMetaData;
import com.kingsrook.qqq.middleware.javalin.QJavalinRouteProviderInterface;
import com.kingsrook.qqq.middleware.javalin.QJavalinUtils;
import io.javalin.config.JavalinConfig;
import io.javalin.http.ContentType;
import io.javalin.http.Context;
/*******************************************************************************
** Machine webhook routes. The UI routes are registered through AlertsUiApi.
*******************************************************************************/
public class AlertsRouteProvider implements QJavalinRouteProviderInterface
{
private static final QLogger LOG = QLogger.getLogger(AlertsRouteProvider.class);
public static final String WEBHOOK_PATH = "/qqq/hooks/alerts/alertmanager";
public static final String LEGACY_SUNSET = "Tue, 13 Apr 2027 00:00:00 GMT";
public static final String BASE_PATH = "/qqq/v1/alerts";
static final int MAX_INGEST_BYTES = 1024 * 1024;
private QInstance qInstance;
/*******************************************************************************
** Register this provider once with the instance's Javalin meta-data.
*******************************************************************************/
public static void register(QInstance qInstance)
{
QJavalinMetaData javalinMetaData = QJavalinMetaData.ofOrWithNew(qInstance);
boolean registered = CollectionUtils.nonNullList(javalinMetaData.getAdditionalRouteProviderReferences()).stream()
.anyMatch(reference -> reference != null && AlertsRouteProvider.class.getName().equals(reference.getName()));
if(!registered)
{
javalinMetaData.withAdditionalRouteProviderReference(new QCodeReference(AlertsRouteProvider.class));
}
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public void setQInstance(QInstance qInstance)
{
this.qInstance = qInstance;
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public void acceptJavalinConfig(JavalinConfig config)
{
config.routes.post(WEBHOOK_PATH, this::ingestAlertmanager);
if(Boolean.TRUE.equals(AlertsRuntime.find(qInstance).getConfig().getLegacyAlertmanagerPath()))
{
config.routes.post(BASE_PATH + "/ingest/alertmanager", context ->
{
context.header("Deprecation", "true");
context.header("Sunset", LEGACY_SUNSET);
LOG.warn("Deprecated Alertmanager webhook called; migrate to " + WEBHOOK_PATH);
ingestAlertmanager(context);
});
}
}
/*******************************************************************************
** Alertmanager's webhook (no QQQ session: a bearer token instead).
*******************************************************************************/
private void ingestAlertmanager(Context context)
{
try
{
if(context.body().length() > MAX_INGEST_BYTES)
{
throw (new QBadRequestException("The payload is larger than 1 MB."));
}
com.kingsrook.qbits.alerts.engine.AlertmanagerIngest ingest = new com.kingsrook.qbits.alerts.engine.AlertmanagerIngest(AlertsRuntime.get(qInstance));
ingest.authenticate(context.header("Authorization"));
com.kingsrook.qbits.alerts.engine.AlertmanagerIngest.Result result = ingest.ingest(readJsonBody(context));
context.contentType(ContentType.APPLICATION_JSON);
context.result(JsonUtils.toJson(Map.of("raised", result.raised(), "resolved", result.resolved(), "ignored", result.ignored())));
}
catch(Exception e)
{
QJavalinUtils.handleException(null, context, e);
}
finally
{
QContext.clear();
}
}
/*******************************************************************************
** The JSON body (an object), or 400.
*******************************************************************************/
@SuppressWarnings("unchecked")
private static Map<String, Object> readJsonBody(Context context) throws QBadRequestException
{
String contentType = context.contentType();
if(contentType == null || !contentType.toLowerCase().startsWith("application/json"))
{
throw (new QBadRequestException("The request body must be JSON (Content-Type: application/json)."));
}
String body = context.body();
if(!StringUtils.hasContent(body))
{
return (Map.of());
}
try
{
return (JsonUtils.toObject(body, Map.class));
}
catch(Exception e)
{
throw (new QBadRequestException("The request body is not valid JSON."));
}
}
}
@@ -0,0 +1,306 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.api;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import com.kingsrook.qqq.middleware.javalin.schemabuilder.ToSchema;
import com.kingsrook.qqq.openapi.model.Schema;
import com.kingsrook.qqq.openapi.model.Type;
/*******************************************************************************
** Explicit versioned wire schemas, independent of persistence entities.
*******************************************************************************/
public final class AlertsSchemas
{
/*******************************************************************************
** Utility class.
*******************************************************************************/
private AlertsSchemas()
{
}
/*******************************************************************************
** The complete component set shared by the six operations.
*******************************************************************************/
public static Map<String, Schema> components()
{
return (new TreeMap<>(Map.ofEntries(
Map.entry("AlertsActionV1", new AlertsActionV1(null, null, null, null, null).toSchema()),
Map.entry("AlertsInboxItemV1", new AlertsInboxItemV1(null, null, null, null, null, null, null, null, null, null, null, null, null, null, null).toSchema()),
Map.entry("AlertsPanelAlertV1", new AlertsPanelAlertV1(null, null, null, null, null, null, null, null, null).toSchema()),
Map.entry("AlertsFollowV1", new AlertsFollowV1(null).toSchema()),
Map.entry("AlertsInboxSummaryV1", new AlertsInboxSummaryV1(null, null, null, null, null, null, null, null).toSchema()),
Map.entry("AlertsInboxPageV1", new AlertsInboxPageV1(null, null, null, null).toSchema()),
Map.entry("AlertsRecordPanelV1", new AlertsRecordPanelV1(null, null, null, null, null, null, null, null).toSchema()),
Map.entry("AlertsMutationResultV1", new AlertsMutationResultV1(null).toSchema()),
Map.entry("AlertsInboxTargetV1", new AlertsInboxTargetV1(null, null, null, null).toSchema()),
Map.entry("AlertsUnreadTargetV1", new AlertsUnreadTargetV1(null, null, null).toSchema()),
Map.entry("AlertsErrorV1", new AlertsErrorV1(null).toSchema()))));
}
/*******************************************************************************
** An available action: operationId targets an inbox operation with this item id; process actions provide a complete href.
*******************************************************************************/
public record AlertsActionV1(String name, String label, String operationId, String processName, String href) implements ToSchema
{
/*******************************************************************************
** Describe the public JSON shape.
*******************************************************************************/
@Override
public Schema toSchema()
{
return (new Schema().withType(Type.OBJECT).withDescription("An available action: operationId targets an inbox operation with this item id; process actions provide a complete href.").withProperties(new TreeMap<>(Map.ofEntries(
Map.entry("name", new Schema().withType(Type.STRING)),
Map.entry("label", new Schema().withType(Type.STRING)),
Map.entry("operationId", new Schema().withType(Type.STRING)),
Map.entry("processName", new Schema().withType(Type.STRING)),
Map.entry("href", new Schema().withType(Type.STRING))))));
}
}
/*******************************************************************************
** A notification recipient. body is included only in page items and banners; alertId only for ALERT notifications.
*******************************************************************************/
public record AlertsInboxItemV1(Integer id, Integer notificationId, String title, String body, String severity, String category, String source, String href, String linkLabel, String deliveredAt, String age, Boolean unread, Boolean sticky, Integer alertId, List<AlertsActionV1> actions) implements ToSchema
{
/*******************************************************************************
** Describe the public JSON shape.
*******************************************************************************/
@Override
public Schema toSchema()
{
return (new Schema().withType(Type.OBJECT).withDescription("A notification recipient. body is included only in page items and banners; alertId only for ALERT notifications.").withProperties(new TreeMap<>(Map.ofEntries(
Map.entry("id", new Schema().withType(Type.INTEGER)),
Map.entry("notificationId", new Schema().withType(Type.INTEGER)),
Map.entry("title", new Schema().withType(Type.STRING).withNullable(true)),
Map.entry("body", new Schema().withType(Type.STRING).withNullable(true)),
Map.entry("severity", new Schema().withType(Type.STRING).withNullable(true)),
Map.entry("category", new Schema().withType(Type.STRING).withNullable(true)),
Map.entry("source", new Schema().withType(Type.STRING).withNullable(true)),
Map.entry("href", new Schema().withType(Type.STRING).withNullable(true).withDescription("Existing safe link, or null.")),
Map.entry("linkLabel", new Schema().withType(Type.STRING).withNullable(true)),
Map.entry("deliveredAt", new Schema().withType(Type.STRING).withNullable(true)),
Map.entry("age", new Schema().withType(Type.STRING)),
Map.entry("unread", new Schema().withType(Type.BOOLEAN)),
Map.entry("sticky", new Schema().withType(Type.BOOLEAN)),
Map.entry("alertId", new Schema().withType(Type.INTEGER).withNullable(true)),
Map.entry("actions", new Schema().withType(Type.ARRAY).withItems(new Schema().withRefToSchema("AlertsActionV1")))))));
}
}
/*******************************************************************************
** A visible open alert with permission-aware process actions.
*******************************************************************************/
public record AlertsPanelAlertV1(Integer alertId, String title, String severity, String status, String group, String age, String raisedAt, String href, List<AlertsActionV1> actions) implements ToSchema
{
/*******************************************************************************
** Describe the public JSON shape.
*******************************************************************************/
@Override
public Schema toSchema()
{
return (new Schema().withType(Type.OBJECT).withDescription("A visible open alert with permission-aware process actions.").withProperties(new TreeMap<>(Map.ofEntries(
Map.entry("alertId", new Schema().withType(Type.INTEGER)),
Map.entry("title", new Schema().withType(Type.STRING).withNullable(true)),
Map.entry("severity", new Schema().withType(Type.STRING).withNullable(true)),
Map.entry("status", new Schema().withType(Type.STRING).withNullable(true)),
Map.entry("group", new Schema().withType(Type.STRING).withNullable(true)),
Map.entry("age", new Schema().withType(Type.STRING)),
Map.entry("raisedAt", new Schema().withType(Type.STRING).withNullable(true)),
Map.entry("href", new Schema().withType(Type.STRING)),
Map.entry("actions", new Schema().withType(Type.ARRAY).withItems(new Schema().withRefToSchema("AlertsActionV1")))))));
}
}
/*******************************************************************************
** Capability discovery only. Next obtains the follow URL from its collaboration module.
*******************************************************************************/
public record AlertsFollowV1(Boolean available) implements ToSchema
{
/*******************************************************************************
** Describe the public JSON shape.
*******************************************************************************/
@Override
public Schema toSchema()
{
return (new Schema().withType(Type.OBJECT).withDescription("Capability discovery only. Next obtains the follow URL from its collaboration module.").withProperties(new TreeMap<>(Map.ofEntries(
Map.entry("available", new Schema().withType(Type.BOOLEAN).withDescription("True exactly when the collaboration UI API extension is registered."))))));
}
}
/*******************************************************************************
** Bell summary, latest ten items and up to three sticky banners.
*******************************************************************************/
public record AlertsInboxSummaryV1(Integer unreadCount, String highestUnreadSeverity, List<AlertsInboxItemV1> items, List<AlertsInboxItemV1> banners, String notificationsHref, String inboxHref, String alertsHref, Integer pollSeconds) implements ToSchema
{
/*******************************************************************************
** Describe the public JSON shape.
*******************************************************************************/
@Override
public Schema toSchema()
{
return (new Schema().withType(Type.OBJECT).withDescription("Bell summary, latest ten items and up to three sticky banners.").withProperties(new TreeMap<>(Map.ofEntries(
Map.entry("unreadCount", new Schema().withType(Type.INTEGER)),
Map.entry("highestUnreadSeverity", new Schema().withType(Type.STRING).withNullable(true)),
Map.entry("items", new Schema().withType(Type.ARRAY).withItems(new Schema().withRefToSchema("AlertsInboxItemV1"))),
Map.entry("banners", new Schema().withType(Type.ARRAY).withItems(new Schema().withRefToSchema("AlertsInboxItemV1"))),
Map.entry("notificationsHref", new Schema().withType(Type.STRING).withDescription("Existing notifications page link; retained for compatibility.")),
Map.entry("inboxHref", new Schema().withType(Type.STRING).withDescription("Canonical inbox navigation link.")),
Map.entry("alertsHref", new Schema().withType(Type.STRING)),
Map.entry("pollSeconds", new Schema().withType(Type.INTEGER))))));
}
}
/*******************************************************************************
** Filtered notification page.
*******************************************************************************/
public record AlertsInboxPageV1(List<AlertsInboxItemV1> items, Integer total, Integer offset, Integer limit) implements ToSchema
{
/*******************************************************************************
** Describe the public JSON shape.
*******************************************************************************/
@Override
public Schema toSchema()
{
return (new Schema().withType(Type.OBJECT).withDescription("Filtered notification page.").withProperties(new TreeMap<>(Map.ofEntries(
Map.entry("items", new Schema().withType(Type.ARRAY).withItems(new Schema().withRefToSchema("AlertsInboxItemV1"))),
Map.entry("total", new Schema().withType(Type.INTEGER)),
Map.entry("offset", new Schema().withType(Type.INTEGER)),
Map.entry("limit", new Schema().withType(Type.INTEGER))))));
}
}
/*******************************************************************************
** Open alerts, recent resolutions and collaboration capability. watching is deprecated legacy subscription state.
*******************************************************************************/
public record AlertsRecordPanelV1(Boolean visible, Integer openCount, List<AlertsPanelAlertV1> open, Integer resolvedLast30Days, String viewAllHref, Boolean canManage, Boolean watching, AlertsFollowV1 follow) implements ToSchema
{
/*******************************************************************************
** Describe the public JSON shape.
*******************************************************************************/
@Override
public Schema toSchema()
{
return (new Schema().withType(Type.OBJECT).withDescription("Open alerts, recent resolutions and collaboration capability. watching is deprecated legacy subscription state.").withProperties(new TreeMap<>(Map.ofEntries(
Map.entry("visible", new Schema().withType(Type.BOOLEAN)),
Map.entry("openCount", new Schema().withType(Type.INTEGER)),
Map.entry("open", new Schema().withType(Type.ARRAY).withItems(new Schema().withRefToSchema("AlertsPanelAlertV1"))),
Map.entry("resolvedLast30Days", new Schema().withType(Type.INTEGER)),
Map.entry("viewAllHref", new Schema().withType(Type.STRING).withNullable(true)),
Map.entry("canManage", new Schema().withType(Type.BOOLEAN)),
Map.entry("watching", new Schema().withType(Type.BOOLEAN).withDescription("Deprecated: existing RECORD subscriptions only; does not represent collaboration follow state.")),
Map.entry("follow", new Schema().withRefToSchema("AlertsFollowV1"))))));
}
}
/*******************************************************************************
** Number of the caller own recipient rows changed.
*******************************************************************************/
public record AlertsMutationResultV1(Integer updated) implements ToSchema
{
/*******************************************************************************
** Describe the public JSON shape.
*******************************************************************************/
@Override
public Schema toSchema()
{
return (new Schema().withType(Type.OBJECT).withDescription("Number of the caller own recipient rows changed.").withProperties(new TreeMap<>(Map.ofEntries(
Map.entry("updated", new Schema().withType(Type.INTEGER))))));
}
}
/*******************************************************************************
** Select id, nonempty ids (first 500), legacy alertId, or all:true in that precedence. All scans are capped at 1000 rows.
*******************************************************************************/
public record AlertsInboxTargetV1(Integer id, List<Integer> ids, Integer alertId, Boolean all) implements ToSchema
{
/*******************************************************************************
** Describe the public JSON shape.
*******************************************************************************/
@Override
public Schema toSchema()
{
return (new Schema().withType(Type.OBJECT).withDescription("Select id, nonempty ids (first 500), legacy alertId, or all:true in that precedence. All scans are capped at 1000 rows.").withProperties(new TreeMap<>(Map.ofEntries(
Map.entry("id", new Schema().withType(Type.INTEGER)),
Map.entry("ids", new Schema().withType(Type.ARRAY).withItems(new Schema().withType(Type.INTEGER))),
Map.entry("alertId", new Schema().withType(Type.INTEGER)),
Map.entry("all", new Schema().withType(Type.BOOLEAN))))));
}
}
/*******************************************************************************
** Select id or nonempty ids (first 500), in that precedence. Legacy alertId is also accepted for compatibility. all is not supported.
*******************************************************************************/
public record AlertsUnreadTargetV1(Integer id, List<Integer> ids, Integer alertId) implements ToSchema
{
/*******************************************************************************
** Describe the public JSON shape.
*******************************************************************************/
@Override
public Schema toSchema()
{
return (new Schema().withType(Type.OBJECT).withDescription("Select id or nonempty ids (first 500), in that precedence. Legacy alertId is also accepted for compatibility. all is not supported.").withProperties(new TreeMap<>(Map.ofEntries(
Map.entry("id", new Schema().withType(Type.INTEGER)),
Map.entry("ids", new Schema().withType(Type.ARRAY).withItems(new Schema().withType(Type.INTEGER))),
Map.entry("alertId", new Schema().withType(Type.INTEGER))))));
}
}
/*******************************************************************************
** Framework error response.
*******************************************************************************/
public record AlertsErrorV1(String error) implements ToSchema
{
/*******************************************************************************
** Describe the public JSON shape.
*******************************************************************************/
@Override
public Schema toSchema()
{
return (new Schema().withType(Type.OBJECT).withDescription("Framework error response.").withProperties(new TreeMap<>(Map.ofEntries(
Map.entry("error", new Schema().withType(Type.STRING).withNullable(true))))));
}
}
}
@@ -0,0 +1,60 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.api;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.middleware.javalin.specs.extensions.MiddlewareSpecExtension;
import com.kingsrook.qqq.middleware.javalin.specs.extensions.MiddlewareSpecExtensionsMetaData;
/*******************************************************************************
** The alerts UI API, retaining the established /alerts namespace.
*******************************************************************************/
public final class AlertsUiApi
{
/*******************************************************************************
** Utility class.
*******************************************************************************/
private AlertsUiApi()
{
}
/*******************************************************************************
** Register once, alongside the optional Javalin webhook provider.
*******************************************************************************/
public static void register(QInstance instance)
{
MiddlewareSpecExtensionsMetaData.ofOrWithNew(instance).withExtension(extension());
}
/*******************************************************************************
** The independently versioned, discoverable UI contract.
*******************************************************************************/
public static MiddlewareSpecExtension extension()
{
return (new MiddlewareSpecExtension().withName("alerts").withPathPrefix("/alerts")
.withSemanticVersion("1.0.0").withDescription("Alerts inbox and record panel")
.withSpec(InboxSummarySpec.class).withSpec(InboxSpec.class)
.withSpec(InboxReadSpec.class).withSpec(InboxUnreadSpec.class)
.withSpec(InboxDismissSpec.class).withSpec(RecordPanelSpec.class));
}
}
@@ -0,0 +1,87 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.api;
import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation;
import com.kingsrook.qqq.openapi.model.HttpMethod;
import com.kingsrook.qqq.openapi.model.Schema;
/*******************************************************************************
** Dismiss own notifications.
*******************************************************************************/
public class InboxDismissSpec extends AlertsJsonSpec
{
public static final String OPERATION_ID = "alertsInboxDismiss";
/*******************************************************************************
** Describe the established method and path.
*******************************************************************************/
@Override
public BasicOperation defineBasicOperation()
{
return (new BasicOperation().withHttpMethod(HttpMethod.POST).withPath("/alerts/inbox/dismiss")
.withShortSummary("Dismiss own notifications").withLongDescription("Uses the signed-in caller's permissions and record visibility."));
}
/*******************************************************************************
** Stable identifier for generated clients.
*******************************************************************************/
@Override
protected String operationId()
{
return (OPERATION_ID);
}
/*******************************************************************************
** Versioned response schema.
*******************************************************************************/
@Override
protected String getResponseSchemaName()
{
return ("AlertsMutationResultV1");
}
/*******************************************************************************
** Recipient selectors; precedence is id, ids, alertId, then all.
*******************************************************************************/
@Override
protected Schema defineRequestBodySchema()
{
return (new Schema().withRefToSchema("AlertsInboxTargetV1"));
}
/*******************************************************************************
** Invoke the existing service with the caller session.
*******************************************************************************/
@Override
protected Object handle(JsonInput input) throws Exception
{
return (api().dismiss(input.getBody()));
}
}
@@ -0,0 +1,87 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.api;
import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation;
import com.kingsrook.qqq.openapi.model.HttpMethod;
import com.kingsrook.qqq.openapi.model.Schema;
/*******************************************************************************
** Mark own notifications read.
*******************************************************************************/
public class InboxReadSpec extends AlertsJsonSpec
{
public static final String OPERATION_ID = "alertsInboxRead";
/*******************************************************************************
** Describe the established method and path.
*******************************************************************************/
@Override
public BasicOperation defineBasicOperation()
{
return (new BasicOperation().withHttpMethod(HttpMethod.POST).withPath("/alerts/inbox/read")
.withShortSummary("Mark own notifications read").withLongDescription("Uses the signed-in caller's permissions and record visibility."));
}
/*******************************************************************************
** Stable identifier for generated clients.
*******************************************************************************/
@Override
protected String operationId()
{
return (OPERATION_ID);
}
/*******************************************************************************
** Versioned response schema.
*******************************************************************************/
@Override
protected String getResponseSchemaName()
{
return ("AlertsMutationResultV1");
}
/*******************************************************************************
** Recipient selectors; precedence is id, ids, alertId, then all.
*******************************************************************************/
@Override
protected Schema defineRequestBodySchema()
{
return (new Schema().withRefToSchema("AlertsInboxTargetV1"));
}
/*******************************************************************************
** Invoke the existing service with the caller session.
*******************************************************************************/
@Override
protected Object handle(JsonInput input) throws Exception
{
return (api().markRead(input.getBody()));
}
}
@@ -0,0 +1,96 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.api;
import java.util.List;
import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation;
import com.kingsrook.qqq.openapi.model.HttpMethod;
import com.kingsrook.qqq.openapi.model.In;
import com.kingsrook.qqq.openapi.model.Parameter;
import com.kingsrook.qqq.openapi.model.Schema;
import com.kingsrook.qqq.openapi.model.Type;
/*******************************************************************************
** Page the notification inbox.
*******************************************************************************/
public class InboxSpec extends AlertsJsonSpec
{
public static final String OPERATION_ID = "alertsInbox";
/*******************************************************************************
** Describe the established method and path.
*******************************************************************************/
@Override
public BasicOperation defineBasicOperation()
{
return (new BasicOperation().withHttpMethod(HttpMethod.GET).withPath("/alerts/inbox")
.withShortSummary("Page the notification inbox").withLongDescription("Uses the signed-in caller's permissions and record visibility."));
}
/*******************************************************************************
** Stable identifier for generated clients.
*******************************************************************************/
@Override
protected String operationId()
{
return (OPERATION_ID);
}
/*******************************************************************************
** Versioned response schema.
*******************************************************************************/
@Override
protected String getResponseSchemaName()
{
return ("AlertsInboxPageV1");
}
/*******************************************************************************
** Existing query parameters and paging semantics.
*******************************************************************************/
@Override
public List<Parameter> defineRequestParameters()
{
return (List.of(
new Parameter().withName("status").withIn(In.QUERY).withRequired(false).withSchema(new Schema().withType(Type.STRING)).withDescription("all or unread; other values behave as all."),
new Parameter().withName("category").withIn(In.QUERY).withRequired(false).withSchema(new Schema().withType(Type.STRING)).withDescription("Case-insensitive category filter."),
new Parameter().withName("severity").withIn(In.QUERY).withRequired(false).withSchema(new Schema().withType(Type.STRING)).withDescription("Case-insensitive severity filter."),
new Parameter().withName("offset").withIn(In.QUERY).withRequired(false).withSchema(new Schema().withType(Type.INTEGER)).withDescription("Default 0; negatives clamp to 0; malformed values use the default."),
new Parameter().withName("limit").withIn(In.QUERY).withRequired(false).withSchema(new Schema().withType(Type.INTEGER)).withDescription("Default 25; clamped to 1..100; malformed values use the default.")));
}
/*******************************************************************************
** Invoke the existing service with the caller session.
*******************************************************************************/
@Override
protected Object handle(JsonInput input) throws Exception
{
return (api().inbox(input.getQueryParams()));
}
}
@@ -0,0 +1,88 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.api;
import java.util.Map;
import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation;
import com.kingsrook.qqq.openapi.model.HttpMethod;
import com.kingsrook.qqq.openapi.model.Schema;
/*******************************************************************************
** Read the bell summary.
*******************************************************************************/
public class InboxSummarySpec extends AlertsJsonSpec
{
public static final String OPERATION_ID = "alertsInboxSummary";
/*******************************************************************************
** Describe the established method and path.
*******************************************************************************/
@Override
public BasicOperation defineBasicOperation()
{
return (new BasicOperation().withHttpMethod(HttpMethod.GET).withPath("/alerts/inbox/summary")
.withShortSummary("Read the bell summary").withLongDescription("Uses the signed-in caller's permissions and record visibility."));
}
/*******************************************************************************
** Stable identifier for generated clients.
*******************************************************************************/
@Override
protected String operationId()
{
return (OPERATION_ID);
}
/*******************************************************************************
** Versioned response schema.
*******************************************************************************/
@Override
protected String getResponseSchemaName()
{
return ("AlertsInboxSummaryV1");
}
/*******************************************************************************
** Publish shared components once; all six extension specs register together.
*******************************************************************************/
@Override
public Map<String, Schema> defineComponentSchemas()
{
return (AlertsSchemas.components());
}
/*******************************************************************************
** Invoke the existing service with the caller session.
*******************************************************************************/
@Override
protected Object handle(JsonInput input) throws Exception
{
return (api().inboxSummary());
}
}
@@ -0,0 +1,87 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.api;
import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation;
import com.kingsrook.qqq.openapi.model.HttpMethod;
import com.kingsrook.qqq.openapi.model.Schema;
/*******************************************************************************
** Mark own notifications unread.
*******************************************************************************/
public class InboxUnreadSpec extends AlertsJsonSpec
{
public static final String OPERATION_ID = "alertsInboxUnread";
/*******************************************************************************
** Describe the established method and path.
*******************************************************************************/
@Override
public BasicOperation defineBasicOperation()
{
return (new BasicOperation().withHttpMethod(HttpMethod.POST).withPath("/alerts/inbox/unread")
.withShortSummary("Mark own notifications unread").withLongDescription("Uses the signed-in caller's permissions and record visibility."));
}
/*******************************************************************************
** Stable identifier for generated clients.
*******************************************************************************/
@Override
protected String operationId()
{
return (OPERATION_ID);
}
/*******************************************************************************
** Versioned response schema.
*******************************************************************************/
@Override
protected String getResponseSchemaName()
{
return ("AlertsMutationResultV1");
}
/*******************************************************************************
** Recipient selectors; precedence is id, ids, alertId, then all.
*******************************************************************************/
@Override
protected Schema defineRequestBodySchema()
{
return (new Schema().withRefToSchema("AlertsUnreadTargetV1"));
}
/*******************************************************************************
** Invoke the existing service with the caller session.
*******************************************************************************/
@Override
protected Object handle(JsonInput input) throws Exception
{
return (api().markUnread(input.getBody()));
}
}
@@ -0,0 +1,93 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.api;
import java.util.List;
import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation;
import com.kingsrook.qqq.openapi.model.HttpMethod;
import com.kingsrook.qqq.openapi.model.In;
import com.kingsrook.qqq.openapi.model.Parameter;
import com.kingsrook.qqq.openapi.model.Schema;
import com.kingsrook.qqq.openapi.model.Type;
/*******************************************************************************
** Read visible alerts for a record.
*******************************************************************************/
public class RecordPanelSpec extends AlertsJsonSpec
{
public static final String OPERATION_ID = "alertsRecordPanel";
/*******************************************************************************
** Describe the established method and path.
*******************************************************************************/
@Override
public BasicOperation defineBasicOperation()
{
return (new BasicOperation().withHttpMethod(HttpMethod.GET).withPath("/alerts/record-panel")
.withShortSummary("Read visible alerts for a record").withLongDescription("Uses the signed-in caller's permissions and record visibility."));
}
/*******************************************************************************
** Stable identifier for generated clients.
*******************************************************************************/
@Override
protected String operationId()
{
return (OPERATION_ID);
}
/*******************************************************************************
** Versioned response schema.
*******************************************************************************/
@Override
protected String getResponseSchemaName()
{
return ("AlertsRecordPanelV1");
}
/*******************************************************************************
** Existing query parameters and paging semantics.
*******************************************************************************/
@Override
public List<Parameter> defineRequestParameters()
{
return (List.of(
new Parameter().withName("tableName").withIn(In.QUERY).withRequired(true).withSchema(new Schema().withType(Type.STRING)).withDescription("Parent table name."),
new Parameter().withName("recordId").withIn(In.QUERY).withRequired(true).withSchema(new Schema().withType(Type.STRING)).withDescription("Parent record key.")));
}
/*******************************************************************************
** Invoke the existing service with the caller session.
*******************************************************************************/
@Override
protected Object handle(JsonInput input) throws Exception
{
return (api().recordPanel(input.getQueryParam("tableName"), input.getQueryParam("recordId")));
}
}
@@ -0,0 +1,255 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.customizers;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import com.kingsrook.qbits.alerts.AlertsQBitConfig;
import com.kingsrook.qbits.alerts.AlertsRuntime;
import com.kingsrook.qbits.alerts.AlertsSecurity;
import com.kingsrook.qbits.alerts.model.AlertsNotification;
import com.kingsrook.qbits.alerts.model.AlertsNotificationPreference;
import com.kingsrook.qbits.alerts.model.AlertsNotificationRecipient;
import com.kingsrook.qbits.alerts.notifications.NotificationService;
import com.kingsrook.qbits.alerts.spi.NotificationAudience;
import com.kingsrook.qbits.alerts.spi.NotificationCategory;
import com.kingsrook.qqq.backend.core.actions.customizers.AbstractPreInsertCustomizer;
import com.kingsrook.qqq.backend.core.actions.customizers.TableCustomizerInterface;
import com.kingsrook.qqq.backend.core.actions.tables.DeleteAction;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.tables.delete.DeleteInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterCriteria;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.tables.Capability;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import com.kingsrook.qqq.backend.core.model.statusmessages.BadInputStatusMessage;
import com.kingsrook.qqq.backend.core.model.statusmessages.PermissionDeniedMessage;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
/*******************************************************************************
** Rules for the notification tables, in the core actions (so the admin, the
** API and the bell all follow them):
** - Notifications: the author is the session user; new ones start as
** DRAFT (sending is a record action); status and the send bookkeeping
** can't be edited; links must be app paths or https; an audience needs
** its values. Deleting one deletes its recipient rows.
** - Recipients: people change only read and dismissed on their own rows
** (the owner lock); the qbit inserts and deletes them.
** - Notification settings: the user id is the session's; SECURITY can't be
** muted in-app.
** The system user (the qbit itself) is not restricted.
*******************************************************************************/
public class AlertsNotificationCustomizer implements TableCustomizerInterface
{
private static final Set<String> NOTIFICATION_SYSTEM_FIELDS = Set.of("status", "authorUserId", "sentAt", "retractedAt", "recipientCount", "readCount");
private static final Set<String> RECIPIENT_EDITABLE_FIELDS = Set.of("id", "readAt", "dismissedAt");
/*******************************************************************************
** Stamp the user and author before QQQ's required-field and security-lock
** checks, so they check the values this customizer sets.
*******************************************************************************/
@Override
public AbstractPreInsertCustomizer.WhenToRun whenToRunPreInsert(InsertInput insertInput, boolean isPreview)
{
return (AbstractPreInsertCustomizer.WhenToRun.BEFORE_ALL_VALIDATIONS);
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public List<QRecord> preInsert(InsertInput insertInput, List<QRecord> records, boolean isPreview) throws QException
{
if(AlertsSecurity.isSystemUser())
{
return (records);
}
String tableName = insertInput.getTableName();
if(AlertsNotificationRecipient.TABLE_NAME.equals(tableName))
{
return (AlertsWriteGuardCustomizer.deny(tableName, Capability.TABLE_INSERT, records));
}
String userId = AlertsSecurity.userId(QContext.getQSession());
for(QRecord record : records)
{
if(AlertsNotification.TABLE_NAME.equals(tableName))
{
record.setValue("authorUserId", userId);
record.setValue("status", NotificationService.STATUS_DRAFT);
for(String field : List.of("sentAt", "retractedAt", "recipientCount", "readCount"))
{
record.removeValue(field);
}
if(!StringUtils.hasContent(record.getValueString("sourceName")))
{
record.setValue("sourceName", "admin");
}
checkNotification(record);
}
else if(AlertsNotificationPreference.TABLE_NAME.equals(tableName))
{
if(!isAlertsAdmin() || record.getValue("userId") == null)
{
record.setValue("userId", userId);
}
checkPreference(record);
}
}
return (records);
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public List<QRecord> preUpdate(UpdateInput updateInput, List<QRecord> records, boolean isPreview, Optional<List<QRecord>> oldRecordList) throws QException
{
if(AlertsSecurity.isSystemUser())
{
return (records);
}
String tableName = updateInput.getTableName();
for(QRecord record : records)
{
if(AlertsNotification.TABLE_NAME.equals(tableName))
{
for(String field : NOTIFICATION_SYSTEM_FIELDS)
{
record.removeValue(field);
}
checkNotification(record);
}
else if(AlertsNotificationRecipient.TABLE_NAME.equals(tableName))
{
for(String field : new ArrayList<>(record.getValues().keySet()))
{
if(!RECIPIENT_EDITABLE_FIELDS.contains(field))
{
record.removeValue(field);
}
}
}
else if(AlertsNotificationPreference.TABLE_NAME.equals(tableName))
{
record.removeValue("userId");
QRecord merged = new QRecord(record);
oldRecordList.flatMap(old -> old.stream().filter(o -> o.getValue("id") != null && o.getValue("id").equals(record.getValue("id"))).findFirst())
.ifPresent(old -> old.getValues().forEach((field, value) -> merged.getValues().putIfAbsent(field, value)));
checkPreference(merged);
merged.getErrors().forEach(record::addError);
}
}
return (records);
}
/*******************************************************************************
** People never delete recipient rows; deleting a notification deletes its
** recipients first (as the qbit).
*******************************************************************************/
@Override
public List<QRecord> preDelete(DeleteInput deleteInput, List<QRecord> records, boolean isPreview) throws QException
{
String tableName = deleteInput.getTableName();
if(AlertsNotificationRecipient.TABLE_NAME.equals(tableName))
{
return (AlertsSecurity.isSystemUser() ? records : AlertsWriteGuardCustomizer.deny(tableName, Capability.TABLE_DELETE, records));
}
if(AlertsNotification.TABLE_NAME.equals(tableName) && !isPreview)
{
List<Serializable> ids = records.stream().map(record -> (Serializable) record.getValueInteger("id")).filter(id -> id != null).toList();
if(!ids.isEmpty())
{
AlertsRuntime.get().asSystem(() -> new DeleteAction().execute(new DeleteInput(AlertsNotificationRecipient.TABLE_NAME)
.withQueryFilter(new QQueryFilter(new QFilterCriteria("notificationId", QCriteriaOperator.IN, ids)))));
}
}
return (records);
}
/*******************************************************************************
** A notification's link and audience (the fields present on the record).
*******************************************************************************/
static void checkNotification(QRecord record)
{
if(record.getValues().containsKey("linkUrl") && StringUtils.hasContent(record.getValueString("linkUrl")) && NotificationService.safeLink(record.getValueString("linkUrl")) == null)
{
record.addError(new BadInputStatusMessage("The link must be an app path (starting with /) or an https URL."));
}
if(record.getValues().containsKey("audienceType"))
{
NotificationAudience audience = NotificationAudience.parse(record.getValueString("audienceType"), record.getValueString("audienceValue"));
if(audience == null)
{
record.addError(new BadInputStatusMessage("Choose who the notification is for."));
}
else if(audience.getType() != NotificationAudience.Type.ALL_USERS && audience.getValues().isEmpty())
{
record.addError(new BadInputStatusMessage("List the " + switch(audience.getType())
{
case ROLES -> "roles or groups";
case PERMISSION -> "permission";
default -> "user ids";
} + " in Audience Members."));
}
}
}
/*******************************************************************************
** SECURITY notices can't be muted in-app.
*******************************************************************************/
static void checkPreference(QRecord record)
{
if(NotificationCategory.SECURITY.name().equals(record.getValueString("category")) && Boolean.TRUE.equals(record.getValueBoolean("inAppMuted")))
{
record.addError(new PermissionDeniedMessage("Security notices can't be muted in-app; you can still choose how they are emailed."));
}
}
/*******************************************************************************
**
*******************************************************************************/
private static boolean isAlertsAdmin()
{
QSession session = QContext.getQSession();
return (session != null && session.hasPermission(AlertsQBitConfig.PERMISSION_ADMIN));
}
}
@@ -0,0 +1,152 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.customizers;
import java.util.List;
import java.util.Optional;
import com.kingsrook.qbits.alerts.AlertsQBitConfig;
import com.kingsrook.qbits.alerts.AlertsSecurity;
import com.kingsrook.qbits.alerts.model.AlertsMute;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues;
import com.kingsrook.qbits.alerts.model.AlertsSubscription;
import com.kingsrook.qbits.alerts.model.AlertsUserPreference;
import com.kingsrook.qqq.backend.core.actions.customizers.TableCustomizerInterface;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import com.kingsrook.qqq.backend.core.model.statusmessages.BadInputStatusMessage;
import com.kingsrook.qqq.backend.core.model.statusmessages.PermissionDeniedMessage;
/*******************************************************************************
** Keeps personal rows personal (design section 7.1), in the core actions:
** - Subscriptions: anyone with alerts.view subscribes themselves (the user
** id is set from the session); only alerts.admin may create team or
** channel subscriptions or subscribe someone else.
** - My Alert Settings: the user id is the session's.
** - Mutes: the creator is recorded; only alerts.admin may suppress alerts
** (SUPPRESS_ALERTS, a maintenance window), others only silence.
*******************************************************************************/
public class AlertsSubscriptionCustomizer implements TableCustomizerInterface
{
/*******************************************************************************
**
*******************************************************************************/
@Override
public List<QRecord> preInsert(InsertInput insertInput, List<QRecord> records, boolean isPreview) throws QException
{
for(QRecord record : records)
{
apply(insertInput.getTableName(), record, true);
}
return (records);
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public List<QRecord> preUpdate(UpdateInput updateInput, List<QRecord> records, boolean isPreview, Optional<List<QRecord>> oldRecordList) throws QException
{
for(QRecord record : records)
{
apply(updateInput.getTableName(), record, false);
}
return (records);
}
/*******************************************************************************
** Stamp or check one record.
*******************************************************************************/
static void apply(String tableName, QRecord record, boolean isInsert)
{
if(AlertsSecurity.isSystemUser())
{
return;
}
QSession session = QContext.getQSession();
String userId = AlertsSecurity.userId(session);
boolean admin = session != null && session.hasPermission(AlertsQBitConfig.PERMISSION_ADMIN);
switch(tableName)
{
case AlertsSubscription.TABLE_NAME ->
{
String subscriberType = record.getValueString("subscriberType");
if(isInsert)
{
record.setValue("createdByUserId", userId);
if(subscriberType == null)
{
subscriberType = AlertsPossibleValues.SubscriberType.USER.name();
record.setValue("subscriberType", subscriberType);
}
if(AlertsPossibleValues.SubscriberType.USER.name().equals(subscriberType) && (!admin || record.getValue("userId") == null))
{
record.setValue("userId", userId);
}
}
if(!admin && subscriberType != null && !AlertsPossibleValues.SubscriberType.USER.name().equals(subscriberType))
{
record.addError(new PermissionDeniedMessage("Only alerts admins can subscribe a team or a channel."));
}
if(AlertsPossibleValues.SubscriberType.TEAM.name().equals(subscriberType) && record.getValue("teamId") == null)
{
record.addError(new BadInputStatusMessage("Choose the team to subscribe."));
}
if(AlertsPossibleValues.SubscriberType.CHANNEL.name().equals(subscriberType) && record.getValue("channelId") == null)
{
record.addError(new BadInputStatusMessage("Choose the channel to subscribe."));
}
}
case AlertsUserPreference.TABLE_NAME ->
{
if(isInsert && (!admin || record.getValue("userId") == null))
{
record.setValue("userId", userId);
}
}
case AlertsMute.TABLE_NAME ->
{
if(isInsert)
{
record.setValue("createdByUserId", userId);
}
if(!admin && AlertsPossibleValues.MuteEffect.SUPPRESS_ALERTS.name().equals(record.getValueString("effect")))
{
record.addError(new PermissionDeniedMessage("Only alerts admins can create maintenance windows that suppress alerts."));
}
}
default ->
{
//////////////////////////////
// nothing for other tables //
//////////////////////////////
}
}
}
}
@@ -0,0 +1,99 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.customizers;
import java.util.List;
import java.util.Optional;
import com.kingsrook.qbits.alerts.AlertsSecurity;
import com.kingsrook.qqq.backend.core.actions.customizers.TableCustomizerInterface;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.tables.delete.DeleteInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.tables.Capability;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import com.kingsrook.qqq.backend.core.model.statusmessages.PermissionDeniedMessage;
/*******************************************************************************
** Enforces, in the core actions, what a table's capabilities hide in the UI
** and API: an insert, update or delete the table does not offer is rejected
** unless the qbit itself (the system user) makes it. So alerts, timelines
** and notifications only change through the engine and record actions,
** whoever calls the table actions (admins included).
*******************************************************************************/
public class AlertsWriteGuardCustomizer implements TableCustomizerInterface
{
/*******************************************************************************
**
*******************************************************************************/
@Override
public List<QRecord> preInsert(InsertInput insertInput, List<QRecord> records, boolean isPreview) throws QException
{
return (deny(insertInput.getTableName(), Capability.TABLE_INSERT, records));
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public List<QRecord> preUpdate(UpdateInput updateInput, List<QRecord> records, boolean isPreview, Optional<List<QRecord>> oldRecordList) throws QException
{
return (deny(updateInput.getTableName(), Capability.TABLE_UPDATE, records));
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public List<QRecord> preDelete(DeleteInput deleteInput, List<QRecord> records, boolean isPreview) throws QException
{
return (deny(deleteInput.getTableName(), Capability.TABLE_DELETE, records));
}
/*******************************************************************************
** Add an error to every record when the table lacks the capability and the
** caller is not the system user.
*******************************************************************************/
static List<QRecord> deny(String tableName, Capability capability, List<QRecord> records)
{
if(AlertsSecurity.isSystemUser())
{
return (records);
}
QTableMetaData table = QContext.getQInstance().getTable(tableName);
if(table != null && table.getDisabledCapabilities() != null && table.getDisabledCapabilities().contains(capability))
{
for(QRecord record : records)
{
record.addError(new PermissionDeniedMessage("Only the Alerts qbit changes this table; use the record actions instead."));
}
}
return (records);
}
}
@@ -0,0 +1,53 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.delivery;
import java.util.List;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
/*******************************************************************************
** A channel type (design section 5.6): in-app, email, an email list, and
** later Slack, Teams, webhooks, PagerDuty and Alertmanager. Register more
** with AlertsQBitConfig.withChannelType, so another qbit can add one without
** touching this one.
**
** The message is already rendered and redacted for the channel's detail
** level; a channel never sees an alert's raw details. Secrets come only from
** the channel's secretRef, resolved at send time.
*******************************************************************************/
public interface AlertChannelInterface
{
/***************************************************************************
** The channel type this implements (an alerts_channel channelType).
***************************************************************************/
String getType();
/***************************************************************************
** Problems with a channel row's settings (empty when it can send).
***************************************************************************/
List<String> validate(QRecord channel, AlertSecretResolver secrets);
/***************************************************************************
** Send one message to one recipient (an address for email; null for
** channels that post to a fixed place). Never throws: the result says
** SENT, RETRY or FAILED (permanent).
***************************************************************************/
DeliveryResult deliver(AlertMessage message, QRecord channel, String recipientAddress, AlertSecretResolver secrets);
}
@@ -0,0 +1,164 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.delivery;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.kingsrook.qbits.alerts.AlertsRuntime;
import com.kingsrook.qbits.alerts.engine.AlertsDb;
import com.kingsrook.qbits.alerts.model.AlertsChannel;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.ChannelType;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.HealthStatus;
import com.kingsrook.qqq.backend.core.actions.customizers.QCodeLoader;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
/*******************************************************************************
** The channel types (built-in in-app, email, email list, Slack, Teams,
** webhook, PagerDuty and Alertmanager, plus any the config adds) and the two default channel rows every install has: "in-app"
** (the bell; always available) and "email" (a person's own address).
*******************************************************************************/
public class AlertChannels
{
private static final QLogger LOG = QLogger.getLogger(AlertChannels.class);
public static final String DEFAULT_IN_APP = "in-app";
public static final String DEFAULT_EMAIL = "email";
private final AlertsRuntime runtime;
private final Map<String, AlertChannelInterface> types = new LinkedHashMap<>();
private final AlertSecretResolver secrets = new AlertSecretResolver();
/*******************************************************************************
** Constructor
*******************************************************************************/
public AlertChannels(AlertsRuntime runtime)
{
this.runtime = runtime;
register(new InAppChannel());
register(new EmailChannel(runtime.getConfig(), ChannelType.EMAIL));
register(new EmailChannel(runtime.getConfig(), ChannelType.EMAIL_LIST));
for(AlertChannelInterface external : com.kingsrook.qbits.alerts.delivery.channels.ExternalChannels.all())
{
register(external);
}
for(QCodeReference reference : runtime.getConfig().getChannelTypes())
{
try
{
AlertChannelInterface channel = QCodeLoader.getAdHoc(AlertChannelInterface.class, reference);
if(channel != null)
{
register(channel);
}
}
catch(Exception e)
{
LOG.warn("Could not load an alerts channel type", e, logPair("channelType", reference.getName()));
}
}
}
/*******************************************************************************
** Add (or replace) a channel type.
*******************************************************************************/
public void register(AlertChannelInterface channel)
{
types.put(channel.getType(), channel);
}
/*******************************************************************************
** The implementation for a channel type, or null.
*******************************************************************************/
public AlertChannelInterface forType(String channelType)
{
return (channelType == null ? null : types.get(channelType));
}
/*******************************************************************************
** The registered type names.
*******************************************************************************/
public List<String> typeNames()
{
return (List.copyOf(types.keySet()));
}
/*******************************************************************************
** The secret resolver.
*******************************************************************************/
public AlertSecretResolver getSecrets()
{
return (secrets);
}
/*******************************************************************************
** The default in-app or email channel row, created if missing. Runs in the
** caller's (system) context.
*******************************************************************************/
public QRecord defaultChannel(ChannelType channelType) throws QException
{
String name = channelType == ChannelType.IN_APP ? DEFAULT_IN_APP : DEFAULT_EMAIL;
QRecord existing = AlertsDb.first(AlertsChannel.TABLE_NAME, AlertsDb.eq("name", name));
if(existing != null)
{
return (existing);
}
return (AlertsDb.insert(AlertsChannel.TABLE_NAME, new QRecord()
.withValue("name", name)
.withValue("label", channelType == ChannelType.IN_APP ? "In-App (Bell)" : "Email (Personal Address)")
.withValue("channelType", channelType.name())
.withValue("enabled", true)
.withValue("detailLevel", channelType == ChannelType.IN_APP ? "FULL" : "MINIMAL")
.withValue("minSeverity", "INFO")
.withValue("rateLimitPerHour", channelType == ChannelType.IN_APP ? 0 : 60)
.withValue("healthStatus", HealthStatus.HEALTHY.name())
.withValue("consecutiveFailures", 0)));
}
/*******************************************************************************
** Make sure both default channels exist.
*******************************************************************************/
public void ensureDefaults() throws QException
{
runtime.asSystem(() ->
{
defaultChannel(ChannelType.IN_APP);
defaultChannel(ChannelType.EMAIL);
return (null);
});
}
}
@@ -0,0 +1,78 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.delivery;
import java.util.List;
/*******************************************************************************
** A rendered, redacted message for one channel and recipient: one alert, or
** a batch of several that arrived together ("3 new alerts").
**
** @param subject one line (email subject, chat headline)
** @param text plain-text body
** @param html simple HTML body (escaped)
** @param severity the highest severity in the message
** @param kind RAISED, RESOLVED, REMINDER, ESCALATED, DIGEST or TEST
** @param alertIds the alerts in the message
** @param link a link to the alert (or the Alerts list) in the app
** @param entries one structured entry per alert, for channels that send
** one event per alert (PagerDuty, Alertmanager, webhooks);
** already redacted and capped by the detail level
*******************************************************************************/
public record AlertMessage(String subject, String text, String html, String severity, String kind, List<Integer> alertIds, String link, List<Entry> entries)
{
/*******************************************************************************
** A message without structured entries.
*******************************************************************************/
public AlertMessage(String subject, String text, String html, String severity, String kind, List<Integer> alertIds, String link)
{
this(subject, text, html, severity, kind, alertIds, link, List.of());
}
/*******************************************************************************
** One alert, as structured channels send it.
**
** @param alertId the alert's id (null for a test message)
** @param alertTypeName the type, e.g. cdn.purge.dead
** @param typeLabel the type's label
** @param dedupKey the producer's dedup key
** @param severity INFO, WARNING, ERROR or CRITICAL
** @param status OPEN, ACKNOWLEDGED, SNOOZED or RESOLVED
** @param title the redacted title
** @param summary the redacted summary (null at MINIMAL)
** @param group the group's label
** @param itemCount the record count (null at MINIMAL)
** @param link the alert in the app
** @param firstRaisedAt when it opened (ISO)
** @param resolvedAt when it resolved (ISO), or null
*******************************************************************************/
public record Entry(Integer alertId, String alertTypeName, String typeLabel, String dedupKey, String severity, String status, String title, String summary,
String group, Integer itemCount, String link, String firstRaisedAt, String resolvedAt)
{
/***************************************************************************
** The stable key for systems that dedup (PagerDuty, Alertmanager).
***************************************************************************/
public String stableKey()
{
return ((alertTypeName == null ? "alerts.test" : alertTypeName) + ":" + (dedupKey == null ? String.valueOf(alertId) : dedupKey));
}
}
}
@@ -0,0 +1,232 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.delivery;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.kingsrook.qbits.alerts.home.HomeHtml;
import com.kingsrook.qbits.alerts.model.AlertsAlert;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.DeliveryKind;
import com.kingsrook.qqq.backend.core.alerts.AlertSeverity;
import com.kingsrook.qqq.backend.core.alerts.DetailLevel;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
/*******************************************************************************
** Renders alerts into a message for an external channel, from fixed
** templates (producers supply only data), at a detail level (design 7.4):
** - MINIMAL: severity, type label, group, title, age and one link;
** - STANDARD: adds the summary and the counts;
** - FULL: adds the details.
** The level is the lower of the channel's and the type's ceiling. Every
** string except the generated link goes through AlertRedactor.
*******************************************************************************/
public final class AlertMessageRenderer
{
/*******************************************************************************
** What the renderer knows about one alert.
**
** @param alert the alerts_alert row
** @param typeLabel its type's label
** @param groupLabel its group's label
** @param level the effective detail level for this channel
*******************************************************************************/
public record Item(QRecord alert, String typeLabel, String groupLabel, DetailLevel level)
{
}
/*******************************************************************************
** Rendering only.
*******************************************************************************/
private AlertMessageRenderer()
{
}
/*******************************************************************************
** One message for one or more alerts.
*******************************************************************************/
public static AlertMessage render(List<Item> items, DeliveryKind kind, String publicBaseUrl, Instant now)
{
AlertSeverity highest = AlertSeverity.INFO;
List<Integer> alertIds = new ArrayList<>();
for(Item item : items)
{
AlertSeverity severity = AlertSeverity.fromLabel(item.alert().getValueString("severity"), AlertSeverity.WARNING);
if(severity.compareTo(highest) > 0)
{
highest = severity;
}
alertIds.add(item.alert().getValueInteger("id"));
}
String base = StringUtils.hasContent(publicBaseUrl) ? publicBaseUrl.replaceAll("/+$", "") : "";
String prefix = kind == DeliveryKind.TEST ? "TEST: " : "";
String subject;
String link;
if(items.size() == 1)
{
QRecord alert = items.get(0).alert();
String state = kind == DeliveryKind.RESOLVED ? "RESOLVED" : AlertSeverity.fromLabel(alert.getValueString("severity"), AlertSeverity.WARNING).name();
subject = prefix + "[" + state + "] " + AlertRedactor.redact(alert.getValueString("title"));
link = base + "/app/" + AlertsAlert.TABLE_NAME + "/" + alert.getValue("id");
}
else
{
String group = commonGroup(items);
subject = prefix + items.size() + (kind == DeliveryKind.RESOLVED ? " alerts resolved" : " new alerts") + (group == null ? "" : " in " + group);
link = base + "/app/" + AlertsAlert.TABLE_NAME;
}
StringBuilder text = new StringBuilder();
StringBuilder html = new StringBuilder("<div style=\"font-family:sans-serif;font-size:14px;line-height:1.5\">");
if(kind == DeliveryKind.TEST)
{
text.append("This is a test notification from Alerts.\n\n");
html.append("<p><strong>This is a test notification from Alerts.</strong></p>");
}
for(Item item : items)
{
QRecord alert = item.alert();
DetailLevel level = item.level() == null ? DetailLevel.MINIMAL : item.level();
String line = "[" + alert.getValueString("severity") + "] " + safe(item.typeLabel()) + (item.groupLabel() == null ? "" : " / " + safe(item.groupLabel()))
+ ": " + safe(alert.getValueString("title")) + " (" + age(alert.getValueInstant("firstRaisedAt"), now) + ")";
text.append(line).append('\n');
html.append("<p><strong>").append(HomeHtml.escape(line)).append("</strong>");
if(level.compareTo(DetailLevel.STANDARD) >= 0)
{
if(StringUtils.hasContent(alert.getValueString("summary")))
{
text.append(safe(alert.getValueString("summary"))).append('\n');
html.append("<br>").append(HomeHtml.escape(safe(alert.getValueString("summary"))));
}
Integer count = alert.getValueInteger("itemCount");
if(count != null)
{
text.append(count == 1 ? "1 record" : count + " records").append('\n');
html.append("<br>").append(count == 1 ? "1 record" : count + " records");
}
}
if(level == DetailLevel.FULL && StringUtils.hasContent(alert.getValueString("details")))
{
text.append(safe(alert.getValueString("details"))).append('\n');
html.append("<br><span style=\"white-space:pre-wrap\">").append(HomeHtml.escape(safe(alert.getValueString("details")))).append("</span>");
}
html.append("</p>");
text.append('\n');
}
text.append("Open: ").append(link).append("\n\n");
text.append("Change or stop these emails: ").append(base).append("/app/alerts_subscription\n");
text.append("Personal data and secrets are removed from alert messages.\n");
html.append("<p><a href=\"").append(HomeHtml.escape(link)).append("\">Open in Alerts</a></p>");
html.append("<p style=\"font-size:12px;opacity:.75\"><a href=\"").append(HomeHtml.escape(base + "/app/alerts_subscription")).append("\">Change or stop these emails</a>. ")
.append("Personal data and secrets are removed from alert messages.</p></div>");
List<AlertMessage.Entry> entries = new ArrayList<>();
for(Item item : items)
{
QRecord alert = item.alert();
DetailLevel level = item.level() == null ? DetailLevel.MINIMAL : item.level();
boolean standard = level.compareTo(DetailLevel.STANDARD) >= 0;
Integer id = alert.getValueInteger("id");
entries.add(new AlertMessage.Entry(id, alert.getValueString("alertTypeName"), safe(item.typeLabel()), alert.getValueString("dedupKey"),
AlertSeverity.fromLabel(alert.getValueString("severity"), AlertSeverity.WARNING).name(),
kind == DeliveryKind.RESOLVED ? "RESOLVED" : (alert.getValueString("status") == null ? "OPEN" : alert.getValueString("status")),
safe(alert.getValueString("title")), standard ? AlertRedactor.redact(alert.getValueString("summary")) : null, item.groupLabel(),
standard ? alert.getValueInteger("itemCount") : null, id == null ? base + "/app/" + AlertsAlert.TABLE_NAME : base + "/app/" + AlertsAlert.TABLE_NAME + "/" + id,
alert.getValueInstant("firstRaisedAt") == null ? null : alert.getValueInstant("firstRaisedAt").toString(),
alert.getValueInstant("resolvedAt") == null ? null : alert.getValueInstant("resolvedAt").toString()));
}
return (new AlertMessage(subject, text.toString(), html.toString(), highest.name(), kind.name(), alertIds, link, entries));
}
/*******************************************************************************
** The group all items share, or null.
*******************************************************************************/
private static String commonGroup(List<Item> items)
{
String group = items.get(0).groupLabel();
for(Item item : items)
{
if(group == null || !group.equals(item.groupLabel()))
{
return (null);
}
}
return (group);
}
/*******************************************************************************
** Redacted text (null is empty).
*******************************************************************************/
private static String safe(String text)
{
return (text == null ? "" : AlertRedactor.redact(text));
}
/*******************************************************************************
** "3 h", "12 min", "2 d".
*******************************************************************************/
public static String age(Instant since, Instant now)
{
if(since == null || now == null)
{
return ("now");
}
Duration duration = Duration.between(since, now);
if(duration.isNegative() || duration.toMinutes() < 1)
{
return ("just now");
}
if(duration.toMinutes() < 60)
{
return (duration.toMinutes() + " min");
}
if(duration.toHours() < 48)
{
return (duration.toHours() + " h");
}
return (duration.toDays() + " d");
}
/*******************************************************************************
** Labels by id, for items (helper for callers that cache them).
*******************************************************************************/
public static String label(Map<Integer, String> labels, Integer id)
{
return (id == null ? null : labels.get(id));
}
}
@@ -0,0 +1,78 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.delivery;
import java.util.List;
import java.util.regex.Pattern;
/*******************************************************************************
** Masks personal data and secrets in every outbound string (design section
** 7.4): URLs with credentials, JWTs, bearer tokens, key= / secret= /
** password= / token= values, email addresses, IPv4 and IPv6 addresses,
** phone numbers, and long hex or base64 strings (32+ characters). Titles and
** summaries are meant to be written without personal data; this is the
** safety net.
*******************************************************************************/
public final class AlertRedactor
{
public static final String MASK = "[redacted]";
private static final List<Pattern> PATTERNS = List.of(
Pattern.compile("\\b[a-zA-Z][a-zA-Z0-9+.-]*://[^\\s/:@]+:[^\\s/@]+@[^\\s]+"),
Pattern.compile("\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+"),
Pattern.compile("(?i)\\bbearer\\s+[A-Za-z0-9._~+/=-]+"),
Pattern.compile("(?i)\\b(api[_-]?key|key|secret|password|passwd|pwd|token|access[_-]?token)\\s*[=:]\\s*[^\\s,;&]+"),
Pattern.compile("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"),
Pattern.compile("\\b(?:(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\b"),
Pattern.compile("(?i)\\b(?:[0-9a-f]{1,4}:){2,7}[0-9a-f]{1,4}\\b"),
Pattern.compile("\\+\\d[\\d ().-]{7,}\\d"),
Pattern.compile("\\(\\d{3}\\)\\s?\\d{3}[-.\\s]\\d{4}\\b"),
Pattern.compile("\\b\\d{3}[-.\\s]\\d{3}[-.\\s]\\d{4}\\b"),
Pattern.compile("\\b[A-Fa-f0-9]{32,}\\b"),
Pattern.compile("\\b[A-Za-z0-9+/_-]{32,}={0,2}"));
/*******************************************************************************
** Masking only.
*******************************************************************************/
private AlertRedactor()
{
}
/*******************************************************************************
** The text with every sensitive match replaced by [redacted] (null stays
** null).
*******************************************************************************/
public static String redact(String text)
{
if(text == null || text.isEmpty())
{
return (text);
}
String result = text;
for(Pattern pattern : PATTERNS)
{
result = pattern.matcher(result).replaceAll(MASK);
}
return (result);
}
}
@@ -0,0 +1,89 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.delivery;
import com.kingsrook.qqq.backend.core.instances.QMetaDataVariableInterpreter;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
/*******************************************************************************
** Resolves a channel's secretRef at send time (design section 7.3). The
** reference is a name, never a value: an environment variable name
** (SLACK_ALERTS_WEBHOOK) or a QQQ variable expression (${env.NAME},
** ${prop.name}), which also covers Kubernetes secrets injected as
** environment variables and .env files. Values are never stored, logged or
** shown.
*******************************************************************************/
public class AlertSecretResolver
{
private final QMetaDataVariableInterpreter interpreter;
/*******************************************************************************
** Constructor
*******************************************************************************/
public AlertSecretResolver()
{
this(new QMetaDataVariableInterpreter());
}
/*******************************************************************************
** Constructor (tests can pass an interpreter with value maps)
*******************************************************************************/
public AlertSecretResolver(QMetaDataVariableInterpreter interpreter)
{
this.interpreter = interpreter;
}
/*******************************************************************************
** The secret's value, or null when the reference is blank or unresolved.
*******************************************************************************/
public String resolve(String secretRef)
{
if(!StringUtils.hasContent(secretRef))
{
return (null);
}
String expression = secretRef.trim().startsWith("${") ? secretRef.trim() : "${env." + secretRef.trim() + "}";
String value = interpreter.interpret(expression);
if(value == null || value.equals(expression) || value.isBlank())
{
return (null);
}
return (value);
}
/*******************************************************************************
** "present" or "missing", for display.
*******************************************************************************/
public String describe(String secretRef)
{
if(!StringUtils.hasContent(secretRef))
{
return ("none");
}
return (resolve(secretRef) == null ? "missing" : "present");
}
}
@@ -0,0 +1,66 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.delivery;
/*******************************************************************************
** The outcome of one delivery attempt.
**
** @param outcome SENT, RETRY (try again later) or FAILED (permanent)
** @param providerMessageId the provider's id for the message, when it has one
** @param error why it did not send (already redacted)
*******************************************************************************/
public record DeliveryResult(Outcome outcome, String providerMessageId, String error)
{
/*******************************************************************************
** Delivery outcomes.
*******************************************************************************/
public enum Outcome
{
SENT, RETRY, FAILED
}
/*******************************************************************************
** Sent.
*******************************************************************************/
public static DeliveryResult sent(String providerMessageId)
{
return (new DeliveryResult(Outcome.SENT, providerMessageId, null));
}
/*******************************************************************************
** Failed for now; try again.
*******************************************************************************/
public static DeliveryResult retry(String error)
{
return (new DeliveryResult(Outcome.RETRY, null, error));
}
/*******************************************************************************
** Failed for good (bad address, channel not configured).
*******************************************************************************/
public static DeliveryResult failed(String error)
{
return (new DeliveryResult(Outcome.FAILED, null, error));
}
}
@@ -0,0 +1,371 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.delivery;
import java.io.Serializable;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.kingsrook.qbits.alerts.AlertsRuntime;
import com.kingsrook.qbits.alerts.engine.AlertsDb;
import com.kingsrook.qbits.alerts.model.AlertsAlert;
import com.kingsrook.qbits.alerts.model.AlertsChannel;
import com.kingsrook.qbits.alerts.model.AlertsDelivery;
import com.kingsrook.qbits.alerts.model.AlertsGroup;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.ChannelType;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.DeliveryKind;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.DeliveryStatus;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.HealthStatus;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.Resolution;
import com.kingsrook.qbits.alerts.model.AlertsType;
import com.kingsrook.qbits.alerts.model.AlertsUserPreference;
import com.kingsrook.qqq.backend.core.alerts.AlertSeverity;
import com.kingsrook.qqq.backend.core.alerts.AlertSignal;
import com.kingsrook.qqq.backend.core.alerts.DetailLevel;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.exceptions.QUserFacingException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterOrderBy;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
/*******************************************************************************
** Delivers PENDING and due RETRYING notifications (design section 5.5).
** Notifications for the same channel, recipient and kind that are due
** together go out as one message ("3 new alerts in CDN"). Retries back off
** 1 min, 5 min, 15 min, 1 h, 4 h, then the row is DEAD; a permanent failure
** is FAILED at once. Channel health follows the qbit-webhooks model: a
** failure puts a channel on PROBATION, three in a row make it UNHEALTHY and
** raise alerts.channel.failing (routed in-app only, so a broken channel can
** never loop), and a success makes it HEALTHY again.
**
** Claims: a row is marked SENDING with a 2-minute lease before it is sent.
** Two replicas that read the same row in the same instant could both send it
** (at-least-once); run the delivery process on one scheduler node to avoid
** that.
*******************************************************************************/
public class DeliveryWorker
{
private static final QLogger LOG = QLogger.getLogger(DeliveryWorker.class);
public static final String CHANNEL_FAILING_TYPE = "alerts.channel.failing";
static final List<Duration> BACKOFF = List.of(Duration.ofMinutes(1), Duration.ofMinutes(5), Duration.ofMinutes(15), Duration.ofHours(1), Duration.ofHours(4));
private static final int BATCH_LIMIT = 200;
private static final int UNHEALTHY_AFTER = 3;
private final AlertsRuntime runtime;
/*******************************************************************************
** Constructor
*******************************************************************************/
public DeliveryWorker(AlertsRuntime runtime)
{
this.runtime = runtime;
}
/*******************************************************************************
** Send everything due now. Returns how many notifications were attempted.
*******************************************************************************/
public int deliverDue() throws QException
{
return (runtime.asSystem(() ->
{
Instant now = runtime.now();
List<QRecord> due = AlertsDb.query(AlertsDelivery.TABLE_NAME, new QQueryFilter()
.withCriteria("status", QCriteriaOperator.IN, List.of(DeliveryStatus.PENDING.name(), DeliveryStatus.RETRYING.name()))
.withCriteria("nextAttemptAt", QCriteriaOperator.LESS_THAN_OR_EQUALS, now)
.withOrderBy(new QFilterOrderBy("id"))
.withLimit(BATCH_LIMIT));
Map<String, List<QRecord>> groups = new LinkedHashMap<>();
for(QRecord row : due)
{
Instant claimedUntil = row.getValueInstant("claimedUntil");
if(claimedUntil != null && claimedUntil.isAfter(now) && DeliveryStatus.SENDING.name().equals(row.getValueString("status")))
{
continue;
}
AlertsDb.update(AlertsDelivery.TABLE_NAME, new QRecord().withValue("id", row.getValue("id")).withValue("status", DeliveryStatus.SENDING.name())
.withValue("claimedUntil", now.plus(Duration.ofMinutes(2))));
groups.computeIfAbsent(row.getValue("channelId") + "|" + row.getValueString("recipientUserId") + "|" + row.getValueString("kind"), key -> new ArrayList<>()).add(row);
}
int attempted = 0;
for(List<QRecord> group : groups.values())
{
attempted += sendGroup(group, now);
}
return (attempted);
}));
}
/*******************************************************************************
** Queue failed or dead notifications again ("Retry delivery").
*******************************************************************************/
public int retry(List<Serializable> notificationIds) throws QException
{
return (runtime.asSystem(() ->
{
int count = 0;
for(Serializable id : notificationIds)
{
QRecord row = AlertsDb.byId(AlertsDelivery.TABLE_NAME, id);
if(row != null && List.of(DeliveryStatus.FAILED.name(), DeliveryStatus.DEAD.name()).contains(row.getValueString("status")))
{
AlertsDb.update(AlertsDelivery.TABLE_NAME, new QRecord().withValue("id", id).withValue("status", DeliveryStatus.PENDING.name())
.withValue("nextAttemptAt", runtime.now()).withValue("attempts", 0).withValue("claimedUntil", null).withValue("lastError", null));
count++;
}
}
return (count);
}));
}
/*******************************************************************************
** Send a TEST message through a channel now, through the real pipeline (a
** logged notification row). Personal channels (in-app, email) go to the
** person running the test. Returns the notification row.
*******************************************************************************/
public QRecord sendTest(Integer channelId, String actorUserId) throws QException
{
return (runtime.asSystem(() ->
{
QRecord channel = AlertsDb.byId(AlertsChannel.TABLE_NAME, channelId);
if(channel == null)
{
throw (new QUserFacingException("The channel was not found."));
}
String channelType = channel.getValueString("channelType");
boolean personal = ChannelType.IN_APP.name().equals(channelType) || ChannelType.EMAIL.name().equals(channelType);
Instant now = runtime.now();
QRecord row = AlertsDb.insert(AlertsDelivery.TABLE_NAME, new QRecord()
.withValue("channelId", channelId)
.withValue("recipientUserId", personal ? actorUserId : null)
.withValue("recipientLabel", personal ? actorUserId : channel.getValueString("label"))
.withValue("kind", DeliveryKind.TEST.name())
.withValue("status", DeliveryStatus.SENDING.name())
.withValue("attempts", 0)
.withValue("nextAttemptAt", now)
.withValue("claimedUntil", now.plus(Duration.ofMinutes(2))));
sendGroup(List.of(row), now);
return (AlertsDb.byId(AlertsDelivery.TABLE_NAME, row.getValue("id")));
}));
}
/*******************************************************************************
** Render and send one group (same channel, recipient and kind).
*******************************************************************************/
private int sendGroup(List<QRecord> rows, Instant now) throws QException
{
QRecord first = rows.get(0);
QRecord channel = AlertsDb.byId(AlertsChannel.TABLE_NAME, first.getValue("channelId"));
AlertChannelInterface impl = channel == null ? null : runtime.getChannels().forType(channel.getValueString("channelType"));
if(impl == null)
{
for(QRecord row : rows)
{
finish(row, DeliveryResult.failed(channel == null ? "The channel no longer exists." : "No implementation for channel type " + channel.getValueString("channelType") + "."), now);
}
return (rows.size());
}
DeliveryKind kind = DeliveryKind.valueOf(first.getValueString("kind"));
List<AlertMessageRenderer.Item> items = new ArrayList<>();
Map<Integer, QRecord> types = new HashMap<>();
Map<Integer, QRecord> groups = new HashMap<>();
for(QRecord row : rows)
{
QRecord alert = row.getValue("alertId") == null ? testAlert(now) : AlertsDb.byId(AlertsAlert.TABLE_NAME, row.getValue("alertId"));
if(alert == null)
{
continue;
}
QRecord type = alert.getValue("alertTypeId") == null ? null : types.computeIfAbsent(alert.getValueInteger("alertTypeId"), id -> quietly(AlertsType.TABLE_NAME, id));
QRecord group = alert.getValue("groupId") == null ? null : groups.computeIfAbsent(alert.getValueInteger("groupId"), id -> quietly(AlertsGroup.TABLE_NAME, id));
DetailLevel level = DetailLevel.lowerOf(DetailLevel.valueOf(channel.getValueString("detailLevel") == null ? "MINIMAL" : channel.getValueString("detailLevel")),
type == null || type.getValueString("externalDetailCeiling") == null ? DetailLevel.STANDARD : DetailLevel.valueOf(type.getValueString("externalDetailCeiling")));
items.add(new AlertMessageRenderer.Item(alert, type == null ? "Alerts" : type.getValueString("label"), group == null ? null : group.getValueString("label"), level));
}
if(items.isEmpty())
{
for(QRecord row : rows)
{
finish(row, DeliveryResult.failed("The alert no longer exists."), now);
}
return (rows.size());
}
AlertMessage message = AlertMessageRenderer.render(items, kind, runtime.getConfig().getPublicBaseUrl(), now);
String address = null;
if(ChannelType.EMAIL.name().equals(channel.getValueString("channelType")) && first.getValueString("recipientUserId") != null)
{
QRecord preference = AlertsDb.first(AlertsUserPreference.TABLE_NAME, AlertsDb.eq("userId", first.getValueString("recipientUserId")));
address = preference == null ? null : preference.getValueString("emailAddress");
if(!StringUtils.hasContent(address))
{
for(QRecord row : rows)
{
finish(row, DeliveryResult.failed("The recipient has no email address in My Alert Settings."), now);
}
return (rows.size());
}
}
DeliveryResult result;
try
{
result = impl.deliver(message, channel, address, runtime.getChannels().getSecrets());
}
catch(Exception e)
{
result = DeliveryResult.retry(AlertRedactor.redact(e.getClass().getSimpleName() + ": " + e.getMessage()));
}
for(QRecord row : rows)
{
finish(row, result, now);
}
updateChannelHealth(channel, result, now);
return (rows.size());
}
/*******************************************************************************
** Record one row's outcome.
*******************************************************************************/
private void finish(QRecord row, DeliveryResult result, Instant now) throws QException
{
int attempts = (row.getValueInteger("attempts") == null ? 0 : row.getValueInteger("attempts")) + 1;
QRecord update = new QRecord().withValue("id", row.getValue("id")).withValue("attempts", attempts).withValue("claimedUntil", null);
switch(result.outcome())
{
case SENT -> update.withValue("status", DeliveryStatus.SENT.name()).withValue("sentAt", now).withValue("providerMessageId", result.providerMessageId()).withValue("lastError", null);
case FAILED -> update.withValue("status", DeliveryStatus.FAILED.name()).withValue("lastError", truncate(result.error()));
case RETRY ->
{
if(attempts > BACKOFF.size())
{
update.withValue("status", DeliveryStatus.DEAD.name()).withValue("lastError", truncate(result.error()));
}
else
{
update.withValue("status", DeliveryStatus.RETRYING.name()).withValue("nextAttemptAt", now.plus(BACKOFF.get(attempts - 1))).withValue("lastError", truncate(result.error()));
}
}
default -> throw (new IllegalStateException("Unexpected outcome " + result.outcome()));
}
AlertsDb.update(AlertsDelivery.TABLE_NAME, update);
}
/*******************************************************************************
** HEALTHY on success; PROBATION, then UNHEALTHY (and an in-app alert) on
** consecutive failures.
*******************************************************************************/
private void updateChannelHealth(QRecord channel, DeliveryResult result, Instant now) throws QException
{
Integer channelId = channel.getValueInteger("id");
if(result.outcome() == DeliveryResult.Outcome.SENT)
{
boolean wasUnhealthy = !HealthStatus.HEALTHY.name().equals(channel.getValueString("healthStatus"));
AlertsDb.update(AlertsChannel.TABLE_NAME, new QRecord().withValue("id", channelId).withValue("healthStatus", HealthStatus.HEALTHY.name())
.withValue("consecutiveFailures", 0).withValue("lastSuccessAt", now));
if(wasUnhealthy)
{
runtime.getEngine().resolve(CHANNEL_FAILING_TYPE, "channel:" + channelId, Resolution.PRODUCER, null, "A later delivery succeeded");
}
return;
}
int failures = (channel.getValueInteger("consecutiveFailures") == null ? 0 : channel.getValueInteger("consecutiveFailures")) + 1;
String health = failures >= UNHEALTHY_AFTER ? HealthStatus.UNHEALTHY.name() : HealthStatus.PROBATION.name();
AlertsDb.update(AlertsChannel.TABLE_NAME, new QRecord().withValue("id", channelId).withValue("healthStatus", health)
.withValue("consecutiveFailures", failures).withValue("lastFailureAt", now).withValue("lastError", truncate(result.error())));
if(failures == UNHEALTHY_AFTER)
{
LOG.warn("Alerts channel is failing", logPair("channel", channel.getValueString("name")), logPair("failures", failures));
runtime.getEngine().raise(new AlertSignal(CHANNEL_FAILING_TYPE)
.withDedupKey("channel:" + channelId)
.withSeverity(AlertSeverity.ERROR)
.withTitle("Alert channel \"" + channel.getValueString("label") + "\" is failing")
.withSummary(failures + " deliveries in a row failed.")
.withDetails(result.error())
.withRecordRef(com.kingsrook.qqq.backend.core.alerts.AlertRecordRef.of(AlertsChannel.TABLE_NAME, channelId)));
}
}
/*******************************************************************************
** The stand-in alert a TEST message describes.
*******************************************************************************/
private static QRecord testAlert(Instant now)
{
return (new QRecord().withValue("title", "Test notification").withValue("severity", AlertSeverity.INFO.name()).withValue("summary", "If you can read this, the channel works.")
.withValue("firstRaisedAt", now));
}
/*******************************************************************************
** A row by id, or null (no exception), for caches.
*******************************************************************************/
private static QRecord quietly(String tableName, Integer id)
{
try
{
return (AlertsDb.byId(tableName, id));
}
catch(QException e)
{
return (null);
}
}
/*******************************************************************************
**
*******************************************************************************/
private static String truncate(String text)
{
return (text == null || text.length() <= 1900 ? text : text.substring(0, 1900) + "…");
}
}
@@ -0,0 +1,176 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.delivery;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.kingsrook.qbits.alerts.AlertsQBitConfig;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.ChannelType;
import com.kingsrook.qqq.backend.core.actions.messaging.SendMessageAction;
import com.kingsrook.qqq.backend.core.model.actions.messaging.Content;
import com.kingsrook.qqq.backend.core.model.actions.messaging.MultiParty;
import com.kingsrook.qqq.backend.core.model.actions.messaging.Party;
import com.kingsrook.qqq.backend.core.model.actions.messaging.SendMessageInput;
import com.kingsrook.qqq.backend.core.model.actions.messaging.email.EmailContentRole;
import com.kingsrook.qqq.backend.core.model.actions.messaging.email.EmailPartyRole;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
/*******************************************************************************
** Email to a person (EMAIL: the address in their settings) or to a fixed
** list (EMAIL_LIST: settings {"addresses": ["ops@example.com", ...]}), sent
** through QQQ's SendMessageAction and the configured messaging provider
** (SMTP or SES). Plain text plus simple HTML, with a link to change or stop
** the emails. Without a messaging provider the channel fails permanently and
** says why.
*******************************************************************************/
public class EmailChannel implements AlertChannelInterface
{
private final AlertsQBitConfig config;
private final String type;
/*******************************************************************************
** Constructor
*******************************************************************************/
public EmailChannel(AlertsQBitConfig config, ChannelType type)
{
this.config = config;
this.type = type.name();
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public String getType()
{
return (type);
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public List<String> validate(QRecord channel, AlertSecretResolver secrets)
{
List<String> problems = new ArrayList<>();
if(!StringUtils.hasContent(config.getMessagingProviderName()))
{
problems.add("Email is not configured: set messagingProviderName in the Alerts QBit config.");
}
if(!StringUtils.hasContent(config.getFromAddress()))
{
problems.add("Email has no From address: set fromAddress in the Alerts QBit config.");
}
if(ChannelType.EMAIL_LIST.name().equals(type) && listAddresses(channel).isEmpty())
{
problems.add("Add the list's addresses to the channel's settings: {\"addresses\": [\"ops@example.com\"]}.");
}
return (problems);
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public DeliveryResult deliver(AlertMessage message, QRecord channel, String recipientAddress, AlertSecretResolver secrets)
{
List<String> problems = validate(channel, secrets);
if(!problems.isEmpty())
{
return (DeliveryResult.failed(problems.get(0)));
}
List<String> addresses = ChannelType.EMAIL_LIST.name().equals(type) ? listAddresses(channel) : (recipientAddress == null ? List.of() : List.of(recipientAddress));
if(addresses.isEmpty())
{
return (DeliveryResult.failed("No email address."));
}
try
{
MultiParty to = new MultiParty();
for(String address : addresses)
{
to.addParty(new Party().withAddress(address).withRole(EmailPartyRole.TO));
}
new SendMessageAction().execute(new SendMessageInput()
.withMessagingProviderName(config.getMessagingProviderName())
.withFrom(new Party().withAddress(config.getFromAddress()).withRole(EmailPartyRole.FROM))
.withTo(to)
.withSubject(message.subject())
.withContent(new Content().withContentRole(EmailContentRole.TEXT).withBody(message.text()))
.withContent(new Content().withContentRole(EmailContentRole.HTML).withBody(message.html())));
return (DeliveryResult.sent(null));
}
catch(Exception e)
{
return (DeliveryResult.retry(AlertRedactor.redact(e.getClass().getSimpleName() + ": " + e.getMessage())));
}
}
/*******************************************************************************
** The addresses in an email list channel's settings.
*******************************************************************************/
@SuppressWarnings("unchecked")
static List<String> listAddresses(QRecord channel)
{
List<String> addresses = new ArrayList<>();
String settings = channel == null ? null : channel.getValueString("settings");
if(!StringUtils.hasContent(settings))
{
return (addresses);
}
try
{
Map<String, Serializable> map = JsonUtils.toObject(settings, Map.class);
Object value = map.get("addresses");
if(value instanceof List<?> list)
{
for(Object address : list)
{
if(address != null && StringUtils.hasContent(String.valueOf(address)))
{
addresses.add(String.valueOf(address).trim());
}
}
}
}
catch(Exception e)
{
//////////////////////////////////////////////////////
// unreadable settings: no addresses (validate says) //
//////////////////////////////////////////////////////
}
return (addresses);
}
}
@@ -0,0 +1,63 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.delivery;
import java.util.List;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.ChannelType;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
/*******************************************************************************
** The bell. The router delivers in-app notifications itself, by writing the
** user's alerts_inbox_item, so there is nothing left to send here; a pending
** in-app row (a retried one, or a test) counts as sent.
*******************************************************************************/
public class InAppChannel implements AlertChannelInterface
{
/*******************************************************************************
**
*******************************************************************************/
@Override
public String getType()
{
return (ChannelType.IN_APP.name());
}
/*******************************************************************************
** Always available.
*******************************************************************************/
@Override
public List<String> validate(QRecord channel, AlertSecretResolver secrets)
{
return (List.of());
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public DeliveryResult deliver(AlertMessage message, QRecord channel, String recipientAddress, AlertSecretResolver secrets)
{
return (DeliveryResult.sent(null));
}
}
@@ -0,0 +1,448 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.delivery.channels;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import com.kingsrook.qbits.alerts.delivery.AlertChannelInterface;
import com.kingsrook.qbits.alerts.delivery.AlertMessage;
import com.kingsrook.qbits.alerts.delivery.AlertSecretResolver;
import com.kingsrook.qbits.alerts.delivery.DeliveryResult;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.ChannelType;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
/*******************************************************************************
** The optional external channels (design section 5.6). None is required;
** each is an admin-configured alerts_channel row whose secret is a
** reference (secretRef), resolved at send time:
** - SLACK: an Incoming Webhook URL (the URL is the secret); Block Kit body.
** - TEAMS: a Teams Workflows "when a webhook request is received" URL (the
** secret); an Adaptive Card. (Office 365 connectors are retired.)
** - WEBHOOK: settings {"url": ...}; the secret is the HMAC signing key; a
** documented JSON body signed with the Standard Webhooks headers (the
** shared format of QRun-IO/qqq#1105, see StandardWebhookSigner).
** - PAGERDUTY: the Events API v2 routing key (the secret); one
** trigger / acknowledge / resolve event per alert, dedup_key = type:key.
** - ALERTMANAGER: settings {"url": "https://alertmanager:9093"} (optional
** bearer secret); POST /api/v2/alerts with the qqq_* labels and
** qqq_origin="qbit-alerts" (the ingest loop guard); endsAt on resolve.
** No vendor SDKs: plain java.net.http and JSON.
*******************************************************************************/
public final class ExternalChannels
{
public static final String ORIGIN_LABEL = "qqq_origin";
public static final String ORIGIN_VALUE = "qbit-alerts";
static final String PAGERDUTY_URL = "https://events.pagerduty.com/v2/enqueue";
/*******************************************************************************
** Channels only.
*******************************************************************************/
private ExternalChannels()
{
}
/*******************************************************************************
** All five, for registration.
*******************************************************************************/
public static List<AlertChannelInterface> all()
{
return (List.of(new Slack(), new Teams(), new Webhook(), new PagerDuty(), new Alertmanager()));
}
/*******************************************************************************
** Slack Incoming Webhook.
*******************************************************************************/
public static class Slack implements AlertChannelInterface
{
/***************************************************************************
**
***************************************************************************/
@Override
public String getType()
{
return (ChannelType.SLACK.name());
}
/***************************************************************************
**
***************************************************************************/
@Override
public List<String> validate(QRecord channel, AlertSecretResolver secrets)
{
return (secrets.resolve(channel.getValueString("secretRef")) == null ? List.of("Set the secret reference to the Slack Incoming Webhook URL.") : List.of());
}
/***************************************************************************
**
***************************************************************************/
@Override
public DeliveryResult deliver(AlertMessage message, QRecord channel, String recipientAddress, AlertSecretResolver secrets)
{
Map<String, Object> body = new LinkedHashMap<>();
body.put("text", message.subject());
body.put("blocks", List.of(
Map.of("type", "section", "text", Map.of("type", "mrkdwn", "text", "*" + slackEscape(message.subject()) + "*\n" + slackEscape(truncate(message.text(), 2800)))),
Map.of("type", "actions", "elements", List.of(Map.of("type", "button", "text", Map.of("type", "plain_text", "text", "Open in Alerts"), "url", message.link())))));
return (HttpChannelSupport.postJson(secrets.resolve(channel.getValueString("secretRef")), null, HttpChannelSupport.json(body), HttpChannelSupport.allowInsecure(channel)));
}
}
/*******************************************************************************
** Microsoft Teams through a Workflows webhook.
*******************************************************************************/
public static class Teams implements AlertChannelInterface
{
/***************************************************************************
**
***************************************************************************/
@Override
public String getType()
{
return (ChannelType.TEAMS.name());
}
/***************************************************************************
**
***************************************************************************/
@Override
public List<String> validate(QRecord channel, AlertSecretResolver secrets)
{
return (secrets.resolve(channel.getValueString("secretRef")) == null ? List.of("Set the secret reference to the Teams Workflows webhook URL.") : List.of());
}
/***************************************************************************
**
***************************************************************************/
@Override
public DeliveryResult deliver(AlertMessage message, QRecord channel, String recipientAddress, AlertSecretResolver secrets)
{
Map<String, Object> card = new LinkedHashMap<>();
card.put("$schema", "http://adaptivecards.io/schemas/adaptive-card.json");
card.put("type", "AdaptiveCard");
card.put("version", "1.4");
card.put("body", List.of(
Map.of("type", "TextBlock", "text", message.subject(), "weight", "Bolder", "wrap", true),
Map.of("type", "TextBlock", "text", truncate(message.text(), 2800), "wrap", true)));
card.put("actions", List.of(Map.of("type", "Action.OpenUrl", "title", "Open in Alerts", "url", message.link())));
Map<String, Object> body = Map.of("type", "message", "attachments", List.of(Map.of("contentType", "application/vnd.microsoft.card.adaptive", "content", card)));
return (HttpChannelSupport.postJson(secrets.resolve(channel.getValueString("secretRef")), null, HttpChannelSupport.json(body), HttpChannelSupport.allowInsecure(channel)));
}
}
/*******************************************************************************
** Generic signed webhook.
*******************************************************************************/
public static class Webhook implements AlertChannelInterface
{
/***************************************************************************
**
***************************************************************************/
@Override
public String getType()
{
return (ChannelType.WEBHOOK.name());
}
/***************************************************************************
**
***************************************************************************/
@Override
public List<String> validate(QRecord channel, AlertSecretResolver secrets)
{
List<String> problems = new ArrayList<>();
if(!StringUtils.hasContent(Objects.toString(HttpChannelSupport.settings(channel).get("url"), null)))
{
problems.add("Add the receiver's URL to the channel's settings: {\"url\": \"https://...\"}.");
}
if(secrets.resolve(channel.getValueString("secretRef")) == null)
{
problems.add("Set the secret reference to the signing key (a whsec_ secret).");
}
return (problems);
}
/***************************************************************************
**
***************************************************************************/
@Override
public DeliveryResult deliver(AlertMessage message, QRecord channel, String recipientAddress, AlertSecretResolver secrets)
{
List<String> problems = validate(channel, secrets);
if(!problems.isEmpty())
{
return (DeliveryResult.failed(problems.get(0)));
}
Map<String, Object> body = new LinkedHashMap<>();
body.put("type", "qqq.alert." + message.kind().toLowerCase(Locale.ROOT));
body.put("subject", message.subject());
body.put("severity", message.severity());
body.put("link", message.link());
body.put("alerts", message.entries());
byte[] bytes = HttpChannelSupport.json(body);
Map<String, String> headers = StandardWebhookSigner.headers(messageId(message), Instant.now(), bytes, secrets.resolve(channel.getValueString("secretRef")));
return (HttpChannelSupport.postJson(Objects.toString(HttpChannelSupport.settings(channel).get("url")), headers, bytes, HttpChannelSupport.allowInsecure(channel)));
}
}
/*******************************************************************************
** PagerDuty Events API v2.
*******************************************************************************/
public static class PagerDuty implements AlertChannelInterface
{
/***************************************************************************
**
***************************************************************************/
@Override
public String getType()
{
return (ChannelType.PAGERDUTY.name());
}
/***************************************************************************
**
***************************************************************************/
@Override
public List<String> validate(QRecord channel, AlertSecretResolver secrets)
{
return (secrets.resolve(channel.getValueString("secretRef")) == null ? List.of("Set the secret reference to the PagerDuty Events API v2 routing key.") : List.of());
}
/***************************************************************************
** One event per alert; the first failure decides the outcome.
***************************************************************************/
@Override
public DeliveryResult deliver(AlertMessage message, QRecord channel, String recipientAddress, AlertSecretResolver secrets)
{
String routingKey = secrets.resolve(channel.getValueString("secretRef"));
if(routingKey == null)
{
return (DeliveryResult.failed(validate(channel, secrets).get(0)));
}
Map<String, Serializable> settings = HttpChannelSupport.settings(channel);
String url = Objects.toString(settings.get("url"), PAGERDUTY_URL);
String source = Objects.toString(settings.get("source"), ORIGIN_VALUE);
for(AlertMessage.Entry entry : entries(message))
{
String action = "TEST".equals(message.kind()) ? "trigger" : switch(entry.status())
{
case "RESOLVED" -> "resolve";
case "ACKNOWLEDGED" -> "acknowledge";
default -> "trigger";
};
Map<String, Object> event = new LinkedHashMap<>();
event.put("routing_key", routingKey);
event.put("event_action", action);
event.put("dedup_key", entry.stableKey());
if("trigger".equals(action))
{
Map<String, Object> payload = new LinkedHashMap<>();
payload.put("summary", truncate(entry.title(), 1024));
payload.put("source", source);
payload.put("severity", entry.severity().toLowerCase(Locale.ROOT));
payload.put("component", entry.typeLabel());
payload.put("group", entry.group());
Map<String, Object> details = new LinkedHashMap<>();
details.put("summary", entry.summary());
details.put("records", entry.itemCount());
details.put("link", entry.link());
details.values().removeIf(Objects::isNull);
payload.put("custom_details", details);
payload.values().removeIf(Objects::isNull);
event.put("payload", payload);
event.put("links", List.of(Map.of("href", entry.link(), "text", "Open in Alerts")));
}
DeliveryResult result = HttpChannelSupport.postJson(url, null, HttpChannelSupport.json(event), HttpChannelSupport.allowInsecure(channel));
if(result.outcome() != DeliveryResult.Outcome.SENT)
{
return (result);
}
}
return (DeliveryResult.sent(null));
}
}
/*******************************************************************************
** Prometheus Alertmanager as a sink.
*******************************************************************************/
public static class Alertmanager implements AlertChannelInterface
{
/***************************************************************************
**
***************************************************************************/
@Override
public String getType()
{
return (ChannelType.ALERTMANAGER.name());
}
/***************************************************************************
**
***************************************************************************/
@Override
public List<String> validate(QRecord channel, AlertSecretResolver secrets)
{
return (StringUtils.hasContent(Objects.toString(HttpChannelSupport.settings(channel).get("url"), null)) ? List.of()
: List.of("Add Alertmanager's base URL to the channel's settings: {\"url\": \"https://alertmanager:9093\"}."));
}
/***************************************************************************
** One POST with every alert. Open alerts get an endsAt a week out, so
** they stay active without a re-post; a resolve sends endsAt = when.
***************************************************************************/
@Override
public DeliveryResult deliver(AlertMessage message, QRecord channel, String recipientAddress, AlertSecretResolver secrets)
{
List<String> problems = validate(channel, secrets);
if(!problems.isEmpty())
{
return (DeliveryResult.failed(problems.get(0)));
}
List<Map<String, Object>> alerts = new ArrayList<>();
for(AlertMessage.Entry entry : entries(message))
{
Map<String, String> labels = new LinkedHashMap<>();
labels.put("alertname", entry.alertTypeName() == null ? "alerts.test" : entry.alertTypeName());
labels.put("severity", entry.severity().toLowerCase(Locale.ROOT));
labels.put("qqq_type", Objects.toString(entry.alertTypeName(), "alerts.test"));
labels.put("qqq_group", Objects.toString(entry.group(), ""));
labels.put("qqq_key", Objects.toString(entry.dedupKey(), ""));
labels.put(ORIGIN_LABEL, ORIGIN_VALUE);
Map<String, Object> alert = new LinkedHashMap<>();
alert.put("labels", labels);
alert.put("annotations", Map.of("summary", entry.title(), "qqq_url", entry.link()));
alert.put("generatorURL", entry.link());
if(entry.firstRaisedAt() != null)
{
alert.put("startsAt", entry.firstRaisedAt());
}
boolean resolved = "RESOLVED".equals(entry.status()) || "TEST".equals(message.kind());
alert.put("endsAt", resolved ? Objects.toString(entry.resolvedAt(), Instant.now().toString()) : Instant.now().plus(7, ChronoUnit.DAYS).toString());
alerts.add(alert);
}
String bearer = secrets.resolve(channel.getValueString("secretRef"));
Map<String, String> headers = bearer == null ? null : Map.of("Authorization", "Bearer " + bearer);
String base = Objects.toString(HttpChannelSupport.settings(channel).get("url")).replaceAll("/+$", "");
return (HttpChannelSupport.postJson(base + "/api/v2/alerts", headers, HttpChannelSupport.json(alerts), HttpChannelSupport.allowInsecure(channel)));
}
}
/*******************************************************************************
** The message's entries (a TEST message gets one stand-in entry).
*******************************************************************************/
static List<AlertMessage.Entry> entries(AlertMessage message)
{
if(message.entries() != null && !message.entries().isEmpty())
{
return (message.entries());
}
return (List.of(new AlertMessage.Entry(null, "alerts.test", "Test", "test", "INFO", "OPEN", message.subject(), null, null, null, message.link(), null, null)));
}
/*******************************************************************************
** A stable id for a webhook delivery (the same on every retry): a hash of
** the kind and each alert's key and state.
*******************************************************************************/
static String messageId(AlertMessage message)
{
StringBuilder content = new StringBuilder(message.kind());
for(AlertMessage.Entry entry : entries(message))
{
content.append('|').append(entry.alertId()).append(':').append(entry.status()).append(':').append(entry.firstRaisedAt()).append(':').append(entry.resolvedAt());
}
try
{
byte[] digest = MessageDigest.getInstance("SHA-256").digest(content.toString().getBytes(StandardCharsets.UTF_8));
return ("msg_" + HexFormat.of().formatHex(digest).substring(0, 32));
}
catch(Exception e)
{
return ("msg_" + Integer.toHexString(content.toString().hashCode()));
}
}
/*******************************************************************************
** Slack mrkdwn escaping (&, &lt;, &gt;).
*******************************************************************************/
static String slackEscape(String text)
{
return (text == null ? "" : text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;"));
}
/*******************************************************************************
**
*******************************************************************************/
static String truncate(String text, int max)
{
return (text == null || text.length() <= max ? text : text.substring(0, max - 1) + "…");
}
}
@@ -0,0 +1,192 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.delivery.channels;
import java.io.Serializable;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import com.kingsrook.qbits.alerts.delivery.AlertRedactor;
import com.kingsrook.qbits.alerts.delivery.DeliveryResult;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
/*******************************************************************************
** Shared HTTP plumbing for the external channels: one pooled client, a 10
** second timeout, JSON bodies, and the outcome rules:
** - 2xx: SENT;
** - 408, 425, 429 and 5xx, or a network error: RETRY;
** - any other 4xx (a bad URL or key): FAILED, permanently.
** URLs must be https unless the channel's settings say "allowInsecureHttp"
** (for local receivers and tests). Error text is redacted and never includes
** the URL, which for Slack and Teams is itself the secret.
*******************************************************************************/
public final class HttpChannelSupport
{
static final Duration TIMEOUT = Duration.ofSeconds(10);
private static final HttpClient CLIENT = HttpClient.newBuilder()
.connectTimeout(TIMEOUT)
.followRedirects(HttpClient.Redirect.NEVER)
.build();
/*******************************************************************************
** Helpers only.
*******************************************************************************/
private HttpChannelSupport()
{
}
/*******************************************************************************
** POST a JSON body and classify the response.
*******************************************************************************/
public static DeliveryResult postJson(String url, Map<String, String> headers, byte[] body, boolean allowInsecure)
{
String problem = checkUrl(url, allowInsecure);
if(problem != null)
{
return (DeliveryResult.failed(problem));
}
try
{
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(url))
.timeout(TIMEOUT)
.header("Content-Type", "application/json")
.header("User-Agent", "qbit-alerts")
.POST(HttpRequest.BodyPublishers.ofByteArray(body));
if(headers != null)
{
headers.forEach(request::header);
}
HttpResponse<String> response = CLIENT.send(request.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
return (classify(response.statusCode(), response.body()));
}
catch(InterruptedException e)
{
Thread.currentThread().interrupt();
return (DeliveryResult.retry("Interrupted while sending."));
}
catch(Exception e)
{
return (DeliveryResult.retry(AlertRedactor.redact(e.getClass().getSimpleName() + (e.getMessage() == null ? "" : ": " + stripUrl(e.getMessage(), url)))));
}
}
/*******************************************************************************
** SENT, RETRY or FAILED for an HTTP status.
*******************************************************************************/
static DeliveryResult classify(int status, String body)
{
if(status >= 200 && status < 300)
{
return (DeliveryResult.sent(null));
}
String detail = "HTTP " + status + (StringUtils.hasContent(body) ? ": " + AlertRedactor.redact(StringUtils.safeTruncate(body.trim(), 200, "…")) : "");
if(status == 408 || status == 425 || status == 429 || status >= 500)
{
return (DeliveryResult.retry(detail));
}
return (DeliveryResult.failed(detail));
}
/*******************************************************************************
** Why a URL can't be used (null when it can).
*******************************************************************************/
static String checkUrl(String url, boolean allowInsecure)
{
if(!StringUtils.hasContent(url))
{
return ("No URL is configured (check the channel's secret reference or settings).");
}
String lower = url.trim().toLowerCase(Locale.ROOT);
if(lower.startsWith("https://") || (allowInsecure && lower.startsWith("http://")))
{
return (null);
}
return ("The URL must use https.");
}
/*******************************************************************************
** The channel's settings JSON as a map (empty when blank or unreadable).
*******************************************************************************/
@SuppressWarnings("unchecked")
public static Map<String, Serializable> settings(QRecord channel)
{
String json = channel == null ? null : channel.getValueString("settings");
if(!StringUtils.hasContent(json))
{
return (new LinkedHashMap<>());
}
try
{
return (JsonUtils.toObject(json, LinkedHashMap.class));
}
catch(Exception e)
{
return (new LinkedHashMap<>());
}
}
/*******************************************************************************
** Whether the channel allows plain http (local receivers, tests).
*******************************************************************************/
public static boolean allowInsecure(QRecord channel)
{
return (Boolean.TRUE.equals(settings(channel).get("allowInsecureHttp")));
}
/*******************************************************************************
** JSON bytes.
*******************************************************************************/
public static byte[] json(Object body)
{
return (JsonUtils.toJson(body).getBytes(StandardCharsets.UTF_8));
}
/*******************************************************************************
** Remove a (secret) URL from an error message.
*******************************************************************************/
private static String stripUrl(String message, String url)
{
return (url == null ? message : message.replace(url, "[url]"));
}
}
@@ -0,0 +1,81 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.delivery.channels;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import com.kingsrook.qqq.backend.core.utils.webhooks.WebhookSecret;
import com.kingsrook.qqq.backend.core.utils.webhooks.WebhookSigner;
/*******************************************************************************
** Compatibility adapter for the qbit's existing webhook secret strings.
** Core signs every request. Core requires at least 16 key bytes, whereas the
** previous signer accepted shorter keys. HMAC-SHA256 zero-pads keys to its
** 64-byte block size, so padding a short legacy key to 16 bytes preserves
** its signature exactly. New secrets should use WebhookSecret.generate().
*******************************************************************************/
public final class StandardWebhookSigner
{
/*******************************************************************************
** Signing only.
*******************************************************************************/
private StandardWebhookSigner()
{
}
/*******************************************************************************
** The three core Standard Webhooks headers, preserving legacy short keys.
*******************************************************************************/
public static Map<String, String> headers(String messageId, Instant timestamp, byte[] body, String secret)
{
return (WebhookSigner.headers(messageId, timestamp, body, List.of(parseSecret(secret))));
}
/*******************************************************************************
** Preserve raw UTF-8 and whsec_ base64 secrets, including legacy short keys.
*******************************************************************************/
private static WebhookSecret parseSecret(String secret)
{
if(secret == null || secret.isBlank())
{
throw (new IllegalArgumentException("A webhook signing secret is required"));
}
String trimmed = secret.trim();
byte[] key = trimmed.startsWith(WebhookSecret.PREFIX)
? Base64.getDecoder().decode(trimmed.substring(WebhookSecret.PREFIX.length()))
: trimmed.getBytes(StandardCharsets.UTF_8);
if(key.length == 0)
{
throw (new IllegalArgumentException("A webhook signing secret is required"));
}
if(key.length < WebhookSecret.MINIMUM_KEY_BYTES)
{
return (WebhookSecret.parse(WebhookSecret.PREFIX + Base64.getEncoder().encodeToString(Arrays.copyOf(key, WebhookSecret.MINIMUM_KEY_BYTES))));
}
return (WebhookSecret.parse(trimmed));
}
}
@@ -0,0 +1,56 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.engine;
import java.io.Serializable;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import com.kingsrook.qqq.backend.core.alerts.AlertSignal;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
/*******************************************************************************
** A CODE monitor's check (design section 5.3): return every condition that
** is failing now. The engine raises them (on the monitor's type unless a
** signal names another) and resolves this monitor's open alerts whose keys
** the check did not return (a full-state diff). Checks run as the system
** user, with a timeout; a check that throws marks the monitor CHECK_FAILED.
*******************************************************************************/
public interface AlertCheckInterface
{
/***************************************************************************
** Every currently-failing condition. Keys not returned are resolved.
***************************************************************************/
List<AlertSignal> check(Context context) throws QException;
/*******************************************************************************
** What a check gets.
**
** @param monitor the alerts_monitor row
** @param alertTypeName the monitor's alert type
** @param params the definition's "params" object (may be empty)
** @param now the evaluation time
*******************************************************************************/
record Context(QRecord monitor, String alertTypeName, Map<String, Serializable> params, Instant now)
{
}
}
@@ -0,0 +1,628 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.engine;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import com.kingsrook.qbits.alerts.AlertsRuntime;
import com.kingsrook.qbits.alerts.AlertsSecurity;
import com.kingsrook.qbits.alerts.engine.AlertsEngine.AlertTarget;
import com.kingsrook.qbits.alerts.model.AlertsAlert;
import com.kingsrook.qbits.alerts.model.AlertsChannel;
import com.kingsrook.qbits.alerts.model.AlertsDelivery;
import com.kingsrook.qbits.alerts.model.AlertsGroup;
import com.kingsrook.qbits.alerts.model.AlertsMute;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.ChannelType;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.DeliveryKind;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.DeliveryStatus;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.EventType;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.MuteEffect;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.ScopeType;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.SubscriberType;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.SuppressedReason;
import com.kingsrook.qbits.alerts.model.AlertsSubscription;
import com.kingsrook.qbits.alerts.model.AlertsTeamMember;
import com.kingsrook.qbits.alerts.model.AlertsType;
import com.kingsrook.qbits.alerts.model.AlertsUserPreference;
import com.kingsrook.qqq.backend.core.alerts.AlertSeverity;
import com.kingsrook.qqq.backend.core.context.CapturedContext;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import com.kingsrook.qqq.backend.core.modules.authentication.QAuthenticationModuleDispatcher;
import com.kingsrook.qqq.backend.core.modules.authentication.QAuthenticationModuleInterface;
import com.kingsrook.qqq.backend.core.utils.CollectionUtils;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
/*******************************************************************************
** Routing and fan-out (design section 5.4). For a notifiable event:
** 1. collect the enabled subscriptions whose scope matches the alert, whose
** minimum severity it meets, and whose events include this kind;
** 2. expand team subscriptions to their members; keep channel subscriptions;
** 3. check each person can see the alert (section 7.2);
** 4. apply, in order: the type's notify switch, mutes, flapping, the user's
** pause, channel enabled / minimum severity / address / rate limit, and a
** 10-minute duplicate check;
** 5. write an alerts_delivery row per destination (SUPPRESSED rows keep
** their reason, so "why didn't I get it?" is answered by a table), and an
** ALERT notification recipient row per in-app recipient.
** In-app deliveries are complete when the recipient row is written; other
** channels are left PENDING for the delivery worker.
*******************************************************************************/
public class AlertRouter
{
private static final QLogger LOG = QLogger.getLogger(AlertRouter.class);
private static final int DUPLICATE_WINDOW_MINUTES = 10;
private final AlertsRuntime runtime;
/*******************************************************************************
** One destination for one notification.
*******************************************************************************/
record Destination(String userId, QRecord channel, Integer subscriptionId, String minSeverity, QRecord preference)
{
}
/*******************************************************************************
** Constructor
*******************************************************************************/
public AlertRouter(AlertsRuntime runtime)
{
this.runtime = runtime;
}
/*******************************************************************************
** The notification kind for a timeline event (null: not notifiable).
*******************************************************************************/
public static DeliveryKind kindFor(EventType eventType)
{
return switch(eventType)
{
case RAISED, REOPENED, SEVERITY_CHANGED, FLAPPING_STARTED -> DeliveryKind.RAISED;
case RESOLVED -> DeliveryKind.RESOLVED;
case ESCALATED -> DeliveryKind.ESCALATED;
default -> null;
};
}
/*******************************************************************************
** Fan an event out to its subscribers. Never throws: a routing failure is
** logged, and the alert itself is already recorded.
*******************************************************************************/
public void route(QRecord alert, EventType eventType, Integer eventId)
{
DeliveryKind kind = kindFor(eventType);
if(alert == null || kind == null)
{
return;
}
try
{
Instant now = runtime.now();
AlertTarget target = AlertTarget.of(alert);
QRecord type = AlertsDb.byId(AlertsType.TABLE_NAME, alert.getValue("alertTypeId"));
AlertSeverity severity = AlertSeverity.fromLabel(alert.getValueString("severity"), AlertSeverity.WARNING);
List<Destination> destinations = destinations(target, severity, kind);
if(destinations.isEmpty())
{
return;
}
boolean silent = type != null && Boolean.FALSE.equals(type.getValueBoolean("notify"));
boolean muted = isMuted(target, now, MuteEffect.SILENCE_NOTIFICATIONS);
boolean flapping = Boolean.TRUE.equals(alert.getValueBoolean("flapping")) && eventType != EventType.FLAPPING_STARTED;
if(muted && !Boolean.TRUE.equals(alert.getValueBoolean("muted")))
{
AlertsDb.update(AlertsAlert.TABLE_NAME, new QRecord().withValue("id", alert.getValue("id")).withValue("muted", true));
runtime.getEngine().event(alert.getValueInteger("id"), EventType.MUTED, null, null, null, "A mute silenced notifications", now);
}
Map<String, Optional<Boolean>> visibleByUser = new HashMap<>();
int queued = 0;
for(Destination destination : destinations)
{
SuppressedReason reason = null;
String channelType = destination.channel().getValueString("channelType");
boolean inApp = ChannelType.IN_APP.name().equals(channelType);
if(severity == AlertSeverity.INFO && !inApp && !AlertSeverity.INFO.name().equals(destination.minSeverity()))
{
continue;
}
if(!inApp && "alerts.channel.failing".equals(alert.getValueString("alertTypeName")))
{
///////////////////////////////////////////////////////////////
// a broken channel is only ever reported in-app (no loops) //
///////////////////////////////////////////////////////////////
continue;
}
AlertSeverity channelMin = AlertSeverity.fromLabel(destination.channel().getValueString("minSeverity"), null);
if(channelMin != null && !severity.isAtLeast(channelMin) && !inApp)
{
continue;
}
if(silent)
{
reason = SuppressedReason.TYPE_SILENT;
}
else if(muted)
{
reason = SuppressedReason.MUTED;
}
else if(flapping)
{
reason = SuppressedReason.FLAPPING;
}
else if(destination.userId() != null && !visibleByUser.computeIfAbsent(destination.userId(), userId -> knownVisibility(userId, alert))
.orElse(inApp || (alert.getValue("visibilityPermission") == null && alert.getValue("subjectTableName") == null)))
{
reason = SuppressedReason.NOT_VISIBLE;
}
else if(destination.userId() != null && !inApp && isPaused(destination.preference(), now))
{
reason = SuppressedReason.USER_PAUSED;
}
else if(Boolean.FALSE.equals(destination.channel().getValueBoolean("enabled")))
{
reason = SuppressedReason.CHANNEL_DISABLED;
}
else if(ChannelType.EMAIL.name().equals(channelType) && !StringUtils.hasContent(emailAddress(destination)))
{
reason = SuppressedReason.NO_ADDRESS;
}
else if(!inApp && isRateLimited(destination.channel(), now))
{
reason = SuppressedReason.RATE_LIMITED;
}
else if(isDuplicate(alert, destination, kind, now))
{
reason = SuppressedReason.DUPLICATE;
}
QRecord notification = new QRecord()
.withValue("alertId", alert.getValue("id"))
.withValue("alertEventId", eventId)
.withValue("subscriptionId", destination.subscriptionId())
.withValue("channelId", destination.channel().getValue("id"))
.withValue("recipientUserId", destination.userId())
.withValue("recipientLabel", recipientLabel(destination))
.withValue("kind", kind.name())
.withValue("attempts", 0);
if(reason != null)
{
notification.setValue("status", DeliveryStatus.SUPPRESSED.name());
notification.setValue("suppressedReason", reason.name());
AlertsDb.insert(AlertsDelivery.TABLE_NAME, notification);
}
else if(inApp)
{
notification.setValue("status", DeliveryStatus.SENT.name());
notification.setValue("sentAt", now);
QRecord inserted = AlertsDb.insert(AlertsDelivery.TABLE_NAME, notification);
runtime.getNotifications().deliverAlert(destination.userId(), alert, now);
LOG.debug("In-app alert delivered", logPair("deliveryId", inserted.getValue("id")));
queued++;
}
else
{
notification.setValue("status", DeliveryStatus.PENDING.name());
notification.setValue("nextAttemptAt", now);
AlertsDb.insert(AlertsDelivery.TABLE_NAME, notification);
queued++;
}
}
if(queued > 0)
{
AlertsDb.update(AlertsAlert.TABLE_NAME, new QRecord().withValue("id", alert.getValue("id")).withValue("lastNotifiedAt", now));
runtime.getEngine().event(alert.getValueInteger("id"), EventType.NOTIFIED, null, null, String.valueOf(queued),
queued == 1 ? "1 notification" : queued + " notifications", now);
}
}
catch(Exception e)
{
LOG.warn("Error routing alert notifications", e, logPair("alertId", alert.getValue("id")), logPair("eventType", eventType));
}
}
/*******************************************************************************
** Whether an active SUPPRESS_ALERTS maintenance window covers the target.
*******************************************************************************/
public boolean isSuppressedByMaintenance(AlertTarget target, Instant now) throws QException
{
return (isMuted(target, now, MuteEffect.SUPPRESS_ALERTS));
}
/*******************************************************************************
** Whether an enabled mute with this effect is active now and covers the
** target.
*******************************************************************************/
boolean isMuted(AlertTarget target, Instant now, MuteEffect effect) throws QException
{
List<QRecord> mutes = AlertsDb.query(AlertsMute.TABLE_NAME, AlertsDb.eq("enabled", true)
.withCriteria("effect", QCriteriaOperator.EQUALS, effect.name())
.withCriteria("startsAt", QCriteriaOperator.LESS_THAN_OR_EQUALS, now)
.withCriteria("endsAt", QCriteriaOperator.GREATER_THAN, now));
Map<Integer, List<String>> groupNames = new HashMap<>();
for(QRecord mute : mutes)
{
if(scopeMatches(mute.getValueString("scopeType"), mute.getValueString("scopeValue"), null, target, groupNames))
{
return (true);
}
}
return (false);
}
/*******************************************************************************
** Every destination for an alert: subscribed users (directly or through a
** team) with their in-app and email channels (or the subscription's
** chosen channels), and subscribed channels.
*******************************************************************************/
List<Destination> destinations(AlertTarget target, AlertSeverity severity, DeliveryKind kind) throws QException
{
Map<Integer, List<String>> groupNames = new HashMap<>();
Map<String, Destination> destinations = new LinkedHashMap<>();
for(QRecord subscription : AlertsDb.query(AlertsSubscription.TABLE_NAME, AlertsDb.eq("enabled", true)))
{
AlertSeverity min = AlertSeverity.fromLabel(subscription.getValueString("minSeverity"), AlertSeverity.WARNING);
if(!severity.isAtLeast(min) || !includesKind(subscription.getValueString("events"), kind)
|| !scopeMatches(subscription.getValueString("scopeType"), subscription.getValueString("scopeValue"), subscription.getValueString("scopeRecordId"), target, groupNames))
{
continue;
}
Integer subscriptionId = subscription.getValueInteger("id");
String minName = subscription.getValueString("minSeverity");
String subscriberType = subscription.getValueString("subscriberType");
if(SubscriberType.CHANNEL.name().equals(subscriberType))
{
QRecord channel = AlertsDb.byId(AlertsChannel.TABLE_NAME, subscription.getValue("channelId"));
if(channel != null)
{
destinations.putIfAbsent("channel:" + channel.getValue("id"), new Destination(null, channel, subscriptionId, minName, null));
}
continue;
}
List<String> userIds = new ArrayList<>();
if(SubscriberType.TEAM.name().equals(subscriberType))
{
for(QRecord member : AlertsDb.query(AlertsTeamMember.TABLE_NAME, AlertsDb.eq("teamId", subscription.getValue("teamId"))))
{
userIds.add(member.getValueString("userId"));
}
}
else if(StringUtils.hasContent(subscription.getValueString("userId")))
{
userIds.add(subscription.getValueString("userId"));
}
for(String userId : userIds)
{
QRecord preference = AlertsDb.first(AlertsUserPreference.TABLE_NAME, AlertsDb.eq("userId", userId));
for(QRecord channel : userChannels(subscription, preference))
{
destinations.putIfAbsent("user:" + userId + ":" + channel.getValue("id"), new Destination(userId, channel, subscriptionId, minName, preference));
}
}
}
// TODO STAND-IN(core=QRun-IO/qqq#1164, removeBy=4.1.0-RC.7): merge record followers
// from RecordFollowersProviderInterface here, before the existing visibility/suppression checks.
return (new ArrayList<>(destinations.values()));
}
/*******************************************************************************
** A user's channels for a subscription: the ones it names, else in-app
** (unless turned off) and email (when enabled in their settings).
*******************************************************************************/
private List<QRecord> userChannels(QRecord subscription, QRecord preference) throws QException
{
List<QRecord> channels = new ArrayList<>();
String overrides = subscription.getValueString("channelOverrideIds");
if(StringUtils.hasContent(overrides))
{
for(String id : overrides.split("[,\\s]+"))
{
if(!id.isBlank())
{
QRecord channel = AlertsDb.byId(AlertsChannel.TABLE_NAME, Integer.valueOf(id.trim()));
if(channel != null)
{
channels.add(channel);
}
}
}
return (channels);
}
if(preference == null || !Boolean.FALSE.equals(preference.getValueBoolean("inAppEnabled")))
{
channels.add(runtime.getChannels().defaultChannel(ChannelType.IN_APP));
}
if(preference != null && Boolean.TRUE.equals(preference.getValueBoolean("emailEnabled")) && StringUtils.hasContent(preference.getValueString("emailAddress")))
{
channels.add(runtime.getChannels().defaultChannel(ChannelType.EMAIL));
}
return (channels);
}
/*******************************************************************************
** Whether a subscription or mute scope covers the target.
*******************************************************************************/
boolean scopeMatches(String scopeType, String scopeValue, String scopeRecordId, AlertTarget target, Map<Integer, List<String>> groupNames) throws QException
{
ScopeType type = scopeType == null ? ScopeType.ALL : ScopeType.valueOf(scopeType);
return switch(type)
{
case ALL -> true;
case ALERT_TYPE -> scopeValue != null && scopeValue.equals(target.typeName());
case MONITOR -> scopeValue != null && target.monitorId() != null && scopeValue.equals(String.valueOf(target.monitorId()));
case TABLE -> scopeValue != null && (scopeValue.equals(target.subjectTableName()) || target.recordKeys().stream().anyMatch(key -> key.startsWith(scopeValue + ":")));
case RECORD -> scopeValue != null && scopeRecordId != null && target.recordKeys().contains(scopeValue + ":" + scopeRecordId);
case ATTRIBUTE -> attributeMatches(scopeValue, target.attributes());
case GROUP -> scopeValue != null && target.groupId() != null && groupNamesWithParents(target.groupId(), groupNames).contains(scopeValue);
};
}
/*******************************************************************************
** The group's name and id, and its parents', for GROUP scopes.
*******************************************************************************/
private List<String> groupNamesWithParents(Integer groupId, Map<Integer, List<String>> cache) throws QException
{
List<String> cached = cache.get(groupId);
if(cached != null)
{
return (cached);
}
List<String> names = new ArrayList<>();
Integer current = groupId;
int depth = 0;
while(current != null && depth++ < 10)
{
QRecord group = AlertsDb.byId(AlertsGroup.TABLE_NAME, current);
if(group == null)
{
break;
}
names.add(group.getValueString("name"));
names.add(String.valueOf(group.getValue("id")));
current = group.getValueInteger("parentGroupId");
}
cache.put(groupId, names);
return (names);
}
/*******************************************************************************
** "key=value" against the alert's attributes.
*******************************************************************************/
private static boolean attributeMatches(String scopeValue, Map<String, String> attributes)
{
if(scopeValue == null || attributes == null || !scopeValue.contains("="))
{
return (false);
}
String[] parts = scopeValue.split("=", 2);
return (parts[1].trim().equals(attributes.get(parts[0].trim())));
}
/*******************************************************************************
** Whether a subscription's events list includes this kind (empty: all).
*******************************************************************************/
private static boolean includesKind(String events, DeliveryKind kind)
{
if(!StringUtils.hasContent(events))
{
return (true);
}
for(String event : events.split("[,\\s]+"))
{
if(event.trim().equalsIgnoreCase(kind.name()))
{
return (true);
}
}
return (false);
}
/*******************************************************************************
** Whether a user can see an alert (section 7.2), when that can be known:
** with a host whose authentication module builds sessions with permissions
** for a user id, the alert is read through that session's record locks.
** Otherwise (empty) the user's permissions are unknown, and the caller
** allows in-app (the bell re-checks the alert under the reader's session)
** but sends externally only alerts with no visibility permission and no
** subject table.
*******************************************************************************/
Optional<Boolean> knownVisibility(String userId, QRecord alert)
{
try
{
QSession session = automatedSession(userId);
if(session != null && CollectionUtils.nullSafeHasContents(session.getPermissions()))
{
QInstance qInstance = runtime.getQInstance();
AlertsSecurity.applyToSession(qInstance, session);
boolean[] visible = new boolean[1];
QContext.withTemporaryContext(new CapturedContext(qInstance, session), () ->
{
visible[0] = AlertsDb.byId(AlertsAlert.TABLE_NAME, alert.getValue("id")) != null;
});
return (Optional.of(visible[0]));
}
}
catch(Exception e)
{
LOG.debug("Could not build a session to check alert visibility", e, logPair("userId", userId));
}
return (Optional.empty());
}
/*******************************************************************************
** A session for a user, from the instance's authentication module (null
** when it can't make one).
*******************************************************************************/
private QSession automatedSession(String userId) throws QException
{
QInstance qInstance = runtime.getQInstance();
if(qInstance.getAuthentication() == null)
{
return (null);
}
QAuthenticationModuleInterface module = new QAuthenticationModuleDispatcher().getQModule(qInstance.getAuthentication());
return (module.createAutomatedSessionForUser(qInstance, userId));
}
/*******************************************************************************
** Whether the user paused notifications (vacation) until after now.
*******************************************************************************/
private static boolean isPaused(QRecord preference, Instant now)
{
return (preference != null && preference.getValueInstant("pausedUntil") != null && preference.getValueInstant("pausedUntil").isAfter(now));
}
/*******************************************************************************
** Whether a channel has reached its hourly limit.
*******************************************************************************/
private boolean isRateLimited(QRecord channel, Instant now) throws QException
{
Integer limit = channel.getValueInteger("rateLimitPerHour");
if(limit == null || limit <= 0)
{
return (false);
}
int lastHour = AlertsDb.count(AlertsDelivery.TABLE_NAME, AlertsDb.eq("channelId", channel.getValue("id"))
.withCriteria("status", QCriteriaOperator.IN, List.of(DeliveryStatus.PENDING.name(), DeliveryStatus.SENDING.name(), DeliveryStatus.SENT.name(), DeliveryStatus.RETRYING.name()))
.withCriteria("createDate", QCriteriaOperator.GREATER_THAN, now.minus(1, ChronoUnit.HOURS)));
return (lastHour >= limit);
}
/*******************************************************************************
** The same alert, channel, recipient and kind within 10 minutes.
*******************************************************************************/
private boolean isDuplicate(QRecord alert, Destination destination, DeliveryKind kind, Instant now) throws QException
{
var filter = AlertsDb.eq("alertId", alert.getValue("id"))
.withCriteria("channelId", QCriteriaOperator.EQUALS, destination.channel().getValue("id"))
.withCriteria("kind", QCriteriaOperator.EQUALS, kind.name())
.withCriteria("status", QCriteriaOperator.IN, List.of(DeliveryStatus.PENDING.name(), DeliveryStatus.SENDING.name(), DeliveryStatus.SENT.name(), DeliveryStatus.RETRYING.name()))
.withCriteria("createDate", QCriteriaOperator.GREATER_THAN, now.minus(DUPLICATE_WINDOW_MINUTES, ChronoUnit.MINUTES));
if(destination.userId() != null)
{
filter.withCriteria("recipientUserId", QCriteriaOperator.EQUALS, destination.userId());
}
return (AlertsDb.count(AlertsDelivery.TABLE_NAME, filter) > 0);
}
/*******************************************************************************
** The email address for a destination.
*******************************************************************************/
static String emailAddress(Destination destination)
{
return (destination.preference() == null ? null : destination.preference().getValueString("emailAddress"));
}
/*******************************************************************************
** Who a notification went to, masked (j***@example.com).
*******************************************************************************/
static String recipientLabel(Destination destination)
{
String channelType = destination.channel().getValueString("channelType");
if(destination.userId() == null)
{
return (destination.channel().getValueString("label"));
}
if(ChannelType.EMAIL.name().equals(channelType))
{
return (maskEmail(emailAddress(destination)));
}
QRecord preference = destination.preference();
String name = preference == null ? null : preference.getValueString("userLabel");
return ((StringUtils.hasContent(name) ? name : destination.userId()) + " (in app)");
}
/*******************************************************************************
** "jane@example.com" to "j***@example.com".
*******************************************************************************/
public static String maskEmail(String address)
{
if(address == null || !address.contains("@"))
{
return (address == null ? null : "***");
}
int at = address.indexOf('@');
return ((at > 0 ? address.charAt(0) : "") + "***" + address.substring(at));
}
}
@@ -0,0 +1,265 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.engine;
import java.io.Serializable;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import com.kingsrook.qbits.alerts.AlertsRuntime;
import com.kingsrook.qbits.alerts.model.AlertsGroup;
import com.kingsrook.qbits.alerts.model.AlertsMonitor;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues;
import com.kingsrook.qbits.alerts.model.AlertsType;
import com.kingsrook.qqq.backend.core.alerts.AlertDefaultMonitor;
import com.kingsrook.qqq.backend.core.alerts.AlertSeverity;
import com.kingsrook.qqq.backend.core.alerts.AlertsInstanceMetaData;
import com.kingsrook.qqq.backend.core.alerts.DetailLevel;
import com.kingsrook.qqq.backend.core.alerts.QAlertTypeMetaData;
import com.kingsrook.qqq.backend.core.alerts.ResolveMode;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
/*******************************************************************************
** Discovery (design section 3.3): upserts every declared alert type into
** alerts_type (installed = true, metadata fields refreshed; the admin fields
** enabled, severityOverride, groupId and notify are kept), creates missing
** groups, seeds default monitors once, and marks types no longer declared
** installed = false. Types are never deleted, so history keeps its labels.
** A signal with an undeclared type is recorded under the "unregistered"
** type, so a typo never loses a signal.
*******************************************************************************/
public class AlertTypeSync
{
private static final QLogger LOG = QLogger.getLogger(AlertTypeSync.class);
public static final String UNREGISTERED = "unregistered";
public static final String DEFAULT_GROUP = "other";
private final AlertsRuntime runtime;
private volatile boolean synced = false;
/*******************************************************************************
** Constructor
*******************************************************************************/
public AlertTypeSync(AlertsRuntime runtime)
{
this.runtime = runtime;
}
/*******************************************************************************
** Sync once per runtime (the first signal, evaluation or page triggers it).
*******************************************************************************/
public void syncIfNeeded() throws QException
{
if(!synced)
{
synchronized(this)
{
if(!synced)
{
sync();
synced = true;
}
}
}
}
/*******************************************************************************
** Upsert every declared type, seed monitors, mark the rest uninstalled.
*******************************************************************************/
public void sync() throws QException
{
runtime.asSystem(() ->
{
AlertsInstanceMetaData metaData = AlertsInstanceMetaData.of(runtime.getQInstance());
Set<String> declared = new HashSet<>();
if(metaData != null)
{
for(QAlertTypeMetaData type : metaData.getAlertTypes().values())
{
upsertType(type);
declared.add(type.getName());
}
}
for(QRecord row : AlertsDb.query(AlertsType.TABLE_NAME, AlertsDb.eq("installed", true)))
{
String name = row.getValueString("name");
if(!declared.contains(name) && !UNREGISTERED.equals(name))
{
AlertsDb.update(AlertsType.TABLE_NAME, new QRecord().withValue("id", row.getValue("id")).withValue("installed", false));
}
}
LOG.info("Alert types synced", logPair("declared", declared.size()));
return (null);
});
}
/*******************************************************************************
** The alerts_type row for a signal's type: the declared one (synced on
** demand) or, for an undeclared name, the "unregistered" type. Runs in the
** caller's (system) context.
*******************************************************************************/
public QRecord typeFor(String alertTypeName) throws QException
{
QRecord row = AlertsDb.first(AlertsType.TABLE_NAME, AlertsDb.eq("name", alertTypeName));
if(row != null)
{
return (row);
}
AlertsInstanceMetaData metaData = AlertsInstanceMetaData.of(runtime.getQInstance());
QAlertTypeMetaData declared = metaData == null ? null : metaData.getAlertType(alertTypeName);
if(declared != null)
{
return (upsertType(declared));
}
LOG.warn("Alert raised with an undeclared type; recording it as unregistered", logPair("alertType", alertTypeName));
QRecord unregistered = AlertsDb.first(AlertsType.TABLE_NAME, AlertsDb.eq("name", UNREGISTERED));
if(unregistered == null)
{
unregistered = upsertType(new QAlertTypeMetaData()
.withName(UNREGISTERED)
.withLabel("Unregistered alert type")
.withSourceName("alerts")
.withGroupName(DEFAULT_GROUP)
.withDefaultSeverity(AlertSeverity.WARNING)
.withDescription("Signals whose type no installed qbit declares. The alert's Type Name says which name was used.")
.withHowToFix("Declare the type with QAlertTypeMetaData in the producing qbit, or fix the type name it raises."));
}
return (unregistered);
}
/*******************************************************************************
** Insert or refresh one type (and its group and seeded monitors).
*******************************************************************************/
QRecord upsertType(QAlertTypeMetaData type) throws QException
{
Map<String, Serializable> metadata = new LinkedHashMap<>();
metadata.put("label", StringUtils.hasContent(type.getLabel()) ? type.getLabel() : type.getName());
metadata.put("sourceName", type.getEffectiveSourceName());
metadata.put("defaultSeverity", type.getDefaultSeverity() == null ? AlertSeverity.WARNING.name() : type.getDefaultSeverity().name());
metadata.put("description", type.getDescription());
metadata.put("howToFix", type.getHowToFix());
metadata.put("subjectTableName", type.getSubjectTableName());
metadata.put("visibilityPermission", type.getVisibilityPermission());
metadata.put("installed", true);
QRecord existing = AlertsDb.first(AlertsType.TABLE_NAME, AlertsDb.eq("name", type.getName()));
QRecord row;
if(existing == null)
{
QRecord record = new QRecord()
.withValue("name", type.getName())
.withValue("groupId", ensureGroup(type.getGroupName()))
.withValue("enabled", true)
.withValue("notify", true)
.withValue("resolveMode", (type.getResolveMode() == null ? ResolveMode.PRODUCER : type.getResolveMode()).name())
.withValue("quietPeriodMinutes", type.getQuietPeriod() == null ? null : (int) type.getQuietPeriod().toMinutes())
.withValue("externalDetailCeiling", (type.getExternalDetailCeiling() == null ? DetailLevel.STANDARD : type.getExternalDetailCeiling()).name())
.withValue("openCount", 0);
metadata.forEach(record::setValue);
row = AlertsDb.insert(AlertsType.TABLE_NAME, record);
}
else
{
QRecord record = new QRecord().withValue("id", existing.getValue("id"));
metadata.forEach(record::setValue);
if(existing.getValue("groupId") == null)
{
record.setValue("groupId", ensureGroup(type.getGroupName()));
}
AlertsDb.update(AlertsType.TABLE_NAME, record);
row = AlertsDb.byId(AlertsType.TABLE_NAME, existing.getValue("id"));
}
for(AlertDefaultMonitor monitor : type.getDefaultMonitors())
{
seedMonitor(row, type, monitor);
}
return (row);
}
/*******************************************************************************
** The id of the group with this name, creating it if missing.
*******************************************************************************/
public Integer ensureGroup(String groupName) throws QException
{
String name = StringUtils.hasContent(groupName) ? groupName : DEFAULT_GROUP;
QRecord existing = AlertsDb.first(AlertsGroup.TABLE_NAME, AlertsDb.eq("name", name));
if(existing != null)
{
return (existing.getValueInteger("id"));
}
QRecord inserted = AlertsDb.insert(AlertsGroup.TABLE_NAME, new QRecord()
.withValue("name", name)
.withValue("label", name.length() <= 3 ? name.toUpperCase(java.util.Locale.ROOT) : AlertsPossibleValues.label(name.replace('-', '_').replace('.', '_').toUpperCase(java.util.Locale.ROOT))));
return (inserted.getValueInteger("id"));
}
/*******************************************************************************
** Insert a seeded monitor once (matched by name and the seeded flag).
*******************************************************************************/
void seedMonitor(QRecord typeRow, QAlertTypeMetaData type, AlertDefaultMonitor monitor) throws QException
{
String name = StringUtils.hasContent(monitor.getName()) ? monitor.getName() : type.getName();
QRecord existing = AlertsDb.first(AlertsMonitor.TABLE_NAME, AlertsDb.eq("name", name).withCriteria("seeded", QCriteriaOperator.EQUALS, true));
if(existing != null)
{
return;
}
AlertsDb.insert(AlertsMonitor.TABLE_NAME, new QRecord()
.withValue("name", name)
.withValue("alertTypeId", typeRow.getValue("id"))
.withValue("kind", monitor.getKind() == null ? null : monitor.getKind().name())
.withValue("enabled", true)
.withValue("seeded", true)
.withValue("sourceName", type.getEffectiveSourceName())
.withValue("description", "Seeded by " + (type.getEffectiveSourceName() == null ? "the alert type" : type.getEffectiveSourceName()) + " for " + type.getName() + ".")
.withValue("definition", JsonUtils.toJson(monitor.getDefinition()))
.withValue("perRecord", Boolean.TRUE.equals(monitor.getPerRecord()))
.withValue("severity", monitor.getSeverity() == null ? null : monitor.getSeverity().name())
.withValue("scheduleSeconds", monitor.getScheduleSeconds() == null ? 300 : monitor.getScheduleSeconds())
.withValue("forMinutes", monitor.getForMinutes() == null ? 0 : monitor.getForMinutes())
.withValue("consecutiveFailures", 0));
}
}
@@ -0,0 +1,256 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.engine;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import com.kingsrook.qbits.alerts.AlertsRuntime;
import com.kingsrook.qbits.alerts.delivery.AlertRedactor;
import com.kingsrook.qbits.alerts.delivery.channels.ExternalChannels;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.Resolution;
import com.kingsrook.qbits.alerts.model.AlertsType;
import com.kingsrook.qqq.backend.core.alerts.AlertSeverity;
import com.kingsrook.qqq.backend.core.alerts.AlertSignal;
import com.kingsrook.qqq.backend.core.alerts.DetailLevel;
import com.kingsrook.qqq.backend.core.alerts.QAlertTypeMetaData;
import com.kingsrook.qqq.backend.core.alerts.ResolveMode;
import com.kingsrook.qqq.backend.core.exceptions.QAuthenticationException;
import com.kingsrook.qqq.backend.core.exceptions.QBadRequestException;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.exceptions.QNotFoundException;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
/*******************************************************************************
** Prometheus Alertmanager as a source (design section 5.7): the webhook
** receiver payload (version 4) becomes raises and resolves.
** - the alert's fingerprint is the dedup key; firing / resolved are raise /
** resolve; the severity label maps to a severity (unknown: WARNING);
** summary / description become title / summary (redacted); labels become
** attributes (bounded);
** - the type is prometheus.(alertname), created on first sight as an
** EXTERNAL type in group "infrastructure" with notifications OFF
** (Alertmanager already notifies people; turning QQQ notifications on is a
** per-type choice);
** - alerts carrying qqq_origin="qbit-alerts" (sent by this qbit's
** Alertmanager channel) are ignored, so nothing loops.
** Authentication: a bearer token compared (in constant time) with the
** configured secret reference. Ingest is off without one.
*******************************************************************************/
public class AlertmanagerIngest
{
public static final String TYPE_PREFIX = "prometheus.";
public static final String GROUP = "infrastructure";
private final AlertsRuntime runtime;
/*******************************************************************************
** What an ingest did.
**
** @param raised alerts raised (or refreshed)
** @param resolved alerts resolved
** @param ignored alerts ignored (loop guard, or no alertname)
*******************************************************************************/
public record Result(int raised, int resolved, int ignored)
{
}
/*******************************************************************************
** Constructor
*******************************************************************************/
public AlertmanagerIngest(AlertsRuntime runtime)
{
this.runtime = runtime;
}
/*******************************************************************************
** Check the bearer token: 404 when ingest is off, 401 when it doesn't match.
*******************************************************************************/
public void authenticate(String authorizationHeader) throws QException
{
String ref = runtime.getConfig().getAlertmanagerIngestTokenSecretRef();
if(!StringUtils.hasContent(ref))
{
throw (new QNotFoundException("Alertmanager ingest is not enabled."));
}
String expected = runtime.getChannels().getSecrets().resolve(ref);
String given = authorizationHeader != null && authorizationHeader.regionMatches(true, 0, "Bearer ", 0, 7) ? authorizationHeader.substring(7).trim() : null;
if(expected == null || given == null || !MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), given.getBytes(StandardCharsets.UTF_8)))
{
throw (new QAuthenticationException("Invalid ingest token."));
}
}
/*******************************************************************************
** Apply one webhook payload.
*******************************************************************************/
@SuppressWarnings("unchecked")
public Result ingest(Map<String, Object> payload) throws QException
{
Object alerts = payload == null ? null : payload.get("alerts");
if(!(alerts instanceof List<?> list))
{
throw (new QBadRequestException("Expected an Alertmanager webhook payload with an \"alerts\" list."));
}
int raised = 0;
int resolved = 0;
int ignored = 0;
for(Object item : list)
{
if(!(item instanceof Map<?, ?> alert))
{
ignored++;
continue;
}
Map<String, Object> labels = alert.get("labels") instanceof Map<?, ?> map ? (Map<String, Object>) map : Map.of();
Map<String, Object> annotations = alert.get("annotations") instanceof Map<?, ?> map ? (Map<String, Object>) map : Map.of();
String alertname = labels.get("alertname") == null ? null : String.valueOf(labels.get("alertname"));
if(alertname == null || ExternalChannels.ORIGIN_VALUE.equals(String.valueOf(labels.get(ExternalChannels.ORIGIN_LABEL))))
{
ignored++;
continue;
}
String typeName = typeName(alertname);
String fingerprint = alert.get("fingerprint") == null ? fingerprint(labels) : String.valueOf(alert.get("fingerprint"));
ensureType(typeName, alertname);
if("resolved".equalsIgnoreCase(String.valueOf(alert.get("status"))))
{
if(runtime.getEngine().resolve(typeName, fingerprint, Resolution.PRODUCER, null, "Resolved in Alertmanager") != null)
{
resolved++;
}
continue;
}
String title = firstNonBlank(annotations.get("summary"), annotations.get("description"), alertname);
AlertSignal signal = new AlertSignal(typeName)
.withDedupKey(fingerprint)
.withSeverity(AlertSeverity.fromLabel(labels.get("severity") == null ? null : String.valueOf(labels.get("severity")), AlertSeverity.WARNING))
.withTitle(AlertRedactor.redact(title))
.withSummary(AlertRedactor.redact(annotations.get("description") == null ? null : String.valueOf(annotations.get("description"))))
.withOccurredAt(parseInstant(alert.get("startsAt")));
for(Map.Entry<String, Object> label : new LinkedHashMap<>(labels).entrySet())
{
signal.withAttribute(label.getKey(), String.valueOf(label.getValue()));
}
runtime.getEngine().raise(signal);
raised++;
}
return (new Result(raised, resolved, ignored));
}
/*******************************************************************************
** Create the EXTERNAL type the first time (notifications off).
*******************************************************************************/
private void ensureType(String typeName, String alertname) throws QException
{
runtime.asSystem(() ->
{
if(AlertsDb.first(AlertsType.TABLE_NAME, AlertsDb.eq("name", typeName)) == null)
{
QRecord type = runtime.getTypeSync().upsertType(new QAlertTypeMetaData()
.withName(typeName)
.withLabel(alertname)
.withSourceName("prometheus")
.withGroupName(GROUP)
.withDefaultSeverity(AlertSeverity.WARNING)
.withResolveMode(ResolveMode.PRODUCER)
.withExternalDetailCeiling(DetailLevel.STANDARD)
.withDescription("Ingested from Prometheus Alertmanager (" + alertname + ").")
.withHowToFix("See the alert's runbook in Prometheus. Alertmanager already notifies its receivers; turn on Notify here only to route it through Alerts too."));
AlertsDb.update(AlertsType.TABLE_NAME, new QRecord().withValue("id", type.getValue("id")).withValue("notify", false));
}
return (null);
});
}
/*******************************************************************************
** "HighCPU Usage" to "prometheus.highcpu-usage".
*******************************************************************************/
public static String typeName(String alertname)
{
String slug = alertname.toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9-]+", "-").replaceAll("^-+|-+$", "");
return (TYPE_PREFIX + (slug.isEmpty() ? "unnamed" : slug));
}
/*******************************************************************************
** A fingerprint from the labels when Alertmanager didn't send one.
*******************************************************************************/
static String fingerprint(Map<String, Object> labels)
{
return (Integer.toHexString(new java.util.TreeMap<>(labels).toString().hashCode()));
}
/*******************************************************************************
**
*******************************************************************************/
private static String firstNonBlank(Object... values)
{
for(Object value : values)
{
if(value != null && StringUtils.hasContent(String.valueOf(value)))
{
return (String.valueOf(value));
}
}
return (null);
}
/*******************************************************************************
** An ISO instant, or null (Alertmanager's zero time is null too).
*******************************************************************************/
private static Instant parseInstant(Object value)
{
try
{
Instant instant = value == null ? null : Instant.parse(String.valueOf(value));
return (instant == null || instant.getEpochSecond() <= 0 ? null : instant);
}
catch(Exception e)
{
return (null);
}
}
}
@@ -0,0 +1,147 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.engine;
import java.io.Serializable;
import java.util.List;
import com.kingsrook.qqq.backend.core.actions.tables.CountAction;
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
import com.kingsrook.qqq.backend.core.actions.tables.UpdateAction;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterCriteria;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.statusmessages.QStatusMessage;
import com.kingsrook.qqq.backend.core.utils.CollectionUtils;
/*******************************************************************************
** Small helpers over QQQ's table actions, for the engine. They run in
** whatever context the caller set up (the engine uses the system user), so
** customizers, audits and ESB listeners apply as for any other write.
*******************************************************************************/
public final class AlertsDb
{
/*******************************************************************************
** Helpers only.
*******************************************************************************/
private AlertsDb()
{
}
/*******************************************************************************
** Query a table.
*******************************************************************************/
public static List<QRecord> query(String tableName, QQueryFilter filter) throws QException
{
return (QueryAction.execute(tableName, filter));
}
/*******************************************************************************
** The first row matching, or null.
*******************************************************************************/
public static QRecord first(String tableName, QQueryFilter filter) throws QException
{
List<QRecord> records = QueryAction.execute(tableName, filter.withLimit(1));
return (CollectionUtils.nullSafeIsEmpty(records) ? null : records.get(0));
}
/*******************************************************************************
** The row with this id, or null.
*******************************************************************************/
public static QRecord byId(String tableName, Serializable id) throws QException
{
if(id == null)
{
return (null);
}
return (first(tableName, new QQueryFilter(new QFilterCriteria("id", QCriteriaOperator.EQUALS, id))));
}
/*******************************************************************************
** Count rows.
*******************************************************************************/
public static int count(String tableName, QQueryFilter filter) throws QException
{
Integer count = CountAction.execute(tableName, filter);
return (count == null ? 0 : count);
}
/*******************************************************************************
** Insert one row; throws when the insert reports an error.
*******************************************************************************/
public static QRecord insert(String tableName, QRecord record) throws QException
{
List<QRecord> inserted = InsertAction.executeForRecords(new InsertInput(tableName).withRecord(record));
QRecord result = inserted.get(0);
throwIfErrors(tableName, result);
return (result);
}
/*******************************************************************************
** Update one row (it must carry its id); throws on an error.
*******************************************************************************/
public static QRecord update(String tableName, QRecord record) throws QException
{
List<QRecord> updated = UpdateAction.executeForRecords(new UpdateInput(tableName).withRecord(record));
QRecord result = updated.get(0);
throwIfErrors(tableName, result);
return (result);
}
/*******************************************************************************
** A filter: field equals value.
*******************************************************************************/
public static QQueryFilter eq(String field, Serializable value)
{
return (new QQueryFilter(new QFilterCriteria(field, QCriteriaOperator.EQUALS, value)));
}
/*******************************************************************************
**
*******************************************************************************/
private static void throwIfErrors(String tableName, QRecord record) throws QException
{
if(CollectionUtils.nullSafeHasContents(record.getErrors()))
{
QStatusMessage error = record.getErrors().get(0);
throw (new QException("Could not write " + tableName + ": " + error.getMessage()));
}
}
}
@@ -0,0 +1,873 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.engine;
import java.io.Serializable;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import com.kingsrook.qbits.alerts.AlertsQBitConfig;
import com.kingsrook.qbits.alerts.AlertsRuntime;
import com.kingsrook.qbits.alerts.model.AlertsAlert;
import com.kingsrook.qbits.alerts.model.AlertsEvent;
import com.kingsrook.qbits.alerts.model.AlertsHeartbeat;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.EventType;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.Resolution;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.Status;
import com.kingsrook.qbits.alerts.model.AlertsRecordRef;
import com.kingsrook.qbits.alerts.model.AlertsType;
import com.kingsrook.qqq.backend.core.alerts.AlertLink;
import com.kingsrook.qqq.backend.core.alerts.AlertRecordRef;
import com.kingsrook.qqq.backend.core.alerts.AlertSeverity;
import com.kingsrook.qqq.backend.core.alerts.AlertSignal;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.exceptions.QUserFacingException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterCriteria;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterOrderBy;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
import com.kingsrook.qqq.backend.core.utils.ValueUtils;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
/*******************************************************************************
** The alert state machine (design section 5.1). Every transition writes its
** alerts_event, and notifiable events go to the router.
**
** - Raise on an open (type, dedupKey) updates that alert: lastRaisedAt,
** occurrences, record refs. A severity increase records SEVERITY_CHANGED,
** unsnoozes and notifies again; a decrease only records it.
** - Raise on a key resolved less than reopenWindowMinutes ago reopens the
** same alert; later, a new alert is created (history stays on the old one).
** - Flapping: flapThreshold open/resolve changes within flapWindowMinutes
** set flapping (one notice; further open/resolve notifications are
** suppressed until it is stable for the window).
** - Acknowledge stops reminders; snooze hides it until a time (it returns
** early when the severity rises); resolve closes it from any open state.
** - Concurrency: openDedupKey (type|key while not resolved) is unique, so an
** insert that loses a race re-reads and updates the winner.
*******************************************************************************/
public class AlertsEngine
{
private static final QLogger LOG = QLogger.getLogger(AlertsEngine.class);
private static final int REPEATED_EVENT_EVERY_MINUTES = 60;
private static final int MAX_KEY_LENGTH = 520;
private final AlertsRuntime runtime;
/*******************************************************************************
** Constructor
*******************************************************************************/
public AlertsEngine(AlertsRuntime runtime)
{
this.runtime = runtime;
}
/*******************************************************************************
** The unique open key of (type, dedupKey).
*******************************************************************************/
public static String openKey(String alertTypeName, String dedupKey)
{
String key = alertTypeName + "|" + dedupKey;
return (key.length() > MAX_KEY_LENGTH ? key.substring(0, MAX_KEY_LENGTH) : key);
}
/*******************************************************************************
** Raise (or refresh) an alert from a producer signal.
*******************************************************************************/
public QRecord raise(AlertSignal signal) throws QException
{
return (raise(signal, null));
}
/*******************************************************************************
** Raise (or refresh) an alert, optionally on behalf of a monitor. Returns
** the alert row, or null when the type is disabled or a maintenance window
** suppresses it.
*******************************************************************************/
public QRecord raise(AlertSignal signal, Integer monitorId) throws QException
{
if(signal == null || !StringUtils.hasContent(signal.getAlertTypeName()))
{
return (null);
}
runtime.getTypeSync().syncIfNeeded();
return (runtime.asSystem(() ->
{
Instant now = signal.getOccurredAt() == null ? runtime.now() : signal.getOccurredAt();
QRecord type = runtime.getTypeSync().typeFor(signal.getAlertTypeName());
if(Boolean.FALSE.equals(type.getValueBoolean("enabled")))
{
return (null);
}
String dedupKey = signal.getEffectiveDedupKey();
AlertSeverity severity = effectiveSeverity(type, signal.getSeverity());
AlertTarget target = AlertTarget.of(type, signal, monitorId);
if(runtime.getRouter().isSuppressedByMaintenance(target, now))
{
LOG.info("Alert suppressed by a maintenance window", logPair("alertType", signal.getAlertTypeName()), logPair("dedupKey", dedupKey));
return (null);
}
String openKey = openKey(signal.getAlertTypeName(), dedupKey);
QRecord open = AlertsDb.first(AlertsAlert.TABLE_NAME, AlertsDb.eq("openDedupKey", openKey));
QRecord alert;
if(open != null)
{
alert = refresh(open, type, signal, severity, monitorId, now);
}
else
{
QRecord recent = recentlyResolved(signal.getAlertTypeName(), dedupKey, now);
if(recent != null)
{
alert = reopen(recent, type, signal, severity, monitorId, now, null, "Raised again within the reopen window");
}
else
{
alert = create(type, signal, dedupKey, openKey, severity, monitorId, now);
}
}
updateTypeCounts(type.getValueInteger("id"), now);
return (alert);
}));
}
/*******************************************************************************
** Resolve the open alert for (type, dedupKey), if there is one.
*******************************************************************************/
public QRecord resolve(String alertTypeName, String dedupKey, Resolution resolution, String userId, String note) throws QException
{
if(!StringUtils.hasContent(alertTypeName))
{
return (null);
}
String key = StringUtils.hasContent(dedupKey) ? dedupKey : alertTypeName;
return (runtime.asSystem(() ->
{
QRecord open = AlertsDb.first(AlertsAlert.TABLE_NAME, AlertsDb.eq("openDedupKey", openKey(alertTypeName, key)));
if(open == null)
{
return (null);
}
return (resolveAlert(open, resolution, userId, note));
}));
}
/*******************************************************************************
** Resolve an alert by id (manual Resolve, monitor clear). A no-op when it is
** already resolved.
*******************************************************************************/
public QRecord resolveById(Integer alertId, Resolution resolution, String userId, String note) throws QException
{
return (runtime.asSystem(() ->
{
QRecord alert = AlertsDb.byId(AlertsAlert.TABLE_NAME, alertId);
if(alert == null || Status.RESOLVED.name().equals(alert.getValueString("status")))
{
return (alert);
}
return (resolveAlert(alert, resolution, userId, note));
}));
}
/*******************************************************************************
** Record a dead-man's switch beat.
*******************************************************************************/
public void heartbeat(String heartbeatKey, Instant at) throws QException
{
if(!StringUtils.hasContent(heartbeatKey))
{
return;
}
runtime.asSystem(() ->
{
Instant when = at == null ? runtime.now() : at;
QRecord existing = AlertsDb.first(AlertsHeartbeat.TABLE_NAME, AlertsDb.eq("heartbeatKey", heartbeatKey));
if(existing == null)
{
AlertsDb.insert(AlertsHeartbeat.TABLE_NAME, new QRecord().withValue("heartbeatKey", heartbeatKey).withValue("lastBeatAt", when).withValue("beatCount", 1));
}
else
{
AlertsDb.update(AlertsHeartbeat.TABLE_NAME, new QRecord().withValue("id", existing.getValue("id")).withValue("lastBeatAt", when)
.withValue("beatCount", ValueUtils.getValueAsInteger(existing.getValue("beatCount")) == null ? 1 : existing.getValueInteger("beatCount") + 1));
}
return (null);
});
}
/*******************************************************************************
** Acknowledge an open alert. Returns false when it was already
** acknowledged or is not open.
*******************************************************************************/
public boolean acknowledge(Integer alertId, String userId) throws QException
{
return (runtime.asSystem(() ->
{
QRecord alert = AlertsDb.byId(AlertsAlert.TABLE_NAME, alertId);
if(alert == null || !Status.OPEN.name().equals(alert.getValueString("status")))
{
return (false);
}
Instant now = runtime.now();
AlertsDb.update(AlertsAlert.TABLE_NAME, new QRecord().withValue("id", alertId).withValue("status", Status.ACKNOWLEDGED.name())
.withValue("acknowledgedByUserId", userId).withValue("acknowledgedAt", now));
event(alertId, EventType.ACKNOWLEDGED, userId, Status.OPEN.name(), Status.ACKNOWLEDGED.name(), null, now);
return (true);
}));
}
/*******************************************************************************
** Snooze an open or acknowledged alert until a time.
*******************************************************************************/
public boolean snooze(Integer alertId, Instant until, String userId) throws QException
{
if(until == null)
{
throw (new QUserFacingException("Choose when the snooze ends."));
}
return (runtime.asSystem(() ->
{
QRecord alert = AlertsDb.byId(AlertsAlert.TABLE_NAME, alertId);
if(alert == null || Status.RESOLVED.name().equals(alert.getValueString("status")))
{
return (false);
}
Instant now = runtime.now();
if(!until.isAfter(now))
{
throw (new QUserFacingException("The snooze must end in the future."));
}
AlertsDb.update(AlertsAlert.TABLE_NAME, new QRecord().withValue("id", alertId).withValue("status", Status.SNOOZED.name()).withValue("snoozedUntil", until));
event(alertId, EventType.SNOOZED, userId, alert.getValueString("status"), Status.SNOOZED.name(), "until " + until, now);
return (true);
}));
}
/*******************************************************************************
** Assign an alert to a user and/or a team.
*******************************************************************************/
public boolean assign(Integer alertId, String assigneeUserId, Integer teamId, String actorUserId) throws QException
{
return (runtime.asSystem(() ->
{
QRecord alert = AlertsDb.byId(AlertsAlert.TABLE_NAME, alertId);
if(alert == null)
{
return (false);
}
AlertsDb.update(AlertsAlert.TABLE_NAME, new QRecord().withValue("id", alertId).withValue("assignedUserId", assigneeUserId).withValue("assignedTeamId", teamId));
String to = assigneeUserId != null ? assigneeUserId : (teamId != null ? "team " + teamId : "nobody");
event(alertId, EventType.ASSIGNED, actorUserId, alert.getValueString("assignedUserId"), to, null, runtime.now());
return (true);
}));
}
/*******************************************************************************
** Add a comment to an alert's timeline.
*******************************************************************************/
public void comment(Integer alertId, String userId, String note) throws QException
{
if(!StringUtils.hasContent(note))
{
throw (new QUserFacingException("Write a comment."));
}
runtime.asSystem(() ->
{
event(alertId, EventType.COMMENTED, userId, null, null, note, runtime.now());
return (null);
});
}
/*******************************************************************************
** Reopen a resolved alert by hand (a new alert is created instead if its
** key is open again already).
*******************************************************************************/
public boolean reopenById(Integer alertId, String userId, String note) throws QException
{
return (runtime.asSystem(() ->
{
QRecord alert = AlertsDb.byId(AlertsAlert.TABLE_NAME, alertId);
if(alert == null || !Status.RESOLVED.name().equals(alert.getValueString("status")))
{
return (false);
}
String openKey = openKey(alert.getValueString("alertTypeName"), alert.getValueString("dedupKey"));
if(AlertsDb.first(AlertsAlert.TABLE_NAME, AlertsDb.eq("openDedupKey", openKey)) != null)
{
return (false);
}
QRecord type = AlertsDb.byId(AlertsType.TABLE_NAME, alert.getValue("alertTypeId"));
reopen(alert, type, null, AlertSeverity.valueOf(alert.getValueString("severity")), alert.getValueInteger("monitorId"), runtime.now(), userId, note);
return (true);
}));
}
/*******************************************************************************
** Periodic upkeep (run by the evaluator's tick): end expired snoozes,
** resolve quiet-period alerts, and end flapping that has calmed down.
** Returns how many alerts changed.
*******************************************************************************/
public int maintenance() throws QException
{
return (runtime.asSystem(() ->
{
Instant now = runtime.now();
int changed = 0;
for(QRecord alert : AlertsDb.query(AlertsAlert.TABLE_NAME, AlertsDb.eq("status", Status.SNOOZED.name())
.withCriteria("snoozedUntil", QCriteriaOperator.LESS_THAN_OR_EQUALS, now)))
{
unsnooze(alert, now, "The snooze ended");
changed++;
}
for(QRecord type : AlertsDb.query(AlertsType.TABLE_NAME, AlertsDb.eq("resolveMode", "QUIET_PERIOD").withCriteria("quietPeriodMinutes", QCriteriaOperator.IS_NOT_BLANK)))
{
Instant cutoff = now.minus(type.getValueInteger("quietPeriodMinutes"), ChronoUnit.MINUTES);
for(QRecord alert : AlertsDb.query(AlertsAlert.TABLE_NAME, AlertsDb.eq("alertTypeId", type.getValue("id"))
.withCriteria("status", QCriteriaOperator.IN, Status.openNames())
.withCriteria("lastRaisedAt", QCriteriaOperator.LESS_THAN, cutoff)))
{
resolveAlert(alert, Resolution.QUIET_PERIOD, null, "No new occurrences for " + type.getValueInteger("quietPeriodMinutes") + " minutes");
changed++;
}
}
Instant calm = now.minus(runtime.getConfig().getFlapWindowMinutes(), ChronoUnit.MINUTES);
for(QRecord alert : AlertsDb.query(AlertsAlert.TABLE_NAME, AlertsDb.eq("flapping", true)))
{
int recent = AlertsDb.count(AlertsEvent.TABLE_NAME, AlertsDb.eq("alertId", alert.getValue("id"))
.withCriteria("eventType", QCriteriaOperator.IN, List.of(EventType.REOPENED.name(), EventType.RESOLVED.name()))
.withCriteria("at", QCriteriaOperator.GREATER_THAN, calm));
if(recent == 0)
{
AlertsDb.update(AlertsAlert.TABLE_NAME, new QRecord().withValue("id", alert.getValue("id")).withValue("flapping", false));
event(alert.getValueInteger("id"), EventType.FLAPPING_ENDED, null, null, null, "Stable for " + runtime.getConfig().getFlapWindowMinutes() + " minutes", now);
changed++;
}
}
return (changed);
}));
}
/*******************************************************************************
** Write a timeline entry; returns its id.
*******************************************************************************/
public Integer event(Integer alertId, EventType eventType, String userId, String from, String to, String note, Instant at) throws QException
{
QRecord inserted = AlertsDb.insert(AlertsEvent.TABLE_NAME, new QRecord()
.withValue("alertId", alertId)
.withValue("eventType", eventType.name())
.withValue("at", at)
.withValue("userId", userId)
.withValue("fromValue", from)
.withValue("toValue", to)
.withValue("note", note));
return (inserted.getValueInteger("id"));
}
/*******************************************************************************
** The severity to use: the admin's override, else the signal's, else the
** type's default.
*******************************************************************************/
static AlertSeverity effectiveSeverity(QRecord type, AlertSeverity signalSeverity)
{
AlertSeverity override = AlertSeverity.fromLabel(type.getValueString("severityOverride"), null);
if(override != null)
{
return (override);
}
if(signalSeverity != null)
{
return (signalSeverity);
}
return (AlertSeverity.fromLabel(type.getValueString("defaultSeverity"), AlertSeverity.WARNING));
}
/*******************************************************************************
** A new alert.
*******************************************************************************/
private QRecord create(QRecord type, AlertSignal signal, String dedupKey, String openKey, AlertSeverity severity, Integer monitorId, Instant now) throws QException
{
QRecord record = new QRecord()
.withValue("alertTypeId", type.getValue("id"))
.withValue("alertTypeName", signal.getAlertTypeName())
.withValue("monitorId", monitorId)
.withValue("groupId", type.getValue("groupId"))
.withValue("dedupKey", dedupKey)
.withValue("openDedupKey", openKey)
.withValue("status", Status.OPEN.name())
.withValue("severity", severity.name())
.withValue("firstRaisedAt", now)
.withValue("lastRaisedAt", now)
.withValue("occurrenceCount", 1)
.withValue("reopenCount", 0)
.withValue("flapping", false)
.withValue("muted", false)
.withValue("escalationLevel", 0)
.withValue("subjectTableName", type.getValueString("subjectTableName"))
.withValue("visibilityPermission", type.getValueString("visibilityPermission"))
.withValue("sourceName", type.getValueString("sourceName"));
applySignalText(record, type, signal);
QRecord alert;
try
{
alert = AlertsDb.insert(AlertsAlert.TABLE_NAME, record);
}
catch(QException e)
{
////////////////////////////////////////////////////////////////////
// another replica (or thread) opened the same key first: update //
// the winner instead (the unique openDedupKey makes this safe) //
////////////////////////////////////////////////////////////////////
QRecord winner = AlertsDb.first(AlertsAlert.TABLE_NAME, AlertsDb.eq("openDedupKey", openKey));
if(winner == null)
{
throw (e);
}
return (refresh(winner, type, signal, severity, monitorId, now));
}
Integer alertId = alert.getValueInteger("id");
syncRecordRefs(alertId, signal, monitorId != null);
Integer eventId = event(alertId, EventType.RAISED, null, null, severity.name(), signal.getTitle(), now);
QRecord fresh = AlertsDb.byId(AlertsAlert.TABLE_NAME, alertId);
runtime.getRouter().route(fresh, EventType.RAISED, eventId);
return (fresh);
}
/*******************************************************************************
** A raise on an alert that is already open.
*******************************************************************************/
private QRecord refresh(QRecord open, QRecord type, AlertSignal signal, AlertSeverity severity, Integer monitorId, Instant now) throws QException
{
Integer alertId = open.getValueInteger("id");
AlertSeverity previous = AlertSeverity.fromLabel(open.getValueString("severity"), AlertSeverity.WARNING);
QRecord update = new QRecord()
.withValue("id", alertId)
.withValue("lastRaisedAt", now)
.withValue("occurrenceCount", (open.getValueInteger("occurrenceCount") == null ? 1 : open.getValueInteger("occurrenceCount")) + 1);
if(monitorId != null && open.getValue("monitorId") == null)
{
update.setValue("monitorId", monitorId);
}
applySignalText(update, type, signal);
boolean raisedSeverity = severity.compareTo(previous) > 0;
if(severity != previous)
{
update.setValue("severity", severity.name());
}
if(raisedSeverity && Status.SNOOZED.name().equals(open.getValueString("status")))
{
update.setValue("status", Status.OPEN.name());
update.setValue("snoozedUntil", null);
}
AlertsDb.update(AlertsAlert.TABLE_NAME, update);
syncRecordRefs(alertId, signal, monitorId != null);
if(severity != previous)
{
Integer eventId = event(alertId, EventType.SEVERITY_CHANGED, null, previous.name(), severity.name(), null, now);
if(raisedSeverity)
{
if(Status.SNOOZED.name().equals(open.getValueString("status")))
{
event(alertId, EventType.UNSNOOZED, null, Status.SNOOZED.name(), Status.OPEN.name(), "The severity rose", now);
}
runtime.getRouter().route(AlertsDb.byId(AlertsAlert.TABLE_NAME, alertId), EventType.SEVERITY_CHANGED, eventId);
}
}
else if(shouldRecordRepeat(alertId, now))
{
event(alertId, EventType.REPEATED, null, null, String.valueOf(update.getValueInteger("occurrenceCount")), null, now);
}
return (AlertsDb.byId(AlertsAlert.TABLE_NAME, alertId));
}
/*******************************************************************************
** Reopen a resolved alert (raised again within the window, or by hand).
*******************************************************************************/
private QRecord reopen(QRecord resolved, QRecord type, AlertSignal signal, AlertSeverity severity, Integer monitorId, Instant now, String userId, String note) throws QException
{
Integer alertId = resolved.getValueInteger("id");
QRecord update = new QRecord()
.withValue("id", alertId)
.withValue("status", Status.OPEN.name())
.withValue("openDedupKey", openKey(resolved.getValueString("alertTypeName"), resolved.getValueString("dedupKey")))
.withValue("severity", severity.name())
.withValue("lastRaisedAt", now)
.withValue("occurrenceCount", (resolved.getValueInteger("occurrenceCount") == null ? 0 : resolved.getValueInteger("occurrenceCount")) + 1)
.withValue("reopenCount", (resolved.getValueInteger("reopenCount") == null ? 0 : resolved.getValueInteger("reopenCount")) + 1)
.withValue("resolvedAt", null)
.withValue("resolvedByUserId", null)
.withValue("resolution", null)
.withValue("resolutionNote", null)
.withValue("acknowledgedAt", null)
.withValue("acknowledgedByUserId", null)
.withValue("snoozedUntil", null);
if(monitorId != null)
{
update.setValue("monitorId", monitorId);
}
if(signal != null)
{
applySignalText(update, type, signal);
}
AlertsDb.update(AlertsAlert.TABLE_NAME, update);
if(signal != null)
{
syncRecordRefs(alertId, signal, monitorId != null);
}
Integer eventId = event(alertId, EventType.REOPENED, userId, Status.RESOLVED.name(), Status.OPEN.name(), note, now);
boolean flapStarted = checkFlapping(alertId, now);
if(!flapStarted)
{
runtime.getRouter().route(AlertsDb.byId(AlertsAlert.TABLE_NAME, alertId), EventType.REOPENED, eventId);
}
return (AlertsDb.byId(AlertsAlert.TABLE_NAME, alertId));
}
/*******************************************************************************
** Close an open alert.
*******************************************************************************/
private QRecord resolveAlert(QRecord alert, Resolution resolution, String userId, String note) throws QException
{
Integer alertId = alert.getValueInteger("id");
Instant now = runtime.now();
AlertsDb.update(AlertsAlert.TABLE_NAME, new QRecord()
.withValue("id", alertId)
.withValue("status", Status.RESOLVED.name())
.withValue("openDedupKey", null)
.withValue("resolvedAt", now)
.withValue("resolvedByUserId", userId)
.withValue("resolution", resolution == null ? Resolution.MANUAL.name() : resolution.name())
.withValue("resolutionNote", note)
.withValue("snoozedUntil", null));
for(QRecord ref : AlertsDb.query(AlertsRecordRef.TABLE_NAME, AlertsDb.eq("alertId", alertId).withCriteria("active", QCriteriaOperator.EQUALS, true)))
{
AlertsDb.update(AlertsRecordRef.TABLE_NAME, new QRecord().withValue("id", ref.getValue("id")).withValue("active", false));
}
Integer eventId = event(alertId, EventType.RESOLVED, userId, alert.getValueString("status"), Status.RESOLVED.name(), note, now);
boolean flapStarted = checkFlapping(alertId, now);
if(!flapStarted)
{
runtime.getRouter().route(AlertsDb.byId(AlertsAlert.TABLE_NAME, alertId), EventType.RESOLVED, eventId);
}
updateTypeCounts(alert.getValueInteger("alertTypeId"), null);
return (AlertsDb.byId(AlertsAlert.TABLE_NAME, alertId));
}
/*******************************************************************************
** End a snooze.
*******************************************************************************/
private void unsnooze(QRecord alert, Instant now, String note) throws QException
{
String back = alert.getValue("acknowledgedAt") != null ? Status.ACKNOWLEDGED.name() : Status.OPEN.name();
AlertsDb.update(AlertsAlert.TABLE_NAME, new QRecord().withValue("id", alert.getValue("id")).withValue("status", back).withValue("snoozedUntil", null));
event(alert.getValueInteger("id"), EventType.UNSNOOZED, null, Status.SNOOZED.name(), back, note, now);
}
/*******************************************************************************
** Start flapping when the alert has changed between open and resolved
** flapThreshold times within the window. Returns true when it just
** started (the router then sends one flapping notice instead).
*******************************************************************************/
private boolean checkFlapping(Integer alertId, Instant now) throws QException
{
AlertsQBitConfig config = runtime.getConfig();
QRecord alert = AlertsDb.byId(AlertsAlert.TABLE_NAME, alertId);
if(Boolean.TRUE.equals(alert.getValueBoolean("flapping")))
{
return (false);
}
int changes = AlertsDb.count(AlertsEvent.TABLE_NAME, AlertsDb.eq("alertId", alertId)
.withCriteria("eventType", QCriteriaOperator.IN, List.of(EventType.REOPENED.name(), EventType.RESOLVED.name()))
.withCriteria("at", QCriteriaOperator.GREATER_THAN, now.minus(config.getFlapWindowMinutes(), ChronoUnit.MINUTES)));
if(changes < config.getFlapThreshold())
{
return (false);
}
AlertsDb.update(AlertsAlert.TABLE_NAME, new QRecord().withValue("id", alertId).withValue("flapping", true));
Integer eventId = event(alertId, EventType.FLAPPING_STARTED, null, null, null, changes + " open/resolve changes in " + config.getFlapWindowMinutes() + " minutes", now);
runtime.getRouter().route(AlertsDb.byId(AlertsAlert.TABLE_NAME, alertId), EventType.FLAPPING_STARTED, eventId);
return (true);
}
/*******************************************************************************
** The most recent alert for (type, key) resolved within the reopen window.
*******************************************************************************/
private QRecord recentlyResolved(String alertTypeName, String dedupKey, Instant now) throws QException
{
Instant cutoff = now.minus(runtime.getConfig().getReopenWindowMinutes(), ChronoUnit.MINUTES);
return (AlertsDb.first(AlertsAlert.TABLE_NAME, AlertsDb.eq("alertTypeName", alertTypeName)
.withCriteria("dedupKey", QCriteriaOperator.EQUALS, dedupKey)
.withCriteria("status", QCriteriaOperator.EQUALS, Status.RESOLVED.name())
.withCriteria("resolvedAt", QCriteriaOperator.GREATER_THAN_OR_EQUALS, cutoff)
.withOrderBy(new QFilterOrderBy("resolvedAt", false))));
}
/*******************************************************************************
** Record a REPEATED entry at most once an hour per alert.
*******************************************************************************/
private boolean shouldRecordRepeat(Integer alertId, Instant now) throws QException
{
QRecord last = AlertsDb.first(AlertsEvent.TABLE_NAME, AlertsDb.eq("alertId", alertId)
.withCriteria("eventType", QCriteriaOperator.IN, List.of(EventType.REPEATED.name(), EventType.RAISED.name(), EventType.REOPENED.name()))
.withOrderBy(new QFilterOrderBy("at", false)));
return (last == null || last.getValueInstant("at") == null || last.getValueInstant("at").isBefore(now.minus(REPEATED_EVENT_EVERY_MINUTES, ChronoUnit.MINUTES)));
}
/*******************************************************************************
** Copy the signal's text, counts, links and attributes onto an alert row.
*******************************************************************************/
private void applySignalText(QRecord record, QRecord type, AlertSignal signal)
{
String title = StringUtils.hasContent(signal.getTitle()) ? signal.getTitle() : type.getValueString("label");
record.setValue("title", title);
record.setValue("summary", signal.getSummary());
record.setValue("details", signal.getDetails());
record.setValue("itemCount", signal.getEffectiveCount());
record.setValue("links", signal.getLinks().isEmpty() ? null : JsonUtils.toJson(linksAsMaps(signal.getLinks())));
record.setValue("attributes", signal.getAttributes().isEmpty() ? null : JsonUtils.toJson(signal.getAttributes()));
String subjectTable = type.getValueString("subjectTableName");
if(subjectTable != null)
{
List<AlertRecordRef> subjectRefs = signal.getRecordRefs().stream().filter(ref -> subjectTable.equals(ref.getTableName())).toList();
record.setValue("subjectRecordId", subjectRefs.size() == 1 ? String.valueOf(subjectRefs.get(0).getPrimaryKey()) : null);
}
}
/*******************************************************************************
** Links as plain maps (the filter as JSON), for storage.
*******************************************************************************/
static List<Map<String, Object>> linksAsMaps(List<AlertLink> links)
{
List<Map<String, Object>> maps = new ArrayList<>();
for(AlertLink link : links)
{
Map<String, Object> map = new LinkedHashMap<>();
map.put("label", link.getLabel());
map.put("tableName", link.getTableName());
map.put("recordId", link.getRecordId() == null ? null : String.valueOf(link.getRecordId()));
map.put("filter", link.getFilter() == null ? null : JsonUtils.toJson(link.getFilter()));
map.put("path", link.getPath());
map.put("url", link.getUrl());
map.values().removeIf(Objects::isNull);
maps.add(map);
}
return (maps);
}
/*******************************************************************************
** Add the signal's record refs to the alert (marking them active). For a
** monitor (a full evaluation), refs it no longer returns become inactive;
** a producer's refs are merged. recordRefCount is the active count.
*******************************************************************************/
private void syncRecordRefs(Integer alertId, AlertSignal signal, boolean fullState) throws QException
{
List<QRecord> existing = AlertsDb.query(AlertsRecordRef.TABLE_NAME, AlertsDb.eq("alertId", alertId));
Map<String, QRecord> byKey = new HashMap<>();
for(QRecord ref : existing)
{
byKey.put(ref.getValueString("tableName") + ":" + ref.getValueString("recordId"), ref);
}
Set<String> current = new LinkedHashSet<>();
for(AlertRecordRef ref : signal.getRecordRefs())
{
String recordId = String.valueOf(ref.getPrimaryKey());
String key = ref.getTableName() + ":" + recordId;
QRecord row = byKey.get(key);
current.add(key);
if(row == null)
{
QRecord inserted = AlertsDb.insert(AlertsRecordRef.TABLE_NAME, new QRecord().withValue("alertId", alertId).withValue("tableName", ref.getTableName())
.withValue("recordId", recordId).withValue("label", ref.getLabel()).withValue("active", true));
byKey.put(key, inserted);
}
else if(!Boolean.TRUE.equals(row.getValueBoolean("active")) || (ref.getLabel() != null && !ref.getLabel().equals(row.getValueString("label"))))
{
AlertsDb.update(AlertsRecordRef.TABLE_NAME, new QRecord().withValue("id", row.getValue("id")).withValue("active", true).withValue("label", ref.getLabel() == null ? row.getValueString("label") : ref.getLabel()));
row.setValue("active", true);
}
}
if(fullState)
{
for(Map.Entry<String, QRecord> entry : byKey.entrySet())
{
if(!current.contains(entry.getKey()) && Boolean.TRUE.equals(entry.getValue().getValueBoolean("active")))
{
AlertsDb.update(AlertsRecordRef.TABLE_NAME, new QRecord().withValue("id", entry.getValue().getValue("id")).withValue("active", false));
entry.getValue().setValue("active", false);
}
}
}
int active = AlertsDb.count(AlertsRecordRef.TABLE_NAME, AlertsDb.eq("alertId", alertId).withCriteria("active", QCriteriaOperator.EQUALS, true));
AlertsDb.update(AlertsAlert.TABLE_NAME, new QRecord().withValue("id", alertId).withValue("recordRefCount", active));
}
/*******************************************************************************
** Refresh a type's denormalized open count (and last-raised time).
*******************************************************************************/
private void updateTypeCounts(Integer typeId, Instant lastRaisedAt) throws QException
{
if(typeId == null)
{
return;
}
int open = AlertsDb.count(AlertsAlert.TABLE_NAME, AlertsDb.eq("alertTypeId", typeId).withCriteria(new QFilterCriteria("status", QCriteriaOperator.IN, Status.openNames())));
QRecord update = new QRecord().withValue("id", typeId).withValue("openCount", open);
if(lastRaisedAt != null)
{
update.setValue("lastRaisedAt", lastRaisedAt);
}
AlertsDb.update(AlertsType.TABLE_NAME, update);
}
/*******************************************************************************
** What a subscription or mute scope is matched against.
*******************************************************************************/
public record AlertTarget(Integer typeId, String typeName, Integer groupId, Integer monitorId, String subjectTableName, Set<String> recordKeys, Map<String, String> attributes)
{
/***************************************************************************
** From a type row and a signal (before the alert exists).
***************************************************************************/
static AlertTarget of(QRecord type, AlertSignal signal, Integer monitorId)
{
Set<String> keys = new LinkedHashSet<>();
for(AlertRecordRef ref : signal.getRecordRefs())
{
keys.add(ref.getTableName() + ":" + ref.getPrimaryKey());
}
return (new AlertTarget(type.getValueInteger("id"), signal.getAlertTypeName(), type.getValueInteger("groupId"), monitorId,
type.getValueString("subjectTableName"), keys, signal.getAttributes()));
}
/***************************************************************************
** From an alert row (its active record refs read from the table).
***************************************************************************/
public static AlertTarget of(QRecord alert) throws QException
{
Set<String> keys = new LinkedHashSet<>();
for(QRecord ref : AlertsDb.query(AlertsRecordRef.TABLE_NAME, AlertsDb.eq("alertId", alert.getValue("id")).withCriteria("active", QCriteriaOperator.EQUALS, true)))
{
keys.add(ref.getValueString("tableName") + ":" + ref.getValueString("recordId"));
}
Map<String, String> attributes = new HashMap<>();
String json = alert.getValueString("attributes");
if(StringUtils.hasContent(json))
{
try
{
Map<String, Serializable> parsed = JsonUtils.toObject(json, Map.class);
parsed.forEach((key, value) -> attributes.put(key, value == null ? null : String.valueOf(value)));
}
catch(java.io.IOException e)
{
LOG.debug("Unreadable alert attributes", e);
}
}
return (new AlertTarget(alert.getValueInteger("alertTypeId"), alert.getValueString("alertTypeName"), alert.getValueInteger("groupId"), alert.getValueInteger("monitorId"),
alert.getValueString("subjectTableName"), keys, attributes));
}
}
}
@@ -0,0 +1,317 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.engine;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.kingsrook.qbits.alerts.AlertsQBitConfig;
import com.kingsrook.qbits.alerts.AlertsRuntime;
import com.kingsrook.qbits.alerts.AlertsSecurity;
import com.kingsrook.qbits.alerts.model.AlertsMonitor;
import com.kingsrook.qbits.alerts.spi.AlertLink;
import com.kingsrook.qbits.alerts.spi.NotificationAudience;
import com.kingsrook.qbits.alerts.spi.NotificationCategory;
import com.kingsrook.qbits.alerts.spi.NotificationSeverity;
import com.kingsrook.qbits.alerts.spi.NotificationSignal;
import com.kingsrook.qqq.backend.core.actions.processes.listeners.ProcessLifecycleListenerInterface;
import com.kingsrook.qqq.backend.core.alerts.AlertMonitorKind;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.actions.processes.ProcessSummaryLine;
import com.kingsrook.qqq.backend.core.model.actions.processes.ProcessSummaryLineInterface;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunProcessInput;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunProcessOutput;
import com.kingsrook.qqq.backend.core.model.actions.processes.Status;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import com.kingsrook.qqq.backend.core.model.session.QSystemUserSession;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.StreamedETLWithFrontendProcess;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
import com.kingsrook.qqq.backend.core.utils.ValueUtils;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
/*******************************************************************************
** Feeds alerts and notifications from QQQ's process lifecycle events (no ESB
** needed). Never affects the process.
** - PROCESS_FAILED and process HEARTBEAT monitors: a failed run raises, a
** completed run resolves and beats the process's heartbeat key. Only
** processes some monitor watches are handled (the watched names are
** cached for a minute).
** - Job notifications (docs/NOTIFICATIONS.md 6.1): when a run started by a
** person fails, or completes with error summary lines (a partial run),
** that person gets a JOB notification linked to the run. System runs and
** the qbit's own processes are skipped. Off with notifyFailedJobs(false).
*******************************************************************************/
public class AlertsProcessListener implements ProcessLifecycleListenerInterface
{
private static final QLogger LOG = QLogger.getLogger(AlertsProcessListener.class);
private static final long CACHE_MILLIS = 60_000;
private static volatile Set<String> watched = null;
private static volatile long watchedAt = 0;
/*******************************************************************************
**
*******************************************************************************/
@Override
public boolean appliesTo(String processName)
{
AlertsRuntime runtime = AlertsRuntime.find(QContext.getQInstance());
if(runtime == null || processName == null)
{
return (false);
}
return (notifiesJobs(runtime, processName) || isWatched(runtime, processName));
}
/*******************************************************************************
** Whether a monitor watches this process.
*******************************************************************************/
private static boolean isWatched(AlertsRuntime runtime, String processName)
{
for(String pattern : watched(runtime))
{
if(processName.equals(pattern) || processName.matches(pattern.replace(".", "\\.").replace("*", ".*")))
{
return (true);
}
}
return (false);
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public void onProcessStarted(RunProcessInput input)
{
////////////////////////////////////////////
// noop - only outcomes matter for alerts //
////////////////////////////////////////////
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public void onProcessCompleted(RunProcessInput input, RunProcessOutput output)
{
AlertsRuntime runtime = AlertsRuntime.find(QContext.getQInstance());
if(runtime == null)
{
return;
}
try
{
if(isWatched(runtime, input.getProcessName()))
{
runtime.getEngine().heartbeat(MonitorEvaluator.processHeartbeatKey(input.getProcessName()), runtime.now());
runtime.getEvaluator().processCompleted(input.getProcessName());
}
int errors = errorCount(output);
if(errors > 0 && notifiesJobs(runtime, input.getProcessName()))
{
notifyStarter(runtime, input, NotificationSeverity.WARNING, "%s finished with errors",
(errors == 1 ? "1 record" : errors + " records") + " had errors. Open the run's results for the details.");
}
}
catch(Exception e)
{
LOG.warn("Error recording a process completion for alerts", e, logPair("processName", input.getProcessName()));
}
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public void onProcessFailed(RunProcessInput input, Exception exception)
{
AlertsRuntime runtime = AlertsRuntime.find(QContext.getQInstance());
if(runtime == null)
{
return;
}
try
{
if(isWatched(runtime, input.getProcessName()))
{
QProcessMetaData process = QContext.getQInstance().getProcess(input.getProcessName());
runtime.getEvaluator().processFailed(input.getProcessName(), process == null ? null : process.getLabel(),
exception == null ? null : exception.getClass().getSimpleName() + ": " + exception.getMessage());
}
if(notifiesJobs(runtime, input.getProcessName()))
{
String message = exception == null || exception.getMessage() == null ? "It stopped with an error." : exception.getMessage();
notifyStarter(runtime, input, NotificationSeverity.ERROR, "%s failed", StringUtils.safeTruncate(message, 1000));
}
}
catch(Exception e)
{
LOG.warn("Error recording a process failure for alerts", e, logPair("processName", input.getProcessName()));
}
}
/*******************************************************************************
** Whether runs of this process notify the person who started them.
*******************************************************************************/
private static boolean notifiesJobs(AlertsRuntime runtime, String processName)
{
return (Boolean.TRUE.equals(runtime.getConfig().getNotifyFailedJobs()) && !processName.startsWith(AlertsQBitConfig.PERMISSION_BASE_NAME));
}
/*******************************************************************************
** How many records a completed run reported as errors (its ERROR summary
** lines), or 1 when the output carries an exception.
*******************************************************************************/
public static int errorCount(RunProcessOutput output)
{
if(output == null)
{
return (0);
}
if(output.getException().isPresent())
{
return (1);
}
int errors = 0;
Object summary = output.getValues() == null ? null : output.getValues().get(StreamedETLWithFrontendProcess.FIELD_PROCESS_SUMMARY);
if(summary instanceof List<?> lines)
{
for(Object line : lines)
{
if(line instanceof ProcessSummaryLineInterface summaryLine && summaryLine.getStatus() == Status.ERROR)
{
Integer count = line instanceof ProcessSummaryLine counted ? counted.getCount() : null;
errors += count == null || count < 1 ? 1 : count;
}
}
}
return (errors);
}
/*******************************************************************************
** Send a JOB notification to the person who started the run (nothing for
** system runs or sessions without a user).
*******************************************************************************/
private static void notifyStarter(AlertsRuntime runtime, RunProcessInput input, NotificationSeverity severity, String titleFormat, String body)
{
QSession session = QContext.getQSession();
String userId = session == null || session instanceof QSystemUserSession ? null : AlertsSecurity.userId(session);
if(userId == null)
{
return;
}
QProcessMetaData process = QContext.getQInstance().getProcess(input.getProcessName());
String label = process == null || process.getLabel() == null ? input.getProcessName() : process.getLabel();
String tableName = process == null ? null : process.getTableName();
runtime.sink().notify(new NotificationSignal(String.format(titleFormat, label))
.withBody(body)
.withSeverity(severity)
.withCategory(NotificationCategory.JOB)
.withSourceName("processes")
.withSourceKey("process:" + input.getProcessUUID())
.withSourceTableName(tableName)
.withLink(jobLink(runtime, input.getProcessName(), input.getProcessUUID(), tableName))
.withAudience(NotificationAudience.user(userId)));
}
/*******************************************************************************
** Where a job notification links: the configured run link pattern, else
** the process's table, else nowhere.
*******************************************************************************/
public static AlertLink jobLink(AlertsRuntime runtime, String processName, String processUUID, String tableName)
{
String pattern = runtime.getConfig().getJobRunLinkPattern();
if(StringUtils.hasContent(pattern))
{
return (AlertLink.toPath(pattern.replace("{processName}", processName).replace("{processUUID}", processUUID == null ? "" : processUUID), "Open the run"));
}
return (tableName == null ? null : AlertLink.toPath("/app/" + tableName, "Open " + tableName));
}
/*******************************************************************************
** Forget the cached names (after monitors change; tests).
*******************************************************************************/
public static void clearCache()
{
watched = null;
}
/*******************************************************************************
** Process names (or * patterns) that enabled PROCESS_FAILED or process
** HEARTBEAT monitors watch.
*******************************************************************************/
private static Set<String> watched(AlertsRuntime runtime)
{
Set<String> current = watched;
if(current != null && System.currentTimeMillis() - watchedAt < CACHE_MILLIS)
{
return (current);
}
Set<String> names = new HashSet<>();
try
{
for(QRecord monitor : runtime.asSystem(() -> AlertsDb.query(AlertsMonitor.TABLE_NAME, AlertsDb.eq("enabled", true)
.withCriteria("kind", QCriteriaOperator.IN, java.util.List.of(AlertMonitorKind.PROCESS_FAILED.name(), AlertMonitorKind.HEARTBEAT.name())))))
{
Map<String, java.io.Serializable> definition = MonitorEvaluator.definition(monitor);
String name = ValueUtils.getValueAsString(definition.get("processName"));
if(name != null)
{
names.add(name);
}
}
}
catch(Exception e)
{
LOG.debug("Could not read process monitors", e);
}
watched = names;
watchedAt = System.currentTimeMillis();
return (names);
}
}
@@ -0,0 +1,79 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.engine;
import java.time.Instant;
import com.kingsrook.qbits.alerts.AlertsRuntime;
import com.kingsrook.qqq.backend.core.alerts.AlertResolution;
import com.kingsrook.qqq.backend.core.alerts.AlertSignal;
import com.kingsrook.qqq.backend.core.alerts.AlertSinkInterface;
import com.kingsrook.qqq.backend.core.context.QContext;
/*******************************************************************************
** The sink registered in the alerts meta-data: a stateless, loadable
** (no-argument) front for the installed runtime's QbitAlertsSink. With no
** runtime in the context the calls are dropped (the core SPI's caller has
** already logged them).
*******************************************************************************/
public class AlertsSinkAdapter implements AlertSinkInterface
{
/*******************************************************************************
**
*******************************************************************************/
@Override
public void raise(AlertSignal signal)
{
AlertsRuntime runtime = AlertsRuntime.find(QContext.getQInstance());
if(runtime != null)
{
runtime.sink().raise(signal);
}
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public void resolve(AlertResolution resolution)
{
AlertsRuntime runtime = AlertsRuntime.find(QContext.getQInstance());
if(runtime != null)
{
runtime.sink().resolve(resolution);
}
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public void heartbeat(String heartbeatKey, Instant at)
{
AlertsRuntime runtime = AlertsRuntime.find(QContext.getQInstance());
if(runtime != null)
{
runtime.sink().heartbeat(heartbeatKey, at);
}
}
}
@@ -0,0 +1,879 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.engine;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import com.kingsrook.qbits.alerts.AlertsRuntime;
import com.kingsrook.qbits.alerts.AlertsSecurity;
import com.kingsrook.qbits.alerts.engine.AlertsEngine.AlertTarget;
import com.kingsrook.qbits.alerts.model.AlertsAlert;
import com.kingsrook.qbits.alerts.model.AlertsHeartbeat;
import com.kingsrook.qbits.alerts.model.AlertsMonitor;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.MonitorStatus;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.Resolution;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.Status;
import com.kingsrook.qbits.alerts.model.AlertsType;
import com.kingsrook.qqq.backend.core.actions.customizers.QCodeLoader;
import com.kingsrook.qqq.backend.core.actions.tables.AggregateAction;
import com.kingsrook.qqq.backend.core.alerts.AlertLink;
import com.kingsrook.qqq.backend.core.alerts.AlertMonitorKind;
import com.kingsrook.qqq.backend.core.alerts.AlertRecordRef;
import com.kingsrook.qqq.backend.core.alerts.AlertSeverity;
import com.kingsrook.qqq.backend.core.alerts.AlertSignal;
import com.kingsrook.qqq.backend.core.context.CapturedContext;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.exceptions.QUserFacingException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.Aggregate;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.AggregateInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.AggregateOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.AggregateResult;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.GroupBy;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterOrderBy;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
import com.kingsrook.qqq.backend.core.utils.ValueUtils;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
/*******************************************************************************
** The monitor engine (design section 5.3). One hidden scheduled process
** claims due monitors (enabled, nextRunAt passed, not claimed by another
** evaluator), evaluates each with a timeout as the system user, and applies
** the result: raise what fires, resolve this monitor's open alerts that no
** longer do (a full-state diff), and record lastStatus / lastValue /
** lastError. A monitor that throws is CHECK_FAILED; three failures in a row
** raise alerts.monitor.failing, because a broken check is itself an
** exception to manage.
**
** Kinds evaluated here: TABLE_QUERY, AGGREGATE, HEARTBEAT and CODE.
** PROCESS_FAILED is driven by process runs (AlertsProcessListener);
** ESB_EVENT and EXTERNAL are event-driven (later phases).
**
** "Run check now" uses preview (the Review step: what would open, update
** and resolve, nothing written) and then runNow (the Result).
*******************************************************************************/
public class MonitorEvaluator
{
private static final QLogger LOG = QLogger.getLogger(MonitorEvaluator.class);
public static final String MONITOR_FAILING_TYPE = "alerts.monitor.failing";
private static final int FAILURES_BEFORE_META_ALERT = 3;
private static final int DEFAULT_SCHEDULE_SECONDS = 300;
private static final int CLAIM_SECONDS = 120;
private final AlertsRuntime runtime;
private final String evaluatorId = "evaluator-" + UUID.randomUUID().toString().substring(0, 8);
private final ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
/*******************************************************************************
** What an evaluation found (and, in a preview, what applying it would do).
**
** @param status OK, FIRING, PENDING (holding for forMinutes),
** CHECK_FAILED or SKIPPED_MUTED
** @param value a short description of the measured value
** @param signals what fires now
** @param wouldOpen dedup keys that would open (or reopen) an alert
** @param wouldUpdate dedup keys whose open alert would be refreshed
** @param wouldResolve open alerts of this monitor that would be resolved
** @param error the error, when the check failed
*******************************************************************************/
public record Plan(MonitorStatus status, String value, List<AlertSignal> signals, List<String> wouldOpen, List<String> wouldUpdate, List<QRecord> wouldResolve, String error)
{
}
/*******************************************************************************
** Constructor
*******************************************************************************/
public MonitorEvaluator(AlertsRuntime runtime)
{
this.runtime = runtime;
}
/*******************************************************************************
** Evaluate every due monitor. Returns how many were evaluated.
*******************************************************************************/
public int evaluateDue() throws QException
{
runtime.getTypeSync().syncIfNeeded();
List<QRecord> due = runtime.asSystem(() ->
{
Instant now = runtime.now();
List<QRecord> candidates = AlertsDb.query(AlertsMonitor.TABLE_NAME, AlertsDb.eq("enabled", true)
.withCriteria("kind", QCriteriaOperator.IN, List.of(AlertMonitorKind.TABLE_QUERY.name(), AlertMonitorKind.AGGREGATE.name(), AlertMonitorKind.HEARTBEAT.name(), AlertMonitorKind.CODE.name()))
.withOrderBy(new QFilterOrderBy("id")));
List<QRecord> claimed = new ArrayList<>();
for(QRecord monitor : candidates)
{
Instant next = monitor.getValueInstant("nextRunAt");
Instant until = monitor.getValueInstant("claimedUntil");
if((next == null || !next.isAfter(now)) && (until == null || until.isBefore(now)))
{
AlertsDb.update(AlertsMonitor.TABLE_NAME, new QRecord().withValue("id", monitor.getValue("id")).withValue("claimedBy", evaluatorId)
.withValue("claimedUntil", now.plusSeconds(CLAIM_SECONDS)));
claimed.add(monitor);
}
}
return (claimed);
});
for(QRecord monitor : due)
{
evaluate(monitor.getValueInteger("id"), true);
}
runtime.getEngine().maintenance();
return (due.size());
}
/*******************************************************************************
** What evaluating the monitor now would do, without writing alerts.
*******************************************************************************/
public Plan preview(Integer monitorId) throws QException
{
return (evaluate(monitorId, false));
}
/*******************************************************************************
** Evaluate the monitor now and apply the result.
*******************************************************************************/
public Plan runNow(Integer monitorId) throws QException
{
return (evaluate(monitorId, true));
}
/*******************************************************************************
** Evaluate one monitor, applying the result or only planning it.
*******************************************************************************/
Plan evaluate(Integer monitorId, boolean apply) throws QException
{
runtime.getTypeSync().syncIfNeeded();
return (runtime.asSystem(() ->
{
QRecord monitor = AlertsDb.byId(AlertsMonitor.TABLE_NAME, monitorId);
if(monitor == null)
{
throw (new QUserFacingException("The monitor was not found."));
}
QRecord type = AlertsDb.byId(AlertsType.TABLE_NAME, monitor.getValue("alertTypeId"));
if(type == null)
{
throw (new QUserFacingException("The monitor's alert type was not found."));
}
Instant now = runtime.now();
long started = System.currentTimeMillis();
String typeName = type.getValueString("name");
AlertTarget target = new AlertTarget(type.getValueInteger("id"), typeName, type.getValueInteger("groupId"), monitorId, type.getValueString("subjectTableName"), Set.of(), Map.of());
if(runtime.getRouter().isSuppressedByMaintenance(target, now))
{
Plan plan = new Plan(MonitorStatus.SKIPPED_MUTED, "skipped: maintenance window", List.of(), List.of(), List.of(), List.of(), null);
if(apply)
{
finish(monitor, plan, now, started);
}
return (plan);
}
List<AlertSignal> signals;
try
{
signals = signalsWithTimeout(monitor, typeName, now);
}
catch(Exception e)
{
String error = rootMessage(e);
Plan plan = new Plan(MonitorStatus.CHECK_FAILED, null, List.of(), List.of(), List.of(), List.of(), error);
if(apply)
{
finish(monitor, plan, now, started);
}
return (plan);
}
AlertMonitorKind kind = AlertMonitorKind.valueOf(monitor.getValueString("kind"));
boolean fullState = kind != AlertMonitorKind.PROCESS_FAILED && kind != AlertMonitorKind.ESB_EVENT && kind != AlertMonitorKind.EXTERNAL;
String value = signals.isEmpty() ? lastValue(kind, monitor) : describe(signals);
////////////////////////////////////////////////////////////////////////
// forMinutes: the condition must hold this long before it fires //
////////////////////////////////////////////////////////////////////////
Integer forMinutes = monitor.getValueInteger("forMinutes");
Instant since = monitor.getValueInstant("conditionSince");
boolean pending = false;
if(!signals.isEmpty() && forMinutes != null && forMinutes > 0)
{
Instant start = since == null ? now : since;
pending = now.isBefore(start.plus(forMinutes, ChronoUnit.MINUTES));
}
List<String> wouldOpen = new ArrayList<>();
List<String> wouldUpdate = new ArrayList<>();
List<QRecord> wouldResolve = new ArrayList<>();
Set<String> keys = new HashSet<>();
for(AlertSignal signal : signals)
{
String signalType = signal.getAlertTypeName() == null ? typeName : signal.getAlertTypeName();
signal.setAlertTypeName(signalType);
keys.add(AlertsEngine.openKey(signalType, signal.getEffectiveDedupKey()));
if(AlertsDb.first(AlertsAlert.TABLE_NAME, AlertsDb.eq("openDedupKey", AlertsEngine.openKey(signalType, signal.getEffectiveDedupKey()))) != null)
{
wouldUpdate.add(signal.getEffectiveDedupKey());
}
else
{
wouldOpen.add(signal.getEffectiveDedupKey());
}
}
if(fullState && !pending)
{
for(QRecord open : AlertsDb.query(AlertsAlert.TABLE_NAME, AlertsDb.eq("monitorId", monitorId).withCriteria("status", QCriteriaOperator.IN, Status.openNames())))
{
if(!keys.contains(open.getValueString("openDedupKey")))
{
wouldResolve.add(open);
}
}
}
MonitorStatus status = signals.isEmpty() ? MonitorStatus.OK : (pending ? MonitorStatus.PENDING : MonitorStatus.FIRING);
Plan plan = new Plan(status, value, signals, pending ? List.of() : wouldOpen, pending ? List.of() : wouldUpdate, wouldResolve, null);
if(!apply)
{
return (plan);
}
if(!pending)
{
for(AlertSignal signal : signals)
{
runtime.getEngine().raise(signal, monitorId);
}
}
for(QRecord open : wouldResolve)
{
runtime.getEngine().resolveById(open.getValueInteger("id"), Resolution.MONITOR, null, "The monitor's latest check was clean");
}
finish(monitor.withValue("conditionSince", signals.isEmpty() ? null : (since == null ? now : since)), plan, now, started);
return (plan);
}));
}
/*******************************************************************************
** A PROCESS_FAILED monitor's process failed: raise.
*******************************************************************************/
public void processFailed(String processName, String processLabel, String error) throws QException
{
for(QRecord monitor : processMonitors(processName))
{
QRecord type = runtime.asSystem(() -> AlertsDb.byId(AlertsType.TABLE_NAME, monitor.getValue("alertTypeId")));
if(type == null)
{
continue;
}
runtime.getEngine().raise(new AlertSignal(type.getValueString("name"))
.withDedupKey(processName)
.withSeverity(AlertSeverity.fromLabel(monitor.getValueString("severity"), null))
.withTitle((StringUtils.hasContent(processLabel) ? processLabel : processName) + " failed")
.withSummary("The latest run failed.")
.withDetails(error)
.withAttribute("processName", processName), monitor.getValueInteger("id"));
}
}
/*******************************************************************************
** A PROCESS_FAILED monitor's process completed: resolve.
*******************************************************************************/
public void processCompleted(String processName) throws QException
{
for(QRecord monitor : processMonitors(processName))
{
QRecord type = runtime.asSystem(() -> AlertsDb.byId(AlertsType.TABLE_NAME, monitor.getValue("alertTypeId")));
if(type != null)
{
runtime.getEngine().resolve(type.getValueString("name"), processName, Resolution.MONITOR, null, "A later run completed");
}
}
}
/*******************************************************************************
** Enabled PROCESS_FAILED monitors for a process (definition processName,
** exact or a * pattern).
*******************************************************************************/
private List<QRecord> processMonitors(String processName) throws QException
{
List<QRecord> matches = new ArrayList<>();
for(QRecord monitor : runtime.asSystem(() -> AlertsDb.query(AlertsMonitor.TABLE_NAME, AlertsDb.eq("enabled", true)
.withCriteria("kind", QCriteriaOperator.EQUALS, AlertMonitorKind.PROCESS_FAILED.name()))))
{
String pattern = ValueUtils.getValueAsString(definition(monitor).get("processName"));
if(pattern != null && processName.matches(pattern.replace(".", "\\.").replace("*", ".*")))
{
matches.add(monitor);
}
}
return (matches);
}
/*******************************************************************************
** Run the kind's check with the configured timeout.
*******************************************************************************/
private List<AlertSignal> signalsWithTimeout(QRecord monitor, String typeName, Instant now) throws Exception
{
CapturedContext context = QContext.capture();
Future<List<AlertSignal>> future = executor.submit(() ->
{
List<AlertSignal>[] result = new List[1];
QContext.withTemporaryContext(context, () -> result[0] = signals(monitor, typeName, now));
return (result[0]);
});
try
{
return (future.get(runtime.getConfig().getMonitorTimeoutSeconds(), TimeUnit.SECONDS));
}
catch(TimeoutException e)
{
future.cancel(true);
throw (new QException("The check took longer than " + runtime.getConfig().getMonitorTimeoutSeconds() + " seconds."));
}
}
/*******************************************************************************
** What fires now, by kind.
*******************************************************************************/
List<AlertSignal> signals(QRecord monitor, String typeName, Instant now) throws QException
{
AlertMonitorKind kind = AlertMonitorKind.valueOf(monitor.getValueString("kind"));
Map<String, Serializable> definition = definition(monitor);
return switch(kind)
{
case TABLE_QUERY -> tableQuery(monitor, typeName, definition);
case AGGREGATE -> aggregate(monitor, typeName, definition);
case HEARTBEAT -> heartbeat(monitor, typeName, definition, now);
case CODE -> code(monitor, typeName, definition, now);
case PROCESS_FAILED, ESB_EVENT, EXTERNAL -> List.of();
};
}
/*******************************************************************************
** TABLE_QUERY: rows matching a filter pass a threshold (default: any).
*******************************************************************************/
private List<AlertSignal> tableQuery(QRecord monitor, String typeName, Map<String, Serializable> definition) throws QException
{
String tableName = requireTable(definition);
QQueryFilter filter = filter(definition);
int threshold = intValue(definition.get("threshold"), 0);
QTableMetaData table = runtime.getQInstance().getTable(tableName);
int count = AlertsDb.count(tableName, filter.clone());
if(count <= threshold)
{
return (List.of());
}
String labelField = ValueUtils.getValueAsString(definition.get("labelField"));
String name = monitor.getValueString("name");
boolean perRecord = Boolean.TRUE.equals(monitor.getValueBoolean("perRecord"));
int maxOpen = runtime.getConfig().getMaxOpenPerMonitor();
List<QRecord> rows = AlertsDb.query(tableName, filter.clone().withLimit(perRecord ? maxOpen + 1 : AlertSignal.MAX_RECORD_REFS));
if(perRecord && count <= maxOpen)
{
List<AlertSignal> signals = new ArrayList<>();
for(QRecord row : rows)
{
Serializable id = row.getValue(table.getPrimaryKeyField());
String label = labelField == null ? null : row.getValueString(labelField);
signals.add(base(monitor, typeName)
.withDedupKey("record:" + id)
.withTitle(name + ": " + (label != null && !label.isBlank() ? label : table.getLabel() + " " + id))
.withRecordRef(AlertRecordRef.of(tableName, id).withLabel(label))
.withLink(AlertLink.toRecord(tableName, id, "Open the record")));
}
return (signals);
}
List<AlertRecordRef> refs = new ArrayList<>();
for(QRecord row : rows)
{
Serializable id = row.getValue(table.getPrimaryKeyField());
refs.add(AlertRecordRef.of(tableName, id).withLabel(labelField == null ? null : row.getValueString(labelField)));
}
AlertSignal signal = base(monitor, typeName)
.withDedupKey("monitor:" + monitor.getValue("id"))
.withTitle(name + ": " + plural(count, table.getLabel()))
.withSummary(perRecord ? "More than " + maxOpen + " records match, so they are grouped into one alert." : null)
.withRecordRefs(refs)
.withCount(count)
.withLink(AlertLink.toTable(tableName, filter(definition), "Matching records"));
return (List.of(signal));
}
/*******************************************************************************
** AGGREGATE: an aggregate (optionally per group) crosses a band.
*******************************************************************************/
private List<AlertSignal> aggregate(QRecord monitor, String typeName, Map<String, Serializable> definition) throws QException
{
String tableName = requireTable(definition);
AggregateOperator operator = AggregateOperator.valueOf(Objects.requireNonNullElse(ValueUtils.getValueAsString(definition.get("aggregate")), "COUNT").toUpperCase(Locale.ROOT));
String fieldName = Objects.requireNonNullElse(ValueUtils.getValueAsString(definition.get("fieldName")), runtime.getQInstance().getTable(tableName).getPrimaryKeyField());
String groupField = ValueUtils.getValueAsString(definition.get("groupBy"));
String comparator = Objects.requireNonNullElse(ValueUtils.getValueAsString(definition.get("comparator")), "GT").toUpperCase(Locale.ROOT);
Aggregate aggregate = new Aggregate(fieldName, operator);
AggregateInput input = new AggregateInput(tableName).withFilter(filter(definition)).withAggregate(aggregate);
GroupBy groupBy = null;
if(groupField != null)
{
QFieldMetaData field = runtime.getQInstance().getTable(tableName).getField(groupField);
groupBy = new GroupBy(field.getType(), groupField);
input.withGroupBy(groupBy);
}
List<AlertSignal> signals = new ArrayList<>();
for(AggregateResult result : new AggregateAction().execute(input).getResults())
{
BigDecimal value = ValueUtils.getValueAsBigDecimal(result.getAggregateValue(aggregate));
if(value == null)
{
value = BigDecimal.ZERO;
}
AlertSeverity severity = band(value, comparator, definition);
if(severity == null)
{
continue;
}
String group = groupBy == null ? null : String.valueOf(result.getGroupByValue(groupBy));
signals.add(base(monitor, typeName)
.withSeverity(severity)
.withDedupKey(group == null ? "aggregate" : "group:" + group)
.withTitle(monitor.getValueString("name") + (group == null ? "" : " (" + group + ")") + ": " + operator.name().toLowerCase(Locale.ROOT) + " " + value.stripTrailingZeros().toPlainString())
.withAttribute("value", value.toPlainString())
.withLink(AlertLink.toTable(tableName, filter(definition), "Records")));
}
return (signals);
}
/*******************************************************************************
** HEARTBEAT: nothing seen (a beat, a process success, a newest row) within
** the expected interval plus grace.
*******************************************************************************/
private List<AlertSignal> heartbeat(QRecord monitor, String typeName, Map<String, Serializable> definition, Instant now) throws QException
{
int expected = intValue(definition.get("expectedEverySeconds"), 0);
int grace = intValue(definition.get("graceSeconds"), 0);
if(expected <= 0)
{
throw (new QException("A heartbeat monitor needs expectedEverySeconds."));
}
Instant last;
String what;
String heartbeatKey = ValueUtils.getValueAsString(definition.get("heartbeatKey"));
String processName = ValueUtils.getValueAsString(definition.get("processName"));
String tableName = ValueUtils.getValueAsString(definition.get("tableName"));
if(heartbeatKey != null || processName != null)
{
String key = heartbeatKey != null ? heartbeatKey : processHeartbeatKey(processName);
QRecord row = AlertsDb.first(AlertsHeartbeat.TABLE_NAME, AlertsDb.eq("heartbeatKey", key));
last = row == null ? null : row.getValueInstant("lastBeatAt");
what = processName != null ? "a successful run of " + processName : "a heartbeat from " + key;
}
else if(tableName != null)
{
String dateField = Objects.requireNonNullElse(ValueUtils.getValueAsString(definition.get("dateField")), "createDate");
QRecord newest = AlertsDb.first(tableName, filter(definition).withOrderBy(new QFilterOrderBy(dateField, false)));
last = newest == null ? null : ValueUtils.getValueAsInstant(newest.getValue(dateField));
what = "a new " + runtime.getQInstance().getTable(tableName).getLabel() + " row";
}
else
{
throw (new QException("A heartbeat monitor needs heartbeatKey, processName or tableName."));
}
Instant baseline = last != null ? last : monitor.getValueInstant("createDate");
if(baseline == null || !now.isAfter(baseline.plusSeconds((long) expected + grace)))
{
return (List.of());
}
String age = last == null ? "yet" : "for " + com.kingsrook.qbits.alerts.delivery.AlertMessageRenderer.age(last, now);
return (List.of(base(monitor, typeName)
.withDedupKey("monitor:" + monitor.getValue("id"))
.withTitle(monitor.getValueString("name") + ": no " + what.replaceFirst("^an? ", "") + " " + age)
.withSummary("Expected " + what + " every " + com.kingsrook.qbits.alerts.delivery.AlertMessageRenderer.age(now.minusSeconds(expected), now) + ".")));
}
/*******************************************************************************
** CODE: an AlertCheckInterface returns what is failing.
*******************************************************************************/
@SuppressWarnings("unchecked")
private List<AlertSignal> code(QRecord monitor, String typeName, Map<String, Serializable> definition, Instant now) throws QException
{
String className = ValueUtils.getValueAsString(definition.get("codeReference"));
if(className == null)
{
throw (new QException("A code monitor needs codeReference (a class implementing AlertCheckInterface)."));
}
AlertCheckInterface check;
try
{
check = QCodeLoader.getAdHoc(AlertCheckInterface.class, new QCodeReference(Class.forName(className)));
}
catch(ClassNotFoundException e)
{
throw (new QException("The check class was not found: " + className));
}
Map<String, Serializable> params = definition.get("params") instanceof Map<?, ?> map ? (Map<String, Serializable>) map : Map.of();
List<AlertSignal> result = check.check(new AlertCheckInterface.Context(monitor, typeName, params, now));
List<AlertSignal> signals = new ArrayList<>();
for(AlertSignal signal : result == null ? List.<AlertSignal>of() : result)
{
if(signal != null)
{
if(signal.getSeverity() == null)
{
signal.setSeverity(AlertSeverity.fromLabel(monitor.getValueString("severity"), null));
}
signals.add(signal);
}
}
return (signals);
}
/*******************************************************************************
** Record the run on the monitor (and the failing meta-alert).
*******************************************************************************/
private void finish(QRecord monitor, Plan plan, Instant now, long started) throws QException
{
Integer monitorId = monitor.getValueInteger("id");
int schedule = monitor.getValueInteger("scheduleSeconds") == null ? DEFAULT_SCHEDULE_SECONDS : Math.max(10, monitor.getValueInteger("scheduleSeconds"));
int failures = plan.status() == MonitorStatus.CHECK_FAILED ? (monitor.getValueInteger("consecutiveFailures") == null ? 0 : monitor.getValueInteger("consecutiveFailures")) + 1 : 0;
QRecord update = new QRecord()
.withValue("id", monitorId)
.withValue("lastRunAt", now)
.withValue("lastStatus", plan.status().name())
.withValue("lastValue", truncate(plan.value(), 200))
.withValue("lastError", truncate(plan.error(), 1900))
.withValue("lastElapsedMs", (int) Math.min(Integer.MAX_VALUE, System.currentTimeMillis() - started))
.withValue("consecutiveFailures", failures)
.withValue("nextRunAt", now.plusSeconds(schedule))
.withValue("claimedBy", null)
.withValue("claimedUntil", null);
if(plan.status() != MonitorStatus.CHECK_FAILED)
{
update.setValue("conditionSince", monitor.getValue("conditionSince"));
}
AlertsDb.update(AlertsMonitor.TABLE_NAME, update);
if(failures == FAILURES_BEFORE_META_ALERT)
{
LOG.warn("Alerts monitor is failing", logPair("monitor", monitor.getValueString("name")), logPair("error", plan.error()));
runtime.getEngine().raise(new AlertSignal(MONITOR_FAILING_TYPE)
.withDedupKey("monitor:" + monitorId)
.withSeverity(AlertSeverity.ERROR)
.withTitle("Monitor \"" + monitor.getValueString("name") + "\" cannot run")
.withSummary(failures + " checks in a row failed.")
.withDetails(plan.error())
.withRecordRef(AlertRecordRef.of(AlertsMonitor.TABLE_NAME, monitorId))
.withLink(AlertLink.toRecord(AlertsMonitor.TABLE_NAME, monitorId, "Open the monitor")));
}
else if(failures == 0 && monitor.getValueInteger("consecutiveFailures") != null && monitor.getValueInteger("consecutiveFailures") >= FAILURES_BEFORE_META_ALERT)
{
runtime.getEngine().resolve(MONITOR_FAILING_TYPE, "monitor:" + monitorId, Resolution.PRODUCER, null, "The monitor ran again");
}
}
/*******************************************************************************
** A signal for the monitor's type and severity.
*******************************************************************************/
private static AlertSignal base(QRecord monitor, String typeName)
{
return (new AlertSignal(typeName).withSeverity(AlertSeverity.fromLabel(monitor.getValueString("severity"), null)));
}
/*******************************************************************************
** The monitor's definition JSON as a map (empty when blank).
*******************************************************************************/
@SuppressWarnings("unchecked")
static Map<String, Serializable> definition(QRecord monitor)
{
String json = monitor.getValueString("definition");
if(!StringUtils.hasContent(json))
{
return (new LinkedHashMap<>());
}
try
{
return (JsonUtils.toObject(json, LinkedHashMap.class));
}
catch(Exception e)
{
throw (new IllegalArgumentException("The monitor's definition is not valid JSON: " + e.getMessage()));
}
}
/*******************************************************************************
** The definition's filter (a QQueryFilter, as an object or a JSON string).
*******************************************************************************/
private static QQueryFilter filter(Map<String, Serializable> definition) throws QException
{
Object filter = definition.get("filter");
if(filter == null)
{
return (new QQueryFilter());
}
try
{
String json = filter instanceof String string ? string : JsonUtils.toJson(filter);
return (JsonUtils.toObject(json, QQueryFilter.class));
}
catch(Exception e)
{
throw (new QException("The monitor's filter is not a valid QQueryFilter: " + e.getMessage()));
}
}
/*******************************************************************************
** The definition's tableName, which must be a table in the instance.
*******************************************************************************/
private String requireTable(Map<String, Serializable> definition) throws QException
{
String tableName = ValueUtils.getValueAsString(definition.get("tableName"));
if(tableName == null || runtime.getQInstance().getTable(tableName) == null)
{
throw (new QException("The monitor's tableName is missing or not a table: " + tableName));
}
return (tableName);
}
/*******************************************************************************
** The severity band an aggregate value falls in (null: none).
*******************************************************************************/
private static AlertSeverity band(BigDecimal value, String comparator, Map<String, Serializable> definition)
{
List<Map.Entry<AlertSeverity, String>> bands = List.of(
Map.entry(AlertSeverity.CRITICAL, "criticalThreshold"),
Map.entry(AlertSeverity.ERROR, "errorThreshold"),
Map.entry(AlertSeverity.WARNING, "warningThreshold"));
for(Map.Entry<AlertSeverity, String> band : bands)
{
BigDecimal threshold = ValueUtils.getValueAsBigDecimal(definition.get(band.getValue()));
if(threshold != null && compare(value, comparator, threshold))
{
return (band.getKey());
}
}
return (null);
}
/*******************************************************************************
** value (comparator) threshold.
*******************************************************************************/
private static boolean compare(BigDecimal value, String comparator, BigDecimal threshold)
{
int c = value.compareTo(threshold);
return switch(comparator)
{
case "GTE", ">=" -> c >= 0;
case "LT", "<" -> c < 0;
case "LTE", "<=" -> c <= 0;
default -> c > 0;
};
}
/*******************************************************************************
** The heartbeat key a process's successful runs beat.
*******************************************************************************/
public static String processHeartbeatKey(String processName)
{
String hyphenated = Objects.requireNonNullElse(processName, "")
.replaceAll("([a-z0-9])([A-Z])", "$1-$2")
.replaceAll("[^A-Za-z0-9]+", "-")
.toLowerCase(Locale.ROOT)
.replaceAll("^-+|-+$", "");
return ("process." + (hyphenated.isEmpty() ? "unnamed" : hyphenated));
}
/*******************************************************************************
** A short description of what fired.
*******************************************************************************/
private static String describe(List<AlertSignal> signals)
{
if(signals.size() == 1)
{
AlertSignal signal = signals.get(0);
return (signal.getEffectiveCount() != null ? plural(signal.getEffectiveCount(), "match") : signal.getTitle());
}
return (signals.size() + " alerts");
}
/*******************************************************************************
** The value to show when nothing fired.
*******************************************************************************/
private static String lastValue(AlertMonitorKind kind, QRecord monitor)
{
return switch(kind)
{
case PROCESS_FAILED, ESB_EVENT, EXTERNAL -> "event-driven";
default -> "clean";
};
}
/*******************************************************************************
** "1 record" / "3 records" (labels are lower-cased).
*******************************************************************************/
static String plural(int count, String noun)
{
String lower = noun == null ? "row" : noun.toLowerCase(Locale.ROOT);
return (count + " " + (count == 1 ? lower : (lower.endsWith("s") || lower.endsWith("h") ? lower + "es" : lower + "s")));
}
/*******************************************************************************
**
*******************************************************************************/
private static int intValue(Object value, int fallback)
{
Integer integer = ValueUtils.getValueAsInteger(value);
return (integer == null ? fallback : integer);
}
/*******************************************************************************
** The innermost message.
*******************************************************************************/
private static String rootMessage(Throwable throwable)
{
Throwable root = throwable;
while(root.getCause() != null && root.getCause() != root)
{
root = root.getCause();
}
String message = root.getMessage();
return (message == null ? root.getClass().getSimpleName() : message);
}
/*******************************************************************************
**
*******************************************************************************/
private static String truncate(String text, int max)
{
return (text == null || text.length() <= max ? text : text.substring(0, max - 1) + "…");
}
/*******************************************************************************
** The id this evaluator claims with.
*******************************************************************************/
public String getEvaluatorId()
{
return (evaluatorId);
}
/*******************************************************************************
** Whether the current session is the system user (for tests).
*******************************************************************************/
static boolean isSystem()
{
return (AlertsSecurity.isSystemUser());
}
}
@@ -0,0 +1,340 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.engine;
import java.time.Instant;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import com.kingsrook.qbits.alerts.AlertsRuntime;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.Resolution;
import com.kingsrook.qbits.alerts.spi.NotificationSignal;
import com.kingsrook.qqq.backend.core.alerts.AlertResolution;
import com.kingsrook.qqq.backend.core.alerts.AlertSeverity;
import com.kingsrook.qqq.backend.core.alerts.AlertSignal;
import com.kingsrook.qqq.backend.core.alerts.AlertSinkInterface;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
/*******************************************************************************
** The qbit's sink (design section 3.2): producers' signals go into a bounded
** in-memory queue drained by a virtual thread into the alerts tables, so a
** producer never waits on the database. If the queue overflows, the signal
** is dropped and counted and alerts.sink.overflow is raised once; past 1,000
** signals a minute for one type, signals are counted, not stored, and
** alerts.producer.flood is raised (section 7.5).
**
** With synchronousSink (tests), signals are processed on the caller's
** thread.
*******************************************************************************/
public class QbitAlertsSink implements AlertSinkInterface
{
private static final QLogger LOG = QLogger.getLogger(QbitAlertsSink.class);
public static final String OVERFLOW_TYPE = "alerts.sink.overflow";
public static final String FLOOD_TYPE = "alerts.producer.flood";
static final int QUEUE_CAPACITY = 10_000;
static final int FLOOD_PER_MINUTE = 1_000;
static final long POLL_MILLIS = 200;
static final long STOP_WAIT_MILLIS = 10_000;
private final AlertsRuntime runtime;
private final BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(QUEUE_CAPACITY);
private final AtomicBoolean started = new AtomicBoolean(false);
private final AtomicBoolean overflowRaised = new AtomicBoolean(false);
private final AtomicLong dropped = new AtomicLong();
private final Map<String, AtomicInteger> perMinute = new ConcurrentHashMap<>();
private volatile long minute = -1;
private volatile Thread drainThread;
private volatile boolean stopping = false;
/*******************************************************************************
** Constructor
*******************************************************************************/
public QbitAlertsSink(AlertsRuntime runtime)
{
this.runtime = runtime;
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public void raise(AlertSignal signal)
{
if(signal == null || signal.getAlertTypeName() == null)
{
return;
}
if(signal.getOccurredAt() == null)
{
signal.setOccurredAt(runtime.now());
}
if(isFlooding(signal.getAlertTypeName()))
{
dropped.incrementAndGet();
return;
}
submit(() -> runtime.getEngine().raise(signal));
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public void resolve(AlertResolution resolution)
{
if(resolution == null || resolution.getAlertTypeName() == null)
{
return;
}
submit(() -> runtime.getEngine().resolve(resolution.getAlertTypeName(), resolution.getEffectiveDedupKey(), Resolution.PRODUCER, null, resolution.getNote()));
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public void heartbeat(String heartbeatKey, Instant at)
{
Instant when = at == null ? runtime.now() : at;
submit(() -> runtime.getEngine().heartbeat(heartbeatKey, when));
}
/*******************************************************************************
** STAND-IN(core=QRun-IO/qqq#1125, removeBy=4.1.0-RC.6)
**
** Queue a notification (it is written and sent by the notification
** service on the drain thread).
*******************************************************************************/
public void notify(NotificationSignal signal)
{
if(signal == null)
{
return;
}
if(signal.getOccurredAt() == null)
{
signal.setOccurredAt(runtime.now());
}
submit(() -> runtime.getNotifications().notify(signal));
}
/*******************************************************************************
** Process everything queued now, on this thread (tests, shutdown).
*******************************************************************************/
public void flush()
{
Runnable work;
while((work = queue.poll()) != null)
{
work.run();
}
}
/*******************************************************************************
** Stop the drain thread. Work it already took off the queue finishes first
** (it is not interrupted), then everything still queued is processed here,
** so no signal submitted before stop() is lost.
*******************************************************************************/
public void stop()
{
stopping = true;
Thread thread = drainThread;
if(thread != null)
{
try
{
thread.join(STOP_WAIT_MILLIS);
}
catch(InterruptedException e)
{
Thread.currentThread().interrupt();
}
if(thread.isAlive())
{
LOG.warn("The alerts drain thread did not stop in time", logPair("waitMillis", STOP_WAIT_MILLIS));
thread.interrupt();
}
}
flush();
drainThread = null;
started.set(false);
}
/*******************************************************************************
** Signals dropped (overflow or flood) since startup.
*******************************************************************************/
public long getDroppedCount()
{
return (dropped.get());
}
/*******************************************************************************
** Queue (or, synchronously, run) one piece of engine work.
*******************************************************************************/
private void submit(EngineWork work)
{
Runnable runnable = () ->
{
try
{
work.run();
}
catch(Exception e)
{
LOG.warn("Error recording an alert signal", e);
}
};
if(Boolean.TRUE.equals(runtime.getConfig().getSynchronousSink()))
{
runnable.run();
return;
}
startIfNeeded();
if(!queue.offer(runnable))
{
dropped.incrementAndGet();
if(overflowRaised.compareAndSet(false, true))
{
LOG.warn("The alerts queue is full; dropping signals", logPair("capacity", QUEUE_CAPACITY));
Thread.ofVirtual().start(() -> safely(() -> runtime.getEngine().raise(new AlertSignal(OVERFLOW_TYPE)
.withSeverity(AlertSeverity.ERROR)
.withTitle("Alert signals are being dropped")
.withSummary("The alerts queue was full, so some signals were not recorded."))));
}
}
}
/*******************************************************************************
** Whether a type is over its per-minute limit (raises the flood alert the
** first time it is).
*******************************************************************************/
private boolean isFlooding(String alertTypeName)
{
long now = runtime.now().getEpochSecond() / 60;
if(now != minute)
{
perMinute.clear();
minute = now;
}
int count = perMinute.computeIfAbsent(alertTypeName, key -> new AtomicInteger()).incrementAndGet();
if(count == FLOOD_PER_MINUTE + 1 && !FLOOD_TYPE.equals(alertTypeName))
{
submit(() -> runtime.getEngine().raise(new AlertSignal(FLOOD_TYPE)
.withDedupKey(alertTypeName)
.withSeverity(AlertSeverity.WARNING)
.withTitle("A producer is flooding alert signals")
.withSummary("More than " + FLOOD_PER_MINUTE + " signals in a minute for one type; the rest were counted, not stored.")
.withAttribute("alertType", alertTypeName)));
}
return (count > FLOOD_PER_MINUTE);
}
/*******************************************************************************
** Start the drain thread once.
*******************************************************************************/
private void startIfNeeded()
{
if(started.compareAndSet(false, true))
{
stopping = false;
drainThread = Thread.ofVirtual().name("alerts-sink").start(() ->
{
while(!stopping && !Thread.currentThread().isInterrupted())
{
try
{
Runnable work = queue.poll(POLL_MILLIS, TimeUnit.MILLISECONDS);
if(work != null)
{
work.run();
}
}
catch(InterruptedException e)
{
Thread.currentThread().interrupt();
}
}
});
}
}
/*******************************************************************************
**
*******************************************************************************/
private static void safely(EngineWork work)
{
try
{
work.run();
}
catch(Exception e)
{
LOG.warn("Error raising an alerts meta-alert", e);
}
}
/*******************************************************************************
** Engine work that may throw.
*******************************************************************************/
@FunctionalInterface
interface EngineWork
{
/***************************************************************************
**
***************************************************************************/
void run() throws Exception;
}
}
@@ -0,0 +1,167 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.home;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.kingsrook.qbits.alerts.AlertsRuntime;
import com.kingsrook.qbits.alerts.AlertsSecurity;
import com.kingsrook.qbits.alerts.engine.AlertsDb;
import com.kingsrook.qbits.alerts.model.AlertsGroup;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.Status;
import com.kingsrook.qqq.backend.core.alerts.AlertSeverity;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
/*******************************************************************************
** Link-only summaries for other pages (design section 6.5): the Admin home
** "Needs Attention", other qbits' homes. They use the owner's numbers and
** permission filtering (the current session's record locks) and never query
** the alert tables themselves. Public API.
*******************************************************************************/
public final class AlertSummaryLoader
{
/*******************************************************************************
** Open alerts in one group, by severity.
**
** @param groupId the group (null: no group)
** @param groupName its name
** @param groupLabel its label
** @param counts open alerts by severity
** @param link the group's filtered Alerts list
*******************************************************************************/
public record GroupSummary(Integer groupId, String groupName, String groupLabel, Map<AlertSeverity, Integer> counts, String link)
{
/***************************************************************************
** Open alerts of this severity or higher.
***************************************************************************/
public int atLeast(AlertSeverity severity)
{
int total = 0;
for(Map.Entry<AlertSeverity, Integer> entry : counts.entrySet())
{
if(entry.getKey().isAtLeast(severity))
{
total += entry.getValue();
}
}
return (total);
}
/***************************************************************************
** "CDN · 1 critical, 2 errors".
***************************************************************************/
public String line()
{
List<String> parts = new ArrayList<>();
for(AlertSeverity severity : List.of(AlertSeverity.CRITICAL, AlertSeverity.ERROR, AlertSeverity.WARNING, AlertSeverity.INFO))
{
Integer count = counts.get(severity);
if(count != null && count > 0)
{
String word = severity.name().toLowerCase();
parts.add(count + " " + (count == 1 ? word : (word.equals("info") ? word : word + "s")));
}
}
return (groupLabel + " · " + String.join(", ", parts));
}
}
/*******************************************************************************
** Loader only.
*******************************************************************************/
private AlertSummaryLoader()
{
}
/*******************************************************************************
** Open alerts the current session can see, by group (largest first). Only
** groups with at least minSeverity alerts are included (null: all).
*******************************************************************************/
public static List<GroupSummary> summarize(AlertSeverity minSeverity) throws QException
{
AlertsRuntime runtime = AlertsRuntime.get();
AlertsSecurity.ensureSessionKeys(runtime.getQInstance(), QContext.getQSession());
Map<Integer, Map<AlertSeverity, Integer>> byGroup = new LinkedHashMap<>();
for(QRecord alert : AlertsDb.query("alerts_alert", new QQueryFilter().withCriteria("status", QCriteriaOperator.IN, Status.openNames()).withLimit(AlertsHome.SCAN_LIMIT)))
{
AlertSeverity severity = AlertSeverity.fromLabel(alert.getValueString("severity"), AlertSeverity.WARNING);
byGroup.computeIfAbsent(alert.getValueInteger("groupId"), key -> new HashMap<>()).merge(severity, 1, Integer::sum);
}
Map<Integer, QRecord> groups = new HashMap<>();
if(AlertsHome.canRead(AlertsGroup.TABLE_NAME))
{
for(QRecord group : AlertsDb.query(AlertsGroup.TABLE_NAME, new QQueryFilter()))
{
groups.put(group.getValueInteger("id"), group);
}
}
List<GroupSummary> summaries = new ArrayList<>();
for(Map.Entry<Integer, Map<AlertSeverity, Integer>> entry : byGroup.entrySet())
{
QRecord group = groups.get(entry.getKey());
GroupSummary summary = new GroupSummary(entry.getKey(), group == null ? null : group.getValueString("name"), group == null ? "Other" : group.getValueString("label"),
entry.getValue(), AlertsHome.listUrl(AlertsDb.eq("groupId", entry.getKey()).withCriteria("status", QCriteriaOperator.IN, Status.openNames())));
if(minSeverity == null || summary.atLeast(minSeverity) > 0)
{
summaries.add(summary);
}
}
summaries.sort((a, b) -> Integer.compare(b.atLeast(AlertSeverity.INFO), a.atLeast(AlertSeverity.INFO)));
return (summaries);
}
/*******************************************************************************
** HTML for a host's "Needs Attention" widget: one linked line per group
** with ERROR or worse, plus "All alerts". Empty when nothing qualifies.
*******************************************************************************/
public static String needsAttentionHtml() throws QException
{
List<GroupSummary> summaries = summarize(AlertSeverity.ERROR);
if(summaries.isEmpty())
{
return ("");
}
StringBuilder html = new StringBuilder("<div style=\"display:flex;flex-direction:column;gap:6px\">");
for(GroupSummary summary : summaries)
{
html.append("<div>").append(HomeHtml.link(summary.link(), summary.line())).append("</div>");
}
html.append("<div>").append(HomeHtml.link("/app/alerts", "All alerts")).append("</div>");
return (html.append("</div>").toString());
}
}
@@ -0,0 +1,754 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.home;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import com.kingsrook.qbits.alerts.AlertsRuntime;
import com.kingsrook.qbits.alerts.api.AlertsApi;
import com.kingsrook.qbits.alerts.delivery.AlertMessageRenderer;
import com.kingsrook.qbits.alerts.engine.AlertsDb;
import com.kingsrook.qbits.alerts.model.AlertsAlert;
import com.kingsrook.qbits.alerts.model.AlertsChannel;
import com.kingsrook.qbits.alerts.model.AlertsDelivery;
import com.kingsrook.qbits.alerts.model.AlertsEvent;
import com.kingsrook.qbits.alerts.model.AlertsGroup;
import com.kingsrook.qbits.alerts.model.AlertsNotification;
import com.kingsrook.qbits.alerts.model.AlertsNotificationRecipient;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.DeliveryStatus;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.EventType;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.HealthStatus;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.Status;
import com.kingsrook.qbits.alerts.model.AlertsSubscription;
import com.kingsrook.qbits.alerts.model.AlertsType;
import com.kingsrook.qbits.alerts.notifications.NotificationService;
import com.kingsrook.qqq.backend.core.actions.permissions.PermissionsHelper;
import com.kingsrook.qqq.backend.core.actions.permissions.TablePermissionSubType;
import com.kingsrook.qqq.backend.core.alerts.AlertSeverity;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.AbstractActionInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterCriteria;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterOrderBy;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.ChartData;
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.QWidgetData;
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.RawHTML;
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.TableData;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
/*******************************************************************************
** The Alerts home (design section 6.2), the single owner of open-alert data.
** Every widget is full width, reads real rows in the viewer's session (so
** the record locks decide what is counted and listed), and has an honest
** empty state. Other pages get link-only summaries from AlertSummaryLoader.
*******************************************************************************/
public final class AlertsHome
{
public static final String KIND_SEVERITY = "severity";
public static final String KIND_MINE = "mine";
public static final String KIND_ACTION = "needsAction";
public static final String KIND_BY_GROUP = "byGroup";
public static final String KIND_TREND = "trend";
public static final String KIND_NOISY = "noisy";
public static final String KIND_DELIVERY = "delivery";
public static final String KIND_NOTIFICATIONS = "notifications";
public static final String KIND_RESOLVED = "resolved";
static final int ROWS = 10;
static final int SCAN_LIMIT = 2000;
static final int TREND_DAYS = 30;
private static final String ALERTS_PATH = "/app/" + AlertsAlert.TABLE_NAME;
private static final DateTimeFormatter DAY = DateTimeFormatter.ofPattern("MMM d", Locale.US);
/*******************************************************************************
** Loaders only.
*******************************************************************************/
private AlertsHome()
{
}
/*******************************************************************************
** The widget data for a kind.
*******************************************************************************/
public static QWidgetData load(String kind, AlertsRuntime runtime) throws QException
{
if(!canRead(AlertsAlert.TABLE_NAME))
{
return (new RawHTML(null, HomeHtml.emptyState("You don't have permission to read alerts.")));
}
Instant now = runtime.now();
return switch(kind == null ? "" : kind)
{
case KIND_SEVERITY -> severity(runtime, now);
case KIND_MINE -> mine(now);
case KIND_ACTION -> needsAction(now);
case KIND_BY_GROUP -> byGroup(now);
case KIND_TREND -> trend(now);
case KIND_NOISY -> noisy(now);
case KIND_DELIVERY -> delivery(now);
case KIND_NOTIFICATIONS -> notifications(now);
case KIND_RESOLVED -> resolved(now);
default -> new RawHTML(null, HomeHtml.emptyState("Unknown Alerts widget."));
};
}
/*******************************************************************************
** Open by severity: four tiles, each with the unacknowledged count and the
** oldest age, linking to the filtered list.
*******************************************************************************/
static QWidgetData severity(AlertsRuntime runtime, Instant now) throws QException
{
List<QRecord> open = openAlerts();
List<HomeHtml.Tile> tiles = new ArrayList<>();
for(AlertSeverity severity : List.of(AlertSeverity.CRITICAL, AlertSeverity.ERROR, AlertSeverity.WARNING, AlertSeverity.INFO))
{
List<QRecord> these = open.stream().filter(alert -> severity.name().equals(alert.getValueString("severity"))).toList();
long unacked = these.stream().filter(alert -> Status.OPEN.name().equals(alert.getValueString("status"))).count();
Instant oldest = these.stream().map(alert -> alert.getValueInstant("firstRaisedAt")).filter(java.util.Objects::nonNull).min(Comparator.naturalOrder()).orElse(null);
String note = these.isEmpty() ? "none open" : unacked + " unacknowledged · oldest " + AlertMessageRenderer.age(oldest, now);
tiles.add(new HomeHtml.Tile(AlertsPossibleValues.label(severity.name()), HomeHtml.number(these.size()), note,
listUrl(new QQueryFilter().withCriteria("severity", QCriteriaOperator.EQUALS, severity.name()).withCriteria("status", QCriteriaOperator.IN, Status.openNames()))));
}
String scope = open.isEmpty() ? "No open alerts you can see." : HomeHtml.plural(open.size(), "open alert") + " you can see.";
if(runtime.getConfig().getSchedulerName() == null)
{
scope += " No scheduler is configured, so monitors and email delivery only run when started by hand.";
}
return (new RawHTML(null, HomeHtml.tiles(tiles) + HomeHtml.note(scope)));
}
/*******************************************************************************
** My alerts: assigned to me, or in my bell (not dismissed); unacknowledged first.
*******************************************************************************/
static QWidgetData mine(Instant now) throws QException
{
QSession session = QContext.getQSession();
String userId = session == null || session.getUser() == null ? null : session.getUser().getIdReference();
if(userId == null)
{
return (new RawHTML(null, HomeHtml.emptyState("Your session has no user, so there are no personal alerts.")));
}
Map<Integer, QRecord> mine = new LinkedHashMap<>();
for(QRecord alert : AlertsDb.query(AlertsAlert.TABLE_NAME, AlertsDb.eq("assignedUserId", userId).withCriteria("status", QCriteriaOperator.IN, Status.openNames())))
{
mine.put(alert.getValueInteger("id"), alert);
}
if(canRead(AlertsNotificationRecipient.TABLE_NAME))
{
List<Integer> ids = AlertsApi.myAlertIds(userId, SCAN_LIMIT);
if(!ids.isEmpty())
{
for(QRecord alert : AlertsDb.query(AlertsAlert.TABLE_NAME, new QQueryFilter().withCriteria("id", QCriteriaOperator.IN, ids).withCriteria("status", QCriteriaOperator.IN, Status.openNames())))
{
mine.putIfAbsent(alert.getValueInteger("id"), alert);
}
}
}
List<QRecord> sorted = new ArrayList<>(mine.values());
sorted.sort(Comparator.comparing((QRecord alert) -> Status.OPEN.name().equals(alert.getValueString("status")) ? 0 : 1).thenComparing(AlertsHome::bySeverityThenAge));
int subscriptions = canRead(AlertsSubscription.TABLE_NAME) ? AlertsDb.count(AlertsSubscription.TABLE_NAME, AlertsDb.eq("userId", userId).withCriteria("enabled", QCriteriaOperator.EQUALS, true)) : 0;
String empty = "Nothing needs you. You have " + HomeHtml.plural(subscriptions, "subscription") + ".";
TableData table = alertTable(sorted.subList(0, Math.min(ROWS, sorted.size())), now, "Status", alert -> statusBadge(alert), empty);
return (table.withLinkText(subscriptions == 0 ? "Manage subscriptions" : "View my alerts").withLinkURL(subscriptions == 0 ? "/app/" + AlertsSubscription.TABLE_NAME
: listUrl(new QQueryFilter().withCriteria("assignedUserId", QCriteriaOperator.EQUALS, userId).withCriteria("status", QCriteriaOperator.IN, Status.openNames()))));
}
/*******************************************************************************
** Needs action: open, unacknowledged, unsnoozed; by severity, then age.
*******************************************************************************/
static QWidgetData needsAction(Instant now) throws QException
{
List<QRecord> open = new ArrayList<>(AlertsDb.query(AlertsAlert.TABLE_NAME, AlertsDb.eq("status", Status.OPEN.name()).withLimit(SCAN_LIMIT)));
open.sort(AlertsHome::bySeverityThenAge);
TableData table = alertTable(open.subList(0, Math.min(ROWS, open.size())), now, "Owner", AlertsHome::owner, "No open alerts need action.");
return (table.withLinkText("View all").withLinkURL(listUrl(AlertsDb.eq("status", Status.OPEN.name()))));
}
/*******************************************************************************
** By group: open count, oldest, and a 7-day trend of opened alerts.
*******************************************************************************/
static QWidgetData byGroup(Instant now) throws QException
{
List<QRecord> open = openAlerts();
Map<Integer, String> labels = labels(AlertsGroup.TABLE_NAME, "label");
Map<Integer, Integer> counts = new LinkedHashMap<>();
Map<Integer, Instant> oldest = new HashMap<>();
for(QRecord alert : open)
{
Integer group = alert.getValueInteger("groupId");
counts.merge(group, 1, Integer::sum);
Instant first = alert.getValueInstant("firstRaisedAt");
if(first != null && (oldest.get(group) == null || first.isBefore(oldest.get(group))))
{
oldest.put(group, first);
}
}
Instant since = now.minus(7, ChronoUnit.DAYS).truncatedTo(ChronoUnit.DAYS);
Map<Integer, int[]> trends = new HashMap<>();
for(QRecord alert : AlertsDb.query(AlertsAlert.TABLE_NAME, new QQueryFilter().withCriteria("firstRaisedAt", QCriteriaOperator.GREATER_THAN_OR_EQUALS, since).withLimit(SCAN_LIMIT)))
{
int day = (int) ChronoUnit.DAYS.between(since, alert.getValueInstant("firstRaisedAt").truncatedTo(ChronoUnit.DAYS));
if(day >= 0 && day < 8)
{
trends.computeIfAbsent(alert.getValueInteger("groupId"), key -> new int[8])[day]++;
}
}
List<Map<String, Object>> rows = new ArrayList<>();
List<Integer> groups = new ArrayList<>(counts.keySet());
groups.sort(Comparator.comparing((Integer group) -> -counts.get(group)));
for(Integer group : groups)
{
Map<String, Object> row = new HashMap<>();
String label = group == null ? "No group" : labels.getOrDefault(group, "Group " + group);
row.put("group", group == null ? HomeHtml.escape(label) : HomeHtml.link(listUrl(AlertsDb.eq("groupId", group).withCriteria("status", QCriteriaOperator.IN, Status.openNames())), label));
row.put("open", HomeHtml.number(counts.get(group)));
row.put("oldest", HomeHtml.escape(AlertMessageRenderer.age(oldest.get(group), now)));
row.put("trend", sparkline(trends.getOrDefault(group, new int[8])));
rows.add(row);
}
return (table(List.of(column("Group", "group"), column("Open", "open"), column("Oldest", "oldest"), column("7 days", "trend")), rows,
"No open alerts in any group."));
}
/*******************************************************************************
** Trend: alerts opened and resolved per day for 30 days, with mean time to
** acknowledge and to resolve.
*******************************************************************************/
static QWidgetData trend(Instant now) throws QException
{
LocalDate today = LocalDate.ofInstant(now, ZoneOffset.UTC);
LocalDate start = today.minusDays(TREND_DAYS - 1L);
Instant since = start.atStartOfDay(ZoneOffset.UTC).toInstant();
Map<LocalDate, int[]> perDay = new LinkedHashMap<>();
for(LocalDate day = start; !day.isAfter(today); day = day.plusDays(1))
{
perDay.put(day, new int[2]);
}
List<QRecord> events = canRead(AlertsEvent.TABLE_NAME) ? AlertsDb.query(AlertsEvent.TABLE_NAME, new QQueryFilter()
.withCriteria("eventType", QCriteriaOperator.IN, List.of(EventType.RAISED.name(), EventType.REOPENED.name(), EventType.RESOLVED.name()))
.withCriteria("at", QCriteriaOperator.GREATER_THAN_OR_EQUALS, since).withLimit(SCAN_LIMIT * 5)) : List.of();
LocalDate first = null;
for(QRecord event : events)
{
LocalDate day = LocalDate.ofInstant(event.getValueInstant("at"), ZoneOffset.UTC);
int[] counts = perDay.get(day);
if(counts != null)
{
counts[EventType.RESOLVED.name().equals(event.getValueString("eventType")) ? 1 : 0]++;
first = first == null || day.isBefore(first) ? day : first;
}
}
List<String> labels = new ArrayList<>();
List<Number> opened = new ArrayList<>();
List<Number> resolved = new ArrayList<>();
for(Map.Entry<LocalDate, int[]> entry : perDay.entrySet())
{
if(first != null && entry.getKey().isBefore(first))
{
continue;
}
labels.add(DAY.format(entry.getKey()));
opened.add(entry.getValue()[0]);
resolved.add(entry.getValue()[1]);
}
ChartData chart = new ChartData().withChartData(new ChartData.Data()
.withLabels(labels)
.withDatasets(List.of(
new ChartData.Data.Dataset().withLabel("Opened").withData(opened).withColor(HomeHtml.BAD_COLOR),
new ChartData.Data.Dataset().withLabel("Resolved").withData(resolved).withColor(HomeHtml.OK_COLOR))));
chart.setSublabel(events.isEmpty() ? "No alerts opened or resolved in the last " + TREND_DAYS + " days." : meanTimes(since));
return (chart);
}
/*******************************************************************************
** Noisy: the types that opened, reopened or flapped most in 7 days.
*******************************************************************************/
static QWidgetData noisy(Instant now) throws QException
{
Instant since = now.minus(7, ChronoUnit.DAYS);
Map<String, int[]> counts = new HashMap<>();
Map<String, Integer> typeIds = new HashMap<>();
if(canRead(AlertsEvent.TABLE_NAME))
{
Map<Integer, QRecord> alerts = new HashMap<>();
for(QRecord event : AlertsDb.query(AlertsEvent.TABLE_NAME, new QQueryFilter()
.withCriteria("eventType", QCriteriaOperator.IN, List.of(EventType.RAISED.name(), EventType.REOPENED.name(), EventType.FLAPPING_STARTED.name()))
.withCriteria("at", QCriteriaOperator.GREATER_THAN_OR_EQUALS, since).withLimit(SCAN_LIMIT * 5)))
{
Integer alertId = event.getValueInteger("alertId");
QRecord alert = alerts.computeIfAbsent(alertId, id -> quietly(id));
if(alert == null)
{
continue;
}
String key = alert.getValueString("alertTypeName");
typeIds.put(key, alert.getValueInteger("alertTypeId"));
int[] c = counts.computeIfAbsent(key, k -> new int[3]);
switch(EventType.valueOf(event.getValueString("eventType")))
{
case RAISED -> c[0]++;
case REOPENED -> c[1]++;
default -> c[2]++;
}
}
}
List<String> keys = new ArrayList<>(counts.keySet());
keys.sort(Comparator.comparing((String key) -> -(counts.get(key)[0] + counts.get(key)[1] + counts.get(key)[2])));
Map<Integer, String> labels = labels(AlertsType.TABLE_NAME, "label");
List<Map<String, Object>> rows = new ArrayList<>();
for(String key : keys.subList(0, Math.min(ROWS, keys.size())))
{
Integer typeId = typeIds.get(key);
Map<String, Object> row = new HashMap<>();
String label = typeId != null && labels.containsKey(typeId) ? labels.get(typeId) : key;
row.put("type", typeId == null ? HomeHtml.escape(label) : HomeHtml.link("/app/" + AlertsType.TABLE_NAME + "/" + typeId, label));
row.put("opened", HomeHtml.number(counts.get(key)[0]));
row.put("reopened", HomeHtml.number(counts.get(key)[1]));
row.put("flapping", HomeHtml.number(counts.get(key)[2]));
rows.add(row);
}
return (table(List.of(column("Alert Type", "type"), column("Opened", "opened"), column("Reopened", "reopened"), column("Flapping", "flapping")), rows,
"Nothing was noisy in the last 7 days."));
}
/*******************************************************************************
** Notifications, link-only (the Notifications table is the owner):
** scheduled, sent this week, drafts.
*******************************************************************************/
static QWidgetData notifications(Instant now) throws QException
{
if(!canRead(AlertsNotification.TABLE_NAME))
{
return (new RawHTML(null, HomeHtml.emptyState("Notifications are shown to notification authors.")));
}
QQueryFilter scheduled = AlertsDb.eq("status", NotificationService.STATUS_SCHEDULED);
QQueryFilter drafts = AlertsDb.eq("status", NotificationService.STATUS_DRAFT);
QQueryFilter sent = AlertsDb.eq("status", NotificationService.STATUS_SENT).withCriteria("category", QCriteriaOperator.NOT_EQUALS, "ALERT")
.withCriteria("sentAt", QCriteriaOperator.GREATER_THAN_OR_EQUALS, now.minus(7, ChronoUnit.DAYS));
String line = HomeHtml.link(listUrl(AlertsNotification.TABLE_NAME, scheduled), HomeHtml.plural(AlertsDb.count(AlertsNotification.TABLE_NAME, scheduled), "scheduled notification"))
+ " &middot; " + HomeHtml.link(listUrl(AlertsNotification.TABLE_NAME, sent), HomeHtml.number(AlertsDb.count(AlertsNotification.TABLE_NAME, sent)) + " sent this week")
+ " &middot; " + HomeHtml.link(listUrl(AlertsNotification.TABLE_NAME, drafts), HomeHtml.plural(AlertsDb.count(AlertsNotification.TABLE_NAME, drafts), "draft"));
return (new RawHTML(null, "<p style=\"margin:0\">" + line + "</p>"));
}
/*******************************************************************************
** Delivery health (alerts admins): unhealthy channels and failed or dead
** deliveries in 24 hours; one line when all is well.
*******************************************************************************/
static QWidgetData delivery(Instant now) throws QException
{
if(!canRead(AlertsChannel.TABLE_NAME) || !canRead(AlertsDelivery.TABLE_NAME))
{
return (new RawHTML(null, HomeHtml.emptyState("Delivery health is shown to alerts admins.")));
}
List<QRecord> channels = AlertsDb.query(AlertsChannel.TABLE_NAME, new QQueryFilter().withOrderBy(new QFilterOrderBy("label")));
Instant since = now.minus(24, ChronoUnit.HOURS);
List<Map<String, Object>> rows = new ArrayList<>();
for(QRecord channel : channels)
{
int failed = AlertsDb.count(AlertsDelivery.TABLE_NAME, AlertsDb.eq("channelId", channel.getValue("id"))
.withCriteria("status", QCriteriaOperator.IN, List.of(DeliveryStatus.FAILED.name(), DeliveryStatus.DEAD.name()))
.withCriteria("createDate", QCriteriaOperator.GREATER_THAN_OR_EQUALS, since));
String health = channel.getValueString("healthStatus");
if(failed == 0 && (health == null || HealthStatus.HEALTHY.name().equals(health)))
{
continue;
}
Map<String, Object> row = new HashMap<>();
row.put("channel", HomeHtml.link("/app/" + AlertsChannel.TABLE_NAME + "/" + channel.getValue("id"), channel.getValueString("label")));
row.put("health", HomeHtml.badge(AlertsPossibleValues.label(health == null ? "HEALTHY" : health), HealthStatus.UNHEALTHY.name().equals(health) ? HomeHtml.BAD_COLOR : HomeHtml.WARN_COLOR));
row.put("failed", HomeHtml.link(listUrl(AlertsDelivery.TABLE_NAME, AlertsDb.eq("channelId", channel.getValue("id"))
.withCriteria("status", QCriteriaOperator.IN, List.of(DeliveryStatus.FAILED.name(), DeliveryStatus.DEAD.name()))), HomeHtml.number(failed)));
row.put("error", HomeHtml.escape(StringUtils.hasContent(channel.getValueString("lastError")) ? StringUtils.safeTruncate(channel.getValueString("lastError"), 120, "…") : ""));
rows.add(row);
}
if(rows.isEmpty())
{
return (new RawHTML(null, HomeHtml.emptyState(channels.isEmpty() ? "No channels yet." : "All " + HomeHtml.plural(channels.size(), "channel") + " delivered normally in the last 24 hours.")));
}
return (table(List.of(column("Channel", "channel"), column("Health", "health"), column("Failed, 24 h", "failed"), column("Last Error", "error")), rows, ""));
}
/*******************************************************************************
** Recently resolved: the newest 5, how and by whom, and how long they ran.
*******************************************************************************/
static QWidgetData resolved(Instant now) throws QException
{
List<QRecord> recent = AlertsDb.query(AlertsAlert.TABLE_NAME, AlertsDb.eq("status", Status.RESOLVED.name()).withOrderBy(new QFilterOrderBy("resolvedAt", false)).withLimit(5));
List<Map<String, Object>> rows = new ArrayList<>();
for(QRecord alert : recent)
{
Map<String, Object> row = new HashMap<>();
row.put("alert", alertCell(alert));
String how = AlertsPossibleValues.label(alert.getValueString("resolution"));
String who = alert.getValueString("resolvedByUserId");
row.put("resolved", HomeHtml.escape((how == null ? "" : how) + (who == null ? "" : " by " + who) + ", " + AlertMessageRenderer.age(alert.getValueInstant("resolvedAt"), now) + " ago"));
row.put("duration", HomeHtml.escape(duration(alert.getValueInstant("firstRaisedAt"), alert.getValueInstant("resolvedAt"))));
rows.add(row);
}
TableData table = table(List.of(column("Alert", "alert"), column("Resolved", "resolved"), column("Duration", "duration")), rows, "No alerts have been resolved yet.");
return (table.withLinkText("View all").withLinkURL(listUrl(AlertsDb.eq("status", Status.RESOLVED.name()))));
}
/*******************************************************************************
** Mean time to acknowledge and to resolve, for alerts opened since.
*******************************************************************************/
private static String meanTimes(Instant since) throws QException
{
long ackTotal = 0;
long ackCount = 0;
long resTotal = 0;
long resCount = 0;
for(QRecord alert : AlertsDb.query(AlertsAlert.TABLE_NAME, new QQueryFilter().withCriteria("firstRaisedAt", QCriteriaOperator.GREATER_THAN_OR_EQUALS, since).withLimit(SCAN_LIMIT)))
{
Instant first = alert.getValueInstant("firstRaisedAt");
if(first == null)
{
continue;
}
if(alert.getValueInstant("acknowledgedAt") != null)
{
ackTotal += Duration.between(first, alert.getValueInstant("acknowledgedAt")).toMinutes();
ackCount++;
}
if(alert.getValueInstant("resolvedAt") != null)
{
resTotal += Duration.between(first, alert.getValueInstant("resolvedAt")).toMinutes();
resCount++;
}
}
String mtta = ackCount == 0 ? "none acknowledged" : minutes(ackTotal / ackCount);
String mttr = resCount == 0 ? "none resolved" : minutes(resTotal / resCount);
return ("Opened and resolved per day. Mean time to acknowledge: " + mtta + ". Mean time to resolve: " + mttr + ".");
}
/*******************************************************************************
** Open alerts the viewer can see.
*******************************************************************************/
static List<QRecord> openAlerts() throws QException
{
return (AlertsDb.query(AlertsAlert.TABLE_NAME, new QQueryFilter(new QFilterCriteria("status", QCriteriaOperator.IN, Status.openNames())).withLimit(SCAN_LIMIT)));
}
/*******************************************************************************
** A four-column alert table: Alert, Severity, Age, and one more.
*******************************************************************************/
private static TableData alertTable(List<QRecord> alerts, Instant now, String lastHeader, java.util.function.Function<QRecord, String> last, String empty)
{
List<Map<String, Object>> rows = new ArrayList<>();
for(QRecord alert : alerts)
{
Map<String, Object> row = new HashMap<>();
row.put("alert", alertCell(alert));
row.put("severity", severityBadge(alert.getValueString("severity")));
row.put("age", HomeHtml.escape(AlertMessageRenderer.age(alert.getValueInstant("firstRaisedAt"), now)));
row.put("last", last.apply(alert));
rows.add(row);
}
return (table(List.of(column("Alert", "alert"), column("Severity", "severity"), column("Age", "age"), column(lastHeader, "last")), rows, empty));
}
/*******************************************************************************
** The alert's title, linked, with its type as a muted fact.
*******************************************************************************/
static String alertCell(QRecord alert)
{
return (HomeHtml.card(HomeHtml.link("/app/" + AlertsAlert.TABLE_NAME + "/" + alert.getValue("id"), alert.getValueString("title")),
alert.getValue("itemCount") == null ? null : HomeHtml.escape(HomeHtml.plural(alert.getValueInteger("itemCount"), "record"))));
}
/*******************************************************************************
** A severity pill.
*******************************************************************************/
public static String severityBadge(String severity)
{
String color = switch(severity == null ? "" : severity)
{
case "CRITICAL", "ERROR" -> HomeHtml.BAD_COLOR;
case "WARNING" -> HomeHtml.WARN_COLOR;
default -> HomeHtml.INFO_COLOR;
};
return (HomeHtml.badge(severity == null ? "" : AlertsPossibleValues.label(severity), color));
}
/*******************************************************************************
** A status pill.
*******************************************************************************/
private static String statusBadge(QRecord alert)
{
String status = alert.getValueString("status");
return (HomeHtml.badge(AlertsPossibleValues.label(status), Status.OPEN.name().equals(status) ? HomeHtml.BAD_COLOR : HomeHtml.OFF_COLOR));
}
/*******************************************************************************
** The assignee, team, or "Unassigned".
*******************************************************************************/
private static String owner(QRecord alert)
{
if(alert.getValueString("assignedUserId") != null)
{
return (HomeHtml.escape(alert.getValueString("assignedUserId")));
}
if(alert.getValue("assignedTeamId") != null)
{
return (HomeHtml.escape("Team " + alert.getValue("assignedTeamId")));
}
return (HomeHtml.muted("Unassigned"));
}
/*******************************************************************************
** Most severe first, then oldest first.
*******************************************************************************/
static int bySeverityThenAge(QRecord a, QRecord b)
{
int severity = AlertSeverity.fromLabel(b.getValueString("severity"), AlertSeverity.INFO).compareTo(AlertSeverity.fromLabel(a.getValueString("severity"), AlertSeverity.INFO));
if(severity != 0)
{
return (severity);
}
Instant aFirst = a.getValueInstant("firstRaisedAt");
Instant bFirst = b.getValueInstant("firstRaisedAt");
if(aFirst == null || bFirst == null)
{
return (0);
}
return (aFirst.compareTo(bFirst));
}
/*******************************************************************************
** A 7-day block sparkline.
*******************************************************************************/
static String sparkline(int[] counts)
{
String blocks = "▁▂▃▄▅▆▇█";
int max = 0;
for(int count : counts)
{
max = Math.max(max, count);
}
StringBuilder line = new StringBuilder();
for(int count : counts)
{
line.append(max == 0 ? blocks.charAt(0) : blocks.charAt(Math.min(7, (int) Math.round(7.0 * count / max))));
}
return ("<span aria-label=\"opened per day\" style=\"font-family:monospace;letter-spacing:1px\">" + line + "</span>");
}
/*******************************************************************************
** Labels by id for a small table.
*******************************************************************************/
private static Map<Integer, String> labels(String tableName, String field) throws QException
{
Map<Integer, String> labels = new HashMap<>();
if(canRead(tableName))
{
for(QRecord row : AlertsDb.query(tableName, new QQueryFilter().withLimit(SCAN_LIMIT)))
{
labels.put(row.getValueInteger("id"), row.getValueString(field));
}
}
return (labels);
}
/*******************************************************************************
** An alert by id in the viewer's session (null when not visible).
*******************************************************************************/
private static QRecord quietly(Integer id)
{
try
{
return (AlertsDb.byId(AlertsAlert.TABLE_NAME, id));
}
catch(QException e)
{
return (null);
}
}
/*******************************************************************************
** Whether the viewer may read a table.
*******************************************************************************/
static boolean canRead(String tableName)
{
return (PermissionsHelper.hasTablePermission(new AbstractActionInput(), tableName, TablePermissionSubType.READ));
}
/*******************************************************************************
** The Alerts list filtered.
*******************************************************************************/
public static String listUrl(QQueryFilter filter)
{
return (listUrl(AlertsAlert.TABLE_NAME, filter));
}
/*******************************************************************************
** A table's list, filtered.
*******************************************************************************/
static String listUrl(String tableName, QQueryFilter filter)
{
return ("/app/" + tableName + "?filter=" + URLEncoder.encode(JsonUtils.toJson(filter), StandardCharsets.UTF_8));
}
/*******************************************************************************
** "2 h 5 min", "3 d".
*******************************************************************************/
static String duration(Instant from, Instant to)
{
if(from == null || to == null)
{
return ("");
}
return (minutes(Duration.between(from, to).toMinutes()));
}
/*******************************************************************************
**
*******************************************************************************/
private static String minutes(long minutes)
{
if(minutes < 60)
{
return (minutes + " min");
}
if(minutes < 48 * 60)
{
return ((minutes / 60) + " h" + (minutes % 60 == 0 ? "" : " " + (minutes % 60) + " min"));
}
return ((minutes / 1440) + " d");
}
/*******************************************************************************
** A table column of HTML cells.
*******************************************************************************/
private static TableData.Column column(String header, String accessor)
{
return (new TableData.Column("html", header, accessor, null, "left").withVerticalAlign("top"));
}
/*******************************************************************************
** A table without pagination controls, with an honest empty state.
*******************************************************************************/
private static TableData table(List<TableData.Column> columns, List<Map<String, Object>> rows, String empty)
{
return (new TableData(null, columns, rows)
.withRowsPerPage(Math.max(ROWS, rows.size()))
.withHidePaginationDropdown(true)
.withNoRowsFoundHTML(HomeHtml.emptyState(empty)));
}
/*******************************************************************************
** Every widget kind.
*******************************************************************************/
static Set<String> kinds()
{
return (Set.of(KIND_SEVERITY, KIND_MINE, KIND_ACTION, KIND_BY_GROUP, KIND_TREND, KIND_NOISY, KIND_DELIVERY, KIND_RESOLVED));
}
}
@@ -0,0 +1,65 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.home;
import java.io.Serializable;
import java.util.Map;
import com.kingsrook.qbits.alerts.AlertsPreferences;
import com.kingsrook.qbits.alerts.AlertsRuntime;
import com.kingsrook.qbits.alerts.AlertsSecurity;
import com.kingsrook.qqq.backend.core.actions.dashboard.widgets.AbstractWidgetRenderer;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.widgets.RenderWidgetInput;
import com.kingsrook.qqq.backend.core.model.actions.widgets.RenderWidgetOutput;
import com.kingsrook.qqq.backend.core.model.metadata.dashboard.QWidgetMetaData;
/*******************************************************************************
** Renders the Alerts home widgets. Which one is in the widget's "kind"
** default value. Data is read in the viewer's session (with the alerts
** record-security keys applied), so permissions and locks decide what shows.
** The first visit also sets up the viewer's settings (and, for admins, the
** bootstrap subscription).
*******************************************************************************/
public class AlertsHomeWidgetRenderer extends AbstractWidgetRenderer
{
public static final String KIND = "kind";
/*******************************************************************************
**
*******************************************************************************/
@Override
public RenderWidgetOutput render(RenderWidgetInput input) throws QException
{
AlertsRuntime runtime = AlertsRuntime.get();
AlertsSecurity.ensureSessionKeys(runtime.getQInstance(), QContext.getQSession());
AlertsPreferences.ensure(runtime, QContext.getQSession());
runtime.getTypeSync().syncIfNeeded();
String kind = null;
if(input.getWidgetMetaData() instanceof QWidgetMetaData widget)
{
Map<String, Serializable> defaults = widget.getDefaultValues();
kind = defaults == null || defaults.get(KIND) == null ? null : String.valueOf(defaults.get(KIND));
}
return (new RenderWidgetOutput(AlertsHome.load(kind, runtime)));
}
}
@@ -0,0 +1,298 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.home;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/*******************************************************************************
** Small, theme-neutral HTML pieces for the home widgets: inline styles only
** (no host CSS), colors that read in light and dark themes, text that wraps
** at any width (no inner horizontal scroll), and every value escaped.
*******************************************************************************/
public final class HomeHtml
{
public static final String OK_COLOR = "#16a34a";
public static final String BAD_COLOR = "#dc2626";
public static final String WARN_COLOR = "#d97706";
public static final String INFO_COLOR = "#2563eb";
public static final String OFF_COLOR = "#6b7280";
private static final String MUTED = "opacity:.75";
private static final String WRAP = "overflow-wrap:anywhere;min-width:0";
private static final String TILE = "flex:1 1 170px;min-width:0;border:1px solid rgba(127,127,127,.25);border-radius:10px;padding:12px 14px";
private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("h:mm a", Locale.US);
private static final DateTimeFormatter DATE_TIME = DateTimeFormatter.ofPattern("MMM d, h:mm a", Locale.US);
private static final DateTimeFormatter FULL = DateTimeFormatter.ofPattern("MMM d, yyyy, h:mm a", Locale.US);
/*******************************************************************************
** One summary tile: a label, a value (linked when href is set) and an
** optional note.
*******************************************************************************/
public record Tile(String label, String value, String note, String href)
{
}
/*******************************************************************************
** Utility class - no instances.
*******************************************************************************/
private HomeHtml()
{
}
/*******************************************************************************
** HTML-escape a value (null is empty).
*******************************************************************************/
public static String escape(Object value)
{
if(value == null)
{
return ("");
}
String text = String.valueOf(value);
StringBuilder escaped = new StringBuilder(text.length() + 16);
for(char c : text.toCharArray())
{
switch(c)
{
case '<' -> escaped.append("&lt;");
case '>' -> escaped.append("&gt;");
case '&' -> escaped.append("&amp;");
case '"' -> escaped.append("&quot;");
case '\'' -> escaped.append("&#39;");
default -> escaped.append(c);
}
}
return (escaped.toString());
}
/*******************************************************************************
** A link in the text color, underlined.
*******************************************************************************/
public static String link(String href, Object text)
{
return ("<a href=\"" + escape(href) + "\" style=\"color:inherit;text-decoration:underline;text-underline-offset:2px\">" + escape(text) + "</a>");
}
/*******************************************************************************
** Muted (secondary) text.
*******************************************************************************/
public static String muted(Object text)
{
return ("<span style=\"" + MUTED + ";font-size:13px\">" + escape(text) + "</span>");
}
/*******************************************************************************
** A pill with a colored border and text.
*******************************************************************************/
public static String badge(String text, String color)
{
return ("<span style=\"display:inline-block;white-space:nowrap;padding:1px 8px;border-radius:999px;font-size:12px;font-weight:600;line-height:1.5;"
+ "color:" + color + ";border:1px solid " + color + "\">" + escape(text) + "</span>");
}
/*******************************************************************************
** A primary line (already HTML) with muted facts (already HTML) after it,
** wrapping onto more lines on narrow screens.
*******************************************************************************/
public static String card(String primaryHtml, String... factsHtml)
{
List<String> facts = new ArrayList<>();
for(String fact : factsHtml)
{
if(fact != null && !fact.isBlank())
{
facts.add(fact);
}
}
StringBuilder html = new StringBuilder("<span style=\"display:flex;flex-wrap:wrap;align-items:baseline;column-gap:10px;row-gap:2px;min-width:0\">");
html.append("<span style=\"").append(WRAP).append("\">").append(primaryHtml == null ? "" : primaryHtml).append("</span>");
if(!facts.isEmpty())
{
html.append("<span style=\"").append(WRAP).append(';').append(MUTED).append(";font-size:13px\">").append(String.join(" &middot; ", facts)).append("</span>");
}
return (html.append("</span>").toString());
}
/*******************************************************************************
** SQL (or any long text) as monospace, on one line, cut at maxChars and
** wrapped anywhere; the full text is in the title tooltip.
*******************************************************************************/
public static String code(String text, int maxChars)
{
String oneLine = text == null ? "" : text.replaceAll("\\s+", " ").trim();
String shown = oneLine.length() > maxChars ? oneLine.substring(0, maxChars - 1) + "…" : oneLine;
return ("<code title=\"" + escape(oneLine.length() > 2000 ? oneLine.substring(0, 2000) : oneLine) + "\" style=\"font-size:12px;" + WRAP + "\">" + escape(shown) + "</code>");
}
/*******************************************************************************
** Wrapping summary tiles: they grow to fill each row, so there are no holes.
*******************************************************************************/
public static String tiles(List<Tile> tiles)
{
StringBuilder html = new StringBuilder("<div style=\"display:flex;flex-wrap:wrap;gap:12px\">");
for(Tile tile : tiles)
{
html.append("<div style=\"").append(TILE).append("\">");
html.append("<div style=\"font-size:12px;").append(MUTED).append(";text-transform:uppercase;letter-spacing:.04em;").append(WRAP).append("\">")
.append(escape(tile.label())).append("</div>");
String value = tile.href() == null ? escape(tile.value())
: "<a href=\"" + escape(tile.href()) + "\" style=\"color:inherit;text-decoration:none\">" + escape(tile.value()) + "</a>";
html.append("<div style=\"font-size:26px;font-weight:700;line-height:1.3;").append(WRAP).append("\">").append(value).append("</div>");
if(tile.note() != null)
{
html.append("<div style=\"").append(MUTED).append(";font-size:13px;").append(WRAP).append("\">").append(escape(tile.note())).append("</div>");
}
html.append("</div>");
}
return (html.append("</div>").toString());
}
/*******************************************************************************
** Link buttons, wrapping.
*******************************************************************************/
public static String actions(List<String[]> labelsAndHrefs)
{
StringBuilder html = new StringBuilder("<div style=\"display:flex;flex-wrap:wrap;gap:8px;margin-top:12px\">");
for(String[] action : labelsAndHrefs)
{
html.append("<a href=\"").append(escape(action[1]))
.append("\" style=\"display:inline-flex;align-items:center;padding:8px 12px;border-radius:8px;border:1px solid rgba(127,127,127,.3);")
.append("background:rgba(127,127,127,.08);color:inherit;text-decoration:none;font-size:13px;font-weight:500\">")
.append(escape(action[0])).append("</a>");
}
return (html.append("</div>").toString());
}
/*******************************************************************************
** An honest empty or unavailable state.
*******************************************************************************/
public static String emptyState(String message)
{
return ("<div style=\"padding:18px 4px;" + MUTED + ";font-size:14px;" + WRAP + "\">" + escape(message) + "</div>");
}
/*******************************************************************************
** A muted explanatory note under a widget's content.
*******************************************************************************/
public static String note(String text)
{
return ("<div style=\"margin-top:10px;" + MUTED + ";font-size:13px;" + WRAP + "\">" + escape(text) + "</div>");
}
/*******************************************************************************
** A whole number with thousands separators.
*******************************************************************************/
public static String number(long value)
{
return (String.format(Locale.US, "%,d", value));
}
/*******************************************************************************
** "1 run", "2 runs".
*******************************************************************************/
public static String plural(long count, String noun)
{
return (number(count) + " " + noun + (count == 1 ? "" : "s"));
}
/*******************************************************************************
** A duration in milliseconds: "850 ms", "4.2 s", "3m 05s".
*******************************************************************************/
public static String duration(Integer millis)
{
if(millis == null)
{
return ("");
}
if(millis < 1000)
{
return (millis + " ms");
}
if(millis < 60_000)
{
return (String.format(Locale.US, "%.1f s", millis / 1000.0));
}
long seconds = millis / 1000;
return (String.format(Locale.US, "%dm %02ds", seconds / 60, seconds % 60));
}
/*******************************************************************************
** An instant, compact: the time today, the date and time this year, the
** full date otherwise.
*******************************************************************************/
public static String when(Instant instant, Instant now, ZoneId zoneId)
{
if(instant == null)
{
return ("");
}
ZonedDateTime when = instant.atZone(zoneId);
ZonedDateTime today = now.atZone(zoneId);
if(when.toLocalDate().equals(today.toLocalDate()))
{
return (TIME.format(when));
}
if(when.getYear() == today.getYear())
{
return (DATE_TIME.format(when));
}
return (FULL.format(when));
}
}
@@ -0,0 +1,100 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.metadata;
import java.util.ArrayList;
import java.util.List;
import com.kingsrook.qbits.alerts.AlertsPermissionChecker;
import com.kingsrook.qbits.alerts.AlertsQBitConfig;
import com.kingsrook.qbits.alerts.model.AlertsAlert;
import com.kingsrook.qbits.alerts.model.AlertsChannel;
import com.kingsrook.qbits.alerts.model.AlertsDelivery;
import com.kingsrook.qbits.alerts.model.AlertsGroup;
import com.kingsrook.qbits.alerts.model.AlertsMonitor;
import com.kingsrook.qbits.alerts.model.AlertsMute;
import com.kingsrook.qbits.alerts.model.AlertsNotification;
import com.kingsrook.qbits.alerts.model.AlertsNotificationPreference;
import com.kingsrook.qbits.alerts.model.AlertsSubscription;
import com.kingsrook.qbits.alerts.model.AlertsTeam;
import com.kingsrook.qbits.alerts.model.AlertsType;
import com.kingsrook.qbits.alerts.model.AlertsUserPreference;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.metadata.MetaDataProducerMultiOutput;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.layout.QAppMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.layout.QIcon;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitComponentMetaDataProducer;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitProductionContext;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
/*******************************************************************************
** The top-level Alerts app (design section 6.1). Its home is the Alerts
** dashboard; its nav lists the main tables in the design's order. The
** timeline, alert records, team members and notification recipients are not in the nav:
** they are child lists and relations on their parents, and stay standard
** tables reachable by URL and the API. Tables a user can't read are hidden
** by permission. No processes in the nav.
*******************************************************************************/
public class AlertsAppMetaDataProducer extends QBitComponentMetaDataProducer<QAppMetaData, AlertsQBitConfig>
{
/** the main tables, in nav order. */
public static final List<String> MAIN_TABLES = List.of(AlertsAlert.TABLE_NAME, AlertsNotification.TABLE_NAME, AlertsMonitor.TABLE_NAME, AlertsType.TABLE_NAME, AlertsGroup.TABLE_NAME,
AlertsSubscription.TABLE_NAME, AlertsUserPreference.TABLE_NAME, AlertsNotificationPreference.TABLE_NAME, AlertsTeam.TABLE_NAME, AlertsChannel.TABLE_NAME, AlertsMute.TABLE_NAME, AlertsDelivery.TABLE_NAME);
/*******************************************************************************
**
*******************************************************************************/
@Override
public QAppMetaData produce(QInstance qInstance) throws QException
{
QAppMetaData app = new QAppMetaData()
.withName(AlertsQBitConfig.APP_NAME)
.withLabel("Alerts")
.withIcon(new QIcon("notifications_active"))
.withPermissionRules(AlertsPermissionChecker.rules(AlertsQBitConfig.PERMISSION_VIEW))
.withWidgets(new ArrayList<>(AlertsHomeWidgetsMetaDataProducer.homeWidgetNames()));
MetaDataProducerMultiOutput produced = QBitProductionContext.peekMetaDataProducerMultiOutput();
if(produced != null)
{
for(String tableName : MAIN_TABLES)
{
QTableMetaData table = produced.get(QTableMetaData.class, tableName);
if(table != null)
{
app.withChild(table);
}
}
}
return (app);
}
/*******************************************************************************
** last, so the tables and widgets exist in the output
*******************************************************************************/
@Override
public int getSortOrder()
{
return (900);
}
}
@@ -0,0 +1,114 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.metadata;
import java.util.List;
import com.kingsrook.qbits.alerts.AlertsPermissionChecker;
import com.kingsrook.qbits.alerts.AlertsQBitConfig;
import com.kingsrook.qbits.alerts.home.AlertsHome;
import com.kingsrook.qbits.alerts.home.AlertsHomeWidgetRenderer;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.WidgetType;
import com.kingsrook.qqq.backend.core.model.metadata.MetaDataProducerMultiOutput;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.dashboard.QWidgetMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitComponentMetaDataProducer;
/*******************************************************************************
** The Alerts home dashboard (design section 6.2), in page order, all full
** width: open by severity, my alerts, needs action, by group, trend, noisy
** types, delivery health (admins) and recently resolved.
*******************************************************************************/
public class AlertsHomeWidgetsMetaDataProducer extends QBitComponentMetaDataProducer<MetaDataProducerMultiOutput, AlertsQBitConfig>
{
public static final String SEVERITY = "alertsHomeOpenBySeverity";
public static final String MINE = "alertsHomeMyAlerts";
public static final String ACTION = "alertsHomeNeedsAction";
public static final String BY_GROUP = "alertsHomeByGroup";
public static final String TREND = "alertsHomeTrend";
public static final String NOISY = "alertsHomeNoisy";
public static final String DELIVERY = "alertsHomeDeliveryHealth";
public static final String RESOLVED = "alertsHomeRecentlyResolved";
public static final String NOTICES = "alertsHomeNotifications";
/*******************************************************************************
** The home widget names, in page order.
*******************************************************************************/
public static List<String> homeWidgetNames()
{
return (List.of(SEVERITY, MINE, ACTION, BY_GROUP, TREND, NOISY, DELIVERY, NOTICES, RESOLVED));
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public MetaDataProducerMultiOutput produce(QInstance qInstance) throws QException
{
String html = WidgetType.HTML.getType();
String table = WidgetType.TABLE.getType();
MetaDataProducerMultiOutput output = new MetaDataProducerMultiOutput();
output.add(widget(SEVERITY, "Open Alerts", html, AlertsHome.KIND_SEVERITY, AlertsQBitConfig.PERMISSION_VIEW));
output.add(widget(MINE, "My Alerts", table, AlertsHome.KIND_MINE, AlertsQBitConfig.PERMISSION_VIEW));
output.add(widget(ACTION, "Needs Action", table, AlertsHome.KIND_ACTION, AlertsQBitConfig.PERMISSION_VIEW));
output.add(widget(BY_GROUP, "By Group", table, AlertsHome.KIND_BY_GROUP, AlertsQBitConfig.PERMISSION_VIEW));
output.add(widget(TREND, "Opened and Resolved, 30 Days", WidgetType.LINE_CHART.getType(), AlertsHome.KIND_TREND, AlertsQBitConfig.PERMISSION_VIEW));
output.add(widget(NOISY, "Noisiest Alert Types, 7 Days", table, AlertsHome.KIND_NOISY, AlertsQBitConfig.PERMISSION_VIEW));
output.add(widget(DELIVERY, "Delivery Health", html, AlertsHome.KIND_DELIVERY, AlertsQBitConfig.PERMISSION_ADMIN));
output.add(widget(NOTICES, "Notifications", html, AlertsHome.KIND_NOTIFICATIONS, AlertsQBitConfig.PERMISSION_NOTIFICATION_ADMIN));
output.add(widget(RESOLVED, "Recently Resolved", table, AlertsHome.KIND_RESOLVED, AlertsQBitConfig.PERMISSION_VIEW));
return (output);
}
/*******************************************************************************
** One full-width card widget.
*******************************************************************************/
private static QWidgetMetaData widget(String name, String label, String type, String kind, String permission)
{
return (new QWidgetMetaData()
.withName(name)
.withLabel(label)
.withType(type)
.withGridColumns(12)
.withIsCard(true)
.withShowReloadButton(true)
.withCodeReference(new QCodeReference(AlertsHomeWidgetRenderer.class))
.withDefaultValue(AlertsHomeWidgetRenderer.KIND, kind)
.withPermissionRules(AlertsPermissionChecker.rules(permission)));
}
/*******************************************************************************
** after the tables and processes, before the app
*******************************************************************************/
@Override
public int getSortOrder()
{
return (300);
}
}
@@ -0,0 +1,163 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.metadata;
import java.util.ArrayList;
import java.util.List;
import com.kingsrook.qbits.alerts.AlertsPermissionChecker;
import com.kingsrook.qbits.alerts.AlertsQBitConfig;
import com.kingsrook.qbits.alerts.processes.AlertsAction;
import com.kingsrook.qbits.alerts.processes.AlertsActionSteps;
import com.kingsrook.qbits.alerts.processes.AlertsScheduledSteps;
import com.kingsrook.qqq.backend.core.actions.processes.BackendStep;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.metadata.MetaDataProducerMultiOutput;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.layout.QIcon;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QBackendStepMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QComponentType;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QFrontendComponentMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QFrontendStepMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitComponentMetaDataProducer;
import com.kingsrook.qqq.backend.core.model.metadata.scheduleing.QScheduleMetaData;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.ExtractViaQueryStep;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.StreamedETLWithFrontendProcess;
/*******************************************************************************
** The Alerts processes. None is in any app's nav:
** - the record and table actions (AlertsAction), each a standard streamed
** ETL process on its table: optional input, Review summary lines, Result
** summary lines;
** - two hidden scheduled processes: alertsEvaluateMonitors (monitors, plus
** snooze / quiet-period / flapping upkeep) and alertsDeliverNotifications.
** They exist without a scheduler and run on one only when the config names
** it.
*******************************************************************************/
public class AlertsProcessesMetaDataProducer extends QBitComponentMetaDataProducer<MetaDataProducerMultiOutput, AlertsQBitConfig>
{
public static final String EVALUATE_MONITORS = "alertsEvaluateMonitors";
public static final String DELIVER_NOTIFICATIONS = "alertsDeliverNotifications";
/*******************************************************************************
**
*******************************************************************************/
@Override
public MetaDataProducerMultiOutput produce(QInstance qInstance) throws QException
{
AlertsQBitConfig config = getQBitConfig();
MetaDataProducerMultiOutput output = new MetaDataProducerMultiOutput();
for(QProcessMetaData process : buildProcesses(config))
{
output.add(process);
}
return (output);
}
/*******************************************************************************
** Every process.
*******************************************************************************/
public static List<QProcessMetaData> buildProcesses(AlertsQBitConfig config)
{
List<QProcessMetaData> processes = new ArrayList<>();
for(AlertsAction action : AlertsAction.values())
{
processes.add(action(action));
}
processes.add(scheduled(config, EVALUATE_MONITORS, "Evaluate alert monitors", AlertsScheduledSteps.EvaluateMonitors.class, config.getEvaluateEverySeconds()));
processes.add(scheduled(config, DELIVER_NOTIFICATIONS, "Deliver alert notifications", AlertsScheduledSteps.DeliverNotifications.class, config.getDeliverEverySeconds()));
return (processes);
}
/*******************************************************************************
** One record / table action.
*******************************************************************************/
static QProcessMetaData action(AlertsAction action)
{
QProcessMetaData process = StreamedETLWithFrontendProcess.processMetaDataBuilder()
.withName(action.getProcessName())
.withLabel(action.getLabel())
.withIcon(new QIcon(action.getIcon()))
.withTableName(action.getTableName())
.withSourceTable(action.getTableName())
.withDestinationTable(action.getTableName())
.withExtractStepClass(ExtractViaQueryStep.class)
.withTransformStepClass(AlertsActionSteps.Transform.class)
.withLoadStepClass(AlertsActionSteps.Load.class)
.withSupportsFullValidation(true)
.withDoFullValidation(true)
.withMinInputRecords(1)
.withMaxInputRecords(action.getMaxRecords())
.withPreviewMessage("This is what " + action.getLabel().toLowerCase() + " will do.")
.getProcessMetaData();
process.setPermissionRules(AlertsPermissionChecker.rules(action.getPermissionName()));
if(!action.inputFields().isEmpty())
{
process.withStep(0, new QFrontendStepMetaData()
.withName("input")
.withLabel(action.getLabel())
.withComponent(new QFrontendComponentMetaData().withType(QComponentType.EDIT_FORM))
.withFormFields(action.inputFields()));
}
return (process);
}
/*******************************************************************************
** A hidden process with one backend step and, with a scheduler, a repeat.
*******************************************************************************/
private static QProcessMetaData scheduled(AlertsQBitConfig config, String name, String label, Class<? extends BackendStep> step, Integer repeatSeconds)
{
QProcessMetaData process = new QProcessMetaData()
.withName(name)
.withLabel(label)
.withIsHidden(true)
.withIcon(new QIcon("schedule"))
.withPermissionRules(AlertsPermissionChecker.rules(AlertsQBitConfig.PERMISSION_ADMIN))
.withStep(new QBackendStepMetaData().withName("run").withCode(new QCodeReference(step)));
if(config.getSchedulerName() != null)
{
process.withSchedule(new QScheduleMetaData()
.withSchedulerName(config.getSchedulerName())
.withRepeatSeconds(repeatSeconds)
.withInitialDelaySeconds(repeatSeconds));
}
return (process);
}
/*******************************************************************************
** after the tables
*******************************************************************************/
@Override
public int getSortOrder()
{
return (200);
}
}
@@ -0,0 +1,693 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.metadata;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.kingsrook.qbits.alerts.AlertsQBitConfig;
import com.kingsrook.qbits.alerts.AlertsSecurity;
import com.kingsrook.qbits.alerts.customizers.AlertsNotificationCustomizer;
import com.kingsrook.qbits.alerts.customizers.AlertsSubscriptionCustomizer;
import com.kingsrook.qbits.alerts.customizers.AlertsWriteGuardCustomizer;
import com.kingsrook.qbits.alerts.model.AlertsAlert;
import com.kingsrook.qbits.alerts.model.AlertsChannel;
import com.kingsrook.qbits.alerts.model.AlertsDelivery;
import com.kingsrook.qbits.alerts.model.AlertsEvent;
import com.kingsrook.qbits.alerts.model.AlertsGroup;
import com.kingsrook.qbits.alerts.model.AlertsHeartbeat;
import com.kingsrook.qbits.alerts.model.AlertsMonitor;
import com.kingsrook.qbits.alerts.model.AlertsMute;
import com.kingsrook.qbits.alerts.model.AlertsNotification;
import com.kingsrook.qbits.alerts.model.AlertsNotificationPreference;
import com.kingsrook.qbits.alerts.model.AlertsNotificationRecipient;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues;
import com.kingsrook.qbits.alerts.model.AlertsRecordRef;
import com.kingsrook.qbits.alerts.model.AlertsSubscription;
import com.kingsrook.qbits.alerts.model.AlertsTeam;
import com.kingsrook.qbits.alerts.model.AlertsTeamMember;
import com.kingsrook.qbits.alerts.model.AlertsType;
import com.kingsrook.qbits.alerts.model.AlertsUserPreference;
import com.kingsrook.qbits.alerts.notifications.NotificationService;
import com.kingsrook.qbits.alerts.spi.NotificationAudience;
import com.kingsrook.qbits.alerts.spi.NotificationCategory;
import com.kingsrook.qbits.alerts.spi.NotificationSeverity;
import com.kingsrook.qqq.backend.core.actions.customizers.TableCustomizers;
import com.kingsrook.qqq.backend.core.actions.dashboard.widgets.ChildRecordListRenderer;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.instances.QInstanceEnricher;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterOrderBy;
import com.kingsrook.qqq.backend.core.model.data.QRecordEntity;
import com.kingsrook.qqq.backend.core.model.metadata.audits.AuditLevel;
import com.kingsrook.qqq.backend.core.model.metadata.audits.QAuditRules;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.dashboard.QWidgetMetaDataInterface;
import com.kingsrook.qqq.backend.core.model.metadata.fields.AdornmentType;
import com.kingsrook.qqq.backend.core.model.metadata.fields.FieldAdornment;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
import com.kingsrook.qqq.backend.core.model.metadata.joins.JoinOn;
import com.kingsrook.qqq.backend.core.model.metadata.joins.JoinType;
import com.kingsrook.qqq.backend.core.model.metadata.joins.QJoinMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.layout.QIcon;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.PermissionLevel;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.QPermissionRules;
import com.kingsrook.qqq.backend.core.model.metadata.possiblevalues.QPossibleValueSource;
import com.kingsrook.qqq.backend.core.model.metadata.security.RecordSecurityLock;
import com.kingsrook.qqq.backend.core.model.metadata.tables.Capability;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QFieldSection;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.tables.Tier;
import com.kingsrook.qqq.backend.core.model.metadata.tables.UniqueKey;
/*******************************************************************************
** Builds the Alerts tables, joins, possible-value sources and record-view
** child lists. Every table is an ordinary QQQ table (query, view, export,
** audit, API) secured by QQQ mechanisms rather than by hiding it:
** - Permissions: QQQ's per-table read / insert / edit / delete permissions
** (AlertsQBitConfig lists them per role).
** - Record security locks (AlertsSecurity): an alert, its timeline and records
** are visible only when the session holds the type's
** visibility permission (if any) and can read its subject table (if any).
** Subscriptions, settings and notification recipient rows are the user's own (admins hold
** the all-access key).
** - Tables the qbit writes (alerts, timeline, records, the delivery log,
** heartbeats) have no insert or delete capability; people change
** alerts through record actions, never by editing rows.
*******************************************************************************/
public final class AlertsTableMetaDataHelper
{
public static final String JOIN_ALERT_EVENT = "alerts_alert_join_alerts_event";
public static final String JOIN_ALERT_RECORD_REF = "alerts_alert_join_alerts_record_ref";
public static final String JOIN_ALERT_DELIVERY = "alerts_alert_join_alerts_delivery";
public static final String JOIN_TYPE_ALERT = "alerts_type_join_alerts_alert";
public static final String JOIN_TYPE_MONITOR = "alerts_type_join_alerts_monitor";
public static final String JOIN_GROUP_TYPE = "alerts_group_join_alerts_type";
public static final String JOIN_MONITOR_ALERT = "alerts_monitor_join_alerts_alert";
public static final String JOIN_TEAM_MEMBER = "alerts_team_join_alerts_team_member";
public static final String JOIN_NOTIFICATION_RECIPIENT = "alerts_notification_join_alerts_notification_recipient";
public static final String JOIN_CHANNEL_DELIVERY = "alerts_channel_join_alerts_delivery";
/*******************************************************************************
** Builders only.
*******************************************************************************/
private AlertsTableMetaDataHelper()
{
}
/*******************************************************************************
** alerts_alert
*******************************************************************************/
public static QTableMetaData buildAlertTable(AlertsQBitConfig config) throws QException
{
QTableMetaData table = text(base(config, AlertsAlert.TABLE_NAME, "Alerts", "notifications_active", AlertsAlert.class), "details", "links", "attributes")
.withRecordLabelFormat("%s")
.withRecordLabelFields("title")
.withRecordSecurityLock(AlertsSecurity.visibilityLock(null))
.withAuditRules(new QAuditRules().withAuditLevel(AuditLevel.FIELD))
.withSection(new QFieldSection("identity", new QIcon("badge"), Tier.T1, List.of("id", "title", "severity", "status", "alertTypeId", "groupId")))
.withSection(new QFieldSection("problem", "Problem", new QIcon("report"), Tier.T2, List.of("summary", "details", "itemCount", "recordRefCount", "subjectTableName", "subjectRecordId", "sourceName")))
.withSection(new QFieldSection("handling", "Handling", new QIcon("assignment_ind"), Tier.T2, List.of("assignedUserId", "assignedTeamId", "acknowledgedByUserId", "acknowledgedAt",
"snoozedUntil", "muted", "resolvedAt", "resolvedByUserId", "resolution", "resolutionNote")))
.withSection(widgetSection(JOIN_ALERT_EVENT, "Timeline", "history"))
.withSection(widgetSection(JOIN_ALERT_RECORD_REF, "Records", "link"))
.withSection(widgetSection(JOIN_ALERT_DELIVERY, "Notifications", "send"))
.withSection(new QFieldSection("occurrence", "Occurrences", new QIcon("repeat"), Tier.T3, List.of("firstRaisedAt", "lastRaisedAt", "occurrenceCount", "reopenCount", "flapping",
"lastNotifiedAt", "monitorId", "dedupKey", "alertTypeName", "visibilityPermission", "openDedupKey", "escalationLevel", "links", "attributes", "createDate", "modifyDate")));
return (readOnly(table));
}
/*******************************************************************************
** alerts_type
*******************************************************************************/
public static QTableMetaData buildTypeTable(AlertsQBitConfig config) throws QException
{
QTableMetaData table = text(base(config, AlertsType.TABLE_NAME, "Alert Types", "category", AlertsType.class), "description", "howToFix")
.withRecordLabelFormat("%s")
.withRecordLabelFields("label")
.withUniqueKey(new UniqueKey("name"))
.withAuditRules(new QAuditRules().withAuditLevel(AuditLevel.FIELD))
.withSection(new QFieldSection("identity", new QIcon("badge"), Tier.T1, List.of("id", "label", "name", "groupId", "sourceName", "openCount")))
.withSection(new QFieldSection("about", "About", new QIcon("info"), Tier.T2, List.of("description", "howToFix", "subjectTableName", "visibilityPermission")))
.withSection(new QFieldSection("tuning", "Tuning", new QIcon("tune"), Tier.T2, List.of("enabled", "notify", "defaultSeverity", "severityOverride", "resolveMode",
"quietPeriodMinutes", "reminderIntervalMinutes", "externalDetailCeiling")))
.withSection(widgetSection(JOIN_TYPE_MONITOR, "Monitors", "monitor_heart"))
.withSection(widgetSection(JOIN_TYPE_ALERT, "Alerts", "notifications_active"))
.withSection(new QFieldSection("system", new QIcon("calendar_month"), Tier.T3, List.of("installed", "lastRaisedAt", "createDate", "modifyDate")));
table.withoutCapabilities(Capability.TABLE_INSERT, Capability.TABLE_DELETE);
return (guard(table));
}
/*******************************************************************************
** alerts_group
*******************************************************************************/
public static QTableMetaData buildGroupTable(AlertsQBitConfig config) throws QException
{
QTableMetaData table = text(base(config, AlertsGroup.TABLE_NAME, "Alert Groups", "folder", AlertsGroup.class), "description")
.withRecordLabelFormat("%s")
.withRecordLabelFields("label")
.withUniqueKey(new UniqueKey("name"))
.withAuditRules(new QAuditRules().withAuditLevel(AuditLevel.FIELD))
.withSection(new QFieldSection("identity", new QIcon("badge"), Tier.T1, List.of("id", "label", "name", "parentGroupId")))
.withSection(new QFieldSection("details", new QIcon("description"), Tier.T2, List.of("description", "ownerTeamId", "icon", "sortOrder")))
.withSection(widgetSection(JOIN_GROUP_TYPE, "Alert Types", "category"))
.withSection(new QFieldSection("system", new QIcon("calendar_month"), Tier.T3, List.of("createDate", "modifyDate")));
return (table);
}
/*******************************************************************************
** alerts_monitor
*******************************************************************************/
public static QTableMetaData buildMonitorTable(AlertsQBitConfig config) throws QException
{
QTableMetaData table = text(base(config, AlertsMonitor.TABLE_NAME, "Monitors", "monitor_heart", AlertsMonitor.class), "description", "definition")
.withRecordLabelFormat("%s")
.withRecordLabelFields("name")
.withAuditRules(new QAuditRules().withAuditLevel(AuditLevel.FIELD))
.withSection(new QFieldSection("identity", new QIcon("badge"), Tier.T1, List.of("id", "name", "alertTypeId", "kind", "enabled", "lastStatus")))
.withSection(new QFieldSection("check", "Check", new QIcon("rule"), Tier.T2, List.of("description", "definition", "perRecord", "severity", "scheduleSeconds", "forMinutes")))
.withSection(new QFieldSection("lastRun", "Last Run", new QIcon("schedule"), Tier.T2, List.of("lastRunAt", "lastValue", "lastError", "lastElapsedMs", "consecutiveFailures", "nextRunAt")))
.withSection(widgetSection(JOIN_MONITOR_ALERT, "Alerts", "notifications_active"))
.withSection(new QFieldSection("system", new QIcon("calendar_month"), Tier.T3, List.of("seeded", "sourceName", "conditionSince", "claimedBy", "claimedUntil", "createDate", "modifyDate")));
table.getField("definition").withFieldAdornment(new FieldAdornment(AdornmentType.CODE_EDITOR).withValue(AdornmentType.CodeEditorValues.languageMode("json")));
table.getField("enabled").setDefaultValue(true);
table.getField("perRecord").setDefaultValue(false);
table.getField("forMinutes").setDefaultValue(0);
table.getField("scheduleSeconds").setDefaultValue(300);
return (guard(table));
}
/*******************************************************************************
** alerts_record_ref
*******************************************************************************/
public static QTableMetaData buildRecordRefTable(AlertsQBitConfig config) throws QException
{
QTableMetaData table = base(config, AlertsRecordRef.TABLE_NAME, "Alert Records", "link", AlertsRecordRef.class)
.withRecordLabelFormat("%s %s")
.withRecordLabelFields("tableName", "recordId")
.withRecordSecurityLock(AlertsSecurity.visibilityLock(JOIN_ALERT_RECORD_REF))
.withSection(new QFieldSection("identity", new QIcon("badge"), Tier.T1, List.of("id", "alertId", "tableName", "recordId", "label", "active")))
.withSection(new QFieldSection("system", new QIcon("calendar_month"), Tier.T3, List.of("createDate", "modifyDate")));
return (readOnly(table));
}
/*******************************************************************************
** alerts_event
*******************************************************************************/
public static QTableMetaData buildEventTable(AlertsQBitConfig config) throws QException
{
QTableMetaData table = base(config, AlertsEvent.TABLE_NAME, "Alert Timeline", "history", AlertsEvent.class)
.withRecordLabelFormat("%s %s")
.withRecordLabelFields("eventType", "at")
.withRecordSecurityLock(AlertsSecurity.visibilityLock(JOIN_ALERT_EVENT))
.withSection(new QFieldSection("identity", new QIcon("badge"), Tier.T1, List.of("id", "alertId", "eventType", "at", "userId")))
.withSection(new QFieldSection("details", new QIcon("description"), Tier.T2, List.of("fromValue", "toValue", "note")))
.withSection(new QFieldSection("system", new QIcon("calendar_month"), Tier.T3, List.of("createDate", "modifyDate")));
return (readOnly(table));
}
/*******************************************************************************
** alerts_subscription
*******************************************************************************/
public static QTableMetaData buildSubscriptionTable(AlertsQBitConfig config) throws QException
{
QTableMetaData table = base(config, AlertsSubscription.TABLE_NAME, "Subscriptions", "notifications", AlertsSubscription.class)
.withRecordLabelFormat("%s %s %s")
.withRecordLabelFields("subscriberType", "scopeType", "scopeValue")
.withRecordSecurityLock(AlertsSecurity.ownerLock("userId"))
.withAuditRules(new QAuditRules().withAuditLevel(AuditLevel.FIELD))
.withSection(new QFieldSection("identity", new QIcon("badge"), Tier.T1, List.of("id", "subscriberType", "userId", "teamId", "channelId", "enabled")))
.withSection(new QFieldSection("scope", "What", new QIcon("filter_alt"), Tier.T2, List.of("scopeType", "scopeValue", "scopeRecordId", "minSeverity", "events")))
.withSection(new QFieldSection("delivery", "How", new QIcon("send"), Tier.T2, List.of("deliveryMode", "channelOverrideIds")))
.withSection(new QFieldSection("system", new QIcon("calendar_month"), Tier.T3, List.of("createdByUserId", "createDate", "modifyDate")));
table.getField("subscriberType").setDefaultValue(AlertsPossibleValues.SubscriberType.USER.name());
table.getField("scopeType").setDefaultValue(AlertsPossibleValues.ScopeType.ALL.name());
table.getField("minSeverity").setDefaultValue("WARNING");
table.getField("deliveryMode").setDefaultValue(AlertsPossibleValues.DeliveryMode.IMMEDIATE.name());
table.getField("events").setDefaultValue("RAISED,ESCALATED,REMINDER,RESOLVED");
table.getField("enabled").setDefaultValue(true);
table.getField("userId").setIsEditable(false);
return (customize(table, AlertsSubscriptionCustomizer.class));
}
/*******************************************************************************
** alerts_user_preference
*******************************************************************************/
public static QTableMetaData buildUserPreferenceTable(AlertsQBitConfig config) throws QException
{
QTableMetaData table = base(config, AlertsUserPreference.TABLE_NAME, "My Alert Settings", "manage_accounts", AlertsUserPreference.class)
.withRecordLabelFormat("%s")
.withRecordLabelFields("userLabel")
.withUniqueKey(new UniqueKey("userId"))
.withRecordSecurityLock(AlertsSecurity.ownerLock("userId"))
.withAuditRules(new QAuditRules().withAuditLevel(AuditLevel.FIELD))
.withSection(new QFieldSection("identity", new QIcon("badge"), Tier.T1, List.of("id", "userLabel", "emailAddress", "userId")))
.withSection(new QFieldSection("delivery", "Delivery", new QIcon("send"), Tier.T2, List.of("inAppEnabled", "emailEnabled", "pausedUntil", "defaultChannelIds")))
.withSection(new QFieldSection("quiet", "Quiet Hours and Digests", new QIcon("bedtime"), Tier.T2, List.of("timeZone", "quietHoursStart", "quietHoursEnd", "quietDays",
"quietBypassSeverity", "digestHour")))
.withSection(new QFieldSection("system", new QIcon("calendar_month"), Tier.T3, List.of("createDate", "modifyDate")));
table.getField("emailEnabled").setDefaultValue(true);
table.getField("inAppEnabled").setDefaultValue(true);
table.getField("quietBypassSeverity").setDefaultValue("CRITICAL");
table.getField("digestHour").setDefaultValue(8);
return (customize(table, AlertsSubscriptionCustomizer.class));
}
/*******************************************************************************
** alerts_team
*******************************************************************************/
public static QTableMetaData buildTeamTable(AlertsQBitConfig config) throws QException
{
QTableMetaData table = text(base(config, AlertsTeam.TABLE_NAME, "Teams", "groups", AlertsTeam.class), "description")
.withRecordLabelFormat("%s")
.withRecordLabelFields("label")
.withUniqueKey(new UniqueKey("name"))
.withAuditRules(new QAuditRules().withAuditLevel(AuditLevel.FIELD))
.withSection(new QFieldSection("identity", new QIcon("badge"), Tier.T1, List.of("id", "label", "name", "memberSource", "memberSourceValue")))
.withSection(new QFieldSection("details", new QIcon("description"), Tier.T2, List.of("description")))
.withSection(widgetSection(JOIN_TEAM_MEMBER, "Members", "person"))
.withSection(new QFieldSection("system", new QIcon("calendar_month"), Tier.T3, List.of("createDate", "modifyDate")));
table.getField("memberSource").setDefaultValue(AlertsPossibleValues.MemberSource.MANUAL.name());
return (table);
}
/*******************************************************************************
** alerts_team_member
*******************************************************************************/
public static QTableMetaData buildTeamMemberTable(AlertsQBitConfig config) throws QException
{
QTableMetaData table = base(config, AlertsTeamMember.TABLE_NAME, "Team Members", "person", AlertsTeamMember.class)
.withRecordLabelFormat("%s %s")
.withRecordLabelFields("teamId", "userId")
.withUniqueKey(new UniqueKey("teamId", "userId"))
.withAuditRules(new QAuditRules().withAuditLevel(AuditLevel.FIELD))
.withSection(new QFieldSection("identity", new QIcon("badge"), Tier.T1, List.of("id", "teamId", "userId", "role")))
.withSection(new QFieldSection("system", new QIcon("calendar_month"), Tier.T3, List.of("createDate", "modifyDate")));
table.getField("role").setDefaultValue(AlertsPossibleValues.TeamRole.MEMBER.name());
return (table);
}
/*******************************************************************************
** alerts_channel
*******************************************************************************/
public static QTableMetaData buildChannelTable(AlertsQBitConfig config) throws QException
{
QTableMetaData table = text(base(config, AlertsChannel.TABLE_NAME, "Channels", "campaign", AlertsChannel.class), "settings")
.withRecordLabelFormat("%s")
.withRecordLabelFields("label")
.withUniqueKey(new UniqueKey("name"))
.withAuditRules(new QAuditRules().withAuditLevel(AuditLevel.FIELD))
.withSection(new QFieldSection("identity", new QIcon("badge"), Tier.T1, List.of("id", "label", "name", "channelType", "enabled", "healthStatus")))
.withSection(new QFieldSection("settings", "Settings", new QIcon("tune"), Tier.T2, List.of("settings", "secretRef", "detailLevel", "minSeverity", "rateLimitPerHour")))
.withSection(new QFieldSection("health", "Health", new QIcon("monitor_heart"), Tier.T2, List.of("lastSuccessAt", "lastFailureAt", "consecutiveFailures", "lastError")))
.withSection(widgetSection(JOIN_CHANNEL_DELIVERY, "Notifications", "send"))
.withSection(new QFieldSection("system", new QIcon("calendar_month"), Tier.T3, List.of("createDate", "modifyDate")));
table.getField("settings").withFieldAdornment(new FieldAdornment(AdornmentType.CODE_EDITOR).withValue(AdornmentType.CodeEditorValues.languageMode("json")));
table.getField("enabled").setDefaultValue(true);
table.getField("detailLevel").setDefaultValue("MINIMAL");
table.getField("minSeverity").setDefaultValue("WARNING");
table.getField("rateLimitPerHour").setDefaultValue(60);
table.getField("healthStatus").setDefaultValue(AlertsPossibleValues.HealthStatus.HEALTHY.name());
return (guard(table));
}
/*******************************************************************************
** alerts_mute
*******************************************************************************/
public static QTableMetaData buildMuteTable(AlertsQBitConfig config) throws QException
{
QTableMetaData table = base(config, AlertsMute.TABLE_NAME, "Mutes and Maintenance", "notifications_off", AlertsMute.class)
.withRecordLabelFormat("%s")
.withRecordLabelFields("name")
.withAuditRules(new QAuditRules().withAuditLevel(AuditLevel.FIELD))
.withSection(new QFieldSection("identity", new QIcon("badge"), Tier.T1, List.of("id", "name", "enabled", "effect")))
.withSection(new QFieldSection("scope", "What and When", new QIcon("filter_alt"), Tier.T2, List.of("scopeType", "scopeValue", "startsAt", "endsAt", "reason")))
.withSection(new QFieldSection("system", new QIcon("calendar_month"), Tier.T3, List.of("createdByUserId", "createDate", "modifyDate")));
table.getField("effect").setDefaultValue(AlertsPossibleValues.MuteEffect.SILENCE_NOTIFICATIONS.name());
table.getField("enabled").setDefaultValue(true);
table.getField("scopeType").setDefaultValue(AlertsPossibleValues.ScopeType.ALL.name());
return (customize(table, AlertsSubscriptionCustomizer.class));
}
/*******************************************************************************
** alerts_delivery
*******************************************************************************/
public static QTableMetaData buildDeliveryTable(AlertsQBitConfig config) throws QException
{
QTableMetaData table = base(config, AlertsDelivery.TABLE_NAME, "Delivery Log", "send", AlertsDelivery.class)
.withRecordLabelFormat("%s %s")
.withRecordLabelFields("kind", "recipientLabel")
.withSection(new QFieldSection("identity", new QIcon("badge"), Tier.T1, List.of("id", "alertId", "kind", "status", "channelId", "recipientLabel")))
.withSection(new QFieldSection("delivery", "Delivery", new QIcon("send"), Tier.T2, List.of("suppressedReason", "attempts", "nextAttemptAt", "sentAt", "lastError", "providerMessageId")))
.withSection(new QFieldSection("system", new QIcon("calendar_month"), Tier.T3, List.of("recipientUserId", "subscriptionId", "alertEventId", "claimedUntil", "createDate", "modifyDate")));
return (readOnly(table));
}
/*******************************************************************************
** alerts_notification (user notifications, docs/NOTIFICATIONS.md 3.1)
*******************************************************************************/
public static QTableMetaData buildNotificationTable(AlertsQBitConfig config) throws QException
{
QTableMetaData table = text(base(config, AlertsNotification.TABLE_NAME, "Notifications", "campaign", AlertsNotification.class), "body", "audienceValue")
.withRecordLabelFormat("%s")
.withRecordLabelFields("title")
.withAuditRules(new QAuditRules().withAuditLevel(AuditLevel.FIELD))
.withSection(new QFieldSection("identity", new QIcon("badge"), Tier.T1, List.of("id", "title", "severity", "category", "status")))
.withSection(new QFieldSection("message", "Message", new QIcon("article"), Tier.T2, List.of("body", "linkUrl", "linkLabel", "sticky")))
.withSection(new QFieldSection("audience", "Audience", new QIcon("groups"), Tier.T2, List.of("audienceType", "audienceValue", "recipientCount", "readCount")))
.withSection(new QFieldSection("schedule", "Schedule", new QIcon("schedule"), Tier.T2, List.of("publishAt", "expireAt", "sentAt", "retractedAt")))
.withSection(widgetSection(JOIN_NOTIFICATION_RECIPIENT, "Recipients", "person"))
.withSection(new QFieldSection("system", new QIcon("calendar_month"), Tier.T3, List.of("authorUserId", "sourceName", "sourceKey", "sourceTableName", "sourceRecordId",
"createDate", "modifyDate")));
table.getField("severity").setDefaultValue(NotificationSeverity.INFO.name());
table.getField("category").setDefaultValue(NotificationCategory.SYSTEM.name());
table.getField("audienceType").setDefaultValue(NotificationAudience.Type.ALL_USERS.name());
table.getField("status").setDefaultValue(NotificationService.STATUS_DRAFT);
table.getField("sticky").setDefaultValue(false);
table.getField("body").withFieldAdornment(new FieldAdornment(AdornmentType.CODE_EDITOR).withValue(AdornmentType.CodeEditorValues.languageMode("markdown")));
return (notificationCustomizer(table, true));
}
/*******************************************************************************
** alerts_notification_recipient (one notification for one user). Users
** see and edit (read, dismissed) only their own rows; the qbit inserts
** and deletes them.
*******************************************************************************/
public static QTableMetaData buildNotificationRecipientTable(AlertsQBitConfig config) throws QException
{
QTableMetaData table = base(config, AlertsNotificationRecipient.TABLE_NAME, "Notification Recipients", "mark_email_read", AlertsNotificationRecipient.class)
.withRecordLabelFormat("%s %s")
.withRecordLabelFields("notificationId", "userId")
.withUniqueKey(new UniqueKey("notificationId", "userId"))
.withRecordSecurityLock(AlertsSecurity.recipientLock("userId"))
.withSection(new QFieldSection("identity", new QIcon("badge"), Tier.T1, List.of("id", "notificationId", "userId", "deliveredAt", "readAt", "dismissedAt")))
.withSection(new QFieldSection("email", "Email", new QIcon("mail"), Tier.T2, List.of("emailStatus", "emailedAt")))
.withSection(new QFieldSection("system", new QIcon("calendar_month"), Tier.T3, List.of("createDate", "modifyDate")));
table.withoutCapabilities(Capability.TABLE_INSERT, Capability.TABLE_DELETE);
return (notificationCustomizer(table, true));
}
/*******************************************************************************
** alerts_notification_preference (a user's settings for one category)
*******************************************************************************/
public static QTableMetaData buildNotificationPreferenceTable(AlertsQBitConfig config) throws QException
{
QTableMetaData table = base(config, AlertsNotificationPreference.TABLE_NAME, "My Notification Settings", "tune", AlertsNotificationPreference.class)
.withRecordLabelFormat("%s %s")
.withRecordLabelFields("userId", "category")
.withUniqueKey(new UniqueKey("userId", "category"))
.withRecordSecurityLock(AlertsSecurity.ownerLock("userId"))
.withAuditRules(new QAuditRules().withAuditLevel(AuditLevel.FIELD))
.withSection(new QFieldSection("identity", new QIcon("badge"), Tier.T1, List.of("id", "category", "inAppMuted", "emailMode", "emailMinSeverity")))
.withSection(new QFieldSection("system", new QIcon("calendar_month"), Tier.T3, List.of("userId", "createDate", "modifyDate")));
table.getField("category").setDefaultValue(NotificationCategory.SYSTEM.name());
table.getField("inAppMuted").setDefaultValue(false);
table.getField("emailMode").setDefaultValue(AlertsPossibleValues.EmailMode.OFF.name());
table.getField("emailMinSeverity").setDefaultValue(NotificationSeverity.WARNING.name());
return (notificationCustomizer(table, false));
}
/*******************************************************************************
** The notification tables' customizer (insert, update and, optionally,
** delete).
*******************************************************************************/
private static QTableMetaData notificationCustomizer(QTableMetaData table, boolean onDelete)
{
QCodeReference reference = new QCodeReference(AlertsNotificationCustomizer.class);
List<TableCustomizers> roles = new ArrayList<>(List.of(TableCustomizers.PRE_INSERT_RECORD, TableCustomizers.PRE_UPDATE_RECORD));
if(onDelete)
{
roles.add(TableCustomizers.PRE_DELETE_RECORD);
}
for(TableCustomizers role : roles)
{
table.withCustomizer(role, reference);
}
return (table);
}
/*******************************************************************************
** alerts_heartbeat
*******************************************************************************/
public static QTableMetaData buildHeartbeatTable(AlertsQBitConfig config) throws QException
{
QTableMetaData table = base(config, AlertsHeartbeat.TABLE_NAME, "Heartbeats", "favorite", AlertsHeartbeat.class)
.withRecordLabelFormat("%s")
.withRecordLabelFields("heartbeatKey")
.withUniqueKey(new UniqueKey("heartbeatKey"))
.withSection(new QFieldSection("identity", new QIcon("badge"), Tier.T1, List.of("id", "heartbeatKey", "lastBeatAt", "beatCount")))
.withSection(new QFieldSection("system", new QIcon("calendar_month"), Tier.T3, List.of("createDate", "modifyDate")));
return (readOnly(table));
}
/*******************************************************************************
** All the tables.
*******************************************************************************/
public static List<QTableMetaData> buildAllTables(AlertsQBitConfig config) throws QException
{
return (List.of(buildAlertTable(config), buildMonitorTable(config), buildTypeTable(config), buildGroupTable(config), buildSubscriptionTable(config),
buildUserPreferenceTable(config), buildTeamTable(config), buildTeamMemberTable(config), buildChannelTable(config), buildMuteTable(config),
buildDeliveryTable(config), buildEventTable(config), buildRecordRefTable(config), buildHeartbeatTable(config), buildNotificationTable(config),
buildNotificationRecipientTable(config), buildNotificationPreferenceTable(config)));
}
/*******************************************************************************
** Table-backed possible-value sources (for the id fields), plus the enums.
*******************************************************************************/
public static List<QPossibleValueSource> buildPossibleValueSources()
{
List<QPossibleValueSource> sources = new ArrayList<>(AlertsPossibleValues.buildEnumSources());
for(String table : List.of(AlertsAlert.TABLE_NAME, AlertsType.TABLE_NAME, AlertsGroup.TABLE_NAME, AlertsMonitor.TABLE_NAME, AlertsTeam.TABLE_NAME,
AlertsChannel.TABLE_NAME, AlertsSubscription.TABLE_NAME, AlertsNotification.TABLE_NAME))
{
sources.add(QPossibleValueSource.newForTable(table));
}
return (sources);
}
/*******************************************************************************
** The one-to-many joins from each parent to its children.
*******************************************************************************/
public static List<QJoinMetaData> buildJoins()
{
List<QJoinMetaData> joins = new ArrayList<>();
joins.add(oneToMany(JOIN_ALERT_EVENT, AlertsAlert.TABLE_NAME, AlertsEvent.TABLE_NAME, "alertId"));
joins.add(oneToMany(JOIN_ALERT_RECORD_REF, AlertsAlert.TABLE_NAME, AlertsRecordRef.TABLE_NAME, "alertId"));
joins.add(oneToMany(JOIN_ALERT_DELIVERY, AlertsAlert.TABLE_NAME, AlertsDelivery.TABLE_NAME, "alertId"));
joins.add(oneToMany(JOIN_TYPE_ALERT, AlertsType.TABLE_NAME, AlertsAlert.TABLE_NAME, "alertTypeId"));
joins.add(oneToMany(JOIN_TYPE_MONITOR, AlertsType.TABLE_NAME, AlertsMonitor.TABLE_NAME, "alertTypeId"));
joins.add(oneToMany(JOIN_GROUP_TYPE, AlertsGroup.TABLE_NAME, AlertsType.TABLE_NAME, "groupId"));
joins.add(oneToMany(JOIN_MONITOR_ALERT, AlertsMonitor.TABLE_NAME, AlertsAlert.TABLE_NAME, "monitorId"));
joins.add(oneToMany(JOIN_TEAM_MEMBER, AlertsTeam.TABLE_NAME, AlertsTeamMember.TABLE_NAME, "teamId"));
joins.add(oneToMany(JOIN_CHANNEL_DELIVERY, AlertsChannel.TABLE_NAME, AlertsDelivery.TABLE_NAME, "channelId"));
joins.add(oneToMany(JOIN_NOTIFICATION_RECIPIENT, AlertsNotification.TABLE_NAME, AlertsNotificationRecipient.TABLE_NAME, "notificationId"));
return (joins);
}
/*******************************************************************************
** The record-view child lists (newest first, a few columns each, "View
** all" beyond the cap).
*******************************************************************************/
public static List<QWidgetMetaDataInterface> buildChildListWidgets()
{
Map<String, QJoinMetaData> joins = new LinkedHashMap<>();
for(QJoinMetaData join : buildJoins())
{
joins.put(join.getName(), join);
}
List<QWidgetMetaDataInterface> widgets = new ArrayList<>();
widgets.add(childList(joins.get(JOIN_ALERT_EVENT), "Timeline", 50, new QFilterOrderBy("at", false), List.of("at", "eventType", "userId", "toValue", "note")));
widgets.add(childList(joins.get(JOIN_ALERT_RECORD_REF), "Records", 25, new QFilterOrderBy("id", true), List.of("tableName", "recordId", "label", "active")));
widgets.add(childList(joins.get(JOIN_ALERT_DELIVERY), "Notifications", 25, new QFilterOrderBy("id", false), List.of("kind", "status", "recipientLabel", "sentAt")));
widgets.add(childList(joins.get(JOIN_TYPE_ALERT), "Alerts", 10, new QFilterOrderBy("lastRaisedAt", false), List.of("title", "severity", "status", "lastRaisedAt")));
widgets.add(childList(joins.get(JOIN_TYPE_MONITOR), "Monitors", 10, new QFilterOrderBy("id", true), List.of("name", "kind", "enabled", "lastStatus")));
widgets.add(childList(joins.get(JOIN_GROUP_TYPE), "Alert Types", 50, new QFilterOrderBy("label", true), List.of("label", "defaultSeverity", "enabled", "openCount")));
widgets.add(childList(joins.get(JOIN_MONITOR_ALERT), "Alerts", 10, new QFilterOrderBy("lastRaisedAt", false), List.of("title", "severity", "status", "lastRaisedAt")));
widgets.add(ChildRecordListRenderer.widgetMetaDataBuilder(joins.get(JOIN_TEAM_MEMBER)).withLabel("Members").withCanAddChildRecord(true).withMaxRows(100)
.withOnlyIncludeFieldNames(List.of("userId", "role")).getWidgetMetaData());
widgets.add(childList(joins.get(JOIN_CHANNEL_DELIVERY), "Notifications", 25, new QFilterOrderBy("id", false), List.of("kind", "status", "recipientLabel", "sentAt")));
widgets.add(childList(joins.get(JOIN_NOTIFICATION_RECIPIENT), "Recipients", 25, new QFilterOrderBy("id", true), List.of("userId", "deliveredAt", "readAt", "dismissedAt", "emailStatus")));
return (widgets);
}
/*******************************************************************************
**
*******************************************************************************/
private static QWidgetMetaDataInterface childList(QJoinMetaData join, String label, int maxRows, QFilterOrderBy orderBy, List<String> fields)
{
return (ChildRecordListRenderer.widgetMetaDataBuilder(join)
.withLabel(label)
.withMaxRows(maxRows)
.withOrderBys(List.of(orderBy))
.withOnlyIncludeFieldNames(fields)
.getWidgetMetaData());
}
/*******************************************************************************
**
*******************************************************************************/
private static QJoinMetaData oneToMany(String name, String left, String right, String rightField)
{
return (new QJoinMetaData()
.withName(name)
.withLeftTable(left)
.withRightTable(right)
.withType(JoinType.ONE_TO_MANY)
.withJoinOn(new JoinOn("id", rightField)));
}
/*******************************************************************************
** A table with QQQ's per-table permissions, entity fields, snake_case
** backend column names, and createDate / modifyDate managed by QQQ.
*******************************************************************************/
private static QTableMetaData base(AlertsQBitConfig config, String name, String label, String icon, Class<? extends QRecordEntity> entity) throws QException
{
QTableMetaData table = new QTableMetaData()
.withName(name)
.withLabel(label)
.withIcon(new QIcon(icon))
.withBackendName(config.getBackendName())
.withPrimaryKeyField("id")
.withPermissionRules(new QPermissionRules().withLevel(PermissionLevel.READ_INSERT_EDIT_DELETE_PERMISSIONS))
.withFieldsFromEntity(entity);
QInstanceEnricher.setInferredFieldBackendNames(table);
return (table);
}
/*******************************************************************************
** Only the qbit writes this table.
*******************************************************************************/
private static QTableMetaData readOnly(QTableMetaData table)
{
table.withoutCapabilities(Capability.TABLE_INSERT, Capability.TABLE_UPDATE, Capability.TABLE_DELETE);
return (guard(table));
}
/*******************************************************************************
** Reject writes the table's capabilities don't allow, in the core actions,
** unless the qbit itself (system user) makes them.
*******************************************************************************/
private static QTableMetaData guard(QTableMetaData table)
{
QCodeReference reference = new QCodeReference(AlertsWriteGuardCustomizer.class);
for(TableCustomizers role : List.of(TableCustomizers.PRE_INSERT_RECORD, TableCustomizers.PRE_UPDATE_RECORD, TableCustomizers.PRE_DELETE_RECORD))
{
table.withCustomizer(role, reference);
}
return (table);
}
/*******************************************************************************
**
*******************************************************************************/
private static QTableMetaData customize(QTableMetaData table, Class<?> customizer)
{
QCodeReference reference = new QCodeReference(customizer);
for(TableCustomizers role : List.of(TableCustomizers.PRE_INSERT_RECORD, TableCustomizers.PRE_UPDATE_RECORD))
{
table.withCustomizer(role, reference);
}
return (table);
}
/*******************************************************************************
** A record-view section showing a child-list widget.
*******************************************************************************/
private static QFieldSection widgetSection(String joinName, String label, String icon)
{
return (new QFieldSection(joinName, label, new QIcon(icon), Tier.T2, null).withWidgetName(joinName));
}
/*******************************************************************************
** Make String fields TEXT (unbounded).
*******************************************************************************/
private static QTableMetaData text(QTableMetaData table, String... names)
{
for(String name : names)
{
QFieldMetaData field = table.getField(name);
field.setType(QFieldType.TEXT);
}
return (table);
}
}
@@ -0,0 +1,81 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.metadata;
import com.kingsrook.qbits.alerts.AlertsQBitConfig;
import com.kingsrook.qbits.alerts.AlertsSecurity;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.metadata.MetaDataProducerMultiOutput;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.dashboard.QWidgetMetaDataInterface;
import com.kingsrook.qqq.backend.core.model.metadata.joins.QJoinMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.possiblevalues.QPossibleValueSource;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitComponentMetaDataProducer;
import com.kingsrook.qqq.backend.core.model.metadata.security.QSecurityKeyType;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
/*******************************************************************************
** Produces the Alerts tables, their joins, possible-value sources,
** record-view child lists and security key types.
*******************************************************************************/
public class AlertsTablesMetaDataProducer extends QBitComponentMetaDataProducer<MetaDataProducerMultiOutput, AlertsQBitConfig>
{
/*******************************************************************************
**
*******************************************************************************/
@Override
public MetaDataProducerMultiOutput produce(QInstance qInstance) throws QException
{
AlertsQBitConfig config = getQBitConfig();
MetaDataProducerMultiOutput output = new MetaDataProducerMultiOutput();
for(QSecurityKeyType keyType : AlertsSecurity.buildSecurityKeyTypes())
{
output.add(keyType);
}
for(QTableMetaData table : AlertsTableMetaDataHelper.buildAllTables(config))
{
output.add(table);
}
for(QJoinMetaData join : AlertsTableMetaDataHelper.buildJoins())
{
output.add(join);
}
for(QPossibleValueSource source : AlertsTableMetaDataHelper.buildPossibleValueSources())
{
output.add(source);
}
for(QWidgetMetaDataInterface widget : AlertsTableMetaDataHelper.buildChildListWidgets())
{
output.add(widget);
}
return (output);
}
/*******************************************************************************
** tables first
*******************************************************************************/
@Override
public int getSortOrder()
{
return (100);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,634 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.model;
import java.time.Instant;
import com.kingsrook.qqq.backend.core.model.data.QField;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.data.QRecordEntity;
import com.kingsrook.qqq.backend.core.model.metadata.fields.ValueTooLongBehavior;
/*******************************************************************************
** A configured destination (in-app, email, an email list). It holds settings
** and a reference to its secret, never the secret.
**
** Generated from the qbit-alerts schema (one definition for the entity,
** the Liquibase changelog and the test DDL).
*******************************************************************************/
public class AlertsChannel extends QRecordEntity
{
public static final String TABLE_NAME = "alerts_channel";
@QField(isEditable = false, isPrimaryKey = true)
private Integer id;
@QField(isRequired = true, maxLength = 100, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String name;
@QField(isRequired = true, maxLength = 200, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String label;
@QField(isRequired = true, maxLength = 20, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, possibleValueSourceName = "alerts_channel_type")
private String channelType;
@QField()
private Boolean enabled;
@QField()
private String settings;
@QField(maxLength = 200, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, label = "Secret Reference")
private String secretRef;
@QField(maxLength = 16, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, possibleValueSourceName = "alerts_detail_level")
private String detailLevel;
@QField(maxLength = 16, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, possibleValueSourceName = "alerts_severity")
private String minSeverity;
@QField()
private Integer rateLimitPerHour;
@QField(isEditable = false, maxLength = 16, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, possibleValueSourceName = "alerts_health_status")
private String healthStatus;
@QField(isEditable = false)
private Instant lastSuccessAt;
@QField(isEditable = false)
private Instant lastFailureAt;
@QField(isEditable = false)
private Integer consecutiveFailures;
@QField(isEditable = false, maxLength = 2000, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String lastError;
@QField(isEditable = false)
private Instant createDate;
@QField(isEditable = false)
private Instant modifyDate;
/*******************************************************************************
** Default constructor.
*******************************************************************************/
public AlertsChannel()
{
}
/*******************************************************************************
** Constructor that populates from a QRecord.
*******************************************************************************/
public AlertsChannel(QRecord record)
{
populateFromQRecord(record);
}
/*******************************************************************************
** Getter for id
*******************************************************************************/
public Integer getId()
{
return (this.id);
}
/*******************************************************************************
** Setter for id
*******************************************************************************/
public void setId(Integer id)
{
this.id = id;
}
/*******************************************************************************
** Fluent setter for id
*******************************************************************************/
public AlertsChannel withId(Integer id)
{
this.id = id;
return (this);
}
/*******************************************************************************
** Getter for name
*******************************************************************************/
public String getName()
{
return (this.name);
}
/*******************************************************************************
** Setter for name
*******************************************************************************/
public void setName(String name)
{
this.name = name;
}
/*******************************************************************************
** Fluent setter for name
*******************************************************************************/
public AlertsChannel withName(String name)
{
this.name = name;
return (this);
}
/*******************************************************************************
** Getter for label
*******************************************************************************/
public String getLabel()
{
return (this.label);
}
/*******************************************************************************
** Setter for label
*******************************************************************************/
public void setLabel(String label)
{
this.label = label;
}
/*******************************************************************************
** Fluent setter for label
*******************************************************************************/
public AlertsChannel withLabel(String label)
{
this.label = label;
return (this);
}
/*******************************************************************************
** Getter for channelType
*******************************************************************************/
public String getChannelType()
{
return (this.channelType);
}
/*******************************************************************************
** Setter for channelType
*******************************************************************************/
public void setChannelType(String channelType)
{
this.channelType = channelType;
}
/*******************************************************************************
** Fluent setter for channelType
*******************************************************************************/
public AlertsChannel withChannelType(String channelType)
{
this.channelType = channelType;
return (this);
}
/*******************************************************************************
** Getter for enabled
*******************************************************************************/
public Boolean getEnabled()
{
return (this.enabled);
}
/*******************************************************************************
** Setter for enabled
*******************************************************************************/
public void setEnabled(Boolean enabled)
{
this.enabled = enabled;
}
/*******************************************************************************
** Fluent setter for enabled
*******************************************************************************/
public AlertsChannel withEnabled(Boolean enabled)
{
this.enabled = enabled;
return (this);
}
/*******************************************************************************
** Getter for settings
*******************************************************************************/
public String getSettings()
{
return (this.settings);
}
/*******************************************************************************
** Setter for settings
*******************************************************************************/
public void setSettings(String settings)
{
this.settings = settings;
}
/*******************************************************************************
** Fluent setter for settings
*******************************************************************************/
public AlertsChannel withSettings(String settings)
{
this.settings = settings;
return (this);
}
/*******************************************************************************
** Getter for secretRef
*******************************************************************************/
public String getSecretRef()
{
return (this.secretRef);
}
/*******************************************************************************
** Setter for secretRef
*******************************************************************************/
public void setSecretRef(String secretRef)
{
this.secretRef = secretRef;
}
/*******************************************************************************
** Fluent setter for secretRef
*******************************************************************************/
public AlertsChannel withSecretRef(String secretRef)
{
this.secretRef = secretRef;
return (this);
}
/*******************************************************************************
** Getter for detailLevel
*******************************************************************************/
public String getDetailLevel()
{
return (this.detailLevel);
}
/*******************************************************************************
** Setter for detailLevel
*******************************************************************************/
public void setDetailLevel(String detailLevel)
{
this.detailLevel = detailLevel;
}
/*******************************************************************************
** Fluent setter for detailLevel
*******************************************************************************/
public AlertsChannel withDetailLevel(String detailLevel)
{
this.detailLevel = detailLevel;
return (this);
}
/*******************************************************************************
** Getter for minSeverity
*******************************************************************************/
public String getMinSeverity()
{
return (this.minSeverity);
}
/*******************************************************************************
** Setter for minSeverity
*******************************************************************************/
public void setMinSeverity(String minSeverity)
{
this.minSeverity = minSeverity;
}
/*******************************************************************************
** Fluent setter for minSeverity
*******************************************************************************/
public AlertsChannel withMinSeverity(String minSeverity)
{
this.minSeverity = minSeverity;
return (this);
}
/*******************************************************************************
** Getter for rateLimitPerHour
*******************************************************************************/
public Integer getRateLimitPerHour()
{
return (this.rateLimitPerHour);
}
/*******************************************************************************
** Setter for rateLimitPerHour
*******************************************************************************/
public void setRateLimitPerHour(Integer rateLimitPerHour)
{
this.rateLimitPerHour = rateLimitPerHour;
}
/*******************************************************************************
** Fluent setter for rateLimitPerHour
*******************************************************************************/
public AlertsChannel withRateLimitPerHour(Integer rateLimitPerHour)
{
this.rateLimitPerHour = rateLimitPerHour;
return (this);
}
/*******************************************************************************
** Getter for healthStatus
*******************************************************************************/
public String getHealthStatus()
{
return (this.healthStatus);
}
/*******************************************************************************
** Setter for healthStatus
*******************************************************************************/
public void setHealthStatus(String healthStatus)
{
this.healthStatus = healthStatus;
}
/*******************************************************************************
** Fluent setter for healthStatus
*******************************************************************************/
public AlertsChannel withHealthStatus(String healthStatus)
{
this.healthStatus = healthStatus;
return (this);
}
/*******************************************************************************
** Getter for lastSuccessAt
*******************************************************************************/
public Instant getLastSuccessAt()
{
return (this.lastSuccessAt);
}
/*******************************************************************************
** Setter for lastSuccessAt
*******************************************************************************/
public void setLastSuccessAt(Instant lastSuccessAt)
{
this.lastSuccessAt = lastSuccessAt;
}
/*******************************************************************************
** Fluent setter for lastSuccessAt
*******************************************************************************/
public AlertsChannel withLastSuccessAt(Instant lastSuccessAt)
{
this.lastSuccessAt = lastSuccessAt;
return (this);
}
/*******************************************************************************
** Getter for lastFailureAt
*******************************************************************************/
public Instant getLastFailureAt()
{
return (this.lastFailureAt);
}
/*******************************************************************************
** Setter for lastFailureAt
*******************************************************************************/
public void setLastFailureAt(Instant lastFailureAt)
{
this.lastFailureAt = lastFailureAt;
}
/*******************************************************************************
** Fluent setter for lastFailureAt
*******************************************************************************/
public AlertsChannel withLastFailureAt(Instant lastFailureAt)
{
this.lastFailureAt = lastFailureAt;
return (this);
}
/*******************************************************************************
** Getter for consecutiveFailures
*******************************************************************************/
public Integer getConsecutiveFailures()
{
return (this.consecutiveFailures);
}
/*******************************************************************************
** Setter for consecutiveFailures
*******************************************************************************/
public void setConsecutiveFailures(Integer consecutiveFailures)
{
this.consecutiveFailures = consecutiveFailures;
}
/*******************************************************************************
** Fluent setter for consecutiveFailures
*******************************************************************************/
public AlertsChannel withConsecutiveFailures(Integer consecutiveFailures)
{
this.consecutiveFailures = consecutiveFailures;
return (this);
}
/*******************************************************************************
** Getter for lastError
*******************************************************************************/
public String getLastError()
{
return (this.lastError);
}
/*******************************************************************************
** Setter for lastError
*******************************************************************************/
public void setLastError(String lastError)
{
this.lastError = lastError;
}
/*******************************************************************************
** Fluent setter for lastError
*******************************************************************************/
public AlertsChannel withLastError(String lastError)
{
this.lastError = lastError;
return (this);
}
/*******************************************************************************
** Getter for createDate
*******************************************************************************/
public Instant getCreateDate()
{
return (this.createDate);
}
/*******************************************************************************
** Setter for createDate
*******************************************************************************/
public void setCreateDate(Instant createDate)
{
this.createDate = createDate;
}
/*******************************************************************************
** Fluent setter for createDate
*******************************************************************************/
public AlertsChannel withCreateDate(Instant createDate)
{
this.createDate = createDate;
return (this);
}
/*******************************************************************************
** Getter for modifyDate
*******************************************************************************/
public Instant getModifyDate()
{
return (this.modifyDate);
}
/*******************************************************************************
** Setter for modifyDate
*******************************************************************************/
public void setModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
}
/*******************************************************************************
** Fluent setter for modifyDate
*******************************************************************************/
public AlertsChannel withModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
return (this);
}
}
@@ -0,0 +1,669 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.model;
import java.time.Instant;
import com.kingsrook.qqq.backend.core.model.data.QField;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.data.QRecordEntity;
import com.kingsrook.qqq.backend.core.model.metadata.fields.ValueTooLongBehavior;
/*******************************************************************************
** One delivery attempt: who, which channel, status, retries and error.
** Suppressed deliveries are logged too, with their reason. Written by the
** qbit; read-only.
**
** Generated from the qbit-alerts schema (one definition for the entity,
** the Liquibase changelog and the test DDL).
*******************************************************************************/
public class AlertsDelivery extends QRecordEntity
{
public static final String TABLE_NAME = "alerts_delivery";
@QField(isEditable = false, isPrimaryKey = true)
private Integer id;
@QField(isEditable = false, possibleValueSourceName = "alerts_alert", label = "Alert")
private Integer alertId;
@QField(isEditable = false, label = "Alert Event")
private Integer alertEventId;
@QField(isEditable = false, possibleValueSourceName = "alerts_subscription", label = "Subscription")
private Integer subscriptionId;
@QField(isEditable = false, possibleValueSourceName = "alerts_channel", label = "Channel")
private Integer channelId;
@QField(isEditable = false, maxLength = 100, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, label = "Recipient")
private String recipientUserId;
@QField(isEditable = false, maxLength = 300, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, label = "Sent To")
private String recipientLabel;
@QField(isEditable = false, maxLength = 16, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, possibleValueSourceName = "alerts_delivery_kind")
private String kind;
@QField(isEditable = false, maxLength = 16, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, possibleValueSourceName = "alerts_delivery_status")
private String status;
@QField(isEditable = false, maxLength = 20, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, possibleValueSourceName = "alerts_suppressed_reason")
private String suppressedReason;
@QField(isEditable = false)
private Integer attempts;
@QField(isEditable = false)
private Instant nextAttemptAt;
@QField(isEditable = false)
private Instant claimedUntil;
@QField(isEditable = false)
private Instant sentAt;
@QField(isEditable = false, maxLength = 300, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String providerMessageId;
@QField(isEditable = false, maxLength = 2000, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String lastError;
@QField(isEditable = false)
private Instant createDate;
@QField(isEditable = false)
private Instant modifyDate;
/*******************************************************************************
** Default constructor.
*******************************************************************************/
public AlertsDelivery()
{
}
/*******************************************************************************
** Constructor that populates from a QRecord.
*******************************************************************************/
public AlertsDelivery(QRecord record)
{
populateFromQRecord(record);
}
/*******************************************************************************
** Getter for id
*******************************************************************************/
public Integer getId()
{
return (this.id);
}
/*******************************************************************************
** Setter for id
*******************************************************************************/
public void setId(Integer id)
{
this.id = id;
}
/*******************************************************************************
** Fluent setter for id
*******************************************************************************/
public AlertsDelivery withId(Integer id)
{
this.id = id;
return (this);
}
/*******************************************************************************
** Getter for alertId
*******************************************************************************/
public Integer getAlertId()
{
return (this.alertId);
}
/*******************************************************************************
** Setter for alertId
*******************************************************************************/
public void setAlertId(Integer alertId)
{
this.alertId = alertId;
}
/*******************************************************************************
** Fluent setter for alertId
*******************************************************************************/
public AlertsDelivery withAlertId(Integer alertId)
{
this.alertId = alertId;
return (this);
}
/*******************************************************************************
** Getter for alertEventId
*******************************************************************************/
public Integer getAlertEventId()
{
return (this.alertEventId);
}
/*******************************************************************************
** Setter for alertEventId
*******************************************************************************/
public void setAlertEventId(Integer alertEventId)
{
this.alertEventId = alertEventId;
}
/*******************************************************************************
** Fluent setter for alertEventId
*******************************************************************************/
public AlertsDelivery withAlertEventId(Integer alertEventId)
{
this.alertEventId = alertEventId;
return (this);
}
/*******************************************************************************
** Getter for subscriptionId
*******************************************************************************/
public Integer getSubscriptionId()
{
return (this.subscriptionId);
}
/*******************************************************************************
** Setter for subscriptionId
*******************************************************************************/
public void setSubscriptionId(Integer subscriptionId)
{
this.subscriptionId = subscriptionId;
}
/*******************************************************************************
** Fluent setter for subscriptionId
*******************************************************************************/
public AlertsDelivery withSubscriptionId(Integer subscriptionId)
{
this.subscriptionId = subscriptionId;
return (this);
}
/*******************************************************************************
** Getter for channelId
*******************************************************************************/
public Integer getChannelId()
{
return (this.channelId);
}
/*******************************************************************************
** Setter for channelId
*******************************************************************************/
public void setChannelId(Integer channelId)
{
this.channelId = channelId;
}
/*******************************************************************************
** Fluent setter for channelId
*******************************************************************************/
public AlertsDelivery withChannelId(Integer channelId)
{
this.channelId = channelId;
return (this);
}
/*******************************************************************************
** Getter for recipientUserId
*******************************************************************************/
public String getRecipientUserId()
{
return (this.recipientUserId);
}
/*******************************************************************************
** Setter for recipientUserId
*******************************************************************************/
public void setRecipientUserId(String recipientUserId)
{
this.recipientUserId = recipientUserId;
}
/*******************************************************************************
** Fluent setter for recipientUserId
*******************************************************************************/
public AlertsDelivery withRecipientUserId(String recipientUserId)
{
this.recipientUserId = recipientUserId;
return (this);
}
/*******************************************************************************
** Getter for recipientLabel
*******************************************************************************/
public String getRecipientLabel()
{
return (this.recipientLabel);
}
/*******************************************************************************
** Setter for recipientLabel
*******************************************************************************/
public void setRecipientLabel(String recipientLabel)
{
this.recipientLabel = recipientLabel;
}
/*******************************************************************************
** Fluent setter for recipientLabel
*******************************************************************************/
public AlertsDelivery withRecipientLabel(String recipientLabel)
{
this.recipientLabel = recipientLabel;
return (this);
}
/*******************************************************************************
** Getter for kind
*******************************************************************************/
public String getKind()
{
return (this.kind);
}
/*******************************************************************************
** Setter for kind
*******************************************************************************/
public void setKind(String kind)
{
this.kind = kind;
}
/*******************************************************************************
** Fluent setter for kind
*******************************************************************************/
public AlertsDelivery withKind(String kind)
{
this.kind = kind;
return (this);
}
/*******************************************************************************
** Getter for status
*******************************************************************************/
public String getStatus()
{
return (this.status);
}
/*******************************************************************************
** Setter for status
*******************************************************************************/
public void setStatus(String status)
{
this.status = status;
}
/*******************************************************************************
** Fluent setter for status
*******************************************************************************/
public AlertsDelivery withStatus(String status)
{
this.status = status;
return (this);
}
/*******************************************************************************
** Getter for suppressedReason
*******************************************************************************/
public String getSuppressedReason()
{
return (this.suppressedReason);
}
/*******************************************************************************
** Setter for suppressedReason
*******************************************************************************/
public void setSuppressedReason(String suppressedReason)
{
this.suppressedReason = suppressedReason;
}
/*******************************************************************************
** Fluent setter for suppressedReason
*******************************************************************************/
public AlertsDelivery withSuppressedReason(String suppressedReason)
{
this.suppressedReason = suppressedReason;
return (this);
}
/*******************************************************************************
** Getter for attempts
*******************************************************************************/
public Integer getAttempts()
{
return (this.attempts);
}
/*******************************************************************************
** Setter for attempts
*******************************************************************************/
public void setAttempts(Integer attempts)
{
this.attempts = attempts;
}
/*******************************************************************************
** Fluent setter for attempts
*******************************************************************************/
public AlertsDelivery withAttempts(Integer attempts)
{
this.attempts = attempts;
return (this);
}
/*******************************************************************************
** Getter for nextAttemptAt
*******************************************************************************/
public Instant getNextAttemptAt()
{
return (this.nextAttemptAt);
}
/*******************************************************************************
** Setter for nextAttemptAt
*******************************************************************************/
public void setNextAttemptAt(Instant nextAttemptAt)
{
this.nextAttemptAt = nextAttemptAt;
}
/*******************************************************************************
** Fluent setter for nextAttemptAt
*******************************************************************************/
public AlertsDelivery withNextAttemptAt(Instant nextAttemptAt)
{
this.nextAttemptAt = nextAttemptAt;
return (this);
}
/*******************************************************************************
** Getter for claimedUntil
*******************************************************************************/
public Instant getClaimedUntil()
{
return (this.claimedUntil);
}
/*******************************************************************************
** Setter for claimedUntil
*******************************************************************************/
public void setClaimedUntil(Instant claimedUntil)
{
this.claimedUntil = claimedUntil;
}
/*******************************************************************************
** Fluent setter for claimedUntil
*******************************************************************************/
public AlertsDelivery withClaimedUntil(Instant claimedUntil)
{
this.claimedUntil = claimedUntil;
return (this);
}
/*******************************************************************************
** Getter for sentAt
*******************************************************************************/
public Instant getSentAt()
{
return (this.sentAt);
}
/*******************************************************************************
** Setter for sentAt
*******************************************************************************/
public void setSentAt(Instant sentAt)
{
this.sentAt = sentAt;
}
/*******************************************************************************
** Fluent setter for sentAt
*******************************************************************************/
public AlertsDelivery withSentAt(Instant sentAt)
{
this.sentAt = sentAt;
return (this);
}
/*******************************************************************************
** Getter for providerMessageId
*******************************************************************************/
public String getProviderMessageId()
{
return (this.providerMessageId);
}
/*******************************************************************************
** Setter for providerMessageId
*******************************************************************************/
public void setProviderMessageId(String providerMessageId)
{
this.providerMessageId = providerMessageId;
}
/*******************************************************************************
** Fluent setter for providerMessageId
*******************************************************************************/
public AlertsDelivery withProviderMessageId(String providerMessageId)
{
this.providerMessageId = providerMessageId;
return (this);
}
/*******************************************************************************
** Getter for lastError
*******************************************************************************/
public String getLastError()
{
return (this.lastError);
}
/*******************************************************************************
** Setter for lastError
*******************************************************************************/
public void setLastError(String lastError)
{
this.lastError = lastError;
}
/*******************************************************************************
** Fluent setter for lastError
*******************************************************************************/
public AlertsDelivery withLastError(String lastError)
{
this.lastError = lastError;
return (this);
}
/*******************************************************************************
** Getter for createDate
*******************************************************************************/
public Instant getCreateDate()
{
return (this.createDate);
}
/*******************************************************************************
** Setter for createDate
*******************************************************************************/
public void setCreateDate(Instant createDate)
{
this.createDate = createDate;
}
/*******************************************************************************
** Fluent setter for createDate
*******************************************************************************/
public AlertsDelivery withCreateDate(Instant createDate)
{
this.createDate = createDate;
return (this);
}
/*******************************************************************************
** Getter for modifyDate
*******************************************************************************/
public Instant getModifyDate()
{
return (this.modifyDate);
}
/*******************************************************************************
** Setter for modifyDate
*******************************************************************************/
public void setModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
}
/*******************************************************************************
** Fluent setter for modifyDate
*******************************************************************************/
public AlertsDelivery withModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
return (this);
}
}
@@ -0,0 +1,396 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.model;
import java.time.Instant;
import com.kingsrook.qqq.backend.core.model.data.QField;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.data.QRecordEntity;
import com.kingsrook.qqq.backend.core.model.metadata.fields.ValueTooLongBehavior;
/*******************************************************************************
** The alert timeline: raised, repeated, acknowledged, snoozed, resolved,
** reopened, notified, commented and so on. Written by the qbit; read-only.
**
** Generated from the qbit-alerts schema (one definition for the entity,
** the Liquibase changelog and the test DDL).
*******************************************************************************/
public class AlertsEvent extends QRecordEntity
{
public static final String TABLE_NAME = "alerts_event";
@QField(isEditable = false, isPrimaryKey = true)
private Integer id;
@QField(isRequired = true, isEditable = false, possibleValueSourceName = "alerts_alert", label = "Alert")
private Integer alertId;
@QField(isEditable = false, maxLength = 30, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, possibleValueSourceName = "alerts_event_type")
private String eventType;
@QField(isEditable = false)
private Instant at;
@QField(isEditable = false, maxLength = 100, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, label = "User")
private String userId;
@QField(isEditable = false, maxLength = 200, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String fromValue;
@QField(isEditable = false, maxLength = 200, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String toValue;
@QField(isEditable = false, maxLength = 2000, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String note;
@QField(isEditable = false)
private Instant createDate;
@QField(isEditable = false)
private Instant modifyDate;
/*******************************************************************************
** Default constructor.
*******************************************************************************/
public AlertsEvent()
{
}
/*******************************************************************************
** Constructor that populates from a QRecord.
*******************************************************************************/
public AlertsEvent(QRecord record)
{
populateFromQRecord(record);
}
/*******************************************************************************
** Getter for id
*******************************************************************************/
public Integer getId()
{
return (this.id);
}
/*******************************************************************************
** Setter for id
*******************************************************************************/
public void setId(Integer id)
{
this.id = id;
}
/*******************************************************************************
** Fluent setter for id
*******************************************************************************/
public AlertsEvent withId(Integer id)
{
this.id = id;
return (this);
}
/*******************************************************************************
** Getter for alertId
*******************************************************************************/
public Integer getAlertId()
{
return (this.alertId);
}
/*******************************************************************************
** Setter for alertId
*******************************************************************************/
public void setAlertId(Integer alertId)
{
this.alertId = alertId;
}
/*******************************************************************************
** Fluent setter for alertId
*******************************************************************************/
public AlertsEvent withAlertId(Integer alertId)
{
this.alertId = alertId;
return (this);
}
/*******************************************************************************
** Getter for eventType
*******************************************************************************/
public String getEventType()
{
return (this.eventType);
}
/*******************************************************************************
** Setter for eventType
*******************************************************************************/
public void setEventType(String eventType)
{
this.eventType = eventType;
}
/*******************************************************************************
** Fluent setter for eventType
*******************************************************************************/
public AlertsEvent withEventType(String eventType)
{
this.eventType = eventType;
return (this);
}
/*******************************************************************************
** Getter for at
*******************************************************************************/
public Instant getAt()
{
return (this.at);
}
/*******************************************************************************
** Setter for at
*******************************************************************************/
public void setAt(Instant at)
{
this.at = at;
}
/*******************************************************************************
** Fluent setter for at
*******************************************************************************/
public AlertsEvent withAt(Instant at)
{
this.at = at;
return (this);
}
/*******************************************************************************
** Getter for userId
*******************************************************************************/
public String getUserId()
{
return (this.userId);
}
/*******************************************************************************
** Setter for userId
*******************************************************************************/
public void setUserId(String userId)
{
this.userId = userId;
}
/*******************************************************************************
** Fluent setter for userId
*******************************************************************************/
public AlertsEvent withUserId(String userId)
{
this.userId = userId;
return (this);
}
/*******************************************************************************
** Getter for fromValue
*******************************************************************************/
public String getFromValue()
{
return (this.fromValue);
}
/*******************************************************************************
** Setter for fromValue
*******************************************************************************/
public void setFromValue(String fromValue)
{
this.fromValue = fromValue;
}
/*******************************************************************************
** Fluent setter for fromValue
*******************************************************************************/
public AlertsEvent withFromValue(String fromValue)
{
this.fromValue = fromValue;
return (this);
}
/*******************************************************************************
** Getter for toValue
*******************************************************************************/
public String getToValue()
{
return (this.toValue);
}
/*******************************************************************************
** Setter for toValue
*******************************************************************************/
public void setToValue(String toValue)
{
this.toValue = toValue;
}
/*******************************************************************************
** Fluent setter for toValue
*******************************************************************************/
public AlertsEvent withToValue(String toValue)
{
this.toValue = toValue;
return (this);
}
/*******************************************************************************
** Getter for note
*******************************************************************************/
public String getNote()
{
return (this.note);
}
/*******************************************************************************
** Setter for note
*******************************************************************************/
public void setNote(String note)
{
this.note = note;
}
/*******************************************************************************
** Fluent setter for note
*******************************************************************************/
public AlertsEvent withNote(String note)
{
this.note = note;
return (this);
}
/*******************************************************************************
** Getter for createDate
*******************************************************************************/
public Instant getCreateDate()
{
return (this.createDate);
}
/*******************************************************************************
** Setter for createDate
*******************************************************************************/
public void setCreateDate(Instant createDate)
{
this.createDate = createDate;
}
/*******************************************************************************
** Fluent setter for createDate
*******************************************************************************/
public AlertsEvent withCreateDate(Instant createDate)
{
this.createDate = createDate;
return (this);
}
/*******************************************************************************
** Getter for modifyDate
*******************************************************************************/
public Instant getModifyDate()
{
return (this.modifyDate);
}
/*******************************************************************************
** Setter for modifyDate
*******************************************************************************/
public void setModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
}
/*******************************************************************************
** Fluent setter for modifyDate
*******************************************************************************/
public AlertsEvent withModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
return (this);
}
}
@@ -0,0 +1,397 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.model;
import java.time.Instant;
import com.kingsrook.qqq.backend.core.model.data.QField;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.data.QRecordEntity;
import com.kingsrook.qqq.backend.core.model.metadata.fields.ValueTooLongBehavior;
/*******************************************************************************
** A category of alerts for people ("Backups", "CDN"), optionally nested. The
** Alerts home groups by these, subscriptions target them, and every alert
** type belongs to one.
**
** Generated from the qbit-alerts schema (one definition for the entity,
** the Liquibase changelog and the test DDL).
*******************************************************************************/
public class AlertsGroup extends QRecordEntity
{
public static final String TABLE_NAME = "alerts_group";
@QField(isEditable = false, isPrimaryKey = true)
private Integer id;
@QField(isRequired = true, maxLength = 100, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String name;
@QField(isRequired = true, maxLength = 200, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String label;
@QField(possibleValueSourceName = "alerts_group", label = "Parent Group")
private Integer parentGroupId;
@QField(maxLength = 50, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String icon;
@QField()
private Integer sortOrder;
@QField()
private String description;
@QField(possibleValueSourceName = "alerts_team", label = "Owner Team")
private Integer ownerTeamId;
@QField(isEditable = false)
private Instant createDate;
@QField(isEditable = false)
private Instant modifyDate;
/*******************************************************************************
** Default constructor.
*******************************************************************************/
public AlertsGroup()
{
}
/*******************************************************************************
** Constructor that populates from a QRecord.
*******************************************************************************/
public AlertsGroup(QRecord record)
{
populateFromQRecord(record);
}
/*******************************************************************************
** Getter for id
*******************************************************************************/
public Integer getId()
{
return (this.id);
}
/*******************************************************************************
** Setter for id
*******************************************************************************/
public void setId(Integer id)
{
this.id = id;
}
/*******************************************************************************
** Fluent setter for id
*******************************************************************************/
public AlertsGroup withId(Integer id)
{
this.id = id;
return (this);
}
/*******************************************************************************
** Getter for name
*******************************************************************************/
public String getName()
{
return (this.name);
}
/*******************************************************************************
** Setter for name
*******************************************************************************/
public void setName(String name)
{
this.name = name;
}
/*******************************************************************************
** Fluent setter for name
*******************************************************************************/
public AlertsGroup withName(String name)
{
this.name = name;
return (this);
}
/*******************************************************************************
** Getter for label
*******************************************************************************/
public String getLabel()
{
return (this.label);
}
/*******************************************************************************
** Setter for label
*******************************************************************************/
public void setLabel(String label)
{
this.label = label;
}
/*******************************************************************************
** Fluent setter for label
*******************************************************************************/
public AlertsGroup withLabel(String label)
{
this.label = label;
return (this);
}
/*******************************************************************************
** Getter for parentGroupId
*******************************************************************************/
public Integer getParentGroupId()
{
return (this.parentGroupId);
}
/*******************************************************************************
** Setter for parentGroupId
*******************************************************************************/
public void setParentGroupId(Integer parentGroupId)
{
this.parentGroupId = parentGroupId;
}
/*******************************************************************************
** Fluent setter for parentGroupId
*******************************************************************************/
public AlertsGroup withParentGroupId(Integer parentGroupId)
{
this.parentGroupId = parentGroupId;
return (this);
}
/*******************************************************************************
** Getter for icon
*******************************************************************************/
public String getIcon()
{
return (this.icon);
}
/*******************************************************************************
** Setter for icon
*******************************************************************************/
public void setIcon(String icon)
{
this.icon = icon;
}
/*******************************************************************************
** Fluent setter for icon
*******************************************************************************/
public AlertsGroup withIcon(String icon)
{
this.icon = icon;
return (this);
}
/*******************************************************************************
** Getter for sortOrder
*******************************************************************************/
public Integer getSortOrder()
{
return (this.sortOrder);
}
/*******************************************************************************
** Setter for sortOrder
*******************************************************************************/
public void setSortOrder(Integer sortOrder)
{
this.sortOrder = sortOrder;
}
/*******************************************************************************
** Fluent setter for sortOrder
*******************************************************************************/
public AlertsGroup withSortOrder(Integer sortOrder)
{
this.sortOrder = sortOrder;
return (this);
}
/*******************************************************************************
** Getter for description
*******************************************************************************/
public String getDescription()
{
return (this.description);
}
/*******************************************************************************
** Setter for description
*******************************************************************************/
public void setDescription(String description)
{
this.description = description;
}
/*******************************************************************************
** Fluent setter for description
*******************************************************************************/
public AlertsGroup withDescription(String description)
{
this.description = description;
return (this);
}
/*******************************************************************************
** Getter for ownerTeamId
*******************************************************************************/
public Integer getOwnerTeamId()
{
return (this.ownerTeamId);
}
/*******************************************************************************
** Setter for ownerTeamId
*******************************************************************************/
public void setOwnerTeamId(Integer ownerTeamId)
{
this.ownerTeamId = ownerTeamId;
}
/*******************************************************************************
** Fluent setter for ownerTeamId
*******************************************************************************/
public AlertsGroup withOwnerTeamId(Integer ownerTeamId)
{
this.ownerTeamId = ownerTeamId;
return (this);
}
/*******************************************************************************
** Getter for createDate
*******************************************************************************/
public Instant getCreateDate()
{
return (this.createDate);
}
/*******************************************************************************
** Setter for createDate
*******************************************************************************/
public void setCreateDate(Instant createDate)
{
this.createDate = createDate;
}
/*******************************************************************************
** Fluent setter for createDate
*******************************************************************************/
public AlertsGroup withCreateDate(Instant createDate)
{
this.createDate = createDate;
return (this);
}
/*******************************************************************************
** Getter for modifyDate
*******************************************************************************/
public Instant getModifyDate()
{
return (this.modifyDate);
}
/*******************************************************************************
** Setter for modifyDate
*******************************************************************************/
public void setModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
}
/*******************************************************************************
** Fluent setter for modifyDate
*******************************************************************************/
public AlertsGroup withModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
return (this);
}
}
@@ -0,0 +1,260 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.model;
import java.time.Instant;
import com.kingsrook.qqq.backend.core.model.data.QField;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.data.QRecordEntity;
import com.kingsrook.qqq.backend.core.model.metadata.fields.ValueTooLongBehavior;
/*******************************************************************************
** The last time each dead-man's switch beat (QAlerts.heartbeat, or a process
** that completed). Heartbeat monitors watch these.
**
** Generated from the qbit-alerts schema (one definition for the entity,
** the Liquibase changelog and the test DDL).
*******************************************************************************/
public class AlertsHeartbeat extends QRecordEntity
{
public static final String TABLE_NAME = "alerts_heartbeat";
@QField(isEditable = false, isPrimaryKey = true)
private Integer id;
@QField(isRequired = true, isEditable = false, maxLength = 300, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String heartbeatKey;
@QField(isEditable = false)
private Instant lastBeatAt;
@QField(isEditable = false)
private Integer beatCount;
@QField(isEditable = false)
private Instant createDate;
@QField(isEditable = false)
private Instant modifyDate;
/*******************************************************************************
** Default constructor.
*******************************************************************************/
public AlertsHeartbeat()
{
}
/*******************************************************************************
** Constructor that populates from a QRecord.
*******************************************************************************/
public AlertsHeartbeat(QRecord record)
{
populateFromQRecord(record);
}
/*******************************************************************************
** Getter for id
*******************************************************************************/
public Integer getId()
{
return (this.id);
}
/*******************************************************************************
** Setter for id
*******************************************************************************/
public void setId(Integer id)
{
this.id = id;
}
/*******************************************************************************
** Fluent setter for id
*******************************************************************************/
public AlertsHeartbeat withId(Integer id)
{
this.id = id;
return (this);
}
/*******************************************************************************
** Getter for heartbeatKey
*******************************************************************************/
public String getHeartbeatKey()
{
return (this.heartbeatKey);
}
/*******************************************************************************
** Setter for heartbeatKey
*******************************************************************************/
public void setHeartbeatKey(String heartbeatKey)
{
this.heartbeatKey = heartbeatKey;
}
/*******************************************************************************
** Fluent setter for heartbeatKey
*******************************************************************************/
public AlertsHeartbeat withHeartbeatKey(String heartbeatKey)
{
this.heartbeatKey = heartbeatKey;
return (this);
}
/*******************************************************************************
** Getter for lastBeatAt
*******************************************************************************/
public Instant getLastBeatAt()
{
return (this.lastBeatAt);
}
/*******************************************************************************
** Setter for lastBeatAt
*******************************************************************************/
public void setLastBeatAt(Instant lastBeatAt)
{
this.lastBeatAt = lastBeatAt;
}
/*******************************************************************************
** Fluent setter for lastBeatAt
*******************************************************************************/
public AlertsHeartbeat withLastBeatAt(Instant lastBeatAt)
{
this.lastBeatAt = lastBeatAt;
return (this);
}
/*******************************************************************************
** Getter for beatCount
*******************************************************************************/
public Integer getBeatCount()
{
return (this.beatCount);
}
/*******************************************************************************
** Setter for beatCount
*******************************************************************************/
public void setBeatCount(Integer beatCount)
{
this.beatCount = beatCount;
}
/*******************************************************************************
** Fluent setter for beatCount
*******************************************************************************/
public AlertsHeartbeat withBeatCount(Integer beatCount)
{
this.beatCount = beatCount;
return (this);
}
/*******************************************************************************
** Getter for createDate
*******************************************************************************/
public Instant getCreateDate()
{
return (this.createDate);
}
/*******************************************************************************
** Setter for createDate
*******************************************************************************/
public void setCreateDate(Instant createDate)
{
this.createDate = createDate;
}
/*******************************************************************************
** Fluent setter for createDate
*******************************************************************************/
public AlertsHeartbeat withCreateDate(Instant createDate)
{
this.createDate = createDate;
return (this);
}
/*******************************************************************************
** Getter for modifyDate
*******************************************************************************/
public Instant getModifyDate()
{
return (this.modifyDate);
}
/*******************************************************************************
** Setter for modifyDate
*******************************************************************************/
public void setModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
}
/*******************************************************************************
** Fluent setter for modifyDate
*******************************************************************************/
public AlertsHeartbeat withModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
return (this);
}
}
@@ -0,0 +1,907 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.model;
import java.time.Instant;
import com.kingsrook.qqq.backend.core.model.data.QField;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.data.QRecordEntity;
import com.kingsrook.qqq.backend.core.model.metadata.fields.ValueTooLongBehavior;
/*******************************************************************************
** A configured check that raises alerts of a type: table query, aggregate
** threshold, heartbeat, process failure or code check. Seeded monitors may be
** tuned or disabled, not deleted.
**
** Generated from the qbit-alerts schema (one definition for the entity,
** the Liquibase changelog and the test DDL).
*******************************************************************************/
public class AlertsMonitor extends QRecordEntity
{
public static final String TABLE_NAME = "alerts_monitor";
@QField(isEditable = false, isPrimaryKey = true)
private Integer id;
@QField(isRequired = true, maxLength = 200, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String name;
@QField(isRequired = true, possibleValueSourceName = "alerts_type", label = "Alert Type")
private Integer alertTypeId;
@QField(isRequired = true, maxLength = 20, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, possibleValueSourceName = "alerts_monitor_kind")
private String kind;
@QField()
private Boolean enabled;
@QField(isEditable = false)
private Boolean seeded;
@QField(isEditable = false, maxLength = 100, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, label = "Source")
private String sourceName;
@QField()
private String description;
@QField()
private String definition;
@QField(label = "One Alert per Record")
private Boolean perRecord;
@QField(maxLength = 16, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, possibleValueSourceName = "alerts_severity")
private String severity;
@QField(label = "Check Every (Seconds)")
private Integer scheduleSeconds;
@QField(label = "Must Hold For (Minutes)")
private Integer forMinutes;
@QField(isEditable = false)
private Instant nextRunAt;
@QField(isEditable = false, maxLength = 100, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String claimedBy;
@QField(isEditable = false)
private Instant claimedUntil;
@QField(isEditable = false)
private Instant lastRunAt;
@QField(isEditable = false, maxLength = 20, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, possibleValueSourceName = "alerts_monitor_status")
private String lastStatus;
@QField(isEditable = false, maxLength = 200, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String lastValue;
@QField(isEditable = false, maxLength = 2000, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String lastError;
@QField(isEditable = false, label = "Last Elapsed (ms)")
private Integer lastElapsedMs;
@QField(isEditable = false)
private Integer consecutiveFailures;
@QField(isEditable = false)
private Instant conditionSince;
@QField(isEditable = false)
private Instant createDate;
@QField(isEditable = false)
private Instant modifyDate;
/*******************************************************************************
** Default constructor.
*******************************************************************************/
public AlertsMonitor()
{
}
/*******************************************************************************
** Constructor that populates from a QRecord.
*******************************************************************************/
public AlertsMonitor(QRecord record)
{
populateFromQRecord(record);
}
/*******************************************************************************
** Getter for id
*******************************************************************************/
public Integer getId()
{
return (this.id);
}
/*******************************************************************************
** Setter for id
*******************************************************************************/
public void setId(Integer id)
{
this.id = id;
}
/*******************************************************************************
** Fluent setter for id
*******************************************************************************/
public AlertsMonitor withId(Integer id)
{
this.id = id;
return (this);
}
/*******************************************************************************
** Getter for name
*******************************************************************************/
public String getName()
{
return (this.name);
}
/*******************************************************************************
** Setter for name
*******************************************************************************/
public void setName(String name)
{
this.name = name;
}
/*******************************************************************************
** Fluent setter for name
*******************************************************************************/
public AlertsMonitor withName(String name)
{
this.name = name;
return (this);
}
/*******************************************************************************
** Getter for alertTypeId
*******************************************************************************/
public Integer getAlertTypeId()
{
return (this.alertTypeId);
}
/*******************************************************************************
** Setter for alertTypeId
*******************************************************************************/
public void setAlertTypeId(Integer alertTypeId)
{
this.alertTypeId = alertTypeId;
}
/*******************************************************************************
** Fluent setter for alertTypeId
*******************************************************************************/
public AlertsMonitor withAlertTypeId(Integer alertTypeId)
{
this.alertTypeId = alertTypeId;
return (this);
}
/*******************************************************************************
** Getter for kind
*******************************************************************************/
public String getKind()
{
return (this.kind);
}
/*******************************************************************************
** Setter for kind
*******************************************************************************/
public void setKind(String kind)
{
this.kind = kind;
}
/*******************************************************************************
** Fluent setter for kind
*******************************************************************************/
public AlertsMonitor withKind(String kind)
{
this.kind = kind;
return (this);
}
/*******************************************************************************
** Getter for enabled
*******************************************************************************/
public Boolean getEnabled()
{
return (this.enabled);
}
/*******************************************************************************
** Setter for enabled
*******************************************************************************/
public void setEnabled(Boolean enabled)
{
this.enabled = enabled;
}
/*******************************************************************************
** Fluent setter for enabled
*******************************************************************************/
public AlertsMonitor withEnabled(Boolean enabled)
{
this.enabled = enabled;
return (this);
}
/*******************************************************************************
** Getter for seeded
*******************************************************************************/
public Boolean getSeeded()
{
return (this.seeded);
}
/*******************************************************************************
** Setter for seeded
*******************************************************************************/
public void setSeeded(Boolean seeded)
{
this.seeded = seeded;
}
/*******************************************************************************
** Fluent setter for seeded
*******************************************************************************/
public AlertsMonitor withSeeded(Boolean seeded)
{
this.seeded = seeded;
return (this);
}
/*******************************************************************************
** Getter for sourceName
*******************************************************************************/
public String getSourceName()
{
return (this.sourceName);
}
/*******************************************************************************
** Setter for sourceName
*******************************************************************************/
public void setSourceName(String sourceName)
{
this.sourceName = sourceName;
}
/*******************************************************************************
** Fluent setter for sourceName
*******************************************************************************/
public AlertsMonitor withSourceName(String sourceName)
{
this.sourceName = sourceName;
return (this);
}
/*******************************************************************************
** Getter for description
*******************************************************************************/
public String getDescription()
{
return (this.description);
}
/*******************************************************************************
** Setter for description
*******************************************************************************/
public void setDescription(String description)
{
this.description = description;
}
/*******************************************************************************
** Fluent setter for description
*******************************************************************************/
public AlertsMonitor withDescription(String description)
{
this.description = description;
return (this);
}
/*******************************************************************************
** Getter for definition
*******************************************************************************/
public String getDefinition()
{
return (this.definition);
}
/*******************************************************************************
** Setter for definition
*******************************************************************************/
public void setDefinition(String definition)
{
this.definition = definition;
}
/*******************************************************************************
** Fluent setter for definition
*******************************************************************************/
public AlertsMonitor withDefinition(String definition)
{
this.definition = definition;
return (this);
}
/*******************************************************************************
** Getter for perRecord
*******************************************************************************/
public Boolean getPerRecord()
{
return (this.perRecord);
}
/*******************************************************************************
** Setter for perRecord
*******************************************************************************/
public void setPerRecord(Boolean perRecord)
{
this.perRecord = perRecord;
}
/*******************************************************************************
** Fluent setter for perRecord
*******************************************************************************/
public AlertsMonitor withPerRecord(Boolean perRecord)
{
this.perRecord = perRecord;
return (this);
}
/*******************************************************************************
** Getter for severity
*******************************************************************************/
public String getSeverity()
{
return (this.severity);
}
/*******************************************************************************
** Setter for severity
*******************************************************************************/
public void setSeverity(String severity)
{
this.severity = severity;
}
/*******************************************************************************
** Fluent setter for severity
*******************************************************************************/
public AlertsMonitor withSeverity(String severity)
{
this.severity = severity;
return (this);
}
/*******************************************************************************
** Getter for scheduleSeconds
*******************************************************************************/
public Integer getScheduleSeconds()
{
return (this.scheduleSeconds);
}
/*******************************************************************************
** Setter for scheduleSeconds
*******************************************************************************/
public void setScheduleSeconds(Integer scheduleSeconds)
{
this.scheduleSeconds = scheduleSeconds;
}
/*******************************************************************************
** Fluent setter for scheduleSeconds
*******************************************************************************/
public AlertsMonitor withScheduleSeconds(Integer scheduleSeconds)
{
this.scheduleSeconds = scheduleSeconds;
return (this);
}
/*******************************************************************************
** Getter for forMinutes
*******************************************************************************/
public Integer getForMinutes()
{
return (this.forMinutes);
}
/*******************************************************************************
** Setter for forMinutes
*******************************************************************************/
public void setForMinutes(Integer forMinutes)
{
this.forMinutes = forMinutes;
}
/*******************************************************************************
** Fluent setter for forMinutes
*******************************************************************************/
public AlertsMonitor withForMinutes(Integer forMinutes)
{
this.forMinutes = forMinutes;
return (this);
}
/*******************************************************************************
** Getter for nextRunAt
*******************************************************************************/
public Instant getNextRunAt()
{
return (this.nextRunAt);
}
/*******************************************************************************
** Setter for nextRunAt
*******************************************************************************/
public void setNextRunAt(Instant nextRunAt)
{
this.nextRunAt = nextRunAt;
}
/*******************************************************************************
** Fluent setter for nextRunAt
*******************************************************************************/
public AlertsMonitor withNextRunAt(Instant nextRunAt)
{
this.nextRunAt = nextRunAt;
return (this);
}
/*******************************************************************************
** Getter for claimedBy
*******************************************************************************/
public String getClaimedBy()
{
return (this.claimedBy);
}
/*******************************************************************************
** Setter for claimedBy
*******************************************************************************/
public void setClaimedBy(String claimedBy)
{
this.claimedBy = claimedBy;
}
/*******************************************************************************
** Fluent setter for claimedBy
*******************************************************************************/
public AlertsMonitor withClaimedBy(String claimedBy)
{
this.claimedBy = claimedBy;
return (this);
}
/*******************************************************************************
** Getter for claimedUntil
*******************************************************************************/
public Instant getClaimedUntil()
{
return (this.claimedUntil);
}
/*******************************************************************************
** Setter for claimedUntil
*******************************************************************************/
public void setClaimedUntil(Instant claimedUntil)
{
this.claimedUntil = claimedUntil;
}
/*******************************************************************************
** Fluent setter for claimedUntil
*******************************************************************************/
public AlertsMonitor withClaimedUntil(Instant claimedUntil)
{
this.claimedUntil = claimedUntil;
return (this);
}
/*******************************************************************************
** Getter for lastRunAt
*******************************************************************************/
public Instant getLastRunAt()
{
return (this.lastRunAt);
}
/*******************************************************************************
** Setter for lastRunAt
*******************************************************************************/
public void setLastRunAt(Instant lastRunAt)
{
this.lastRunAt = lastRunAt;
}
/*******************************************************************************
** Fluent setter for lastRunAt
*******************************************************************************/
public AlertsMonitor withLastRunAt(Instant lastRunAt)
{
this.lastRunAt = lastRunAt;
return (this);
}
/*******************************************************************************
** Getter for lastStatus
*******************************************************************************/
public String getLastStatus()
{
return (this.lastStatus);
}
/*******************************************************************************
** Setter for lastStatus
*******************************************************************************/
public void setLastStatus(String lastStatus)
{
this.lastStatus = lastStatus;
}
/*******************************************************************************
** Fluent setter for lastStatus
*******************************************************************************/
public AlertsMonitor withLastStatus(String lastStatus)
{
this.lastStatus = lastStatus;
return (this);
}
/*******************************************************************************
** Getter for lastValue
*******************************************************************************/
public String getLastValue()
{
return (this.lastValue);
}
/*******************************************************************************
** Setter for lastValue
*******************************************************************************/
public void setLastValue(String lastValue)
{
this.lastValue = lastValue;
}
/*******************************************************************************
** Fluent setter for lastValue
*******************************************************************************/
public AlertsMonitor withLastValue(String lastValue)
{
this.lastValue = lastValue;
return (this);
}
/*******************************************************************************
** Getter for lastError
*******************************************************************************/
public String getLastError()
{
return (this.lastError);
}
/*******************************************************************************
** Setter for lastError
*******************************************************************************/
public void setLastError(String lastError)
{
this.lastError = lastError;
}
/*******************************************************************************
** Fluent setter for lastError
*******************************************************************************/
public AlertsMonitor withLastError(String lastError)
{
this.lastError = lastError;
return (this);
}
/*******************************************************************************
** Getter for lastElapsedMs
*******************************************************************************/
public Integer getLastElapsedMs()
{
return (this.lastElapsedMs);
}
/*******************************************************************************
** Setter for lastElapsedMs
*******************************************************************************/
public void setLastElapsedMs(Integer lastElapsedMs)
{
this.lastElapsedMs = lastElapsedMs;
}
/*******************************************************************************
** Fluent setter for lastElapsedMs
*******************************************************************************/
public AlertsMonitor withLastElapsedMs(Integer lastElapsedMs)
{
this.lastElapsedMs = lastElapsedMs;
return (this);
}
/*******************************************************************************
** Getter for consecutiveFailures
*******************************************************************************/
public Integer getConsecutiveFailures()
{
return (this.consecutiveFailures);
}
/*******************************************************************************
** Setter for consecutiveFailures
*******************************************************************************/
public void setConsecutiveFailures(Integer consecutiveFailures)
{
this.consecutiveFailures = consecutiveFailures;
}
/*******************************************************************************
** Fluent setter for consecutiveFailures
*******************************************************************************/
public AlertsMonitor withConsecutiveFailures(Integer consecutiveFailures)
{
this.consecutiveFailures = consecutiveFailures;
return (this);
}
/*******************************************************************************
** Getter for conditionSince
*******************************************************************************/
public Instant getConditionSince()
{
return (this.conditionSince);
}
/*******************************************************************************
** Setter for conditionSince
*******************************************************************************/
public void setConditionSince(Instant conditionSince)
{
this.conditionSince = conditionSince;
}
/*******************************************************************************
** Fluent setter for conditionSince
*******************************************************************************/
public AlertsMonitor withConditionSince(Instant conditionSince)
{
this.conditionSince = conditionSince;
return (this);
}
/*******************************************************************************
** Getter for createDate
*******************************************************************************/
public Instant getCreateDate()
{
return (this.createDate);
}
/*******************************************************************************
** Setter for createDate
*******************************************************************************/
public void setCreateDate(Instant createDate)
{
this.createDate = createDate;
}
/*******************************************************************************
** Fluent setter for createDate
*******************************************************************************/
public AlertsMonitor withCreateDate(Instant createDate)
{
this.createDate = createDate;
return (this);
}
/*******************************************************************************
** Getter for modifyDate
*******************************************************************************/
public Instant getModifyDate()
{
return (this.modifyDate);
}
/*******************************************************************************
** Setter for modifyDate
*******************************************************************************/
public void setModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
}
/*******************************************************************************
** Fluent setter for modifyDate
*******************************************************************************/
public AlertsMonitor withModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
return (this);
}
}
@@ -0,0 +1,464 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.model;
import java.time.Instant;
import com.kingsrook.qqq.backend.core.model.data.QField;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.data.QRecordEntity;
import com.kingsrook.qqq.backend.core.model.metadata.fields.ValueTooLongBehavior;
/*******************************************************************************
** A maintenance window or mute rule that silences notifications (or, for
** admins, suppresses alerts) for a scope and a time.
**
** Generated from the qbit-alerts schema (one definition for the entity,
** the Liquibase changelog and the test DDL).
*******************************************************************************/
public class AlertsMute extends QRecordEntity
{
public static final String TABLE_NAME = "alerts_mute";
@QField(isEditable = false, isPrimaryKey = true)
private Integer id;
@QField(isRequired = true, maxLength = 200, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String name;
@QField(maxLength = 2000, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String reason;
@QField(isRequired = true, maxLength = 20, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, possibleValueSourceName = "alerts_scope_type")
private String scopeType;
@QField(maxLength = 300, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String scopeValue;
@QField(isRequired = true)
private Instant startsAt;
@QField(isRequired = true)
private Instant endsAt;
@QField(maxLength = 30, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, possibleValueSourceName = "alerts_mute_effect")
private String effect;
@QField()
private Boolean enabled;
@QField(isEditable = false, maxLength = 100, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, label = "Created By")
private String createdByUserId;
@QField(isEditable = false)
private Instant createDate;
@QField(isEditable = false)
private Instant modifyDate;
/*******************************************************************************
** Default constructor.
*******************************************************************************/
public AlertsMute()
{
}
/*******************************************************************************
** Constructor that populates from a QRecord.
*******************************************************************************/
public AlertsMute(QRecord record)
{
populateFromQRecord(record);
}
/*******************************************************************************
** Getter for id
*******************************************************************************/
public Integer getId()
{
return (this.id);
}
/*******************************************************************************
** Setter for id
*******************************************************************************/
public void setId(Integer id)
{
this.id = id;
}
/*******************************************************************************
** Fluent setter for id
*******************************************************************************/
public AlertsMute withId(Integer id)
{
this.id = id;
return (this);
}
/*******************************************************************************
** Getter for name
*******************************************************************************/
public String getName()
{
return (this.name);
}
/*******************************************************************************
** Setter for name
*******************************************************************************/
public void setName(String name)
{
this.name = name;
}
/*******************************************************************************
** Fluent setter for name
*******************************************************************************/
public AlertsMute withName(String name)
{
this.name = name;
return (this);
}
/*******************************************************************************
** Getter for reason
*******************************************************************************/
public String getReason()
{
return (this.reason);
}
/*******************************************************************************
** Setter for reason
*******************************************************************************/
public void setReason(String reason)
{
this.reason = reason;
}
/*******************************************************************************
** Fluent setter for reason
*******************************************************************************/
public AlertsMute withReason(String reason)
{
this.reason = reason;
return (this);
}
/*******************************************************************************
** Getter for scopeType
*******************************************************************************/
public String getScopeType()
{
return (this.scopeType);
}
/*******************************************************************************
** Setter for scopeType
*******************************************************************************/
public void setScopeType(String scopeType)
{
this.scopeType = scopeType;
}
/*******************************************************************************
** Fluent setter for scopeType
*******************************************************************************/
public AlertsMute withScopeType(String scopeType)
{
this.scopeType = scopeType;
return (this);
}
/*******************************************************************************
** Getter for scopeValue
*******************************************************************************/
public String getScopeValue()
{
return (this.scopeValue);
}
/*******************************************************************************
** Setter for scopeValue
*******************************************************************************/
public void setScopeValue(String scopeValue)
{
this.scopeValue = scopeValue;
}
/*******************************************************************************
** Fluent setter for scopeValue
*******************************************************************************/
public AlertsMute withScopeValue(String scopeValue)
{
this.scopeValue = scopeValue;
return (this);
}
/*******************************************************************************
** Getter for startsAt
*******************************************************************************/
public Instant getStartsAt()
{
return (this.startsAt);
}
/*******************************************************************************
** Setter for startsAt
*******************************************************************************/
public void setStartsAt(Instant startsAt)
{
this.startsAt = startsAt;
}
/*******************************************************************************
** Fluent setter for startsAt
*******************************************************************************/
public AlertsMute withStartsAt(Instant startsAt)
{
this.startsAt = startsAt;
return (this);
}
/*******************************************************************************
** Getter for endsAt
*******************************************************************************/
public Instant getEndsAt()
{
return (this.endsAt);
}
/*******************************************************************************
** Setter for endsAt
*******************************************************************************/
public void setEndsAt(Instant endsAt)
{
this.endsAt = endsAt;
}
/*******************************************************************************
** Fluent setter for endsAt
*******************************************************************************/
public AlertsMute withEndsAt(Instant endsAt)
{
this.endsAt = endsAt;
return (this);
}
/*******************************************************************************
** Getter for effect
*******************************************************************************/
public String getEffect()
{
return (this.effect);
}
/*******************************************************************************
** Setter for effect
*******************************************************************************/
public void setEffect(String effect)
{
this.effect = effect;
}
/*******************************************************************************
** Fluent setter for effect
*******************************************************************************/
public AlertsMute withEffect(String effect)
{
this.effect = effect;
return (this);
}
/*******************************************************************************
** Getter for enabled
*******************************************************************************/
public Boolean getEnabled()
{
return (this.enabled);
}
/*******************************************************************************
** Setter for enabled
*******************************************************************************/
public void setEnabled(Boolean enabled)
{
this.enabled = enabled;
}
/*******************************************************************************
** Fluent setter for enabled
*******************************************************************************/
public AlertsMute withEnabled(Boolean enabled)
{
this.enabled = enabled;
return (this);
}
/*******************************************************************************
** Getter for createdByUserId
*******************************************************************************/
public String getCreatedByUserId()
{
return (this.createdByUserId);
}
/*******************************************************************************
** Setter for createdByUserId
*******************************************************************************/
public void setCreatedByUserId(String createdByUserId)
{
this.createdByUserId = createdByUserId;
}
/*******************************************************************************
** Fluent setter for createdByUserId
*******************************************************************************/
public AlertsMute withCreatedByUserId(String createdByUserId)
{
this.createdByUserId = createdByUserId;
return (this);
}
/*******************************************************************************
** Getter for createDate
*******************************************************************************/
public Instant getCreateDate()
{
return (this.createDate);
}
/*******************************************************************************
** Setter for createDate
*******************************************************************************/
public void setCreateDate(Instant createDate)
{
this.createDate = createDate;
}
/*******************************************************************************
** Fluent setter for createDate
*******************************************************************************/
public AlertsMute withCreateDate(Instant createDate)
{
this.createDate = createDate;
return (this);
}
/*******************************************************************************
** Getter for modifyDate
*******************************************************************************/
public Instant getModifyDate()
{
return (this.modifyDate);
}
/*******************************************************************************
** Setter for modifyDate
*******************************************************************************/
public void setModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
}
/*******************************************************************************
** Fluent setter for modifyDate
*******************************************************************************/
public AlertsMute withModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
return (this);
}
}
@@ -0,0 +1,798 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.model;
import java.time.Instant;
import com.kingsrook.qqq.backend.core.model.data.QField;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.data.QRecordEntity;
import com.kingsrook.qqq.backend.core.model.metadata.fields.ValueTooLongBehavior;
/*******************************************************************************
** A message for people: an announcement an admin writes, or one a producer emits (a failed job, a share, a security notice, a release). One recipient row per user it reaches.
**
** Generated from the qbit-alerts schema (one definition for the entity,
** the Liquibase changelog and the test DDL).
*******************************************************************************/
public class AlertsNotification extends QRecordEntity
{
public static final String TABLE_NAME = "alerts_notification";
@QField(isEditable = false, isPrimaryKey = true)
private Integer id;
@QField(isRequired = true, maxLength = 200, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String title;
@QField(label = "Message")
private String body;
@QField(isRequired = true, maxLength = 16, possibleValueSourceName = "alerts_notification_severity")
private String severity;
@QField(isRequired = true, maxLength = 16, possibleValueSourceName = "alerts_notification_category")
private String category;
@QField(isEditable = false, maxLength = 16, possibleValueSourceName = "alerts_notification_status")
private String status;
@QField(maxLength = 100, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, label = "Source")
private String sourceName;
@QField(maxLength = 200, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String sourceKey;
@QField(maxLength = 100, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, label = "Source Table")
private String sourceTableName;
@QField(maxLength = 100, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, label = "Source Record")
private String sourceRecordId;
@QField(maxLength = 1000, valueTooLongBehavior = ValueTooLongBehavior.ERROR, label = "Link")
private String linkUrl;
@QField(maxLength = 200, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String linkLabel;
@QField(isRequired = true, maxLength = 16, possibleValueSourceName = "alerts_audience_type", label = "Audience")
private String audienceType;
@QField(label = "Audience Members")
private String audienceValue;
@QField()
private Instant publishAt;
@QField()
private Instant expireAt;
@QField(label = "Sticky Banner")
private Boolean sticky;
@QField(isEditable = false, maxLength = 100, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, label = "Author")
private String authorUserId;
@QField(isEditable = false)
private Instant sentAt;
@QField(isEditable = false)
private Instant retractedAt;
@QField(isEditable = false, label = "Recipients")
private Integer recipientCount;
@QField(isEditable = false, label = "Read")
private Integer readCount;
@QField(isEditable = false)
private Instant createDate;
@QField(isEditable = false)
private Instant modifyDate;
/*******************************************************************************
** Default constructor.
*******************************************************************************/
public AlertsNotification()
{
}
/*******************************************************************************
** Constructor that populates from a QRecord.
*******************************************************************************/
public AlertsNotification(QRecord record)
{
populateFromQRecord(record);
}
/*******************************************************************************
** Getter for id
*******************************************************************************/
public Integer getId()
{
return (this.id);
}
/*******************************************************************************
** Setter for id
*******************************************************************************/
public void setId(Integer id)
{
this.id = id;
}
/*******************************************************************************
** Fluent setter for id
*******************************************************************************/
public AlertsNotification withId(Integer id)
{
this.id = id;
return (this);
}
/*******************************************************************************
** Getter for title
*******************************************************************************/
public String getTitle()
{
return (this.title);
}
/*******************************************************************************
** Setter for title
*******************************************************************************/
public void setTitle(String title)
{
this.title = title;
}
/*******************************************************************************
** Fluent setter for title
*******************************************************************************/
public AlertsNotification withTitle(String title)
{
this.title = title;
return (this);
}
/*******************************************************************************
** Getter for body
*******************************************************************************/
public String getBody()
{
return (this.body);
}
/*******************************************************************************
** Setter for body
*******************************************************************************/
public void setBody(String body)
{
this.body = body;
}
/*******************************************************************************
** Fluent setter for body
*******************************************************************************/
public AlertsNotification withBody(String body)
{
this.body = body;
return (this);
}
/*******************************************************************************
** Getter for severity
*******************************************************************************/
public String getSeverity()
{
return (this.severity);
}
/*******************************************************************************
** Setter for severity
*******************************************************************************/
public void setSeverity(String severity)
{
this.severity = severity;
}
/*******************************************************************************
** Fluent setter for severity
*******************************************************************************/
public AlertsNotification withSeverity(String severity)
{
this.severity = severity;
return (this);
}
/*******************************************************************************
** Getter for category
*******************************************************************************/
public String getCategory()
{
return (this.category);
}
/*******************************************************************************
** Setter for category
*******************************************************************************/
public void setCategory(String category)
{
this.category = category;
}
/*******************************************************************************
** Fluent setter for category
*******************************************************************************/
public AlertsNotification withCategory(String category)
{
this.category = category;
return (this);
}
/*******************************************************************************
** Getter for status
*******************************************************************************/
public String getStatus()
{
return (this.status);
}
/*******************************************************************************
** Setter for status
*******************************************************************************/
public void setStatus(String status)
{
this.status = status;
}
/*******************************************************************************
** Fluent setter for status
*******************************************************************************/
public AlertsNotification withStatus(String status)
{
this.status = status;
return (this);
}
/*******************************************************************************
** Getter for sourceName
*******************************************************************************/
public String getSourceName()
{
return (this.sourceName);
}
/*******************************************************************************
** Setter for sourceName
*******************************************************************************/
public void setSourceName(String sourceName)
{
this.sourceName = sourceName;
}
/*******************************************************************************
** Fluent setter for sourceName
*******************************************************************************/
public AlertsNotification withSourceName(String sourceName)
{
this.sourceName = sourceName;
return (this);
}
/*******************************************************************************
** Getter for sourceKey
*******************************************************************************/
public String getSourceKey()
{
return (this.sourceKey);
}
/*******************************************************************************
** Setter for sourceKey
*******************************************************************************/
public void setSourceKey(String sourceKey)
{
this.sourceKey = sourceKey;
}
/*******************************************************************************
** Fluent setter for sourceKey
*******************************************************************************/
public AlertsNotification withSourceKey(String sourceKey)
{
this.sourceKey = sourceKey;
return (this);
}
/*******************************************************************************
** Getter for sourceTableName
*******************************************************************************/
public String getSourceTableName()
{
return (this.sourceTableName);
}
/*******************************************************************************
** Setter for sourceTableName
*******************************************************************************/
public void setSourceTableName(String sourceTableName)
{
this.sourceTableName = sourceTableName;
}
/*******************************************************************************
** Fluent setter for sourceTableName
*******************************************************************************/
public AlertsNotification withSourceTableName(String sourceTableName)
{
this.sourceTableName = sourceTableName;
return (this);
}
/*******************************************************************************
** Getter for sourceRecordId
*******************************************************************************/
public String getSourceRecordId()
{
return (this.sourceRecordId);
}
/*******************************************************************************
** Setter for sourceRecordId
*******************************************************************************/
public void setSourceRecordId(String sourceRecordId)
{
this.sourceRecordId = sourceRecordId;
}
/*******************************************************************************
** Fluent setter for sourceRecordId
*******************************************************************************/
public AlertsNotification withSourceRecordId(String sourceRecordId)
{
this.sourceRecordId = sourceRecordId;
return (this);
}
/*******************************************************************************
** Getter for linkUrl
*******************************************************************************/
public String getLinkUrl()
{
return (this.linkUrl);
}
/*******************************************************************************
** Setter for linkUrl
*******************************************************************************/
public void setLinkUrl(String linkUrl)
{
this.linkUrl = linkUrl;
}
/*******************************************************************************
** Fluent setter for linkUrl
*******************************************************************************/
public AlertsNotification withLinkUrl(String linkUrl)
{
this.linkUrl = linkUrl;
return (this);
}
/*******************************************************************************
** Getter for linkLabel
*******************************************************************************/
public String getLinkLabel()
{
return (this.linkLabel);
}
/*******************************************************************************
** Setter for linkLabel
*******************************************************************************/
public void setLinkLabel(String linkLabel)
{
this.linkLabel = linkLabel;
}
/*******************************************************************************
** Fluent setter for linkLabel
*******************************************************************************/
public AlertsNotification withLinkLabel(String linkLabel)
{
this.linkLabel = linkLabel;
return (this);
}
/*******************************************************************************
** Getter for audienceType
*******************************************************************************/
public String getAudienceType()
{
return (this.audienceType);
}
/*******************************************************************************
** Setter for audienceType
*******************************************************************************/
public void setAudienceType(String audienceType)
{
this.audienceType = audienceType;
}
/*******************************************************************************
** Fluent setter for audienceType
*******************************************************************************/
public AlertsNotification withAudienceType(String audienceType)
{
this.audienceType = audienceType;
return (this);
}
/*******************************************************************************
** Getter for audienceValue
*******************************************************************************/
public String getAudienceValue()
{
return (this.audienceValue);
}
/*******************************************************************************
** Setter for audienceValue
*******************************************************************************/
public void setAudienceValue(String audienceValue)
{
this.audienceValue = audienceValue;
}
/*******************************************************************************
** Fluent setter for audienceValue
*******************************************************************************/
public AlertsNotification withAudienceValue(String audienceValue)
{
this.audienceValue = audienceValue;
return (this);
}
/*******************************************************************************
** Getter for publishAt
*******************************************************************************/
public Instant getPublishAt()
{
return (this.publishAt);
}
/*******************************************************************************
** Setter for publishAt
*******************************************************************************/
public void setPublishAt(Instant publishAt)
{
this.publishAt = publishAt;
}
/*******************************************************************************
** Fluent setter for publishAt
*******************************************************************************/
public AlertsNotification withPublishAt(Instant publishAt)
{
this.publishAt = publishAt;
return (this);
}
/*******************************************************************************
** Getter for expireAt
*******************************************************************************/
public Instant getExpireAt()
{
return (this.expireAt);
}
/*******************************************************************************
** Setter for expireAt
*******************************************************************************/
public void setExpireAt(Instant expireAt)
{
this.expireAt = expireAt;
}
/*******************************************************************************
** Fluent setter for expireAt
*******************************************************************************/
public AlertsNotification withExpireAt(Instant expireAt)
{
this.expireAt = expireAt;
return (this);
}
/*******************************************************************************
** Getter for sticky
*******************************************************************************/
public Boolean getSticky()
{
return (this.sticky);
}
/*******************************************************************************
** Setter for sticky
*******************************************************************************/
public void setSticky(Boolean sticky)
{
this.sticky = sticky;
}
/*******************************************************************************
** Fluent setter for sticky
*******************************************************************************/
public AlertsNotification withSticky(Boolean sticky)
{
this.sticky = sticky;
return (this);
}
/*******************************************************************************
** Getter for authorUserId
*******************************************************************************/
public String getAuthorUserId()
{
return (this.authorUserId);
}
/*******************************************************************************
** Setter for authorUserId
*******************************************************************************/
public void setAuthorUserId(String authorUserId)
{
this.authorUserId = authorUserId;
}
/*******************************************************************************
** Fluent setter for authorUserId
*******************************************************************************/
public AlertsNotification withAuthorUserId(String authorUserId)
{
this.authorUserId = authorUserId;
return (this);
}
/*******************************************************************************
** Getter for sentAt
*******************************************************************************/
public Instant getSentAt()
{
return (this.sentAt);
}
/*******************************************************************************
** Setter for sentAt
*******************************************************************************/
public void setSentAt(Instant sentAt)
{
this.sentAt = sentAt;
}
/*******************************************************************************
** Fluent setter for sentAt
*******************************************************************************/
public AlertsNotification withSentAt(Instant sentAt)
{
this.sentAt = sentAt;
return (this);
}
/*******************************************************************************
** Getter for retractedAt
*******************************************************************************/
public Instant getRetractedAt()
{
return (this.retractedAt);
}
/*******************************************************************************
** Setter for retractedAt
*******************************************************************************/
public void setRetractedAt(Instant retractedAt)
{
this.retractedAt = retractedAt;
}
/*******************************************************************************
** Fluent setter for retractedAt
*******************************************************************************/
public AlertsNotification withRetractedAt(Instant retractedAt)
{
this.retractedAt = retractedAt;
return (this);
}
/*******************************************************************************
** Getter for recipientCount
*******************************************************************************/
public Integer getRecipientCount()
{
return (this.recipientCount);
}
/*******************************************************************************
** Setter for recipientCount
*******************************************************************************/
public void setRecipientCount(Integer recipientCount)
{
this.recipientCount = recipientCount;
}
/*******************************************************************************
** Fluent setter for recipientCount
*******************************************************************************/
public AlertsNotification withRecipientCount(Integer recipientCount)
{
this.recipientCount = recipientCount;
return (this);
}
/*******************************************************************************
** Getter for readCount
*******************************************************************************/
public Integer getReadCount()
{
return (this.readCount);
}
/*******************************************************************************
** Setter for readCount
*******************************************************************************/
public void setReadCount(Integer readCount)
{
this.readCount = readCount;
}
/*******************************************************************************
** Fluent setter for readCount
*******************************************************************************/
public AlertsNotification withReadCount(Integer readCount)
{
this.readCount = readCount;
return (this);
}
/*******************************************************************************
** Getter for createDate
*******************************************************************************/
public Instant getCreateDate()
{
return (this.createDate);
}
/*******************************************************************************
** Setter for createDate
*******************************************************************************/
public void setCreateDate(Instant createDate)
{
this.createDate = createDate;
}
/*******************************************************************************
** Fluent setter for createDate
*******************************************************************************/
public AlertsNotification withCreateDate(Instant createDate)
{
this.createDate = createDate;
return (this);
}
/*******************************************************************************
** Getter for modifyDate
*******************************************************************************/
public Instant getModifyDate()
{
return (this.modifyDate);
}
/*******************************************************************************
** Setter for modifyDate
*******************************************************************************/
public void setModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
}
/*******************************************************************************
** Fluent setter for modifyDate
*******************************************************************************/
public AlertsNotification withModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
return (this);
}
}
@@ -0,0 +1,302 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.model;
import java.time.Instant;
import com.kingsrook.qqq.backend.core.model.data.QField;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.data.QRecordEntity;
import com.kingsrook.qqq.backend.core.model.metadata.fields.ValueTooLongBehavior;
/*******************************************************************************
** A user's settings for one notification category: muted in-app (never for security), and email off, immediate or in a daily digest, from a minimum severity.
**
** Generated from the qbit-alerts schema (one definition for the entity,
** the Liquibase changelog and the test DDL).
*******************************************************************************/
public class AlertsNotificationPreference extends QRecordEntity
{
public static final String TABLE_NAME = "alerts_notification_preference";
@QField(isEditable = false, isPrimaryKey = true)
private Integer id;
@QField(isRequired = true, isEditable = false, maxLength = 100, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, label = "User")
private String userId;
@QField(isRequired = true, maxLength = 16, possibleValueSourceName = "alerts_notification_category")
private String category;
@QField(label = "Muted In-App")
private Boolean inAppMuted;
@QField(maxLength = 16, possibleValueSourceName = "alerts_email_mode", label = "Email")
private String emailMode;
@QField(maxLength = 16, possibleValueSourceName = "alerts_notification_severity", label = "Email From Severity")
private String emailMinSeverity;
@QField(isEditable = false)
private Instant createDate;
@QField(isEditable = false)
private Instant modifyDate;
/*******************************************************************************
** Default constructor.
*******************************************************************************/
public AlertsNotificationPreference()
{
}
/*******************************************************************************
** Constructor that populates from a QRecord.
*******************************************************************************/
public AlertsNotificationPreference(QRecord record)
{
populateFromQRecord(record);
}
/*******************************************************************************
** Getter for id
*******************************************************************************/
public Integer getId()
{
return (this.id);
}
/*******************************************************************************
** Setter for id
*******************************************************************************/
public void setId(Integer id)
{
this.id = id;
}
/*******************************************************************************
** Fluent setter for id
*******************************************************************************/
public AlertsNotificationPreference withId(Integer id)
{
this.id = id;
return (this);
}
/*******************************************************************************
** Getter for userId
*******************************************************************************/
public String getUserId()
{
return (this.userId);
}
/*******************************************************************************
** Setter for userId
*******************************************************************************/
public void setUserId(String userId)
{
this.userId = userId;
}
/*******************************************************************************
** Fluent setter for userId
*******************************************************************************/
public AlertsNotificationPreference withUserId(String userId)
{
this.userId = userId;
return (this);
}
/*******************************************************************************
** Getter for category
*******************************************************************************/
public String getCategory()
{
return (this.category);
}
/*******************************************************************************
** Setter for category
*******************************************************************************/
public void setCategory(String category)
{
this.category = category;
}
/*******************************************************************************
** Fluent setter for category
*******************************************************************************/
public AlertsNotificationPreference withCategory(String category)
{
this.category = category;
return (this);
}
/*******************************************************************************
** Getter for inAppMuted
*******************************************************************************/
public Boolean getInAppMuted()
{
return (this.inAppMuted);
}
/*******************************************************************************
** Setter for inAppMuted
*******************************************************************************/
public void setInAppMuted(Boolean inAppMuted)
{
this.inAppMuted = inAppMuted;
}
/*******************************************************************************
** Fluent setter for inAppMuted
*******************************************************************************/
public AlertsNotificationPreference withInAppMuted(Boolean inAppMuted)
{
this.inAppMuted = inAppMuted;
return (this);
}
/*******************************************************************************
** Getter for emailMode
*******************************************************************************/
public String getEmailMode()
{
return (this.emailMode);
}
/*******************************************************************************
** Setter for emailMode
*******************************************************************************/
public void setEmailMode(String emailMode)
{
this.emailMode = emailMode;
}
/*******************************************************************************
** Fluent setter for emailMode
*******************************************************************************/
public AlertsNotificationPreference withEmailMode(String emailMode)
{
this.emailMode = emailMode;
return (this);
}
/*******************************************************************************
** Getter for emailMinSeverity
*******************************************************************************/
public String getEmailMinSeverity()
{
return (this.emailMinSeverity);
}
/*******************************************************************************
** Setter for emailMinSeverity
*******************************************************************************/
public void setEmailMinSeverity(String emailMinSeverity)
{
this.emailMinSeverity = emailMinSeverity;
}
/*******************************************************************************
** Fluent setter for emailMinSeverity
*******************************************************************************/
public AlertsNotificationPreference withEmailMinSeverity(String emailMinSeverity)
{
this.emailMinSeverity = emailMinSeverity;
return (this);
}
/*******************************************************************************
** Getter for createDate
*******************************************************************************/
public Instant getCreateDate()
{
return (this.createDate);
}
/*******************************************************************************
** Setter for createDate
*******************************************************************************/
public void setCreateDate(Instant createDate)
{
this.createDate = createDate;
}
/*******************************************************************************
** Fluent setter for createDate
*******************************************************************************/
public AlertsNotificationPreference withCreateDate(Instant createDate)
{
this.createDate = createDate;
return (this);
}
/*******************************************************************************
** Getter for modifyDate
*******************************************************************************/
public Instant getModifyDate()
{
return (this.modifyDate);
}
/*******************************************************************************
** Setter for modifyDate
*******************************************************************************/
public void setModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
}
/*******************************************************************************
** Fluent setter for modifyDate
*******************************************************************************/
public AlertsNotificationPreference withModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
return (this);
}
}
@@ -0,0 +1,364 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.model;
import java.time.Instant;
import com.kingsrook.qqq.backend.core.model.data.QField;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.data.QRecordEntity;
import com.kingsrook.qqq.backend.core.model.metadata.fields.ValueTooLongBehavior;
/*******************************************************************************
** One notification for one user: when it reached them, and whether they read it, dismissed it, or were emailed.
**
** Generated from the qbit-alerts schema (one definition for the entity,
** the Liquibase changelog and the test DDL).
*******************************************************************************/
public class AlertsNotificationRecipient extends QRecordEntity
{
public static final String TABLE_NAME = "alerts_notification_recipient";
@QField(isEditable = false, isPrimaryKey = true)
private Integer id;
@QField(isRequired = true, isEditable = false, possibleValueSourceName = "alerts_notification", label = "Notification")
private Integer notificationId;
@QField(isRequired = true, isEditable = false, maxLength = 100, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, label = "User")
private String userId;
@QField(isEditable = false)
private Instant deliveredAt;
@QField()
private Instant readAt;
@QField()
private Instant dismissedAt;
@QField(isEditable = false)
private Instant emailedAt;
@QField(isEditable = false, maxLength = 16, possibleValueSourceName = "alerts_email_status")
private String emailStatus;
@QField(isEditable = false)
private Instant createDate;
@QField(isEditable = false)
private Instant modifyDate;
/*******************************************************************************
** Default constructor.
*******************************************************************************/
public AlertsNotificationRecipient()
{
}
/*******************************************************************************
** Constructor that populates from a QRecord.
*******************************************************************************/
public AlertsNotificationRecipient(QRecord record)
{
populateFromQRecord(record);
}
/*******************************************************************************
** Getter for id
*******************************************************************************/
public Integer getId()
{
return (this.id);
}
/*******************************************************************************
** Setter for id
*******************************************************************************/
public void setId(Integer id)
{
this.id = id;
}
/*******************************************************************************
** Fluent setter for id
*******************************************************************************/
public AlertsNotificationRecipient withId(Integer id)
{
this.id = id;
return (this);
}
/*******************************************************************************
** Getter for notificationId
*******************************************************************************/
public Integer getNotificationId()
{
return (this.notificationId);
}
/*******************************************************************************
** Setter for notificationId
*******************************************************************************/
public void setNotificationId(Integer notificationId)
{
this.notificationId = notificationId;
}
/*******************************************************************************
** Fluent setter for notificationId
*******************************************************************************/
public AlertsNotificationRecipient withNotificationId(Integer notificationId)
{
this.notificationId = notificationId;
return (this);
}
/*******************************************************************************
** Getter for userId
*******************************************************************************/
public String getUserId()
{
return (this.userId);
}
/*******************************************************************************
** Setter for userId
*******************************************************************************/
public void setUserId(String userId)
{
this.userId = userId;
}
/*******************************************************************************
** Fluent setter for userId
*******************************************************************************/
public AlertsNotificationRecipient withUserId(String userId)
{
this.userId = userId;
return (this);
}
/*******************************************************************************
** Getter for deliveredAt
*******************************************************************************/
public Instant getDeliveredAt()
{
return (this.deliveredAt);
}
/*******************************************************************************
** Setter for deliveredAt
*******************************************************************************/
public void setDeliveredAt(Instant deliveredAt)
{
this.deliveredAt = deliveredAt;
}
/*******************************************************************************
** Fluent setter for deliveredAt
*******************************************************************************/
public AlertsNotificationRecipient withDeliveredAt(Instant deliveredAt)
{
this.deliveredAt = deliveredAt;
return (this);
}
/*******************************************************************************
** Getter for readAt
*******************************************************************************/
public Instant getReadAt()
{
return (this.readAt);
}
/*******************************************************************************
** Setter for readAt
*******************************************************************************/
public void setReadAt(Instant readAt)
{
this.readAt = readAt;
}
/*******************************************************************************
** Fluent setter for readAt
*******************************************************************************/
public AlertsNotificationRecipient withReadAt(Instant readAt)
{
this.readAt = readAt;
return (this);
}
/*******************************************************************************
** Getter for dismissedAt
*******************************************************************************/
public Instant getDismissedAt()
{
return (this.dismissedAt);
}
/*******************************************************************************
** Setter for dismissedAt
*******************************************************************************/
public void setDismissedAt(Instant dismissedAt)
{
this.dismissedAt = dismissedAt;
}
/*******************************************************************************
** Fluent setter for dismissedAt
*******************************************************************************/
public AlertsNotificationRecipient withDismissedAt(Instant dismissedAt)
{
this.dismissedAt = dismissedAt;
return (this);
}
/*******************************************************************************
** Getter for emailedAt
*******************************************************************************/
public Instant getEmailedAt()
{
return (this.emailedAt);
}
/*******************************************************************************
** Setter for emailedAt
*******************************************************************************/
public void setEmailedAt(Instant emailedAt)
{
this.emailedAt = emailedAt;
}
/*******************************************************************************
** Fluent setter for emailedAt
*******************************************************************************/
public AlertsNotificationRecipient withEmailedAt(Instant emailedAt)
{
this.emailedAt = emailedAt;
return (this);
}
/*******************************************************************************
** Getter for emailStatus
*******************************************************************************/
public String getEmailStatus()
{
return (this.emailStatus);
}
/*******************************************************************************
** Setter for emailStatus
*******************************************************************************/
public void setEmailStatus(String emailStatus)
{
this.emailStatus = emailStatus;
}
/*******************************************************************************
** Fluent setter for emailStatus
*******************************************************************************/
public AlertsNotificationRecipient withEmailStatus(String emailStatus)
{
this.emailStatus = emailStatus;
return (this);
}
/*******************************************************************************
** Getter for createDate
*******************************************************************************/
public Instant getCreateDate()
{
return (this.createDate);
}
/*******************************************************************************
** Setter for createDate
*******************************************************************************/
public void setCreateDate(Instant createDate)
{
this.createDate = createDate;
}
/*******************************************************************************
** Fluent setter for createDate
*******************************************************************************/
public AlertsNotificationRecipient withCreateDate(Instant createDate)
{
this.createDate = createDate;
return (this);
}
/*******************************************************************************
** Getter for modifyDate
*******************************************************************************/
public Instant getModifyDate()
{
return (this.modifyDate);
}
/*******************************************************************************
** Setter for modifyDate
*******************************************************************************/
public void setModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
}
/*******************************************************************************
** Fluent setter for modifyDate
*******************************************************************************/
public AlertsNotificationRecipient withModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
return (this);
}
}
@@ -0,0 +1,354 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.model;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import com.kingsrook.qbits.alerts.spi.NotificationAudience;
import com.kingsrook.qbits.alerts.spi.NotificationCategory;
import com.kingsrook.qbits.alerts.spi.NotificationSeverity;
import com.kingsrook.qqq.backend.core.alerts.AlertMonitorKind;
import com.kingsrook.qqq.backend.core.alerts.AlertSeverity;
import com.kingsrook.qqq.backend.core.alerts.DetailLevel;
import com.kingsrook.qqq.backend.core.alerts.ResolveMode;
import com.kingsrook.qqq.backend.core.model.metadata.possiblevalues.QPossibleValue;
import com.kingsrook.qqq.backend.core.model.metadata.possiblevalues.QPossibleValueSource;
import com.kingsrook.qqq.backend.core.model.metadata.possiblevalues.QPossibleValueSourceType;
/*******************************************************************************
** The qbit's enumerated values, stored as strings, and their possible-value
** sources (named alerts_(name), labels in Title Case).
*******************************************************************************/
public final class AlertsPossibleValues
{
public static final String SEVERITY = "alerts_severity";
public static final String STATUS = "alerts_status";
public static final String RESOLVE_MODE = "alerts_resolve_mode";
public static final String DETAIL_LEVEL = "alerts_detail_level";
public static final String MONITOR_KIND = "alerts_monitor_kind";
public static final String MONITOR_STATUS = "alerts_monitor_status";
public static final String EVENT_TYPE = "alerts_event_type";
public static final String RESOLUTION = "alerts_resolution";
public static final String SUBSCRIBER_TYPE = "alerts_subscriber_type";
public static final String SCOPE_TYPE = "alerts_scope_type";
public static final String DELIVERY_MODE = "alerts_delivery_mode";
public static final String MEMBER_SOURCE = "alerts_member_source";
public static final String TEAM_ROLE = "alerts_team_role";
public static final String CHANNEL_TYPE = "alerts_channel_type";
public static final String HEALTH_STATUS = "alerts_health_status";
public static final String MUTE_EFFECT = "alerts_mute_effect";
public static final String DELIVERY_KIND = "alerts_delivery_kind";
public static final String DELIVERY_STATUS = "alerts_delivery_status";
public static final String SUPPRESSED_REASON = "alerts_suppressed_reason";
public static final String NOTIFICATION_SEVERITY = "alerts_notification_severity";
public static final String NOTIFICATION_CATEGORY = "alerts_notification_category";
public static final String NOTIFICATION_STATUS = "alerts_notification_status";
public static final String AUDIENCE_TYPE = "alerts_audience_type";
public static final String EMAIL_STATUS = "alerts_email_status";
public static final String EMAIL_MODE = "alerts_email_mode";
/*******************************************************************************
** An alert's lifecycle state.
*******************************************************************************/
public enum Status
{
OPEN, ACKNOWLEDGED, SNOOZED, RESOLVED;
/*******************************************************************************
** Every state but RESOLVED.
*******************************************************************************/
public static List<String> openNames()
{
return (List.of(OPEN.name(), ACKNOWLEDGED.name(), SNOOZED.name()));
}
}
/*******************************************************************************
** A monitor's last evaluation.
*******************************************************************************/
public enum MonitorStatus
{
OK, FIRING, PENDING, CHECK_FAILED, SKIPPED_MUTED
}
/*******************************************************************************
** Timeline entries.
*******************************************************************************/
public enum EventType
{
RAISED, REPEATED, SEVERITY_CHANGED, ACKNOWLEDGED, SNOOZED, UNSNOOZED, ASSIGNED, COMMENTED, ESCALATED, NOTIFIED, MUTED, FLAPPING_STARTED,
FLAPPING_ENDED, RESOLVED, REOPENED
}
/*******************************************************************************
** How an alert was resolved.
*******************************************************************************/
public enum Resolution
{
PRODUCER, MONITOR, QUIET_PERIOD, MANUAL, EXPIRED
}
/*******************************************************************************
** Who a subscription notifies.
*******************************************************************************/
public enum SubscriberType
{
USER, TEAM, CHANNEL
}
/*******************************************************************************
** What a subscription or mute covers.
*******************************************************************************/
public enum ScopeType
{
ALL, GROUP, ALERT_TYPE, MONITOR, TABLE, RECORD, ATTRIBUTE
}
/*******************************************************************************
** When a subscription's notifications are sent.
*******************************************************************************/
public enum DeliveryMode
{
IMMEDIATE, DIGEST_HOURLY, DIGEST_DAILY
}
/*******************************************************************************
** Where a team's members come from.
*******************************************************************************/
public enum MemberSource
{
MANUAL, ROLE, IDP_GROUP
}
/*******************************************************************************
** A member's role in a team.
*******************************************************************************/
public enum TeamRole
{
MEMBER, LEAD
}
/*******************************************************************************
** Channel kinds (built-in: IN_APP, EMAIL, EMAIL_LIST; the rest arrive with
** their channel implementations).
*******************************************************************************/
public enum ChannelType
{
IN_APP, EMAIL, EMAIL_LIST, SLACK, TEAMS, WEBHOOK, PAGERDUTY, ALERTMANAGER
}
/*******************************************************************************
** Channel delivery health (the qbit-webhooks model).
*******************************************************************************/
public enum HealthStatus
{
HEALTHY, PROBATION, UNHEALTHY
}
/*******************************************************************************
** What a mute does.
*******************************************************************************/
public enum MuteEffect
{
SILENCE_NOTIFICATIONS, SUPPRESS_ALERTS
}
/*******************************************************************************
** Why a notification was sent.
*******************************************************************************/
public enum DeliveryKind
{
RAISED, ESCALATED, REMINDER, RESOLVED, DIGEST, TEST
}
/*******************************************************************************
** A notification's delivery state.
*******************************************************************************/
public enum DeliveryStatus
{
PENDING, SENDING, SENT, RETRYING, FAILED, DEAD, SUPPRESSED
}
/*******************************************************************************
** Why a notification was not sent.
*******************************************************************************/
public enum SuppressedReason
{
QUIET_HOURS, MUTED, FLAPPING, RATE_LIMITED, NOT_VISIBLE, CHANNEL_DISABLED, DUPLICATE, USER_PAUSED, TYPE_SILENT, NO_ADDRESS
}
/*******************************************************************************
** Constants and builders only.
*******************************************************************************/
private AlertsPossibleValues()
{
}
/*******************************************************************************
** Every possible-value source the qbit's fields use (the table-backed ones
** are built with the tables).
*******************************************************************************/
public static List<QPossibleValueSource> buildEnumSources()
{
return (List.of(
enumSource(SEVERITY, AlertSeverity.values()),
enumSource(STATUS, Status.values()),
enumSource(RESOLVE_MODE, ResolveMode.values()),
enumSource(DETAIL_LEVEL, DetailLevel.values()),
enumSource(MONITOR_KIND, AlertMonitorKind.values()),
enumSource(MONITOR_STATUS, MonitorStatus.values()),
enumSource(EVENT_TYPE, EventType.values()),
enumSource(RESOLUTION, Resolution.values()),
enumSource(SUBSCRIBER_TYPE, SubscriberType.values()),
enumSource(SCOPE_TYPE, ScopeType.values()),
enumSource(DELIVERY_MODE, DeliveryMode.values()),
enumSource(MEMBER_SOURCE, MemberSource.values()),
enumSource(TEAM_ROLE, TeamRole.values()),
enumSource(CHANNEL_TYPE, ChannelType.values()),
enumSource(HEALTH_STATUS, HealthStatus.values()),
enumSource(MUTE_EFFECT, MuteEffect.values()),
enumSource(DELIVERY_KIND, DeliveryKind.values()),
enumSource(DELIVERY_STATUS, DeliveryStatus.values()),
enumSource(SUPPRESSED_REASON, SuppressedReason.values()),
enumSource(NOTIFICATION_SEVERITY, NotificationSeverity.values()),
enumSource(NOTIFICATION_CATEGORY, NotificationCategory.values()),
enumSource(NOTIFICATION_STATUS, NotificationStatus.values()),
enumSource(AUDIENCE_TYPE, NotificationAudience.Type.values()),
enumSource(EMAIL_STATUS, EmailStatus.values()),
enumSource(EMAIL_MODE, EmailMode.values())));
}
/*******************************************************************************
** A user notification's state.
*******************************************************************************/
public enum NotificationStatus
{
DRAFT, SCHEDULED, SENT, RETRACTED
}
/*******************************************************************************
** Whether (and how) a recipient was emailed.
*******************************************************************************/
public enum EmailStatus
{
NONE, PENDING, SENT, DIGESTED, SKIPPED, FAILED
}
/*******************************************************************************
** How a user wants a category by email.
*******************************************************************************/
public enum EmailMode
{
OFF, IMMEDIATE, DAILY_DIGEST
}
/*******************************************************************************
** An enum possible-value source: ids are the constant names, labels are
** Title Case ("IN_APP" is "In App").
*******************************************************************************/
public static QPossibleValueSource enumSource(String name, Enum<?>[] values)
{
List<QPossibleValue<?>> possibleValues = new ArrayList<>();
for(Enum<?> value : values)
{
possibleValues.add(new QPossibleValue<>(value.name(), label(value.name())));
}
return (new QPossibleValueSource()
.withName(name)
.withType(QPossibleValueSourceType.ENUM)
.withEnumValues(possibleValues));
}
/*******************************************************************************
** "IN_APP" to "In App" (and "IDP_GROUP" to "IdP Group").
*******************************************************************************/
public static String label(String constant)
{
if(constant == null)
{
return (null);
}
StringBuilder label = new StringBuilder();
for(String word : constant.split("_"))
{
if(word.isEmpty())
{
continue;
}
if(!label.isEmpty())
{
label.append(' ');
}
switch(word)
{
case "IDP" -> label.append("IdP");
case "ESB" -> label.append("ESB");
default -> label.append(word.charAt(0)).append(word.substring(1).toLowerCase(Locale.ROOT));
}
}
return (label.toString());
}
}
@@ -0,0 +1,328 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.model;
import java.time.Instant;
import com.kingsrook.qqq.backend.core.model.data.QField;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.data.QRecordEntity;
import com.kingsrook.qqq.backend.core.model.metadata.fields.ValueTooLongBehavior;
/*******************************************************************************
** A record an alert is about. The label is internal: shown in-app only, to
** users who can see the record.
**
** Generated from the qbit-alerts schema (one definition for the entity,
** the Liquibase changelog and the test DDL).
*******************************************************************************/
public class AlertsRecordRef extends QRecordEntity
{
public static final String TABLE_NAME = "alerts_record_ref";
@QField(isEditable = false, isPrimaryKey = true)
private Integer id;
@QField(isRequired = true, isEditable = false, possibleValueSourceName = "alerts_alert", label = "Alert")
private Integer alertId;
@QField(isEditable = false, maxLength = 100, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String tableName;
@QField(isEditable = false, maxLength = 100, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String recordId;
@QField(isEditable = false, maxLength = 300, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String label;
@QField(isEditable = false)
private Boolean active;
@QField(isEditable = false)
private Instant createDate;
@QField(isEditable = false)
private Instant modifyDate;
/*******************************************************************************
** Default constructor.
*******************************************************************************/
public AlertsRecordRef()
{
}
/*******************************************************************************
** Constructor that populates from a QRecord.
*******************************************************************************/
public AlertsRecordRef(QRecord record)
{
populateFromQRecord(record);
}
/*******************************************************************************
** Getter for id
*******************************************************************************/
public Integer getId()
{
return (this.id);
}
/*******************************************************************************
** Setter for id
*******************************************************************************/
public void setId(Integer id)
{
this.id = id;
}
/*******************************************************************************
** Fluent setter for id
*******************************************************************************/
public AlertsRecordRef withId(Integer id)
{
this.id = id;
return (this);
}
/*******************************************************************************
** Getter for alertId
*******************************************************************************/
public Integer getAlertId()
{
return (this.alertId);
}
/*******************************************************************************
** Setter for alertId
*******************************************************************************/
public void setAlertId(Integer alertId)
{
this.alertId = alertId;
}
/*******************************************************************************
** Fluent setter for alertId
*******************************************************************************/
public AlertsRecordRef withAlertId(Integer alertId)
{
this.alertId = alertId;
return (this);
}
/*******************************************************************************
** Getter for tableName
*******************************************************************************/
public String getTableName()
{
return (this.tableName);
}
/*******************************************************************************
** Setter for tableName
*******************************************************************************/
public void setTableName(String tableName)
{
this.tableName = tableName;
}
/*******************************************************************************
** Fluent setter for tableName
*******************************************************************************/
public AlertsRecordRef withTableName(String tableName)
{
this.tableName = tableName;
return (this);
}
/*******************************************************************************
** Getter for recordId
*******************************************************************************/
public String getRecordId()
{
return (this.recordId);
}
/*******************************************************************************
** Setter for recordId
*******************************************************************************/
public void setRecordId(String recordId)
{
this.recordId = recordId;
}
/*******************************************************************************
** Fluent setter for recordId
*******************************************************************************/
public AlertsRecordRef withRecordId(String recordId)
{
this.recordId = recordId;
return (this);
}
/*******************************************************************************
** Getter for label
*******************************************************************************/
public String getLabel()
{
return (this.label);
}
/*******************************************************************************
** Setter for label
*******************************************************************************/
public void setLabel(String label)
{
this.label = label;
}
/*******************************************************************************
** Fluent setter for label
*******************************************************************************/
public AlertsRecordRef withLabel(String label)
{
this.label = label;
return (this);
}
/*******************************************************************************
** Getter for active
*******************************************************************************/
public Boolean getActive()
{
return (this.active);
}
/*******************************************************************************
** Setter for active
*******************************************************************************/
public void setActive(Boolean active)
{
this.active = active;
}
/*******************************************************************************
** Fluent setter for active
*******************************************************************************/
public AlertsRecordRef withActive(Boolean active)
{
this.active = active;
return (this);
}
/*******************************************************************************
** Getter for createDate
*******************************************************************************/
public Instant getCreateDate()
{
return (this.createDate);
}
/*******************************************************************************
** Setter for createDate
*******************************************************************************/
public void setCreateDate(Instant createDate)
{
this.createDate = createDate;
}
/*******************************************************************************
** Fluent setter for createDate
*******************************************************************************/
public AlertsRecordRef withCreateDate(Instant createDate)
{
this.createDate = createDate;
return (this);
}
/*******************************************************************************
** Getter for modifyDate
*******************************************************************************/
public Instant getModifyDate()
{
return (this.modifyDate);
}
/*******************************************************************************
** Setter for modifyDate
*******************************************************************************/
public void setModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
}
/*******************************************************************************
** Fluent setter for modifyDate
*******************************************************************************/
public AlertsRecordRef withModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
return (this);
}
}
@@ -0,0 +1,601 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.model;
import java.time.Instant;
import com.kingsrook.qqq.backend.core.model.data.QField;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.data.QRecordEntity;
import com.kingsrook.qqq.backend.core.model.metadata.fields.ValueTooLongBehavior;
/*******************************************************************************
** Who hears about what: a user, a team or a channel, scoped to all alerts, a
** group, a type, a monitor, a table or one record, with a minimum severity
** and a delivery mode.
**
** Generated from the qbit-alerts schema (one definition for the entity,
** the Liquibase changelog and the test DDL).
*******************************************************************************/
public class AlertsSubscription extends QRecordEntity
{
public static final String TABLE_NAME = "alerts_subscription";
@QField(isEditable = false, isPrimaryKey = true)
private Integer id;
@QField(isRequired = true, maxLength = 16, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, possibleValueSourceName = "alerts_subscriber_type")
private String subscriberType;
@QField(maxLength = 100, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, label = "User")
private String userId;
@QField(possibleValueSourceName = "alerts_team", label = "Team")
private Integer teamId;
@QField(possibleValueSourceName = "alerts_channel", label = "Channel")
private Integer channelId;
@QField(isRequired = true, maxLength = 20, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, possibleValueSourceName = "alerts_scope_type")
private String scopeType;
@QField(maxLength = 300, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String scopeValue;
@QField(maxLength = 100, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, label = "Scope Record")
private String scopeRecordId;
@QField(maxLength = 16, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, possibleValueSourceName = "alerts_severity")
private String minSeverity;
@QField(maxLength = 200, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String events;
@QField(maxLength = 20, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, possibleValueSourceName = "alerts_delivery_mode")
private String deliveryMode;
@QField(maxLength = 200, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, label = "Channels")
private String channelOverrideIds;
@QField()
private Boolean enabled;
@QField(isEditable = false, maxLength = 100, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, label = "Created By")
private String createdByUserId;
@QField(isEditable = false)
private Instant createDate;
@QField(isEditable = false)
private Instant modifyDate;
/*******************************************************************************
** Default constructor.
*******************************************************************************/
public AlertsSubscription()
{
}
/*******************************************************************************
** Constructor that populates from a QRecord.
*******************************************************************************/
public AlertsSubscription(QRecord record)
{
populateFromQRecord(record);
}
/*******************************************************************************
** Getter for id
*******************************************************************************/
public Integer getId()
{
return (this.id);
}
/*******************************************************************************
** Setter for id
*******************************************************************************/
public void setId(Integer id)
{
this.id = id;
}
/*******************************************************************************
** Fluent setter for id
*******************************************************************************/
public AlertsSubscription withId(Integer id)
{
this.id = id;
return (this);
}
/*******************************************************************************
** Getter for subscriberType
*******************************************************************************/
public String getSubscriberType()
{
return (this.subscriberType);
}
/*******************************************************************************
** Setter for subscriberType
*******************************************************************************/
public void setSubscriberType(String subscriberType)
{
this.subscriberType = subscriberType;
}
/*******************************************************************************
** Fluent setter for subscriberType
*******************************************************************************/
public AlertsSubscription withSubscriberType(String subscriberType)
{
this.subscriberType = subscriberType;
return (this);
}
/*******************************************************************************
** Getter for userId
*******************************************************************************/
public String getUserId()
{
return (this.userId);
}
/*******************************************************************************
** Setter for userId
*******************************************************************************/
public void setUserId(String userId)
{
this.userId = userId;
}
/*******************************************************************************
** Fluent setter for userId
*******************************************************************************/
public AlertsSubscription withUserId(String userId)
{
this.userId = userId;
return (this);
}
/*******************************************************************************
** Getter for teamId
*******************************************************************************/
public Integer getTeamId()
{
return (this.teamId);
}
/*******************************************************************************
** Setter for teamId
*******************************************************************************/
public void setTeamId(Integer teamId)
{
this.teamId = teamId;
}
/*******************************************************************************
** Fluent setter for teamId
*******************************************************************************/
public AlertsSubscription withTeamId(Integer teamId)
{
this.teamId = teamId;
return (this);
}
/*******************************************************************************
** Getter for channelId
*******************************************************************************/
public Integer getChannelId()
{
return (this.channelId);
}
/*******************************************************************************
** Setter for channelId
*******************************************************************************/
public void setChannelId(Integer channelId)
{
this.channelId = channelId;
}
/*******************************************************************************
** Fluent setter for channelId
*******************************************************************************/
public AlertsSubscription withChannelId(Integer channelId)
{
this.channelId = channelId;
return (this);
}
/*******************************************************************************
** Getter for scopeType
*******************************************************************************/
public String getScopeType()
{
return (this.scopeType);
}
/*******************************************************************************
** Setter for scopeType
*******************************************************************************/
public void setScopeType(String scopeType)
{
this.scopeType = scopeType;
}
/*******************************************************************************
** Fluent setter for scopeType
*******************************************************************************/
public AlertsSubscription withScopeType(String scopeType)
{
this.scopeType = scopeType;
return (this);
}
/*******************************************************************************
** Getter for scopeValue
*******************************************************************************/
public String getScopeValue()
{
return (this.scopeValue);
}
/*******************************************************************************
** Setter for scopeValue
*******************************************************************************/
public void setScopeValue(String scopeValue)
{
this.scopeValue = scopeValue;
}
/*******************************************************************************
** Fluent setter for scopeValue
*******************************************************************************/
public AlertsSubscription withScopeValue(String scopeValue)
{
this.scopeValue = scopeValue;
return (this);
}
/*******************************************************************************
** Getter for scopeRecordId
*******************************************************************************/
public String getScopeRecordId()
{
return (this.scopeRecordId);
}
/*******************************************************************************
** Setter for scopeRecordId
*******************************************************************************/
public void setScopeRecordId(String scopeRecordId)
{
this.scopeRecordId = scopeRecordId;
}
/*******************************************************************************
** Fluent setter for scopeRecordId
*******************************************************************************/
public AlertsSubscription withScopeRecordId(String scopeRecordId)
{
this.scopeRecordId = scopeRecordId;
return (this);
}
/*******************************************************************************
** Getter for minSeverity
*******************************************************************************/
public String getMinSeverity()
{
return (this.minSeverity);
}
/*******************************************************************************
** Setter for minSeverity
*******************************************************************************/
public void setMinSeverity(String minSeverity)
{
this.minSeverity = minSeverity;
}
/*******************************************************************************
** Fluent setter for minSeverity
*******************************************************************************/
public AlertsSubscription withMinSeverity(String minSeverity)
{
this.minSeverity = minSeverity;
return (this);
}
/*******************************************************************************
** Getter for events
*******************************************************************************/
public String getEvents()
{
return (this.events);
}
/*******************************************************************************
** Setter for events
*******************************************************************************/
public void setEvents(String events)
{
this.events = events;
}
/*******************************************************************************
** Fluent setter for events
*******************************************************************************/
public AlertsSubscription withEvents(String events)
{
this.events = events;
return (this);
}
/*******************************************************************************
** Getter for deliveryMode
*******************************************************************************/
public String getDeliveryMode()
{
return (this.deliveryMode);
}
/*******************************************************************************
** Setter for deliveryMode
*******************************************************************************/
public void setDeliveryMode(String deliveryMode)
{
this.deliveryMode = deliveryMode;
}
/*******************************************************************************
** Fluent setter for deliveryMode
*******************************************************************************/
public AlertsSubscription withDeliveryMode(String deliveryMode)
{
this.deliveryMode = deliveryMode;
return (this);
}
/*******************************************************************************
** Getter for channelOverrideIds
*******************************************************************************/
public String getChannelOverrideIds()
{
return (this.channelOverrideIds);
}
/*******************************************************************************
** Setter for channelOverrideIds
*******************************************************************************/
public void setChannelOverrideIds(String channelOverrideIds)
{
this.channelOverrideIds = channelOverrideIds;
}
/*******************************************************************************
** Fluent setter for channelOverrideIds
*******************************************************************************/
public AlertsSubscription withChannelOverrideIds(String channelOverrideIds)
{
this.channelOverrideIds = channelOverrideIds;
return (this);
}
/*******************************************************************************
** Getter for enabled
*******************************************************************************/
public Boolean getEnabled()
{
return (this.enabled);
}
/*******************************************************************************
** Setter for enabled
*******************************************************************************/
public void setEnabled(Boolean enabled)
{
this.enabled = enabled;
}
/*******************************************************************************
** Fluent setter for enabled
*******************************************************************************/
public AlertsSubscription withEnabled(Boolean enabled)
{
this.enabled = enabled;
return (this);
}
/*******************************************************************************
** Getter for createdByUserId
*******************************************************************************/
public String getCreatedByUserId()
{
return (this.createdByUserId);
}
/*******************************************************************************
** Setter for createdByUserId
*******************************************************************************/
public void setCreatedByUserId(String createdByUserId)
{
this.createdByUserId = createdByUserId;
}
/*******************************************************************************
** Fluent setter for createdByUserId
*******************************************************************************/
public AlertsSubscription withCreatedByUserId(String createdByUserId)
{
this.createdByUserId = createdByUserId;
return (this);
}
/*******************************************************************************
** Getter for createDate
*******************************************************************************/
public Instant getCreateDate()
{
return (this.createDate);
}
/*******************************************************************************
** Setter for createDate
*******************************************************************************/
public void setCreateDate(Instant createDate)
{
this.createDate = createDate;
}
/*******************************************************************************
** Fluent setter for createDate
*******************************************************************************/
public AlertsSubscription withCreateDate(Instant createDate)
{
this.createDate = createDate;
return (this);
}
/*******************************************************************************
** Getter for modifyDate
*******************************************************************************/
public Instant getModifyDate()
{
return (this.modifyDate);
}
/*******************************************************************************
** Setter for modifyDate
*******************************************************************************/
public void setModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
}
/*******************************************************************************
** Fluent setter for modifyDate
*******************************************************************************/
public AlertsSubscription withModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
return (this);
}
}
@@ -0,0 +1,327 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.model;
import java.time.Instant;
import com.kingsrook.qqq.backend.core.model.data.QField;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.data.QRecordEntity;
import com.kingsrook.qqq.backend.core.model.metadata.fields.ValueTooLongBehavior;
/*******************************************************************************
** A named set of users who can be subscribed together.
**
** Generated from the qbit-alerts schema (one definition for the entity,
** the Liquibase changelog and the test DDL).
*******************************************************************************/
public class AlertsTeam extends QRecordEntity
{
public static final String TABLE_NAME = "alerts_team";
@QField(isEditable = false, isPrimaryKey = true)
private Integer id;
@QField(isRequired = true, maxLength = 100, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String name;
@QField(isRequired = true, maxLength = 200, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String label;
@QField(maxLength = 20, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, possibleValueSourceName = "alerts_member_source")
private String memberSource;
@QField(maxLength = 200, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String memberSourceValue;
@QField()
private String description;
@QField(isEditable = false)
private Instant createDate;
@QField(isEditable = false)
private Instant modifyDate;
/*******************************************************************************
** Default constructor.
*******************************************************************************/
public AlertsTeam()
{
}
/*******************************************************************************
** Constructor that populates from a QRecord.
*******************************************************************************/
public AlertsTeam(QRecord record)
{
populateFromQRecord(record);
}
/*******************************************************************************
** Getter for id
*******************************************************************************/
public Integer getId()
{
return (this.id);
}
/*******************************************************************************
** Setter for id
*******************************************************************************/
public void setId(Integer id)
{
this.id = id;
}
/*******************************************************************************
** Fluent setter for id
*******************************************************************************/
public AlertsTeam withId(Integer id)
{
this.id = id;
return (this);
}
/*******************************************************************************
** Getter for name
*******************************************************************************/
public String getName()
{
return (this.name);
}
/*******************************************************************************
** Setter for name
*******************************************************************************/
public void setName(String name)
{
this.name = name;
}
/*******************************************************************************
** Fluent setter for name
*******************************************************************************/
public AlertsTeam withName(String name)
{
this.name = name;
return (this);
}
/*******************************************************************************
** Getter for label
*******************************************************************************/
public String getLabel()
{
return (this.label);
}
/*******************************************************************************
** Setter for label
*******************************************************************************/
public void setLabel(String label)
{
this.label = label;
}
/*******************************************************************************
** Fluent setter for label
*******************************************************************************/
public AlertsTeam withLabel(String label)
{
this.label = label;
return (this);
}
/*******************************************************************************
** Getter for memberSource
*******************************************************************************/
public String getMemberSource()
{
return (this.memberSource);
}
/*******************************************************************************
** Setter for memberSource
*******************************************************************************/
public void setMemberSource(String memberSource)
{
this.memberSource = memberSource;
}
/*******************************************************************************
** Fluent setter for memberSource
*******************************************************************************/
public AlertsTeam withMemberSource(String memberSource)
{
this.memberSource = memberSource;
return (this);
}
/*******************************************************************************
** Getter for memberSourceValue
*******************************************************************************/
public String getMemberSourceValue()
{
return (this.memberSourceValue);
}
/*******************************************************************************
** Setter for memberSourceValue
*******************************************************************************/
public void setMemberSourceValue(String memberSourceValue)
{
this.memberSourceValue = memberSourceValue;
}
/*******************************************************************************
** Fluent setter for memberSourceValue
*******************************************************************************/
public AlertsTeam withMemberSourceValue(String memberSourceValue)
{
this.memberSourceValue = memberSourceValue;
return (this);
}
/*******************************************************************************
** Getter for description
*******************************************************************************/
public String getDescription()
{
return (this.description);
}
/*******************************************************************************
** Setter for description
*******************************************************************************/
public void setDescription(String description)
{
this.description = description;
}
/*******************************************************************************
** Fluent setter for description
*******************************************************************************/
public AlertsTeam withDescription(String description)
{
this.description = description;
return (this);
}
/*******************************************************************************
** Getter for createDate
*******************************************************************************/
public Instant getCreateDate()
{
return (this.createDate);
}
/*******************************************************************************
** Setter for createDate
*******************************************************************************/
public void setCreateDate(Instant createDate)
{
this.createDate = createDate;
}
/*******************************************************************************
** Fluent setter for createDate
*******************************************************************************/
public AlertsTeam withCreateDate(Instant createDate)
{
this.createDate = createDate;
return (this);
}
/*******************************************************************************
** Getter for modifyDate
*******************************************************************************/
public Instant getModifyDate()
{
return (this.modifyDate);
}
/*******************************************************************************
** Setter for modifyDate
*******************************************************************************/
public void setModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
}
/*******************************************************************************
** Fluent setter for modifyDate
*******************************************************************************/
public AlertsTeam withModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
return (this);
}
}
@@ -0,0 +1,259 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.model;
import java.time.Instant;
import com.kingsrook.qqq.backend.core.model.data.QField;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.data.QRecordEntity;
import com.kingsrook.qqq.backend.core.model.metadata.fields.ValueTooLongBehavior;
/*******************************************************************************
** One user in a team.
**
** Generated from the qbit-alerts schema (one definition for the entity,
** the Liquibase changelog and the test DDL).
*******************************************************************************/
public class AlertsTeamMember extends QRecordEntity
{
public static final String TABLE_NAME = "alerts_team_member";
@QField(isEditable = false, isPrimaryKey = true)
private Integer id;
@QField(isRequired = true, possibleValueSourceName = "alerts_team", label = "Team")
private Integer teamId;
@QField(isRequired = true, maxLength = 100, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, label = "User")
private String userId;
@QField(maxLength = 16, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, possibleValueSourceName = "alerts_team_role")
private String role;
@QField(isEditable = false)
private Instant createDate;
@QField(isEditable = false)
private Instant modifyDate;
/*******************************************************************************
** Default constructor.
*******************************************************************************/
public AlertsTeamMember()
{
}
/*******************************************************************************
** Constructor that populates from a QRecord.
*******************************************************************************/
public AlertsTeamMember(QRecord record)
{
populateFromQRecord(record);
}
/*******************************************************************************
** Getter for id
*******************************************************************************/
public Integer getId()
{
return (this.id);
}
/*******************************************************************************
** Setter for id
*******************************************************************************/
public void setId(Integer id)
{
this.id = id;
}
/*******************************************************************************
** Fluent setter for id
*******************************************************************************/
public AlertsTeamMember withId(Integer id)
{
this.id = id;
return (this);
}
/*******************************************************************************
** Getter for teamId
*******************************************************************************/
public Integer getTeamId()
{
return (this.teamId);
}
/*******************************************************************************
** Setter for teamId
*******************************************************************************/
public void setTeamId(Integer teamId)
{
this.teamId = teamId;
}
/*******************************************************************************
** Fluent setter for teamId
*******************************************************************************/
public AlertsTeamMember withTeamId(Integer teamId)
{
this.teamId = teamId;
return (this);
}
/*******************************************************************************
** Getter for userId
*******************************************************************************/
public String getUserId()
{
return (this.userId);
}
/*******************************************************************************
** Setter for userId
*******************************************************************************/
public void setUserId(String userId)
{
this.userId = userId;
}
/*******************************************************************************
** Fluent setter for userId
*******************************************************************************/
public AlertsTeamMember withUserId(String userId)
{
this.userId = userId;
return (this);
}
/*******************************************************************************
** Getter for role
*******************************************************************************/
public String getRole()
{
return (this.role);
}
/*******************************************************************************
** Setter for role
*******************************************************************************/
public void setRole(String role)
{
this.role = role;
}
/*******************************************************************************
** Fluent setter for role
*******************************************************************************/
public AlertsTeamMember withRole(String role)
{
this.role = role;
return (this);
}
/*******************************************************************************
** Getter for createDate
*******************************************************************************/
public Instant getCreateDate()
{
return (this.createDate);
}
/*******************************************************************************
** Setter for createDate
*******************************************************************************/
public void setCreateDate(Instant createDate)
{
this.createDate = createDate;
}
/*******************************************************************************
** Fluent setter for createDate
*******************************************************************************/
public AlertsTeamMember withCreateDate(Instant createDate)
{
this.createDate = createDate;
return (this);
}
/*******************************************************************************
** Getter for modifyDate
*******************************************************************************/
public Instant getModifyDate()
{
return (this.modifyDate);
}
/*******************************************************************************
** Setter for modifyDate
*******************************************************************************/
public void setModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
}
/*******************************************************************************
** Fluent setter for modifyDate
*******************************************************************************/
public AlertsTeamMember withModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
return (this);
}
}
@@ -0,0 +1,805 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.model;
import java.time.Instant;
import com.kingsrook.qqq.backend.core.model.data.QField;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.data.QRecordEntity;
import com.kingsrook.qqq.backend.core.model.metadata.fields.ValueTooLongBehavior;
/*******************************************************************************
** A kind of problem a source can report (e.g. cdn.purge.dead), synced from
** QAlertTypeMetaData at startup. Metadata fields are refreshed at boot; the
** admin fields (enabled, severityOverride, groupId, notify) are kept.
**
** Generated from the qbit-alerts schema (one definition for the entity,
** the Liquibase changelog and the test DDL).
*******************************************************************************/
public class AlertsType extends QRecordEntity
{
public static final String TABLE_NAME = "alerts_type";
@QField(isEditable = false, isPrimaryKey = true)
private Integer id;
@QField(isRequired = true, isEditable = false, maxLength = 200, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String name;
@QField(maxLength = 200, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String label;
@QField(isEditable = false, maxLength = 100, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, label = "Source")
private String sourceName;
@QField(possibleValueSourceName = "alerts_group", label = "Group")
private Integer groupId;
@QField(isEditable = false, maxLength = 16, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, possibleValueSourceName = "alerts_severity")
private String defaultSeverity;
@QField(maxLength = 16, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, possibleValueSourceName = "alerts_severity")
private String severityOverride;
@QField()
private Boolean enabled;
@QField(isEditable = false)
private Boolean installed;
@QField()
private Boolean notify;
@QField()
private String description;
@QField(label = "How to Fix")
private String howToFix;
@QField(isEditable = false, maxLength = 100, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, label = "Subject Table")
private String subjectTableName;
@QField(isEditable = false, maxLength = 200, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String visibilityPermission;
@QField(maxLength = 20, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, possibleValueSourceName = "alerts_resolve_mode")
private String resolveMode;
@QField()
private Integer quietPeriodMinutes;
@QField(maxLength = 16, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, possibleValueSourceName = "alerts_detail_level")
private String externalDetailCeiling;
@QField()
private Integer reminderIntervalMinutes;
@QField(isEditable = false)
private Instant lastRaisedAt;
@QField(isEditable = false)
private Integer openCount;
@QField(isEditable = false)
private Instant createDate;
@QField(isEditable = false)
private Instant modifyDate;
/*******************************************************************************
** Default constructor.
*******************************************************************************/
public AlertsType()
{
}
/*******************************************************************************
** Constructor that populates from a QRecord.
*******************************************************************************/
public AlertsType(QRecord record)
{
populateFromQRecord(record);
}
/*******************************************************************************
** Getter for id
*******************************************************************************/
public Integer getId()
{
return (this.id);
}
/*******************************************************************************
** Setter for id
*******************************************************************************/
public void setId(Integer id)
{
this.id = id;
}
/*******************************************************************************
** Fluent setter for id
*******************************************************************************/
public AlertsType withId(Integer id)
{
this.id = id;
return (this);
}
/*******************************************************************************
** Getter for name
*******************************************************************************/
public String getName()
{
return (this.name);
}
/*******************************************************************************
** Setter for name
*******************************************************************************/
public void setName(String name)
{
this.name = name;
}
/*******************************************************************************
** Fluent setter for name
*******************************************************************************/
public AlertsType withName(String name)
{
this.name = name;
return (this);
}
/*******************************************************************************
** Getter for label
*******************************************************************************/
public String getLabel()
{
return (this.label);
}
/*******************************************************************************
** Setter for label
*******************************************************************************/
public void setLabel(String label)
{
this.label = label;
}
/*******************************************************************************
** Fluent setter for label
*******************************************************************************/
public AlertsType withLabel(String label)
{
this.label = label;
return (this);
}
/*******************************************************************************
** Getter for sourceName
*******************************************************************************/
public String getSourceName()
{
return (this.sourceName);
}
/*******************************************************************************
** Setter for sourceName
*******************************************************************************/
public void setSourceName(String sourceName)
{
this.sourceName = sourceName;
}
/*******************************************************************************
** Fluent setter for sourceName
*******************************************************************************/
public AlertsType withSourceName(String sourceName)
{
this.sourceName = sourceName;
return (this);
}
/*******************************************************************************
** Getter for groupId
*******************************************************************************/
public Integer getGroupId()
{
return (this.groupId);
}
/*******************************************************************************
** Setter for groupId
*******************************************************************************/
public void setGroupId(Integer groupId)
{
this.groupId = groupId;
}
/*******************************************************************************
** Fluent setter for groupId
*******************************************************************************/
public AlertsType withGroupId(Integer groupId)
{
this.groupId = groupId;
return (this);
}
/*******************************************************************************
** Getter for defaultSeverity
*******************************************************************************/
public String getDefaultSeverity()
{
return (this.defaultSeverity);
}
/*******************************************************************************
** Setter for defaultSeverity
*******************************************************************************/
public void setDefaultSeverity(String defaultSeverity)
{
this.defaultSeverity = defaultSeverity;
}
/*******************************************************************************
** Fluent setter for defaultSeverity
*******************************************************************************/
public AlertsType withDefaultSeverity(String defaultSeverity)
{
this.defaultSeverity = defaultSeverity;
return (this);
}
/*******************************************************************************
** Getter for severityOverride
*******************************************************************************/
public String getSeverityOverride()
{
return (this.severityOverride);
}
/*******************************************************************************
** Setter for severityOverride
*******************************************************************************/
public void setSeverityOverride(String severityOverride)
{
this.severityOverride = severityOverride;
}
/*******************************************************************************
** Fluent setter for severityOverride
*******************************************************************************/
public AlertsType withSeverityOverride(String severityOverride)
{
this.severityOverride = severityOverride;
return (this);
}
/*******************************************************************************
** Getter for enabled
*******************************************************************************/
public Boolean getEnabled()
{
return (this.enabled);
}
/*******************************************************************************
** Setter for enabled
*******************************************************************************/
public void setEnabled(Boolean enabled)
{
this.enabled = enabled;
}
/*******************************************************************************
** Fluent setter for enabled
*******************************************************************************/
public AlertsType withEnabled(Boolean enabled)
{
this.enabled = enabled;
return (this);
}
/*******************************************************************************
** Getter for installed
*******************************************************************************/
public Boolean getInstalled()
{
return (this.installed);
}
/*******************************************************************************
** Setter for installed
*******************************************************************************/
public void setInstalled(Boolean installed)
{
this.installed = installed;
}
/*******************************************************************************
** Fluent setter for installed
*******************************************************************************/
public AlertsType withInstalled(Boolean installed)
{
this.installed = installed;
return (this);
}
/*******************************************************************************
** Getter for notify
*******************************************************************************/
public Boolean getNotify()
{
return (this.notify);
}
/*******************************************************************************
** Setter for notify
*******************************************************************************/
public void setNotify(Boolean notify)
{
this.notify = notify;
}
/*******************************************************************************
** Fluent setter for notify
*******************************************************************************/
public AlertsType withNotify(Boolean notify)
{
this.notify = notify;
return (this);
}
/*******************************************************************************
** Getter for description
*******************************************************************************/
public String getDescription()
{
return (this.description);
}
/*******************************************************************************
** Setter for description
*******************************************************************************/
public void setDescription(String description)
{
this.description = description;
}
/*******************************************************************************
** Fluent setter for description
*******************************************************************************/
public AlertsType withDescription(String description)
{
this.description = description;
return (this);
}
/*******************************************************************************
** Getter for howToFix
*******************************************************************************/
public String getHowToFix()
{
return (this.howToFix);
}
/*******************************************************************************
** Setter for howToFix
*******************************************************************************/
public void setHowToFix(String howToFix)
{
this.howToFix = howToFix;
}
/*******************************************************************************
** Fluent setter for howToFix
*******************************************************************************/
public AlertsType withHowToFix(String howToFix)
{
this.howToFix = howToFix;
return (this);
}
/*******************************************************************************
** Getter for subjectTableName
*******************************************************************************/
public String getSubjectTableName()
{
return (this.subjectTableName);
}
/*******************************************************************************
** Setter for subjectTableName
*******************************************************************************/
public void setSubjectTableName(String subjectTableName)
{
this.subjectTableName = subjectTableName;
}
/*******************************************************************************
** Fluent setter for subjectTableName
*******************************************************************************/
public AlertsType withSubjectTableName(String subjectTableName)
{
this.subjectTableName = subjectTableName;
return (this);
}
/*******************************************************************************
** Getter for visibilityPermission
*******************************************************************************/
public String getVisibilityPermission()
{
return (this.visibilityPermission);
}
/*******************************************************************************
** Setter for visibilityPermission
*******************************************************************************/
public void setVisibilityPermission(String visibilityPermission)
{
this.visibilityPermission = visibilityPermission;
}
/*******************************************************************************
** Fluent setter for visibilityPermission
*******************************************************************************/
public AlertsType withVisibilityPermission(String visibilityPermission)
{
this.visibilityPermission = visibilityPermission;
return (this);
}
/*******************************************************************************
** Getter for resolveMode
*******************************************************************************/
public String getResolveMode()
{
return (this.resolveMode);
}
/*******************************************************************************
** Setter for resolveMode
*******************************************************************************/
public void setResolveMode(String resolveMode)
{
this.resolveMode = resolveMode;
}
/*******************************************************************************
** Fluent setter for resolveMode
*******************************************************************************/
public AlertsType withResolveMode(String resolveMode)
{
this.resolveMode = resolveMode;
return (this);
}
/*******************************************************************************
** Getter for quietPeriodMinutes
*******************************************************************************/
public Integer getQuietPeriodMinutes()
{
return (this.quietPeriodMinutes);
}
/*******************************************************************************
** Setter for quietPeriodMinutes
*******************************************************************************/
public void setQuietPeriodMinutes(Integer quietPeriodMinutes)
{
this.quietPeriodMinutes = quietPeriodMinutes;
}
/*******************************************************************************
** Fluent setter for quietPeriodMinutes
*******************************************************************************/
public AlertsType withQuietPeriodMinutes(Integer quietPeriodMinutes)
{
this.quietPeriodMinutes = quietPeriodMinutes;
return (this);
}
/*******************************************************************************
** Getter for externalDetailCeiling
*******************************************************************************/
public String getExternalDetailCeiling()
{
return (this.externalDetailCeiling);
}
/*******************************************************************************
** Setter for externalDetailCeiling
*******************************************************************************/
public void setExternalDetailCeiling(String externalDetailCeiling)
{
this.externalDetailCeiling = externalDetailCeiling;
}
/*******************************************************************************
** Fluent setter for externalDetailCeiling
*******************************************************************************/
public AlertsType withExternalDetailCeiling(String externalDetailCeiling)
{
this.externalDetailCeiling = externalDetailCeiling;
return (this);
}
/*******************************************************************************
** Getter for reminderIntervalMinutes
*******************************************************************************/
public Integer getReminderIntervalMinutes()
{
return (this.reminderIntervalMinutes);
}
/*******************************************************************************
** Setter for reminderIntervalMinutes
*******************************************************************************/
public void setReminderIntervalMinutes(Integer reminderIntervalMinutes)
{
this.reminderIntervalMinutes = reminderIntervalMinutes;
}
/*******************************************************************************
** Fluent setter for reminderIntervalMinutes
*******************************************************************************/
public AlertsType withReminderIntervalMinutes(Integer reminderIntervalMinutes)
{
this.reminderIntervalMinutes = reminderIntervalMinutes;
return (this);
}
/*******************************************************************************
** Getter for lastRaisedAt
*******************************************************************************/
public Instant getLastRaisedAt()
{
return (this.lastRaisedAt);
}
/*******************************************************************************
** Setter for lastRaisedAt
*******************************************************************************/
public void setLastRaisedAt(Instant lastRaisedAt)
{
this.lastRaisedAt = lastRaisedAt;
}
/*******************************************************************************
** Fluent setter for lastRaisedAt
*******************************************************************************/
public AlertsType withLastRaisedAt(Instant lastRaisedAt)
{
this.lastRaisedAt = lastRaisedAt;
return (this);
}
/*******************************************************************************
** Getter for openCount
*******************************************************************************/
public Integer getOpenCount()
{
return (this.openCount);
}
/*******************************************************************************
** Setter for openCount
*******************************************************************************/
public void setOpenCount(Integer openCount)
{
this.openCount = openCount;
}
/*******************************************************************************
** Fluent setter for openCount
*******************************************************************************/
public AlertsType withOpenCount(Integer openCount)
{
this.openCount = openCount;
return (this);
}
/*******************************************************************************
** Getter for createDate
*******************************************************************************/
public Instant getCreateDate()
{
return (this.createDate);
}
/*******************************************************************************
** Setter for createDate
*******************************************************************************/
public void setCreateDate(Instant createDate)
{
this.createDate = createDate;
}
/*******************************************************************************
** Fluent setter for createDate
*******************************************************************************/
public AlertsType withCreateDate(Instant createDate)
{
this.createDate = createDate;
return (this);
}
/*******************************************************************************
** Getter for modifyDate
*******************************************************************************/
public Instant getModifyDate()
{
return (this.modifyDate);
}
/*******************************************************************************
** Setter for modifyDate
*******************************************************************************/
public void setModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
}
/*******************************************************************************
** Fluent setter for modifyDate
*******************************************************************************/
public AlertsType withModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
return (this);
}
}
@@ -0,0 +1,601 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.model;
import java.time.Instant;
import com.kingsrook.qqq.backend.core.model.data.QField;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.data.QRecordEntity;
import com.kingsrook.qqq.backend.core.model.metadata.fields.ValueTooLongBehavior;
/*******************************************************************************
** Per-user alert settings: email address, quiet hours, digest hour, time zone
** and a vacation pause. Created with defaults the first time a user opens
** Alerts.
**
** Generated from the qbit-alerts schema (one definition for the entity,
** the Liquibase changelog and the test DDL).
*******************************************************************************/
public class AlertsUserPreference extends QRecordEntity
{
public static final String TABLE_NAME = "alerts_user_preference";
@QField(isEditable = false, isPrimaryKey = true)
private Integer id;
@QField(isRequired = true, isEditable = false, maxLength = 100, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, label = "User")
private String userId;
@QField(maxLength = 200, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, label = "Name")
private String userLabel;
@QField(maxLength = 300, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String emailAddress;
@QField(maxLength = 64, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String timeZone;
@QField(maxLength = 5, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String quietHoursStart;
@QField(maxLength = 5, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String quietHoursEnd;
@QField(maxLength = 50, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String quietDays;
@QField(maxLength = 16, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, possibleValueSourceName = "alerts_severity")
private String quietBypassSeverity;
@QField()
private Integer digestHour;
@QField(maxLength = 200, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS, label = "Default Channels")
private String defaultChannelIds;
@QField()
private Boolean emailEnabled;
@QField(label = "In-App Enabled")
private Boolean inAppEnabled;
@QField()
private Instant pausedUntil;
@QField(isEditable = false)
private Instant createDate;
@QField(isEditable = false)
private Instant modifyDate;
/*******************************************************************************
** Default constructor.
*******************************************************************************/
public AlertsUserPreference()
{
}
/*******************************************************************************
** Constructor that populates from a QRecord.
*******************************************************************************/
public AlertsUserPreference(QRecord record)
{
populateFromQRecord(record);
}
/*******************************************************************************
** Getter for id
*******************************************************************************/
public Integer getId()
{
return (this.id);
}
/*******************************************************************************
** Setter for id
*******************************************************************************/
public void setId(Integer id)
{
this.id = id;
}
/*******************************************************************************
** Fluent setter for id
*******************************************************************************/
public AlertsUserPreference withId(Integer id)
{
this.id = id;
return (this);
}
/*******************************************************************************
** Getter for userId
*******************************************************************************/
public String getUserId()
{
return (this.userId);
}
/*******************************************************************************
** Setter for userId
*******************************************************************************/
public void setUserId(String userId)
{
this.userId = userId;
}
/*******************************************************************************
** Fluent setter for userId
*******************************************************************************/
public AlertsUserPreference withUserId(String userId)
{
this.userId = userId;
return (this);
}
/*******************************************************************************
** Getter for userLabel
*******************************************************************************/
public String getUserLabel()
{
return (this.userLabel);
}
/*******************************************************************************
** Setter for userLabel
*******************************************************************************/
public void setUserLabel(String userLabel)
{
this.userLabel = userLabel;
}
/*******************************************************************************
** Fluent setter for userLabel
*******************************************************************************/
public AlertsUserPreference withUserLabel(String userLabel)
{
this.userLabel = userLabel;
return (this);
}
/*******************************************************************************
** Getter for emailAddress
*******************************************************************************/
public String getEmailAddress()
{
return (this.emailAddress);
}
/*******************************************************************************
** Setter for emailAddress
*******************************************************************************/
public void setEmailAddress(String emailAddress)
{
this.emailAddress = emailAddress;
}
/*******************************************************************************
** Fluent setter for emailAddress
*******************************************************************************/
public AlertsUserPreference withEmailAddress(String emailAddress)
{
this.emailAddress = emailAddress;
return (this);
}
/*******************************************************************************
** Getter for timeZone
*******************************************************************************/
public String getTimeZone()
{
return (this.timeZone);
}
/*******************************************************************************
** Setter for timeZone
*******************************************************************************/
public void setTimeZone(String timeZone)
{
this.timeZone = timeZone;
}
/*******************************************************************************
** Fluent setter for timeZone
*******************************************************************************/
public AlertsUserPreference withTimeZone(String timeZone)
{
this.timeZone = timeZone;
return (this);
}
/*******************************************************************************
** Getter for quietHoursStart
*******************************************************************************/
public String getQuietHoursStart()
{
return (this.quietHoursStart);
}
/*******************************************************************************
** Setter for quietHoursStart
*******************************************************************************/
public void setQuietHoursStart(String quietHoursStart)
{
this.quietHoursStart = quietHoursStart;
}
/*******************************************************************************
** Fluent setter for quietHoursStart
*******************************************************************************/
public AlertsUserPreference withQuietHoursStart(String quietHoursStart)
{
this.quietHoursStart = quietHoursStart;
return (this);
}
/*******************************************************************************
** Getter for quietHoursEnd
*******************************************************************************/
public String getQuietHoursEnd()
{
return (this.quietHoursEnd);
}
/*******************************************************************************
** Setter for quietHoursEnd
*******************************************************************************/
public void setQuietHoursEnd(String quietHoursEnd)
{
this.quietHoursEnd = quietHoursEnd;
}
/*******************************************************************************
** Fluent setter for quietHoursEnd
*******************************************************************************/
public AlertsUserPreference withQuietHoursEnd(String quietHoursEnd)
{
this.quietHoursEnd = quietHoursEnd;
return (this);
}
/*******************************************************************************
** Getter for quietDays
*******************************************************************************/
public String getQuietDays()
{
return (this.quietDays);
}
/*******************************************************************************
** Setter for quietDays
*******************************************************************************/
public void setQuietDays(String quietDays)
{
this.quietDays = quietDays;
}
/*******************************************************************************
** Fluent setter for quietDays
*******************************************************************************/
public AlertsUserPreference withQuietDays(String quietDays)
{
this.quietDays = quietDays;
return (this);
}
/*******************************************************************************
** Getter for quietBypassSeverity
*******************************************************************************/
public String getQuietBypassSeverity()
{
return (this.quietBypassSeverity);
}
/*******************************************************************************
** Setter for quietBypassSeverity
*******************************************************************************/
public void setQuietBypassSeverity(String quietBypassSeverity)
{
this.quietBypassSeverity = quietBypassSeverity;
}
/*******************************************************************************
** Fluent setter for quietBypassSeverity
*******************************************************************************/
public AlertsUserPreference withQuietBypassSeverity(String quietBypassSeverity)
{
this.quietBypassSeverity = quietBypassSeverity;
return (this);
}
/*******************************************************************************
** Getter for digestHour
*******************************************************************************/
public Integer getDigestHour()
{
return (this.digestHour);
}
/*******************************************************************************
** Setter for digestHour
*******************************************************************************/
public void setDigestHour(Integer digestHour)
{
this.digestHour = digestHour;
}
/*******************************************************************************
** Fluent setter for digestHour
*******************************************************************************/
public AlertsUserPreference withDigestHour(Integer digestHour)
{
this.digestHour = digestHour;
return (this);
}
/*******************************************************************************
** Getter for defaultChannelIds
*******************************************************************************/
public String getDefaultChannelIds()
{
return (this.defaultChannelIds);
}
/*******************************************************************************
** Setter for defaultChannelIds
*******************************************************************************/
public void setDefaultChannelIds(String defaultChannelIds)
{
this.defaultChannelIds = defaultChannelIds;
}
/*******************************************************************************
** Fluent setter for defaultChannelIds
*******************************************************************************/
public AlertsUserPreference withDefaultChannelIds(String defaultChannelIds)
{
this.defaultChannelIds = defaultChannelIds;
return (this);
}
/*******************************************************************************
** Getter for emailEnabled
*******************************************************************************/
public Boolean getEmailEnabled()
{
return (this.emailEnabled);
}
/*******************************************************************************
** Setter for emailEnabled
*******************************************************************************/
public void setEmailEnabled(Boolean emailEnabled)
{
this.emailEnabled = emailEnabled;
}
/*******************************************************************************
** Fluent setter for emailEnabled
*******************************************************************************/
public AlertsUserPreference withEmailEnabled(Boolean emailEnabled)
{
this.emailEnabled = emailEnabled;
return (this);
}
/*******************************************************************************
** Getter for inAppEnabled
*******************************************************************************/
public Boolean getInAppEnabled()
{
return (this.inAppEnabled);
}
/*******************************************************************************
** Setter for inAppEnabled
*******************************************************************************/
public void setInAppEnabled(Boolean inAppEnabled)
{
this.inAppEnabled = inAppEnabled;
}
/*******************************************************************************
** Fluent setter for inAppEnabled
*******************************************************************************/
public AlertsUserPreference withInAppEnabled(Boolean inAppEnabled)
{
this.inAppEnabled = inAppEnabled;
return (this);
}
/*******************************************************************************
** Getter for pausedUntil
*******************************************************************************/
public Instant getPausedUntil()
{
return (this.pausedUntil);
}
/*******************************************************************************
** Setter for pausedUntil
*******************************************************************************/
public void setPausedUntil(Instant pausedUntil)
{
this.pausedUntil = pausedUntil;
}
/*******************************************************************************
** Fluent setter for pausedUntil
*******************************************************************************/
public AlertsUserPreference withPausedUntil(Instant pausedUntil)
{
this.pausedUntil = pausedUntil;
return (this);
}
/*******************************************************************************
** Getter for createDate
*******************************************************************************/
public Instant getCreateDate()
{
return (this.createDate);
}
/*******************************************************************************
** Setter for createDate
*******************************************************************************/
public void setCreateDate(Instant createDate)
{
this.createDate = createDate;
}
/*******************************************************************************
** Fluent setter for createDate
*******************************************************************************/
public AlertsUserPreference withCreateDate(Instant createDate)
{
this.createDate = createDate;
return (this);
}
/*******************************************************************************
** Getter for modifyDate
*******************************************************************************/
public Instant getModifyDate()
{
return (this.modifyDate);
}
/*******************************************************************************
** Setter for modifyDate
*******************************************************************************/
public void setModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
}
/*******************************************************************************
** Fluent setter for modifyDate
*******************************************************************************/
public AlertsUserPreference withModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
return (this);
}
}
@@ -0,0 +1,242 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.notifications;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import com.kingsrook.qbits.alerts.AlertsRuntime;
import com.kingsrook.qbits.alerts.spi.NotificationAudience;
import com.kingsrook.qqq.backend.core.actions.customizers.QCodeLoader;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import com.kingsrook.qqq.backend.core.modules.authentication.QAuthenticationModuleDispatcher;
import com.kingsrook.qqq.backend.core.modules.authentication.QAuthenticationModuleInterface;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
/*******************************************************************************
** Resolves a notification audience to user ids at send time
** (docs/NOTIFICATIONS.md section 4): ALL_USERS and ROLES from the user
** directory, PERMISSION by building each directory user's session, USERS as
** given. The result is capped at maxAudienceSize. Call it as the system user.
*******************************************************************************/
public class AlertsAudienceResolver
{
private static final QLogger LOG = QLogger.getLogger(AlertsAudienceResolver.class);
private final AlertsRuntime runtime;
/*******************************************************************************
** The users an audience reached: ids in order, labels where known, and why
** some could not be resolved.
*******************************************************************************/
public record Resolved(List<String> userIds, Map<String, String> labels, List<String> warnings)
{
}
/*******************************************************************************
** Constructor
*******************************************************************************/
public AlertsAudienceResolver(AlertsRuntime runtime)
{
this.runtime = runtime;
}
/*******************************************************************************
** Resolve an audience to users.
*******************************************************************************/
public Resolved resolve(NotificationAudience audience) throws QException
{
Map<String, String> users = new LinkedHashMap<>();
List<String> warnings = new ArrayList<>();
if(audience == null)
{
warnings.add("No audience is set.");
return (new Resolved(List.of(), Map.of(), warnings));
}
switch(audience.getType())
{
case USERS ->
{
Map<String, String> labels = labelsIfKnown();
for(String userId : audience.getValues())
{
users.put(userId, labels.getOrDefault(userId, userId));
}
if(audience.getValues().isEmpty())
{
warnings.add("Name at least one user id.");
}
}
case ALL_USERS ->
{
for(AlertsUserDirectoryInterface.DirectoryUser user : directory().listUsers())
{
users.put(user.userId(), label(user));
}
}
case ROLES ->
{
Set<String> wanted = audience.getValues().stream().map(role -> role.toLowerCase(Locale.ROOT)).collect(Collectors.toSet());
boolean anyRoles = false;
for(AlertsUserDirectoryInterface.DirectoryUser user : directory().listUsers())
{
Set<String> roles = user.roles() == null ? Set.of() : user.roles();
anyRoles |= !roles.isEmpty();
if(roles.stream().anyMatch(role -> wanted.contains(role.toLowerCase(Locale.ROOT))))
{
users.put(user.userId(), label(user));
}
}
if(!anyRoles)
{
warnings.add("The user directory lists no roles, so a roles audience reaches nobody. Configure a user directory (AlertsQBitConfig.withUserDirectory).");
}
}
case PERMISSION ->
{
String permission = audience.getValues().isEmpty() ? null : audience.getValues().get(0);
boolean anySession = false;
for(AlertsUserDirectoryInterface.DirectoryUser user : permission == null ? List.<AlertsUserDirectoryInterface.DirectoryUser>of() : directory().listUsers())
{
QSession session = automatedSession(user.userId());
anySession |= session != null;
if(session != null && session.hasPermission(permission))
{
users.put(user.userId(), label(user));
}
}
if(permission == null)
{
warnings.add("Name the permission.");
}
else if(!anySession)
{
warnings.add("The authentication module could not build sessions for users, so their permissions are unknown and a permission audience reaches nobody.");
}
}
default -> warnings.add("Unknown audience.");
}
List<String> ids = new ArrayList<>(users.keySet());
int max = runtime.getConfig().getMaxAudienceSize();
if(ids.size() > max)
{
warnings.add("The audience has " + ids.size() + " users; only the first " + max + " (maxAudienceSize) are reached.");
ids = new ArrayList<>(ids.subList(0, max));
}
Map<String, String> labels = new LinkedHashMap<>();
for(String id : ids)
{
labels.put(id, users.get(id));
}
return (new Resolved(ids, labels, warnings));
}
/*******************************************************************************
** The configured directory, or the known-users default.
*******************************************************************************/
public AlertsUserDirectoryInterface directory()
{
QCodeReference reference = runtime.getConfig().getUserDirectory();
if(reference != null)
{
AlertsUserDirectoryInterface directory = QCodeLoader.getAdHoc(AlertsUserDirectoryInterface.class, reference);
if(directory != null)
{
return (directory);
}
}
return (new KnownUsersDirectory());
}
/*******************************************************************************
** Labels for the directory's users (empty when it can't be read).
*******************************************************************************/
private Map<String, String> labelsIfKnown()
{
Map<String, String> labels = new LinkedHashMap<>();
try
{
for(AlertsUserDirectoryInterface.DirectoryUser user : directory().listUsers())
{
labels.put(user.userId(), label(user));
}
}
catch(Exception e)
{
LOG.debug("Could not read the user directory for labels", e);
}
return (labels);
}
/*******************************************************************************
**
*******************************************************************************/
private static String label(AlertsUserDirectoryInterface.DirectoryUser user)
{
return (user.label() == null || user.label().isBlank() ? user.userId() : user.label());
}
/*******************************************************************************
** A session for a user from the instance's authentication module (null
** when it can't make one).
*******************************************************************************/
private QSession automatedSession(String userId)
{
try
{
QInstance qInstance = runtime.getQInstance();
if(qInstance.getAuthentication() == null)
{
return (null);
}
QAuthenticationModuleInterface module = new QAuthenticationModuleDispatcher().getQModule(qInstance.getAuthentication());
return (module.createAutomatedSessionForUser(qInstance, userId));
}
catch(Exception e)
{
LOG.debug("Could not build a session for a user", e, logPair("userId", userId));
return (null);
}
}
}
@@ -0,0 +1,169 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.notifications;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import com.kingsrook.qbits.alerts.AlertsRuntime;
import com.kingsrook.qbits.alerts.spi.AlertLink;
import com.kingsrook.qbits.alerts.spi.NotificationAudience;
import com.kingsrook.qbits.alerts.spi.NotificationCategory;
import com.kingsrook.qbits.alerts.spi.NotificationSeverity;
import com.kingsrook.qbits.alerts.spi.NotificationSignal;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
/*******************************************************************************
** Ready-made notifications for the automatic sources hosts wire up
** (docs/NOTIFICATIONS.md 6.1): security notices, shares and assignments,
** and release announcements. Each one is a NotificationSignal sent through
** the alerts sink (queued; it never throws into the caller). With no Alerts
** qbit installed they do nothing.
**
** Core has no sign-in or API key events yet, so a host calls the security
** notices from its authentication customizer or API key screens.
*******************************************************************************/
public final class AlertsNotices
{
private static final QLogger LOG = QLogger.getLogger(AlertsNotices.class);
private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("MMM d, yyyy").withZone(ZoneOffset.UTC);
/*******************************************************************************
** Helpers only.
*******************************************************************************/
private AlertsNotices()
{
}
/*******************************************************************************
** A sign-in from a new device or place (where: e.g. "Firefox on Windows,
** near Columbus, OH").
*******************************************************************************/
public static void newSignIn(String userId, String where)
{
send(new NotificationSignal("New sign-in to your account")
.withBody("A sign-in from " + where + ". If this wasn't you, change your password now.")
.withSeverity(NotificationSeverity.WARNING), userId, null);
}
/*******************************************************************************
** An API key was created for the user.
*******************************************************************************/
public static void apiKeyCreated(String userId, String keyLabel)
{
send(new NotificationSignal("API key created: " + keyLabel)
.withBody("A new API key was created on your account. If you didn't create it, revoke it now.")
.withSeverity(NotificationSeverity.INFO), userId, null);
}
/*******************************************************************************
** An API key expires soon (one notification per key, refreshed on repeat).
*******************************************************************************/
public static void apiKeyExpiring(String userId, String keyLabel, Instant expiresAt)
{
send(new NotificationSignal("API key expires " + DATE.format(expiresAt) + ": " + keyLabel)
.withBody("Create a new key and update the clients that use this one before it expires.")
.withSeverity(NotificationSeverity.WARNING), userId, "apikey-expiring:" + keyLabel);
}
/*******************************************************************************
** The user's permissions or roles changed (what: e.g. "You were added to
** the Editors role").
*******************************************************************************/
public static void permissionChanged(String userId, String what)
{
send(new NotificationSignal("Your access changed")
.withBody(what + ". If you didn't expect this, contact an administrator.")
.withSeverity(NotificationSeverity.INFO), userId, null);
}
/*******************************************************************************
** Something was shared with or assigned to a user (a notebook, a record
** lock, an approval waiting for them).
*******************************************************************************/
public static void shared(String userId, String title, AlertLink link, String sourceName)
{
sendSignal(new NotificationSignal(title).withCategory(NotificationCategory.SHARE).withSourceName(sourceName).withLink(link)
.withAudience(NotificationAudience.user(userId)));
}
/*******************************************************************************
** A release announcement to every user ("Version 2.4 is out").
*******************************************************************************/
public static void release(String version, String notesMarkdown, AlertLink link)
{
sendSignal(new NotificationSignal("Version " + version + " is out").withBody(notesMarkdown).withSeverity(NotificationSeverity.SUCCESS)
.withCategory(NotificationCategory.RELEASE).withSourceName("release").withSourceKey("release:" + version).withLink(link)
.withAudience(NotificationAudience.allUsers()));
}
/*******************************************************************************
**
*******************************************************************************/
private static void send(NotificationSignal signal, String userId, String sourceKey)
{
if(userId == null)
{
return;
}
sendSignal(signal.withCategory(NotificationCategory.SECURITY).withSourceName("security").withSourceKey(sourceKey)
.withAudience(NotificationAudience.user(userId)));
}
/*******************************************************************************
** Through the installed qbit's sink (nothing when it isn't installed).
*******************************************************************************/
private static void sendSignal(NotificationSignal signal)
{
try
{
QInstance qInstance = QContext.getQInstance();
AlertsRuntime runtime = AlertsRuntime.find(qInstance);
if(runtime != null && signal.getAudience() != null)
{
runtime.sink().notify(signal);
}
}
catch(Exception e)
{
LOG.warn("Could not send a notification", e);
}
}
}
@@ -0,0 +1,47 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.notifications;
import java.util.List;
import java.util.Set;
import com.kingsrook.qqq.backend.core.exceptions.QException;
/*******************************************************************************
** The host's list of people, for notification audiences (docs/NOTIFICATIONS.md
** section 4). Set it with AlertsQBitConfig.withUserDirectory. Without one,
** the directory is everyone who has used Alerts (KnownUsersDirectory).
*******************************************************************************/
public interface AlertsUserDirectoryInterface
{
/*******************************************************************************
** Every active user, with their roles or groups (for ROLES audiences).
*******************************************************************************/
List<DirectoryUser> listUsers() throws QException;
/*******************************************************************************
** One person: their QQQ user id (the session's user id reference), a
** display label, an email address (may be null), and their roles or groups.
*******************************************************************************/
record DirectoryUser(String userId, String label, String emailAddress, Set<String> roles)
{
}
}
@@ -0,0 +1,56 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.notifications;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import com.kingsrook.qbits.alerts.engine.AlertsDb;
import com.kingsrook.qbits.alerts.model.AlertsUserPreference;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
/*******************************************************************************
** The default user directory: everyone who has used Alerts, that is, who has
** a row in My Alert Settings (created the first time a user opens the bell,
** the Alerts home or a record panel). It knows no roles. Called as the
** system user.
*******************************************************************************/
public class KnownUsersDirectory implements AlertsUserDirectoryInterface
{
/*******************************************************************************
**
*******************************************************************************/
@Override
public List<DirectoryUser> listUsers() throws QException
{
List<DirectoryUser> users = new ArrayList<>();
for(QRecord preference : AlertsDb.query(AlertsUserPreference.TABLE_NAME, new QQueryFilter()))
{
String userId = preference.getValueString("userId");
if(userId != null)
{
users.add(new DirectoryUser(userId, preference.getValueString("userLabel"), preference.getValueString("emailAddress"), Set.of()));
}
}
return (users);
}
}
@@ -0,0 +1,372 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.notifications;
import java.time.DateTimeException;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.kingsrook.qbits.alerts.AlertsQBitConfig;
import com.kingsrook.qbits.alerts.AlertsRuntime;
import com.kingsrook.qbits.alerts.engine.AlertsDb;
import com.kingsrook.qbits.alerts.model.AlertsNotification;
import com.kingsrook.qbits.alerts.model.AlertsNotificationPreference;
import com.kingsrook.qbits.alerts.model.AlertsNotificationRecipient;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.EmailMode;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.EmailStatus;
import com.kingsrook.qbits.alerts.model.AlertsUserPreference;
import com.kingsrook.qbits.alerts.spi.NotificationCategory;
import com.kingsrook.qbits.alerts.spi.NotificationSeverity;
import com.kingsrook.qqq.backend.core.actions.messaging.SendMessageAction;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.actions.messaging.Content;
import com.kingsrook.qqq.backend.core.model.actions.messaging.MultiParty;
import com.kingsrook.qqq.backend.core.model.actions.messaging.Party;
import com.kingsrook.qqq.backend.core.model.actions.messaging.SendMessageInput;
import com.kingsrook.qqq.backend.core.model.actions.messaging.email.EmailContentRole;
import com.kingsrook.qqq.backend.core.model.actions.messaging.email.EmailPartyRole;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
/*******************************************************************************
** Email for user notifications (docs/NOTIFICATIONS.md section 7), opt-in per
** user and category in My Notification Settings:
** - IMMEDIATE: one email per notification at or above the minimum severity;
** - DAILY_DIGEST: one email at the user's digest hour (in their time zone,
** from My Alert Settings) listing the day's unread notifications.
** Inert without a messaging provider and a From address. ALERT
** notifications are never emailed here (alert subscriptions already email
** them). SECURITY emails carry the title and link only. Runs as the system
** user from the delivery job.
*******************************************************************************/
public class NotificationEmailer
{
private static final QLogger LOG = QLogger.getLogger(NotificationEmailer.class);
static final int SCAN = 500;
private final AlertsRuntime runtime;
/*******************************************************************************
** What one run did.
*******************************************************************************/
public record Result(int sent, int digests, int skipped, int failed)
{
}
/*******************************************************************************
** Constructor
*******************************************************************************/
public NotificationEmailer(AlertsRuntime runtime)
{
this.runtime = runtime;
}
/*******************************************************************************
** Whether email can be sent at all.
*******************************************************************************/
public boolean isConfigured()
{
AlertsQBitConfig config = runtime.getConfig();
return (StringUtils.hasContent(config.getMessagingProviderName()) && StringUtils.hasContent(config.getFromAddress()));
}
/*******************************************************************************
** Send what is due: immediate emails, and digests for users at their hour.
*******************************************************************************/
public Result run() throws QException
{
if(!isConfigured())
{
return (new Result(0, 0, 0, 0));
}
Instant now = runtime.now();
return (runtime.asSystem(() ->
{
Map<String, Map<String, QRecord>> preferences = new HashMap<>();
for(QRecord preference : AlertsDb.query(AlertsNotificationPreference.TABLE_NAME, new QQueryFilter()
.withCriteria("emailMode", QCriteriaOperator.IN, List.of(EmailMode.IMMEDIATE.name(), EmailMode.DAILY_DIGEST.name()))))
{
preferences.computeIfAbsent(preference.getValueString("userId"), k -> new HashMap<>()).put(preference.getValueString("category"), preference);
}
if(preferences.isEmpty())
{
return (new Result(0, 0, 0, 0));
}
List<QRecord> recipients = AlertsDb.query(AlertsNotificationRecipient.TABLE_NAME, new QQueryFilter()
.withCriteria("userId", QCriteriaOperator.IN, new ArrayList<>(preferences.keySet()))
.withCriteria("emailStatus", QCriteriaOperator.IN, List.of(EmailStatus.NONE.name(), EmailStatus.PENDING.name()))
.withCriteria("deliveredAt", QCriteriaOperator.GREATER_THAN_OR_EQUALS, now.minus(1, ChronoUnit.DAYS))
.withLimit(SCAN));
Map<Integer, QRecord> notifications = notifications(recipients, now);
Map<String, QRecord> settings = userSettings(preferences.keySet());
int sent = 0;
int skipped = 0;
int failed = 0;
Map<String, List<QRecord[]>> digests = new LinkedHashMap<>();
for(QRecord recipient : recipients)
{
QRecord notification = notifications.get(recipient.getValueInteger("notificationId"));
String userId = recipient.getValueString("userId");
QRecord preference = notification == null ? null : preferences.get(userId).get(notification.getValueString("category"));
if(notification == null || preference == null || NotificationCategory.ALERT.name().equals(notification.getValueString("category"))
|| !atLeast(notification.getValueString("severity"), preference.getValueString("emailMinSeverity")))
{
mark(recipient, EmailStatus.SKIPPED, null);
skipped++;
}
else if(EmailMode.IMMEDIATE.name().equals(preference.getValueString("emailMode")))
{
boolean ok = send(address(settings.get(userId)), notification.getValueString("title"), List.of(notification));
mark(recipient, ok ? EmailStatus.SENT : EmailStatus.FAILED, ok ? now : null);
if(ok)
{
sent++;
}
else
{
failed++;
}
}
else if(recipient.getValue("readAt") == null)
{
digests.computeIfAbsent(userId, k -> new ArrayList<>()).add(new QRecord[] {recipient, notification});
}
}
int digestCount = 0;
for(Map.Entry<String, List<QRecord[]>> digest : digests.entrySet())
{
QRecord setting = settings.get(digest.getKey());
if(!isDigestHour(setting, now))
{
continue;
}
List<QRecord> items = digest.getValue().stream().map(pair -> pair[1]).toList();
boolean ok = send(address(setting), items.size() == 1 ? "1 new notification" : items.size() + " new notifications", items);
for(QRecord[] pair : digest.getValue())
{
mark(pair[0], ok ? EmailStatus.DIGESTED : EmailStatus.FAILED, ok ? now : null);
}
digestCount += ok ? 1 : 0;
failed += ok ? 0 : 1;
}
return (new Result(sent, digestCount, skipped, failed));
}));
}
/*******************************************************************************
** Whether it is the user's digest hour now (their time zone, default UTC).
*******************************************************************************/
static boolean isDigestHour(QRecord setting, Instant now)
{
Integer hour = setting == null ? null : setting.getValueInteger("digestHour");
ZoneId zone = ZoneOffset.UTC;
try
{
if(setting != null && StringUtils.hasContent(setting.getValueString("timeZone")))
{
zone = ZoneId.of(setting.getValueString("timeZone"));
}
}
catch(DateTimeException e)
{
zone = ZoneOffset.UTC;
}
return (now.atZone(zone).getHour() == (hour == null ? 8 : hour));
}
/*******************************************************************************
** Whether a severity is at least the minimum (default WARNING).
*******************************************************************************/
static boolean atLeast(String severity, String minimum)
{
return (NotificationSeverity.fromName(severity, NotificationSeverity.INFO).compareTo(NotificationSeverity.fromName(minimum, NotificationSeverity.WARNING)) >= 0);
}
/*******************************************************************************
** One email: the notifications' titles, bodies (not for SECURITY) and
** links. False when it could not be sent (or there is no address).
*******************************************************************************/
private boolean send(String address, String subject, List<QRecord> items)
{
if(!StringUtils.hasContent(address))
{
return (false);
}
StringBuilder text = new StringBuilder();
StringBuilder html = new StringBuilder("<div style=\"font-family:sans-serif\">");
for(QRecord item : items)
{
String title = item.getValueString("title");
String body = NotificationCategory.SECURITY.name().equals(item.getValueString("category")) ? null : item.getValueString("body");
String link = absolute(NotificationService.safeLink(item.getValueString("linkUrl")));
text.append(title).append("\n");
html.append("<h3 style=\"margin:16px 0 4px\">").append(escape(title)).append("</h3>");
if(StringUtils.hasContent(body))
{
text.append(body).append("\n");
html.append("<p style=\"white-space:pre-wrap;margin:0\">").append(escape(body)).append("</p>");
}
if(link != null)
{
text.append(link).append("\n");
html.append("<p style=\"margin:4px 0\"><a href=\"").append(escape(link)).append("\">")
.append(escape(StringUtils.hasContent(item.getValueString("linkLabel")) ? item.getValueString("linkLabel") : "Open")).append("</a></p>");
}
text.append("\n");
}
String settings = absolute("/app/" + AlertsNotificationPreference.TABLE_NAME);
text.append("Change these emails in My Notification Settings: ").append(settings).append("\n");
html.append("<p style=\"color:#666;font-size:12px;margin-top:24px\">Change these emails in <a href=\"").append(escape(settings)).append("\">My Notification Settings</a>.</p></div>");
try
{
new SendMessageAction().execute(new SendMessageInput()
.withMessagingProviderName(runtime.getConfig().getMessagingProviderName())
.withFrom(new Party().withAddress(runtime.getConfig().getFromAddress()).withRole(EmailPartyRole.FROM))
.withTo(new MultiParty().withParty(new Party().withAddress(address).withRole(EmailPartyRole.TO)))
.withSubject(subject)
.withContent(new Content().withContentRole(EmailContentRole.TEXT).withBody(text.toString()))
.withContent(new Content().withContentRole(EmailContentRole.HTML).withBody(html.toString())));
return (true);
}
catch(Exception e)
{
LOG.warn("Could not email a notification", e, logPair("subject", subject));
return (false);
}
}
/*******************************************************************************
** A link made absolute with the public base URL (relative app paths).
*******************************************************************************/
private String absolute(String link)
{
String base = runtime.getConfig().getPublicBaseUrl();
if(link == null || !link.startsWith("/") || !StringUtils.hasContent(base))
{
return (link);
}
return (base.replaceAll("/+$", "") + link);
}
/*******************************************************************************
**
*******************************************************************************/
private static String escape(String value)
{
return (value == null ? "" : value.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;"));
}
/*******************************************************************************
** The live (SENT, published, not expired) notifications for the rows.
*******************************************************************************/
private static Map<Integer, QRecord> notifications(List<QRecord> recipients, Instant now) throws QException
{
Map<Integer, QRecord> live = new HashMap<>();
List<Integer> ids = recipients.stream().map(recipient -> recipient.getValueInteger("notificationId")).distinct().toList();
if(ids.isEmpty())
{
return (live);
}
for(QRecord notification : AlertsDb.query(AlertsNotification.TABLE_NAME, new QQueryFilter().withCriteria("id", QCriteriaOperator.IN, ids)
.withCriteria("status", QCriteriaOperator.EQUALS, NotificationService.STATUS_SENT)))
{
Instant expireAt = notification.getValueInstant("expireAt");
if(expireAt == null || expireAt.isAfter(now))
{
live.put(notification.getValueInteger("id"), notification);
}
}
return (live);
}
/*******************************************************************************
** My Alert Settings rows (address, time zone, digest hour) by user.
*******************************************************************************/
private static Map<String, QRecord> userSettings(java.util.Set<String> userIds) throws QException
{
Map<String, QRecord> settings = new HashMap<>();
for(QRecord setting : AlertsDb.query(AlertsUserPreference.TABLE_NAME, new QQueryFilter().withCriteria("userId", QCriteriaOperator.IN, new ArrayList<>(userIds))))
{
settings.put(setting.getValueString("userId"), setting);
}
return (settings);
}
/*******************************************************************************
**
*******************************************************************************/
private static String address(QRecord setting)
{
return (setting == null ? null : setting.getValueString("emailAddress"));
}
/*******************************************************************************
**
*******************************************************************************/
private static void mark(QRecord recipient, EmailStatus status, Instant at) throws QException
{
QRecord update = new QRecord().withValue("id", recipient.getValue("id")).withValue("emailStatus", status.name());
if(at != null)
{
update.setValue("emailedAt", at);
}
AlertsDb.update(AlertsNotificationRecipient.TABLE_NAME, update);
}
}
@@ -0,0 +1,589 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.notifications;
import java.io.Serializable;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.kingsrook.qbits.alerts.AlertsRuntime;
import com.kingsrook.qbits.alerts.engine.AlertsDb;
import com.kingsrook.qbits.alerts.model.AlertsAlert;
import com.kingsrook.qbits.alerts.model.AlertsNotification;
import com.kingsrook.qbits.alerts.model.AlertsNotificationPreference;
import com.kingsrook.qbits.alerts.model.AlertsNotificationRecipient;
import com.kingsrook.qbits.alerts.spi.AlertLink;
import com.kingsrook.qbits.alerts.spi.NotificationAudience;
import com.kingsrook.qbits.alerts.spi.NotificationCategory;
import com.kingsrook.qbits.alerts.spi.NotificationSeverity;
import com.kingsrook.qbits.alerts.spi.NotificationSignal;
import com.kingsrook.qqq.backend.core.actions.tables.DeleteAction;
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
import com.kingsrook.qqq.backend.core.actions.tables.UpdateAction;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.exceptions.QUserFacingException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.actions.tables.delete.DeleteInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterCriteria;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.utils.CollectionUtils;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
/*******************************************************************************
** User notifications (docs/NOTIFICATIONS.md): writes notifications from
** producer signals and alerts, resolves audiences into one recipient row per
** user, retracts, sends scheduled ones when they are due, and purges old
** ones. Everything runs as the system user; what each person sees is
** filtered by their own recipient rows (owner record lock).
*******************************************************************************/
public class NotificationService
{
private static final QLogger LOG = QLogger.getLogger(NotificationService.class);
public static final String STATUS_DRAFT = "DRAFT";
public static final String STATUS_SCHEDULED = "SCHEDULED";
public static final String STATUS_SENT = "SENT";
public static final String STATUS_RETRACTED = "RETRACTED";
static final int BATCH = 500;
private final AlertsRuntime runtime;
private final AlertsAudienceResolver resolver;
/*******************************************************************************
** What a send did.
*******************************************************************************/
public record SendResult(int added, int total, List<String> warnings)
{
}
/*******************************************************************************
** Constructor
*******************************************************************************/
public NotificationService(AlertsRuntime runtime)
{
this.runtime = runtime;
this.resolver = new AlertsAudienceResolver(runtime);
}
/*******************************************************************************
** A producer's notification: written, then sent now (or scheduled for its
** publishAt). A signal whose sourceKey and audience match a live
** notification updates it and brings it back to unread for its readers.
** Returns the notification id.
*******************************************************************************/
public Integer notify(NotificationSignal signal) throws QException
{
if(signal == null || !StringUtils.hasContent(signal.getTitle()) || signal.getAudience() == null)
{
throw (new QUserFacingException("A notification needs a title and an audience."));
}
Instant now = runtime.now();
return (runtime.asSystem(() ->
{
QRecord values = fromSignal(signal);
QRecord existing = null;
if(StringUtils.hasContent(signal.getSourceKey()))
{
existing = AlertsDb.first(AlertsNotification.TABLE_NAME, AlertsDb.eq("sourceKey", signal.getSourceKey())
.withCriteria("audienceType", QCriteriaOperator.EQUALS, signal.getAudience().getType().name())
.withCriteria("status", QCriteriaOperator.IN, List.of(STATUS_SENT, STATUS_SCHEDULED))
.withCriteria(audienceValueCriteria(signal.getAudience())));
}
boolean scheduled = signal.getPublishAt() != null && signal.getPublishAt().isAfter(now);
Integer id;
if(existing != null)
{
id = existing.getValueInteger("id");
AlertsDb.update(AlertsNotification.TABLE_NAME, values.withValue("id", id));
if(STATUS_SENT.equals(existing.getValueString("status")))
{
markAllUnread(id, now);
}
}
else
{
values.setValue("status", scheduled ? STATUS_SCHEDULED : STATUS_DRAFT);
id = AlertsDb.insert(AlertsNotification.TABLE_NAME, values).getValueInteger("id");
}
if(!scheduled)
{
send(id);
}
return (id);
}));
}
/*******************************************************************************
** Send (or re-send) a notification: resolve its audience and add a
** recipient row for each user who doesn't have one (users who muted the
** category in-app are skipped, except for SECURITY). Marks it SENT.
*******************************************************************************/
public SendResult send(Integer notificationId) throws QException
{
Instant now = runtime.now();
return (runtime.asSystem(() ->
{
QRecord notification = AlertsDb.byId(AlertsNotification.TABLE_NAME, notificationId);
if(notification == null)
{
throw (new QUserFacingException("The notification was not found."));
}
if(STATUS_RETRACTED.equals(notification.getValueString("status")))
{
throw (new QUserFacingException("A retracted notification can't be sent again; copy it instead."));
}
AlertsAudienceResolver.Resolved resolved = resolver.resolve(audienceOf(notification));
Set<String> existing = recipientUserIds(notificationId);
Set<String> muted = mutedUsers(notification.getValueString("category"));
List<QRecord> inserts = new ArrayList<>();
for(String userId : resolved.userIds())
{
if(!existing.contains(userId) && !muted.contains(userId))
{
inserts.add(newRecipient(notificationId, userId, now));
}
}
insertRecipients(inserts);
QRecord update = new QRecord().withValue("id", notificationId)
.withValue("status", STATUS_SENT)
.withValue("recipientCount", existing.size() + inserts.size());
if(notification.getValue("sentAt") == null)
{
update.setValue("sentAt", now);
}
if(notification.getValue("publishAt") == null)
{
update.setValue("publishAt", now);
}
AlertsDb.update(AlertsNotification.TABLE_NAME, update);
LOG.info("Sent a notification", logPair("notificationId", notificationId), logPair("added", inserts.size()), logPair("total", existing.size() + inserts.size()));
return (new SendResult(inserts.size(), existing.size() + inserts.size(), resolved.warnings()));
}));
}
/*******************************************************************************
** Who a notification would reach now (Preview audience).
*******************************************************************************/
public AlertsAudienceResolver.Resolved preview(QRecord notification) throws QException
{
return (runtime.asSystem(() -> resolver.resolve(audienceOf(notification))));
}
/*******************************************************************************
** Schedule a draft for its publishAt (which must be in the future).
*******************************************************************************/
public void schedule(Integer notificationId) throws QException
{
Instant now = runtime.now();
runtime.asSystem(() ->
{
QRecord notification = AlertsDb.byId(AlertsNotification.TABLE_NAME, notificationId);
Instant publishAt = notification == null ? null : notification.getValueInstant("publishAt");
if(publishAt == null || !publishAt.isAfter(now))
{
throw (new QUserFacingException("Set Publish At to a future time first."));
}
AlertsDb.update(AlertsNotification.TABLE_NAME, new QRecord().withValue("id", notificationId).withValue("status", STATUS_SCHEDULED));
return (null);
});
}
/*******************************************************************************
** Retract a notification: it disappears from every bell. Recipient rows
** are kept (for the record).
*******************************************************************************/
public void retract(Integer notificationId) throws QException
{
Instant now = runtime.now();
runtime.asSystem(() -> AlertsDb.update(AlertsNotification.TABLE_NAME, new QRecord().withValue("id", notificationId)
.withValue("status", STATUS_RETRACTED).withValue("retractedAt", now)));
}
/*******************************************************************************
** Send every SCHEDULED notification whose publishAt has passed. Returns
** how many were sent.
*******************************************************************************/
public int sendDue() throws QException
{
Instant now = runtime.now();
List<QRecord> due = runtime.asSystem(() -> AlertsDb.query(AlertsNotification.TABLE_NAME, AlertsDb.eq("status", STATUS_SCHEDULED)
.withCriteria("publishAt", QCriteriaOperator.LESS_THAN_OR_EQUALS, now).withLimit(50)));
int sent = 0;
for(QRecord notification : due)
{
try
{
send(notification.getValueInteger("id"));
sent++;
}
catch(Exception e)
{
LOG.warn("Could not send a scheduled notification", e, logPair("notificationId", notification.getValue("id")));
}
}
return (sent);
}
/*******************************************************************************
** Delete notifications (and their recipients) a week past their expireAt,
** and SENT or RETRACTED ones older than notificationRetentionDays. At most
** 500 per call. Returns how many were deleted.
*******************************************************************************/
public int purge() throws QException
{
Instant now = runtime.now();
Instant oldest = now.minus(runtime.getConfig().getNotificationRetentionDays(), ChronoUnit.DAYS);
return (runtime.asSystem(() ->
{
Set<Serializable> ids = new HashSet<>();
for(QRecord row : AlertsDb.query(AlertsNotification.TABLE_NAME, new QQueryFilter()
.withCriteria("expireAt", QCriteriaOperator.LESS_THAN, now.minus(7, ChronoUnit.DAYS)).withLimit(BATCH)))
{
ids.add(row.getValueInteger("id"));
}
for(QRecord row : AlertsDb.query(AlertsNotification.TABLE_NAME, new QQueryFilter()
.withCriteria("status", QCriteriaOperator.IN, List.of(STATUS_SENT, STATUS_RETRACTED))
.withCriteria("createDate", QCriteriaOperator.LESS_THAN, oldest).withLimit(BATCH)))
{
ids.add(row.getValueInteger("id"));
}
deleteWithRecipients(new ArrayList<>(ids));
return (ids.size());
}));
}
/*******************************************************************************
** Delete notifications and their recipient rows (as the system user).
*******************************************************************************/
public void deleteWithRecipients(List<Serializable> notificationIds) throws QException
{
if(CollectionUtils.nullSafeIsEmpty(notificationIds))
{
return;
}
runtime.asSystem(() ->
{
new DeleteAction().execute(new DeleteInput(AlertsNotificationRecipient.TABLE_NAME)
.withQueryFilter(new QQueryFilter(new QFilterCriteria("notificationId", QCriteriaOperator.IN, notificationIds))));
new DeleteAction().execute(new DeleteInput(AlertsNotification.TABLE_NAME).withPrimaryKeys(notificationIds));
return (null);
});
}
/*******************************************************************************
** Put an alert in a user's bell (the in-app channel): one ALERT
** notification per alert (sourceKey alert:id), kept in step with the
** alert's title and severity, and a recipient row for the user that comes
** back to unread on every delivery. Call as the system user.
*******************************************************************************/
public void deliverAlert(String userId, QRecord alert, Instant now) throws QException
{
Integer alertId = alert.getValueInteger("id");
String sourceKey = "alert:" + alertId;
QRecord values = new QRecord()
.withValue("title", StringUtils.safeTruncate(alert.getValueString("title"), 200))
.withValue("body", alert.getValueString("summary"))
.withValue("severity", NotificationSeverity.fromName(alert.getValueString("severity"), NotificationSeverity.WARNING).name())
.withValue("category", NotificationCategory.ALERT.name())
.withValue("sourceName", StringUtils.hasContent(alert.getValueString("sourceName")) ? alert.getValueString("sourceName") : "alerts")
.withValue("sourceKey", sourceKey)
.withValue("sourceTableName", AlertsAlert.TABLE_NAME)
.withValue("sourceRecordId", String.valueOf(alertId))
.withValue("linkUrl", "/app/" + AlertsAlert.TABLE_NAME + "/" + alertId)
.withValue("linkLabel", "Open alert");
QRecord notification = AlertsDb.first(AlertsNotification.TABLE_NAME, AlertsDb.eq("sourceKey", sourceKey)
.withCriteria("category", QCriteriaOperator.EQUALS, NotificationCategory.ALERT.name()));
Integer notificationId;
if(notification == null)
{
notificationId = AlertsDb.insert(AlertsNotification.TABLE_NAME, values
.withValue("audienceType", NotificationAudience.Type.USERS.name())
.withValue("status", STATUS_SENT)
.withValue("publishAt", now)
.withValue("sentAt", now)
.withValue("recipientCount", 0)).getValueInteger("id");
}
else
{
notificationId = notification.getValueInteger("id");
AlertsDb.update(AlertsNotification.TABLE_NAME, values.withValue("id", notificationId).withValue("status", STATUS_SENT));
}
QRecord recipient = AlertsDb.first(AlertsNotificationRecipient.TABLE_NAME, AlertsDb.eq("notificationId", notificationId)
.withCriteria("userId", QCriteriaOperator.EQUALS, userId));
if(recipient == null)
{
AlertsDb.insert(AlertsNotificationRecipient.TABLE_NAME, newRecipient(notificationId, userId, now));
AlertsDb.update(AlertsNotification.TABLE_NAME, new QRecord().withValue("id", notificationId)
.withValue("recipientCount", AlertsDb.count(AlertsNotificationRecipient.TABLE_NAME, AlertsDb.eq("notificationId", notificationId))));
}
else
{
AlertsDb.update(AlertsNotificationRecipient.TABLE_NAME, new QRecord().withValue("id", recipient.getValue("id"))
.withValue("deliveredAt", now).withValue("readAt", null).withValue("dismissedAt", null));
}
}
/*******************************************************************************
** Recount a notification's readers (after people mark it read or unread).
*******************************************************************************/
public void recountRead(Set<Integer> notificationIds) throws QException
{
runtime.asSystem(() ->
{
for(Integer id : notificationIds)
{
int read = AlertsDb.count(AlertsNotificationRecipient.TABLE_NAME, AlertsDb.eq("notificationId", id).withCriteria("readAt", QCriteriaOperator.IS_NOT_BLANK));
AlertsDb.update(AlertsNotification.TABLE_NAME, new QRecord().withValue("id", id).withValue("readCount", read));
}
return (null);
});
}
/*******************************************************************************
** A notification's audience, from its stored fields (null when unknown).
*******************************************************************************/
public static NotificationAudience audienceOf(QRecord notification)
{
return (NotificationAudience.parse(notification.getValueString("audienceType"), notification.getValueString("audienceValue")));
}
/*******************************************************************************
** A link as a URL the UI can follow: a record or table path, an app path,
** or an https URL (anything else is dropped).
*******************************************************************************/
public static String linkUrl(AlertLink link)
{
if(link == null)
{
return (null);
}
if(link.getTableName() != null && link.getRecordId() != null)
{
return ("/app/" + link.getTableName() + "/" + link.getRecordId());
}
if(link.getTableName() != null)
{
return ("/app/" + link.getTableName());
}
return (safeLink(link.getPath() != null ? link.getPath() : link.getUrl()));
}
/*******************************************************************************
** The link if it is a relative app path (one leading slash) or an https URL
** with a host, else null. Backslashes, whitespace and control characters
** are refused anywhere (browsers treat "/\evil.com" as "//evil.com").
*******************************************************************************/
public static String safeLink(String url)
{
if(!StringUtils.hasContent(url))
{
return (null);
}
String trimmed = url.trim();
for(char c : trimmed.toCharArray())
{
if(c == '\\' || Character.isWhitespace(c) || Character.isISOControl(c))
{
return (null);
}
}
if(trimmed.startsWith("/"))
{
return (trimmed.length() > 1 && trimmed.charAt(1) == '/' ? null : trimmed);
}
try
{
java.net.URI uri = new java.net.URI(trimmed);
return ("https".equalsIgnoreCase(uri.getScheme()) && StringUtils.hasContent(uri.getHost()) ? trimmed : null);
}
catch(java.net.URISyntaxException e)
{
return (null);
}
}
/*******************************************************************************
** The notification fields from a signal.
*******************************************************************************/
private QRecord fromSignal(NotificationSignal signal)
{
return (new QRecord()
.withValue("title", StringUtils.safeTruncate(signal.getTitle(), 200))
.withValue("body", signal.getBody())
.withValue("severity", (signal.getSeverity() == null ? NotificationSeverity.INFO : signal.getSeverity()).name())
.withValue("category", (signal.getCategory() == null ? NotificationCategory.SYSTEM : signal.getCategory()).name())
.withValue("sourceName", StringUtils.safeTruncate(signal.getSourceName(), 100))
.withValue("sourceKey", StringUtils.safeTruncate(signal.getSourceKey(), 200))
.withValue("sourceTableName", signal.getSourceTableName())
.withValue("sourceRecordId", signal.getSourceRecordId())
.withValue("linkUrl", linkUrl(signal.getLink()))
.withValue("linkLabel", signal.getLink() == null ? null : signal.getLink().getLabel())
.withValue("audienceType", signal.getAudience().getType().name())
.withValue("audienceValue", signal.getAudience().valuesAsString())
.withValue("publishAt", signal.getPublishAt())
.withValue("expireAt", signal.getExpireAt())
.withValue("sticky", Boolean.TRUE.equals(signal.getSticky())));
}
/*******************************************************************************
** Match the stored audience value (null when there are no values).
*******************************************************************************/
private static QFilterCriteria audienceValueCriteria(NotificationAudience audience)
{
String value = audience.valuesAsString();
return (value == null ? new QFilterCriteria("audienceValue", QCriteriaOperator.IS_BLANK) : new QFilterCriteria("audienceValue", QCriteriaOperator.EQUALS, value));
}
/*******************************************************************************
**
*******************************************************************************/
private static QRecord newRecipient(Integer notificationId, String userId, Instant now)
{
return (new QRecord().withValue("notificationId", notificationId).withValue("userId", userId).withValue("deliveredAt", now).withValue("emailStatus", "NONE"));
}
/*******************************************************************************
** The users who already have this notification.
*******************************************************************************/
private Set<String> recipientUserIds(Integer notificationId) throws QException
{
Set<String> userIds = new HashSet<>();
for(QRecord recipient : AlertsDb.query(AlertsNotificationRecipient.TABLE_NAME, AlertsDb.eq("notificationId", notificationId)))
{
userIds.add(recipient.getValueString("userId"));
}
return (userIds);
}
/*******************************************************************************
** Users who muted a category in-app (never for SECURITY).
*******************************************************************************/
private Set<String> mutedUsers(String category) throws QException
{
Set<String> userIds = new HashSet<>();
if(category == null || NotificationCategory.SECURITY.name().equals(category))
{
return (userIds);
}
for(QRecord preference : AlertsDb.query(AlertsNotificationPreference.TABLE_NAME, AlertsDb.eq("category", category).withCriteria("inAppMuted", QCriteriaOperator.EQUALS, true)))
{
userIds.add(preference.getValueString("userId"));
}
return (userIds);
}
/*******************************************************************************
** Insert recipient rows in batches.
*******************************************************************************/
private void insertRecipients(List<QRecord> recipients) throws QException
{
for(int start = 0; start < recipients.size(); start += BATCH)
{
List<QRecord> batch = recipients.subList(start, Math.min(recipients.size(), start + BATCH));
for(QRecord inserted : new InsertAction().execute(new InsertInput(AlertsNotificationRecipient.TABLE_NAME).withRecords(new ArrayList<>(batch))).getRecords())
{
if(CollectionUtils.nullSafeHasContents(inserted.getErrors()))
{
LOG.warn("Could not add a notification recipient", logPair("error", inserted.getErrors().get(0).getMessage()));
}
}
}
}
/*******************************************************************************
** Bring a notification back to unread (and undismissed) for everyone who
** has it (a producer repeated it).
*******************************************************************************/
private void markAllUnread(Integer notificationId, Instant now) throws QException
{
List<QRecord> updates = new ArrayList<>();
for(QRecord recipient : AlertsDb.query(AlertsNotificationRecipient.TABLE_NAME, AlertsDb.eq("notificationId", notificationId)))
{
updates.add(new QRecord().withValue("id", recipient.getValue("id")).withValue("deliveredAt", now).withValue("readAt", null).withValue("dismissedAt", null));
}
for(int start = 0; start < updates.size(); start += BATCH)
{
new UpdateAction().execute(new UpdateInput(AlertsNotificationRecipient.TABLE_NAME).withRecords(new ArrayList<>(updates.subList(start, Math.min(updates.size(), start + BATCH)))));
}
if(!updates.isEmpty())
{
AlertsDb.update(AlertsNotification.TABLE_NAME, new QRecord().withValue("id", notificationId).withValue("readCount", 0));
}
}
}
@@ -0,0 +1,200 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.processes;
import java.util.List;
import com.kingsrook.qbits.alerts.AlertsQBitConfig;
import com.kingsrook.qbits.alerts.model.AlertsAlert;
import com.kingsrook.qbits.alerts.model.AlertsChannel;
import com.kingsrook.qbits.alerts.model.AlertsDelivery;
import com.kingsrook.qbits.alerts.model.AlertsGroup;
import com.kingsrook.qbits.alerts.model.AlertsMonitor;
import com.kingsrook.qbits.alerts.model.AlertsNotification;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues;
import com.kingsrook.qbits.alerts.model.AlertsTeam;
import com.kingsrook.qbits.alerts.model.AlertsType;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
/*******************************************************************************
** The Alerts record and table actions (design section 6.6). Each is a
** standard streamed ETL process on its table (optional input, Review summary
** lines, Result summary lines), never a nav entry.
*******************************************************************************/
public enum AlertsAction
{
ACKNOWLEDGE("alertsAcknowledge", "Acknowledge", "done", AlertsAlert.TABLE_NAME, AlertsQBitConfig.PERMISSION_MANAGE, null),
SNOOZE("alertsSnooze", "Snooze", "snooze", AlertsAlert.TABLE_NAME, AlertsQBitConfig.PERMISSION_MANAGE, null),
RESOLVE("alertsResolve", "Resolve", "check_circle", AlertsAlert.TABLE_NAME, AlertsQBitConfig.PERMISSION_MANAGE, null),
REOPEN("alertsReopen", "Reopen", "restart_alt", AlertsAlert.TABLE_NAME, AlertsQBitConfig.PERMISSION_MANAGE, 1),
ASSIGN("alertsAssign", "Assign", "assignment_ind", AlertsAlert.TABLE_NAME, AlertsQBitConfig.PERMISSION_MANAGE, null),
COMMENT("alertsAddComment", "Add comment", "comment", AlertsAlert.TABLE_NAME, AlertsQBitConfig.PERMISSION_VIEW, 1),
MUTE_ALERT("alertsMuteAlert", "Mute", "notifications_off", AlertsAlert.TABLE_NAME, AlertsQBitConfig.PERMISSION_MANAGE, 1),
SUBSCRIBE_TYPE("alertsSubscribeToType", "Subscribe me", "notifications", AlertsType.TABLE_NAME, AlertsQBitConfig.PERMISSION_VIEW, 1),
MUTE_TYPE("alertsMuteType", "Mute", "notifications_off", AlertsType.TABLE_NAME, AlertsQBitConfig.PERMISSION_MANAGE, 1),
CREATE_MONITOR("alertsCreateMonitorFromType", "Create monitor", "add_alert", AlertsType.TABLE_NAME, AlertsQBitConfig.PERMISSION_ADMIN, 1),
SUBSCRIBE_GROUP("alertsSubscribeToGroup", "Subscribe me", "notifications", AlertsGroup.TABLE_NAME, AlertsQBitConfig.PERMISSION_VIEW, 1),
MUTE_GROUP("alertsMuteGroup", "Mute", "notifications_off", AlertsGroup.TABLE_NAME, AlertsQBitConfig.PERMISSION_MANAGE, 1),
SUBSCRIBE_MONITOR("alertsSubscribeToMonitor", "Subscribe me", "notifications", AlertsMonitor.TABLE_NAME, AlertsQBitConfig.PERMISSION_VIEW, 1),
MUTE_MONITOR("alertsMuteMonitor", "Mute", "notifications_off", AlertsMonitor.TABLE_NAME, AlertsQBitConfig.PERMISSION_MANAGE, 1),
RUN_CHECK("alertsRunCheckNow", "Run check now", "play_circle", AlertsMonitor.TABLE_NAME, AlertsQBitConfig.PERMISSION_ADMIN, 1),
ENABLE_MONITOR("alertsEnableMonitor", "Enable monitor", "toggle_on", AlertsMonitor.TABLE_NAME, AlertsQBitConfig.PERMISSION_ADMIN, null),
DISABLE_MONITOR("alertsDisableMonitor", "Disable monitor", "toggle_off", AlertsMonitor.TABLE_NAME, AlertsQBitConfig.PERMISSION_ADMIN, null),
SEND_TEST("alertsSendTestNotification", "Send test notification", "send", AlertsChannel.TABLE_NAME, AlertsQBitConfig.PERMISSION_ADMIN, 1),
RETRY_DELIVERY("alertsRetryDelivery", "Retry delivery", "replay", AlertsDelivery.TABLE_NAME, AlertsQBitConfig.PERMISSION_ADMIN, null),
PREVIEW_AUDIENCE("alertsPreviewAudience", "Preview audience", "groups", AlertsNotification.TABLE_NAME, AlertsQBitConfig.PERMISSION_NOTIFICATION_ADMIN, 1),
SEND_NOTIFICATION("alertsSendNotification", "Send now", "send", AlertsNotification.TABLE_NAME, AlertsQBitConfig.PERMISSION_NOTIFICATION_ADMIN, null),
SCHEDULE_NOTIFICATION("alertsScheduleNotification", "Schedule", "schedule_send", AlertsNotification.TABLE_NAME, AlertsQBitConfig.PERMISSION_NOTIFICATION_ADMIN, null),
RETRACT_NOTIFICATION("alertsRetractNotification", "Retract", "unpublished", AlertsNotification.TABLE_NAME, AlertsQBitConfig.PERMISSION_NOTIFICATION_ADMIN, null);
public static final String FIELD_NOTE = "alertsNote";
public static final String FIELD_SNOOZE_HOURS = "alertsSnoozeHours";
public static final String FIELD_ASSIGN_USER = "alertsAssignUserId";
public static final String FIELD_ASSIGN_TEAM = "alertsAssignTeamId";
public static final String FIELD_MIN_SEVERITY = "alertsMinSeverity";
public static final String FIELD_DELIVERY_MODE = "alertsDeliveryMode";
public static final String FIELD_MUTE_MINUTES = "alertsMuteMinutes";
private final String processName;
private final String label;
private final String icon;
private final String tableName;
private final String permissionName;
private final Integer maxRecords;
/*******************************************************************************
**
*******************************************************************************/
AlertsAction(String processName, String label, String icon, String tableName, String permissionName, Integer maxRecords)
{
this.processName = processName;
this.label = label;
this.icon = icon;
this.tableName = tableName;
this.permissionName = permissionName;
this.maxRecords = maxRecords;
}
/*******************************************************************************
** The action for a process name, or null.
*******************************************************************************/
public static AlertsAction forProcess(String processName)
{
for(AlertsAction action : values())
{
if(action.processName.equals(processName))
{
return (action);
}
}
return (null);
}
/*******************************************************************************
** The input form fields (empty: straight to Review).
*******************************************************************************/
public List<QFieldMetaData> inputFields()
{
return switch(this)
{
case SNOOZE -> List.of(new QFieldMetaData(FIELD_SNOOZE_HOURS, QFieldType.INTEGER).withLabel("Snooze for (hours)").withIsRequired(true).withDefaultValue(4));
case RESOLVE -> List.of(new QFieldMetaData(FIELD_NOTE, QFieldType.TEXT).withLabel("Resolution note").withIsRequired(true));
case REOPEN -> List.of(new QFieldMetaData(FIELD_NOTE, QFieldType.TEXT).withLabel("Why reopen"));
case COMMENT -> List.of(new QFieldMetaData(FIELD_NOTE, QFieldType.TEXT).withLabel("Comment").withIsRequired(true));
case ASSIGN -> List.of(
new QFieldMetaData(FIELD_ASSIGN_USER, QFieldType.STRING).withLabel("Assign to user (user id)"),
new QFieldMetaData(FIELD_ASSIGN_TEAM, QFieldType.INTEGER).withLabel("Or a team").withPossibleValueSourceName(AlertsTeam.TABLE_NAME));
case SUBSCRIBE_TYPE, SUBSCRIBE_GROUP, SUBSCRIBE_MONITOR -> List.of(
new QFieldMetaData(FIELD_MIN_SEVERITY, QFieldType.STRING).withLabel("Minimum severity").withIsRequired(true).withDefaultValue("WARNING")
.withPossibleValueSourceName(AlertsPossibleValues.SEVERITY),
new QFieldMetaData(FIELD_DELIVERY_MODE, QFieldType.STRING).withLabel("Delivery").withIsRequired(true).withDefaultValue("IMMEDIATE")
.withPossibleValueSourceName(AlertsPossibleValues.DELIVERY_MODE));
case MUTE_ALERT, MUTE_TYPE, MUTE_GROUP, MUTE_MONITOR -> List.of(
new QFieldMetaData(FIELD_MUTE_MINUTES, QFieldType.INTEGER).withLabel("Mute for (minutes)").withIsRequired(true).withDefaultValue(60),
new QFieldMetaData(FIELD_NOTE, QFieldType.TEXT).withLabel("Reason").withIsRequired(true));
default -> List.of();
};
}
/*******************************************************************************
** Getter for processName
*******************************************************************************/
public String getProcessName()
{
return (this.processName);
}
/*******************************************************************************
** Getter for label
*******************************************************************************/
public String getLabel()
{
return (this.label);
}
/*******************************************************************************
** Getter for icon
*******************************************************************************/
public String getIcon()
{
return (this.icon);
}
/*******************************************************************************
** Getter for tableName
*******************************************************************************/
public String getTableName()
{
return (this.tableName);
}
/*******************************************************************************
** Getter for permissionName
*******************************************************************************/
public String getPermissionName()
{
return (this.permissionName);
}
/*******************************************************************************
** Getter for maxRecords (null: bulk)
*******************************************************************************/
public Integer getMaxRecords()
{
return (this.maxRecords);
}
}
@@ -0,0 +1,653 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.processes;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import com.kingsrook.qbits.alerts.AlertsRuntime;
import com.kingsrook.qbits.alerts.AlertsSecurity;
import com.kingsrook.qbits.alerts.engine.AlertsDb;
import com.kingsrook.qbits.alerts.engine.MonitorEvaluator;
import com.kingsrook.qbits.alerts.model.AlertsMonitor;
import com.kingsrook.qbits.alerts.model.AlertsMute;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.DeliveryStatus;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.MonitorStatus;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.MuteEffect;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.Resolution;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.ScopeType;
import com.kingsrook.qbits.alerts.model.AlertsPossibleValues.SubscriberType;
import com.kingsrook.qbits.alerts.model.AlertsSubscription;
import com.kingsrook.qbits.alerts.notifications.AlertsAudienceResolver;
import com.kingsrook.qbits.alerts.notifications.NotificationService;
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.exceptions.QUserFacingException;
import com.kingsrook.qqq.backend.core.model.actions.processes.ProcessSummaryLine;
import com.kingsrook.qqq.backend.core.model.actions.processes.ProcessSummaryLineInterface;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput;
import com.kingsrook.qqq.backend.core.model.actions.processes.Status;
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.AbstractLoadStep;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.AbstractTransformStep;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.ProcessSummaryProviderInterface;
import com.kingsrook.qqq.backend.core.utils.CollectionUtils;
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
/*******************************************************************************
** The transform (Review) and load (Result) steps shared by every Alerts
** record action. The records come from the standard extract, read in the
** user's session, so an action only ever sees rows the user can read; the
** changes are then made by the engine (which writes the timeline). Review
** says what will happen and what will be skipped; Result says what did.
*******************************************************************************/
public final class AlertsActionSteps
{
static final int AUDIENCE_SAMPLE = 10;
/*******************************************************************************
** Steps only.
*******************************************************************************/
private AlertsActionSteps()
{
}
/*******************************************************************************
** Review: sort the records into "will" and "skipped (why)".
*******************************************************************************/
public static class Transform extends AbstractTransformStep implements ProcessSummaryProviderInterface
{
private ProcessSummaryLine will;
private ProcessSummaryLine skipped;
private final List<ProcessSummaryLine> extra = new ArrayList<>();
/*******************************************************************************
**
*******************************************************************************/
@Override
public void runOnePage(RunBackendStepInput input, RunBackendStepOutput output) throws QException
{
AlertsAction action = action(input);
initLines(action);
for(QRecord record : input.getRecords())
{
String skipReason = skipReason(action, record);
if(skipReason == null)
{
will.incrementCountAndAddPrimaryKey(record.getValue("id"));
output.addRecord(record);
review(action, record);
}
else
{
skipped.incrementCountAndAddPrimaryKey(record.getValue("id"));
skipped.setMessage(skipReason);
}
}
}
/*******************************************************************************
** The Review lines.
*******************************************************************************/
@Override
public ArrayList<ProcessSummaryLineInterface> getProcessSummary(RunBackendStepOutput output, boolean isForResultScreen)
{
ArrayList<ProcessSummaryLineInterface> lines = new ArrayList<>();
if(will == null)
{
return (lines);
}
will.addSelfToListIfAnyCount(lines);
skipped.addSelfToListIfAnyCount(lines);
lines.addAll(extra);
return (lines);
}
/*******************************************************************************
** The skipped line, repeated on the Result screen.
*******************************************************************************/
ProcessSummaryLine skippedLine()
{
return (skipped);
}
/*******************************************************************************
**
*******************************************************************************/
private void initLines(AlertsAction action)
{
if(will != null)
{
return;
}
String noun = noun(action);
will = line(Status.OK, noun + " will be " + pastVerb(action), plural(noun) + " will be " + pastVerb(action), noun + " was " + pastVerb(action), plural(noun) + " were " + pastVerb(action));
skipped = line(Status.INFO, noun + " will be skipped", plural(noun) + " will be skipped", noun + " was skipped", plural(noun) + " were skipped");
}
/*******************************************************************************
** Extra Review detail for one record (Run check now's preview, the
** Resolve warning).
*******************************************************************************/
private void review(AlertsAction action, QRecord record) throws QException
{
if(action == AlertsAction.PREVIEW_AUDIENCE || action == AlertsAction.SEND_NOTIFICATION)
{
extra.addAll(audienceLines(runtime().getNotifications().preview(record), action == AlertsAction.PREVIEW_AUDIENCE));
}
else if(action == AlertsAction.RUN_CHECK)
{
MonitorEvaluator.Plan plan = runtime().getEvaluator().preview(record.getValueInteger("id"));
extra.addAll(planLines(plan, false));
}
else if(action == AlertsAction.RESOLVE && record.getValue("monitorId") != null)
{
QRecord monitor = runtime().asSystem(() -> AlertsDb.byId(AlertsMonitor.TABLE_NAME, record.getValue("monitorId")));
if(monitor != null && MonitorStatus.FIRING.name().equals(monitor.getValueString("lastStatus")) && Boolean.TRUE.equals(monitor.getValueBoolean("enabled")))
{
extra.add(new ProcessSummaryLine(Status.WARNING, null, "The monitor \"" + monitor.getValueString("name") + "\" is still firing, so its alert will reopen at the next check."));
}
}
}
}
/*******************************************************************************
** Result: apply the action to each record.
*******************************************************************************/
public static class Load extends AbstractLoadStep implements ProcessSummaryProviderInterface
{
private ProcessSummaryLine done;
private ProcessSummaryLine failed;
private final List<ProcessSummaryLine> extra = new ArrayList<>();
/*******************************************************************************
**
*******************************************************************************/
@Override
public void runOnePage(RunBackendStepInput input, RunBackendStepOutput output) throws QException
{
AlertsAction action = action(input);
if(done == null)
{
String noun = noun(action);
done = line(Status.OK, noun + " will be " + pastVerb(action), plural(noun) + " will be " + pastVerb(action), noun + " was " + pastVerb(action), plural(noun) + " were " + pastVerb(action));
failed = line(Status.ERROR, noun + " will fail", plural(noun) + " will fail", noun + " could not be changed", plural(noun) + " could not be changed");
}
String actor = AlertsSecurity.userId(QContext.getQSession());
for(QRecord record : input.getRecords())
{
try
{
if(apply(action, record, input, actor))
{
done.incrementCountAndAddPrimaryKey(record.getValue("id"));
}
else
{
failed.incrementCountAndAddPrimaryKey(record.getValue("id"));
}
}
catch(QUserFacingException e)
{
failed.incrementCountAndAddPrimaryKey(record.getValue("id"));
failed.setMessage(e.getMessage());
}
}
}
/*******************************************************************************
** The Result lines.
*******************************************************************************/
@Override
public ArrayList<ProcessSummaryLineInterface> getProcessSummary(RunBackendStepOutput output, boolean isForResultScreen)
{
ArrayList<ProcessSummaryLineInterface> lines = new ArrayList<>();
if(done == null)
{
return (lines);
}
done.addSelfToListIfAnyCount(lines);
failed.addSelfToListIfAnyCount(lines);
if(getTransformStep() instanceof Transform transform && transform.skippedLine() != null)
{
transform.skippedLine().addSelfToListIfAnyCount(lines);
}
lines.addAll(extra);
return (lines);
}
/*******************************************************************************
** Do the action for one record; false when nothing changed.
*******************************************************************************/
private boolean apply(AlertsAction action, QRecord record, RunBackendStepInput input, String actor) throws QException
{
AlertsRuntime runtime = runtime();
Integer id = record.getValueInteger("id");
String note = input.getValueString(AlertsAction.FIELD_NOTE);
Instant now = runtime.now();
return switch(action)
{
case ACKNOWLEDGE -> runtime.getEngine().acknowledge(id, actor);
case SNOOZE ->
{
Integer hours = input.getValueInteger(AlertsAction.FIELD_SNOOZE_HOURS);
yield (runtime.getEngine().snooze(id, now.plus(hours == null || hours < 1 ? 4 : hours, ChronoUnit.HOURS), actor));
}
case RESOLVE ->
{
if(!StringUtils.hasContent(note))
{
throw (new QUserFacingException("A resolution note is required."));
}
runtime.getEngine().resolveById(id, Resolution.MANUAL, actor, note);
yield (true);
}
case REOPEN -> runtime.getEngine().reopenById(id, actor, note);
case ASSIGN -> runtime.getEngine().assign(id, input.getValueString(AlertsAction.FIELD_ASSIGN_USER), input.getValueInteger(AlertsAction.FIELD_ASSIGN_TEAM), actor);
case COMMENT ->
{
runtime.getEngine().comment(id, actor, note);
yield (true);
}
case SUBSCRIBE_TYPE -> subscribe(ScopeType.ALERT_TYPE, record.getValueString("name"), input);
case SUBSCRIBE_GROUP -> subscribe(ScopeType.GROUP, record.getValueString("name"), input);
case SUBSCRIBE_MONITOR -> subscribe(ScopeType.MONITOR, String.valueOf(id), input);
case MUTE_TYPE -> mute(ScopeType.ALERT_TYPE, record.getValueString("name"), "type " + record.getValueString("label"), input, actor);
case MUTE_GROUP -> mute(ScopeType.GROUP, record.getValueString("name"), "group " + record.getValueString("label"), input, actor);
case MUTE_MONITOR -> mute(ScopeType.MONITOR, String.valueOf(id), "monitor " + record.getValueString("name"), input, actor);
case MUTE_ALERT -> mute(ScopeType.ALERT_TYPE, record.getValueString("alertTypeName"), "alert type " + record.getValueString("alertTypeName"), input, actor);
case RUN_CHECK ->
{
MonitorEvaluator.Plan plan = runtime.getEvaluator().runNow(id);
extra.addAll(planLines(plan, true));
yield (plan.status() != MonitorStatus.CHECK_FAILED);
}
case ENABLE_MONITOR, DISABLE_MONITOR -> runtime.asSystem(() ->
{
AlertsDb.update(AlertsMonitor.TABLE_NAME, new QRecord().withValue("id", id).withValue("enabled", action == AlertsAction.ENABLE_MONITOR)
.withValue("nextRunAt", action == AlertsAction.ENABLE_MONITOR ? now : null));
return (true);
});
case SEND_TEST ->
{
QRecord notification = runtime.getDeliveryWorker().sendTest(id, actor);
String status = notification.getValueString("status");
if(!DeliveryStatus.SENT.name().equals(status))
{
extra.add(new ProcessSummaryLine(Status.ERROR, null, "The test did not send: " + Objects.toString(notification.getValueString("lastError"), status)));
yield (false);
}
yield (true);
}
case RETRY_DELIVERY -> runtime.getDeliveryWorker().retry(List.of(id)) > 0;
case CREATE_MONITOR -> createMonitor(record);
case PREVIEW_AUDIENCE ->
{
extra.addAll(audienceLines(runtime.getNotifications().preview(record), true));
yield (true);
}
case SEND_NOTIFICATION ->
{
NotificationService.SendResult result = runtime.getNotifications().send(id);
extra.add(new ProcessSummaryLine(Status.INFO, null, "\"" + record.getValueString("title") + "\" reached " + count(result.added(), "new recipient")
+ " (" + count(result.total(), "recipient") + " in all)."));
yield (true);
}
case SCHEDULE_NOTIFICATION ->
{
runtime.getNotifications().schedule(id);
yield (true);
}
case RETRACT_NOTIFICATION ->
{
runtime.getNotifications().retract(id);
yield (true);
}
};
}
}
/*******************************************************************************
** Why a record is skipped (null: it isn't).
*******************************************************************************/
static String skipReason(AlertsAction action, QRecord record) throws QException
{
String status = record.getValueString("status");
return switch(action)
{
case ACKNOWLEDGE -> AlertsPossibleValues.Status.OPEN.name().equals(status) ? null : "Only open, unacknowledged alerts can be acknowledged.";
case SNOOZE, RESOLVE -> AlertsPossibleValues.Status.RESOLVED.name().equals(status) ? "Resolved alerts are skipped." : null;
case REOPEN -> AlertsPossibleValues.Status.RESOLVED.name().equals(status) ? null : "Only resolved alerts can be reopened.";
case ENABLE_MONITOR -> Boolean.TRUE.equals(record.getValueBoolean("enabled")) ? "Already enabled." : null;
case DISABLE_MONITOR -> Boolean.FALSE.equals(record.getValueBoolean("enabled")) ? "Already disabled." : null;
case RETRY_DELIVERY -> List.of(DeliveryStatus.FAILED.name(), DeliveryStatus.DEAD.name()).contains(status) ? null : "Only failed or dead notifications can be retried.";
case PREVIEW_AUDIENCE, SEND_NOTIFICATION -> NotificationService.STATUS_RETRACTED.equals(status) ? "Retracted notifications can't be sent." : null;
case SCHEDULE_NOTIFICATION -> NotificationService.STATUS_DRAFT.equals(status) ? null : "Only drafts can be scheduled.";
case RETRACT_NOTIFICATION -> NotificationService.STATUS_SENT.equals(status) || NotificationService.STATUS_SCHEDULED.equals(status) ? null : "Only sent or scheduled notifications can be retracted.";
case SUBSCRIBE_TYPE -> alreadySubscribed(ScopeType.ALERT_TYPE, record.getValueString("name"));
case SUBSCRIBE_GROUP -> alreadySubscribed(ScopeType.GROUP, record.getValueString("name"));
case SUBSCRIBE_MONITOR -> alreadySubscribed(ScopeType.MONITOR, String.valueOf(record.getValue("id")));
default -> null;
};
}
/*******************************************************************************
** "You already subscribed" (null when not).
*******************************************************************************/
private static String alreadySubscribed(ScopeType scopeType, String scopeValue) throws QException
{
String userId = AlertsSecurity.userId(QContext.getQSession());
if(userId == null)
{
return ("Your session has no user, so it can't subscribe.");
}
QRecord existing = runtime().asSystem(() -> AlertsDb.first(AlertsSubscription.TABLE_NAME, AlertsDb.eq("userId", userId)
.withCriteria("scopeType", QCriteriaOperator.EQUALS, scopeType.name())
.withCriteria("scopeValue", QCriteriaOperator.EQUALS, scopeValue)));
return (existing == null ? null : "You are already subscribed (subscription " + existing.getValue("id") + ").");
}
/*******************************************************************************
** Create the user's own subscription (through the table, so its rules apply).
*******************************************************************************/
private static boolean subscribe(ScopeType scopeType, String scopeValue, RunBackendStepInput input) throws QException
{
List<QRecord> inserted = InsertAction.executeForRecords(new InsertInput(AlertsSubscription.TABLE_NAME).withRecord(new QRecord()
.withValue("subscriberType", SubscriberType.USER.name())
.withValue("userId", AlertsSecurity.userId(QContext.getQSession()))
.withValue("scopeType", scopeType.name())
.withValue("scopeValue", scopeValue)
.withValue("minSeverity", StringUtils.hasContent(input.getValueString(AlertsAction.FIELD_MIN_SEVERITY)) ? input.getValueString(AlertsAction.FIELD_MIN_SEVERITY) : "WARNING")
.withValue("deliveryMode", StringUtils.hasContent(input.getValueString(AlertsAction.FIELD_DELIVERY_MODE)) ? input.getValueString(AlertsAction.FIELD_DELIVERY_MODE) : "IMMEDIATE")
.withValue("events", "RAISED,ESCALATED,REMINDER,RESOLVED")
.withValue("enabled", true)));
throwIfErrors(inserted);
return (true);
}
/*******************************************************************************
** Create a silence-notifications mute from now (through the table).
*******************************************************************************/
private static boolean mute(ScopeType scopeType, String scopeValue, String what, RunBackendStepInput input, String actor) throws QException
{
Integer minutes = input.getValueInteger(AlertsAction.FIELD_MUTE_MINUTES);
String reason = input.getValueString(AlertsAction.FIELD_NOTE);
if(!StringUtils.hasContent(reason))
{
throw (new QUserFacingException("A reason is required."));
}
Instant now = runtime().now();
List<QRecord> inserted = InsertAction.executeForRecords(new InsertInput(AlertsMute.TABLE_NAME).withRecord(new QRecord()
.withValue("name", "Mute " + what)
.withValue("reason", reason)
.withValue("scopeType", scopeType.name())
.withValue("scopeValue", scopeValue)
.withValue("startsAt", now)
.withValue("endsAt", now.plus(minutes == null || minutes < 1 ? 60 : minutes, ChronoUnit.MINUTES))
.withValue("effect", MuteEffect.SILENCE_NOTIFICATIONS.name())
.withValue("enabled", true)));
throwIfErrors(inserted);
return (true);
}
/*******************************************************************************
** A TABLE_QUERY monitor for the type's subject table (disabled, to be
** finished by the admin), or a heartbeat monitor when it has none.
*******************************************************************************/
private static boolean createMonitor(QRecord type) throws QException
{
String subject = type.getValueString("subjectTableName");
String kind = subject == null ? "HEARTBEAT" : "TABLE_QUERY";
String json = subject == null
? JsonUtils.toJson(Map.of("heartbeatKey", type.getValueString("name"), "expectedEverySeconds", 86400, "graceSeconds", 3600))
: JsonUtils.toJson(Map.of("tableName", subject, "filter", Map.of("criteria", List.of()), "threshold", 0));
runtime().asSystem(() -> AlertsDb.insert(AlertsMonitor.TABLE_NAME, new QRecord()
.withValue("name", type.getValueString("label") + " monitor")
.withValue("alertTypeId", type.getValue("id"))
.withValue("kind", kind)
.withValue("enabled", false)
.withValue("seeded", false)
.withValue("description", "Created from the alert type. Edit the definition, then enable it.")
.withValue("definition", json)
.withValue("perRecord", false)
.withValue("scheduleSeconds", 300)
.withValue("forMinutes", 0)
.withValue("consecutiveFailures", 0)));
return (true);
}
/*******************************************************************************
** Lines describing a monitor evaluation (Review: would; Result: did).
*******************************************************************************/
static List<ProcessSummaryLine> planLines(MonitorEvaluator.Plan plan, boolean applied)
{
List<ProcessSummaryLine> lines = new ArrayList<>();
if(plan.status() == MonitorStatus.CHECK_FAILED)
{
lines.add(new ProcessSummaryLine(Status.ERROR, null, "The check failed: " + plan.error()));
return (lines);
}
if(plan.status() == MonitorStatus.SKIPPED_MUTED)
{
lines.add(new ProcessSummaryLine(Status.INFO, null, "A maintenance window covers this monitor, so it was not checked."));
return (lines);
}
String verb = applied ? "" : "Would ";
lines.add(new ProcessSummaryLine(Status.INFO, null, "Result: " + plan.value()));
if(plan.status() == MonitorStatus.PENDING)
{
lines.add(new ProcessSummaryLine(Status.WARNING, null, "The condition holds, but not yet for the monitor's \"must hold for\" time, so no alert " + (applied ? "was" : "would be") + " opened."));
}
lines.add(new ProcessSummaryLine(plan.wouldOpen().isEmpty() ? Status.INFO : Status.WARNING, null, (applied ? "Opened " : verb + "open ") + count(plan.wouldOpen().size(), "alert") + "."));
lines.add(new ProcessSummaryLine(Status.INFO, null, (applied ? "Updated " : verb + "update ") + count(plan.wouldUpdate().size(), "open alert") + "."));
lines.add(new ProcessSummaryLine(Status.OK, null, (applied ? "Resolved " : verb + "resolve ") + count(plan.wouldResolve().size(), "alert") + "."));
return (lines);
}
/*******************************************************************************
** Review lines for an audience: who it reaches, a sample, and warnings.
*******************************************************************************/
static List<ProcessSummaryLine> audienceLines(AlertsAudienceResolver.Resolved resolved, boolean preview)
{
List<ProcessSummaryLine> lines = new ArrayList<>();
int size = resolved.userIds().size();
lines.add(new ProcessSummaryLine(size == 0 ? Status.WARNING : Status.INFO, null, (preview ? "Would reach " : "Will reach up to ") + count(size, "user") + "."));
if(size > 0)
{
List<String> sample = resolved.userIds().stream().limit(AUDIENCE_SAMPLE).map(userId -> resolved.labels().getOrDefault(userId, userId)).toList();
lines.add(new ProcessSummaryLine(Status.INFO, null, "For example: " + String.join(", ", sample) + (size > sample.size() ? ", and " + (size - sample.size()) + " more." : ".")));
}
for(String warning : resolved.warnings())
{
lines.add(new ProcessSummaryLine(Status.WARNING, null, warning));
}
return (lines);
}
/*******************************************************************************
** The action this process run is.
*******************************************************************************/
static AlertsAction action(RunBackendStepInput input) throws QException
{
AlertsAction action = AlertsAction.forProcess(input.getProcessName());
if(action == null)
{
throw (new QException("Not an Alerts action: " + input.getProcessName()));
}
return (action);
}
/*******************************************************************************
**
*******************************************************************************/
private static AlertsRuntime runtime() throws QException
{
return (AlertsRuntime.get());
}
/*******************************************************************************
** What the action's records are called.
*******************************************************************************/
static String noun(AlertsAction action)
{
return switch(action.getTableName())
{
case "alerts_alert" -> "alert";
case "alerts_type" -> "alert type";
case "alerts_group" -> "group";
case "alerts_monitor" -> "monitor";
case "alerts_channel" -> "channel";
case "alerts_delivery" -> "delivery";
case "alerts_notification" -> "notification";
default -> "record";
};
}
/*******************************************************************************
** The participle for the action ("acknowledged", "snoozed", ...).
*******************************************************************************/
static String pastVerb(AlertsAction action)
{
return switch(action)
{
case ACKNOWLEDGE -> "acknowledged";
case SNOOZE -> "snoozed";
case RESOLVE -> "resolved";
case REOPEN -> "reopened";
case ASSIGN -> "assigned";
case COMMENT -> "commented on";
case SUBSCRIBE_TYPE, SUBSCRIBE_GROUP, SUBSCRIBE_MONITOR -> "subscribed to";
case MUTE_ALERT, MUTE_TYPE, MUTE_GROUP, MUTE_MONITOR -> "muted";
case RUN_CHECK -> "checked";
case ENABLE_MONITOR -> "enabled";
case DISABLE_MONITOR -> "disabled";
case SEND_TEST -> "tested";
case RETRY_DELIVERY -> "queued again";
case CREATE_MONITOR -> "given a new (disabled) monitor";
case PREVIEW_AUDIENCE -> "previewed";
case SEND_NOTIFICATION -> "sent";
case SCHEDULE_NOTIFICATION -> "scheduled";
case RETRACT_NOTIFICATION -> "retracted";
};
}
/*******************************************************************************
** "alert" to "alerts", "alert type" to "alert types".
*******************************************************************************/
static String plural(String noun)
{
return (noun + "s");
}
/*******************************************************************************
** "1 alert", "3 alerts".
*******************************************************************************/
static String count(int n, String noun)
{
return (n + " " + (n == 1 ? noun : noun + "s"));
}
/*******************************************************************************
** A counted summary line.
*******************************************************************************/
static ProcessSummaryLine line(Status status, String singularFuture, String pluralFuture, String singularPast, String pluralPast)
{
ProcessSummaryLine line = new ProcessSummaryLine(status, 0, null);
line.setSingularFutureMessage(singularFuture);
line.setPluralFutureMessage(pluralFuture);
line.setSingularPastMessage(singularPast);
line.setPluralPastMessage(pluralPast);
return (line);
}
/*******************************************************************************
**
*******************************************************************************/
private static void throwIfErrors(List<QRecord> records) throws QUserFacingException
{
for(QRecord record : records)
{
if(CollectionUtils.nullSafeHasContents(record.getErrors()))
{
throw (new QUserFacingException(record.getErrors().get(0).getMessage()));
}
}
}
}
@@ -0,0 +1,83 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.processes;
import com.kingsrook.qbits.alerts.AlertsRuntime;
import com.kingsrook.qbits.alerts.notifications.NotificationEmailer;
import com.kingsrook.qqq.backend.core.actions.processes.BackendStep;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput;
/*******************************************************************************
** The hidden scheduled processes' steps: evaluate due monitors (plus snooze,
** quiet-period and flapping upkeep), and deliver due notifications.
*******************************************************************************/
public final class AlertsScheduledSteps
{
public static final String OUTPUT_COUNT = "count";
/*******************************************************************************
** Steps only.
*******************************************************************************/
private AlertsScheduledSteps()
{
}
/*******************************************************************************
** alertsEvaluateMonitors
*******************************************************************************/
public static class EvaluateMonitors implements BackendStep
{
/***************************************************************************
**
***************************************************************************/
@Override
public void run(RunBackendStepInput input, RunBackendStepOutput output) throws QException
{
output.addValue(OUTPUT_COUNT, AlertsRuntime.get().getEvaluator().evaluateDue());
}
}
/*******************************************************************************
** alertsDeliverNotifications
*******************************************************************************/
public static class DeliverNotifications implements BackendStep
{
/***************************************************************************
**
***************************************************************************/
@Override
public void run(RunBackendStepInput input, RunBackendStepOutput output) throws QException
{
AlertsRuntime runtime = AlertsRuntime.get();
runtime.sink().flush();
runtime.getNotifications().sendDue();
runtime.getNotifications().purge();
new NotificationEmailer(runtime).run();
output.addValue(OUTPUT_COUNT, runtime.getDeliveryWorker().deliverDue());
}
}
}
@@ -0,0 +1,155 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.spi;
import java.io.Serializable;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
/*******************************************************************************
** STAND-IN(core=QRun-IO/qqq#1125, removeBy=4.1.0-RC.6)
**
** A link from an alert to where a person fixes it: a record, a table with a
** filter, an app or widget path, or an absolute URL. Exactly one target is
** expected, so construct these with the static factories.
*******************************************************************************/
public class AlertLink implements Serializable
{
private String label;
private String tableName;
private Serializable recordId;
private QQueryFilter filter;
private String path;
private String url;
/*******************************************************************************
** Link to one record.
*******************************************************************************/
public static AlertLink toRecord(String tableName, Serializable recordId, String label)
{
AlertLink link = new AlertLink();
link.tableName = tableName;
link.recordId = recordId;
link.label = label;
return (link);
}
/*******************************************************************************
** Link to a table, optionally filtered.
*******************************************************************************/
public static AlertLink toTable(String tableName, QQueryFilter filter, String label)
{
AlertLink link = new AlertLink();
link.tableName = tableName;
link.filter = filter;
link.label = label;
return (link);
}
/*******************************************************************************
** Link to an app or widget path within the application (e.g. "/admin/cdn").
*******************************************************************************/
public static AlertLink toPath(String path, String label)
{
AlertLink link = new AlertLink();
link.path = path;
link.label = label;
return (link);
}
/*******************************************************************************
** Link to an absolute URL. Implementations only follow these for types
** that declare them, so producer data cannot inject arbitrary links.
*******************************************************************************/
public static AlertLink toUrl(String url, String label)
{
AlertLink link = new AlertLink();
link.url = url;
link.label = label;
return (link);
}
/*******************************************************************************
** Getter for label
*******************************************************************************/
public String getLabel()
{
return (this.label);
}
/*******************************************************************************
** Getter for tableName
*******************************************************************************/
public String getTableName()
{
return (this.tableName);
}
/*******************************************************************************
** Getter for recordId
*******************************************************************************/
public Serializable getRecordId()
{
return (this.recordId);
}
/*******************************************************************************
** Getter for filter
*******************************************************************************/
public QQueryFilter getFilter()
{
return (this.filter);
}
/*******************************************************************************
** Getter for path
*******************************************************************************/
public String getPath()
{
return (this.path);
}
/*******************************************************************************
** Getter for url
*******************************************************************************/
public String getUrl()
{
return (this.url);
}
}
@@ -0,0 +1,197 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.spi;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
/*******************************************************************************
** STAND-IN(core=QRun-IO/qqq#1125, removeBy=4.1.0-RC.6)
**
** Who a notification is for, resolved to users when it is sent (stand-in for
** core's com.kingsrook.qqq.backend.core.alerts.NotificationAudience).
*******************************************************************************/
public class NotificationAudience implements Serializable
{
/*******************************************************************************
** STAND-IN(core=QRun-IO/qqq#1125, removeBy=4.1.0-RC.6)
**
** The kinds of audience.
*******************************************************************************/
public enum Type
{
ALL_USERS, ROLES, PERMISSION, USERS
}
private final Type type;
private final List<String> values;
/*******************************************************************************
** Constructor (blank values are dropped; values are trimmed).
*******************************************************************************/
public NotificationAudience(Type type, List<String> values)
{
this.type = type == null ? Type.USERS : type;
this.values = values == null ? List.of() : values.stream().filter(Objects::nonNull).map(String::trim).filter(value -> !value.isEmpty()).distinct().toList();
}
/*******************************************************************************
** Every user.
*******************************************************************************/
public static NotificationAudience allUsers()
{
return (new NotificationAudience(Type.ALL_USERS, null));
}
/*******************************************************************************
** Users with any of these roles or groups.
*******************************************************************************/
public static NotificationAudience roles(String... roles)
{
return (new NotificationAudience(Type.ROLES, roles == null ? null : Arrays.asList(roles)));
}
/*******************************************************************************
** Users whose session holds this permission.
*******************************************************************************/
public static NotificationAudience permission(String permission)
{
return (new NotificationAudience(Type.PERMISSION, permission == null ? null : List.of(permission)));
}
/*******************************************************************************
** These users.
*******************************************************************************/
public static NotificationAudience users(String... userIds)
{
return (new NotificationAudience(Type.USERS, userIds == null ? null : Arrays.asList(userIds)));
}
/*******************************************************************************
** One user.
*******************************************************************************/
public static NotificationAudience user(String userId)
{
return (users(userId));
}
/*******************************************************************************
** From the stored form: a type name and a comma- or line-separated value.
** An unknown type is null.
*******************************************************************************/
public static NotificationAudience parse(String type, String value)
{
for(Type candidate : Type.values())
{
if(type != null && candidate.name().equalsIgnoreCase(type.trim()))
{
List<String> values = new ArrayList<>();
if(value != null)
{
values.addAll(Arrays.asList(value.split("[,\\n]")));
}
return (new NotificationAudience(candidate, values));
}
}
return (null);
}
/*******************************************************************************
** The stored form of the values (null when there are none).
*******************************************************************************/
public String valuesAsString()
{
return (values.isEmpty() ? null : String.join(",", values));
}
/*******************************************************************************
** Getter for type
*******************************************************************************/
public Type getType()
{
return (this.type);
}
/*******************************************************************************
** Getter for values
*******************************************************************************/
public List<String> getValues()
{
return (this.values);
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public boolean equals(Object o)
{
return (o instanceof NotificationAudience other && type == other.type && values.equals(other.values));
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public int hashCode()
{
return (Objects.hash(type, values));
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public String toString()
{
return (type + (values.isEmpty() ? "" : values.toString()));
}
}
@@ -0,0 +1,51 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.spi;
/*******************************************************************************
** STAND-IN(core=QRun-IO/qqq#1125, removeBy=4.1.0-RC.6)
**
** What a notification is about (stand-in for core's
** com.kingsrook.qqq.backend.core.alerts.NotificationCategory). Users filter
** and mute by category; SECURITY can never be muted in-app.
*******************************************************************************/
public enum NotificationCategory
{
SYSTEM, JOB, SECURITY, RELEASE, MARKETING, SHARE, ALERT;
/*******************************************************************************
** The category for a name (any case), or the fallback.
*******************************************************************************/
public static NotificationCategory fromName(String name, NotificationCategory fallback)
{
if(name != null)
{
for(NotificationCategory category : values())
{
if(category.name().equalsIgnoreCase(name.trim()))
{
return (category);
}
}
}
return (fallback);
}
}
@@ -0,0 +1,51 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.spi;
/*******************************************************************************
** STAND-IN(core=QRun-IO/qqq#1125, removeBy=4.1.0-RC.6)
**
** How a notification looks to its reader: INFO and SUCCESS are good news,
** WARNING and ERROR need a look, CRITICAL makes the badge red (stand-in for
** core's com.kingsrook.qqq.backend.core.alerts.NotificationSeverity).
*******************************************************************************/
public enum NotificationSeverity
{
INFO, SUCCESS, WARNING, ERROR, CRITICAL;
/*******************************************************************************
** The severity for a name (any case), or the fallback.
*******************************************************************************/
public static NotificationSeverity fromName(String name, NotificationSeverity fallback)
{
if(name != null)
{
for(NotificationSeverity severity : values())
{
if(severity.name().equalsIgnoreCase(name.trim()))
{
return (severity);
}
}
}
return (fallback);
}
}
@@ -0,0 +1,502 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.alerts.spi;
import java.io.Serializable;
import java.time.Instant;
/*******************************************************************************
** STAND-IN(core=QRun-IO/qqq#1125, removeBy=4.1.0-RC.6)
**
** A notification for people (stand-in for core's
** com.kingsrook.qqq.backend.core.alerts.NotificationSignal): what to tell
** them, how urgent it is, what it is about, and who it is for. Send it with
** the alerts sink's notify (core: QAlerts.notify).
*******************************************************************************/
public class NotificationSignal implements Serializable
{
private String title;
private String body;
private NotificationSeverity severity;
private NotificationCategory category;
private String sourceName;
private String sourceKey;
private String sourceTableName;
private String sourceRecordId;
private AlertLink link;
private NotificationAudience audience;
private Instant publishAt;
private Instant expireAt;
private Boolean sticky;
private Instant occurredAt;
/*******************************************************************************
** Default constructor.
*******************************************************************************/
public NotificationSignal()
{
}
/*******************************************************************************
** Constructor with the title.
*******************************************************************************/
public NotificationSignal(String title)
{
this.title = title;
}
/*******************************************************************************
** Getter for title: The headline (plain text, required).
*******************************************************************************/
public String getTitle()
{
return (this.title);
}
/*******************************************************************************
** Setter for title
*******************************************************************************/
public void setTitle(String title)
{
this.title = title;
}
/*******************************************************************************
** Fluent setter for title
*******************************************************************************/
public NotificationSignal withTitle(String title)
{
this.title = title;
return (this);
}
/*******************************************************************************
** Getter for body: The message (markdown).
*******************************************************************************/
public String getBody()
{
return (this.body);
}
/*******************************************************************************
** Setter for body
*******************************************************************************/
public void setBody(String body)
{
this.body = body;
}
/*******************************************************************************
** Fluent setter for body
*******************************************************************************/
public NotificationSignal withBody(String body)
{
this.body = body;
return (this);
}
/*******************************************************************************
** Getter for severity: Default INFO.
*******************************************************************************/
public NotificationSeverity getSeverity()
{
return (this.severity);
}
/*******************************************************************************
** Setter for severity
*******************************************************************************/
public void setSeverity(NotificationSeverity severity)
{
this.severity = severity;
}
/*******************************************************************************
** Fluent setter for severity
*******************************************************************************/
public NotificationSignal withSeverity(NotificationSeverity severity)
{
this.severity = severity;
return (this);
}
/*******************************************************************************
** Getter for category: Default SYSTEM.
*******************************************************************************/
public NotificationCategory getCategory()
{
return (this.category);
}
/*******************************************************************************
** Setter for category
*******************************************************************************/
public void setCategory(NotificationCategory category)
{
this.category = category;
}
/*******************************************************************************
** Fluent setter for category
*******************************************************************************/
public NotificationSignal withCategory(NotificationCategory category)
{
this.category = category;
return (this);
}
/*******************************************************************************
** Getter for sourceName: Who emits it (a qbit or app name).
*******************************************************************************/
public String getSourceName()
{
return (this.sourceName);
}
/*******************************************************************************
** Setter for sourceName
*******************************************************************************/
public void setSourceName(String sourceName)
{
this.sourceName = sourceName;
}
/*******************************************************************************
** Fluent setter for sourceName
*******************************************************************************/
public NotificationSignal withSourceName(String sourceName)
{
this.sourceName = sourceName;
return (this);
}
/*******************************************************************************
** Getter for sourceKey: Dedup key: a second notify with the same key and audience updates the first.
*******************************************************************************/
public String getSourceKey()
{
return (this.sourceKey);
}
/*******************************************************************************
** Setter for sourceKey
*******************************************************************************/
public void setSourceKey(String sourceKey)
{
this.sourceKey = sourceKey;
}
/*******************************************************************************
** Fluent setter for sourceKey
*******************************************************************************/
public NotificationSignal withSourceKey(String sourceKey)
{
this.sourceKey = sourceKey;
return (this);
}
/*******************************************************************************
** Getter for sourceTableName: The table of the record it is about.
*******************************************************************************/
public String getSourceTableName()
{
return (this.sourceTableName);
}
/*******************************************************************************
** Setter for sourceTableName
*******************************************************************************/
public void setSourceTableName(String sourceTableName)
{
this.sourceTableName = sourceTableName;
}
/*******************************************************************************
** Fluent setter for sourceTableName
*******************************************************************************/
public NotificationSignal withSourceTableName(String sourceTableName)
{
this.sourceTableName = sourceTableName;
return (this);
}
/*******************************************************************************
** Getter for sourceRecordId: The record it is about.
*******************************************************************************/
public String getSourceRecordId()
{
return (this.sourceRecordId);
}
/*******************************************************************************
** Setter for sourceRecordId
*******************************************************************************/
public void setSourceRecordId(String sourceRecordId)
{
this.sourceRecordId = sourceRecordId;
}
/*******************************************************************************
** Fluent setter for sourceRecordId
*******************************************************************************/
public NotificationSignal withSourceRecordId(String sourceRecordId)
{
this.sourceRecordId = sourceRecordId;
return (this);
}
/*******************************************************************************
** Getter for link: Where it takes the reader.
*******************************************************************************/
public AlertLink getLink()
{
return (this.link);
}
/*******************************************************************************
** Setter for link
*******************************************************************************/
public void setLink(AlertLink link)
{
this.link = link;
}
/*******************************************************************************
** Fluent setter for link
*******************************************************************************/
public NotificationSignal withLink(AlertLink link)
{
this.link = link;
return (this);
}
/*******************************************************************************
** Getter for audience: Who it is for (required).
*******************************************************************************/
public NotificationAudience getAudience()
{
return (this.audience);
}
/*******************************************************************************
** Setter for audience
*******************************************************************************/
public void setAudience(NotificationAudience audience)
{
this.audience = audience;
}
/*******************************************************************************
** Fluent setter for audience
*******************************************************************************/
public NotificationSignal withAudience(NotificationAudience audience)
{
this.audience = audience;
return (this);
}
/*******************************************************************************
** Getter for publishAt: Not shown before this (default now).
*******************************************************************************/
public Instant getPublishAt()
{
return (this.publishAt);
}
/*******************************************************************************
** Setter for publishAt
*******************************************************************************/
public void setPublishAt(Instant publishAt)
{
this.publishAt = publishAt;
}
/*******************************************************************************
** Fluent setter for publishAt
*******************************************************************************/
public NotificationSignal withPublishAt(Instant publishAt)
{
this.publishAt = publishAt;
return (this);
}
/*******************************************************************************
** Getter for expireAt: Hidden after this.
*******************************************************************************/
public Instant getExpireAt()
{
return (this.expireAt);
}
/*******************************************************************************
** Setter for expireAt
*******************************************************************************/
public void setExpireAt(Instant expireAt)
{
this.expireAt = expireAt;
}
/*******************************************************************************
** Fluent setter for expireAt
*******************************************************************************/
public NotificationSignal withExpireAt(Instant expireAt)
{
this.expireAt = expireAt;
return (this);
}
/*******************************************************************************
** Getter for sticky: A banner until dismissed (meant for CRITICAL).
*******************************************************************************/
public Boolean getSticky()
{
return (this.sticky);
}
/*******************************************************************************
** Setter for sticky
*******************************************************************************/
public void setSticky(Boolean sticky)
{
this.sticky = sticky;
}
/*******************************************************************************
** Fluent setter for sticky
*******************************************************************************/
public NotificationSignal withSticky(Boolean sticky)
{
this.sticky = sticky;
return (this);
}
/*******************************************************************************
** Getter for occurredAt: When it happened (default now).
*******************************************************************************/
public Instant getOccurredAt()
{
return (this.occurredAt);
}
/*******************************************************************************
** Setter for occurredAt
*******************************************************************************/
public void setOccurredAt(Instant occurredAt)
{
this.occurredAt = occurredAt;
}
/*******************************************************************************
** Fluent setter for occurredAt
*******************************************************************************/
public NotificationSignal withOccurredAt(Instant occurredAt)
{
this.occurredAt = occurredAt;
return (this);
}
}
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff. Show more