Skip to content

Observability & Notifications ​

BeechCMS includes built-in systems for real-time admin notifications and zero-overhead activity logging. Both subsystems execute asynchronously at the Cloudflare edge, ensuring that database writes, user logins, and automations never introduce latency to HTTP responses.

Architecture Pipeline ​

All audit logs and notifications are dispatched via the IScheduler abstraction (c.get('scheduler').waitUntil(...)). This offloads database inserts and webhook triggers to Cloudflare Workers background execution while returning immediate responses to clients.

BeechCMS Observability & Notifications Pipeline

Upstash QStash Queue ​

BeechCMS integrates with Upstash QStash as its primary background message queue and webhook delivery engine for serverless edge environments.

Why QStash at the Edge ​

Edge runtimes like Cloudflare Workers are stateless and cannot maintain long-lived TCP connections or run persistent background broker listeners (like RabbitMQ or Celery).

QStash solves this by acting as an HTTP-native serverless message queue:

  • Zero Connection Overhead: Messages are published via standard HTTPS REST calls.
  • At-Least-Once Delivery: Guarantees message persistence until the receiving webhook or worker acknowledges it.
  • Automated Retries & Backoff: Failed webhook endpoints or temporary downtime trigger exponential backoff without tying up Worker CPU time.
  • Cryptographic Signatures: Inbound callbacks are verified using HMAC SHA-256 signing keys to prevent spoofing.

Environment Configuration ​

To enable QStash delivery for notifications and external webhooks, configure these environment variables in your Cloudflare Worker:

ini
QSTASH_URL="https://qstash.upstash.io/v2/publish"
QSTASH_TOKEN="ey..."
QSTASH_CURRENT_SIGNING_KEY="sig_..."
QSTASH_NEXT_SIGNING_KEY="sig_..."

When these variables are detected, observabilityMiddleware automatically instantiates QStashNotificationService instead of local memory queuing.

Activity Logging ​

The activity logging subsystem tracks changes made across the CMS, creating an immutable audit trail for compliance and dashboard activity feeds.

Tracked Events ​

Every action says what happened and every entry says what it happened to (entityType); the specifics are in details, conventionally under op. Nothing secret is ever stored: a password change records that it changed, never the password.

EntityActionsRecorded details
contentcreate, update, trash, restore, purge, publish, discard_draft, bulk_update, importEntry title, seed slug; a bulk operation records one entry with count (and fields); a saved draft is an update with note: "draft saved"
mediaupload, delete, purgeFile name, size, type; orphan cleanup records count
seedcreate, update, deleteop (drop-branch, rename-branch, retype-branch, drop-orphan, mcp-apply, fts-rebuild, …)
authlogin, login_failed, logoutIP, country, city and browser as Cloudflare reports them; a failed attempt adds reason and is recorded only when the account exists
usercreate, updateop: profile, password, avatar-set, avatar-removed, notifications, activate, deactivate, password-reset-requested, password-reset, setup; changed field names, never values
settings, sessionupdate, revokeSite settings: the field names changed. Session: the one revoked
role, assignment, invitationcreate, update, delete, revoke, acceptRole name, the person's email, the scope; an accepted invitation is recorded for the new account
appauthorize, revokeClient name and granted scopes
automation, view, layoutcreate, update, deleteName or title; op: enable/disable/reset

Trashing and purging are separate actions on purpose: the first can be undone, the second cannot. The recorded IP address and approximate location are personal data; retention is currently unlimited and will be configurable (#953).

Programmatic Logging ​

Inside an API handler, use logActivity(c, entry) from apps/api/src/shared/services/activity-log/log-activity.ts: it takes the actor from the session, never throws, and does nothing when there is no logger or session. requestOrigin(c) returns the IP, country, city and browser for the sign-in trail. Where a handler needs full control, the logger itself is on the context:

typescript
import type { Context } from 'hono'
import type { Env, Variables } from '../types'

export async function customActionHandler(c: Context<{ Bindings: Env; Variables: Variables }>) {
  const jwt = c.get('jwtPayload')
  const entryId = c.req.param('id')

  // Perform domain operation
  // ...

  // Asynchronously record the activity log
  c.get('scheduler').waitUntil(
    c.get('activityLogger').log({
      action: 'update',
      entityType: 'content',
      entityId: entryId,
      entitySlug: 'articles',
      actor: {
        id: jwt.sub,
        email: jwt.email ?? 'system',
        name: jwt.name ?? null,
      },
      details: {
        reason: 'Bulk tag update',
      },
    })
  )

  return c.json({ ok: true })
}

Dashboard History ​

  1. Dashboard Cockpit: the Recent Activity widget shows the latest work on content, media and content types, with relative timestamps, to everyone who may see that content. Sign-ins, account and access changes are never shown there: they belong to the person who made them.
  2. Settings → My account → Recent activity: each person's own history, newest first. Every row reads as a sentence: a badge for what happened (red for irreversible or security-relevant), what it happened to, and one line of context (the place and browser of a sign-in, how many entries a bulk operation touched, the file name of an upload). Five rows are visible before the list scrolls. Dates follow the dashboard language.

In-App Notifications ​

BeechCMS provides an in-app notification inbox accessible via the bell icon in the dashboard navigation header.

Severity Levels ​

SeverityUI IndicatorRecommended Use Case
infoBlue badgeGeneral updates, scheduled jobs completed
successEmerald badgeForm submissions, successful content publishes
warningAmber badgeImpending quota limits, unverified draft changes
errorRose badgeWebhook delivery failure, payment gateway alert

Dispatching Alerts ​

You can trigger notifications from custom endpoints, scheduled cron jobs, or background tasks:

typescript
const notificationService = c.get('notificationService')

c.get('scheduler').waitUntil(
  notificationService.notify({
    title: 'New Contact Form Submission',
    message: 'A new lead submitted the contact form on your website.',
    type: 'success',
    link: '/content/leads',
  })
)

Testing & Clocks ​

To ensure tests run fast without monkey-patching Date.now() or crypto.randomUUID(), both D1ActivityLogger and D1NotificationRepository accept injected IClock and IIdGenerator instances.

In test suites (vitest), pass FixedClock and SequentialIdGenerator:

typescript
import { FixedClock } from '../shared/fixed-clock'
import { SequentialIdGenerator } from '../shared/sequential-id-generator'
import { D1ActivityLogger } from '../shared/d1-activity-logger'

const clock = new FixedClock(1700000000000)
const idGen = new SequentialIdGenerator('test-log')
const logger = new D1ActivityLogger(d1Database, clock, idGen)

await logger.log({
  action: 'create',
  entityType: 'content',
  entityId: 'entry-123',
  entitySlug: 'posts',
  actor: { id: 'usr_1', email: 'editor@example.com', name: 'Editor' },
})