Alerts (Event System) — Internals
This document covers the internal implementation of Spaceport's Alerts system. It is intended for contributors and advanced users who need to understand how the dispatcher works, debug handler registration issues, or extend the system.
Architecture
The Alerts system has four core components:
┌─────────────────────────────────────────────────┐
│ Alerts (Dispatcher) │
│ - static List<WeakReference<AlertType>> │
│ - invoke(hookString, context) → Result │
│ - invokeAll(hookStrings, context) → Result │
│ - notifyOf(AlertType) [synchronized] │
└───────────────┬──────────────────────────────────┘
│ registers
┌───────────────┴──────────────────────────────────┐
│ AlertType (Abstract Base) │
│ - hookString, priority, passive, compiledPattern│
│ - buzz(result) [abstract] │
│ - dispose() [abstract] │
└───────────────┬──────────────────────────────────┘
│ extends
┌───────────────┴──────────────────────────────────┐
│ AnnotatedAlert (Runtime Handler) │
│ - className, methodName, Method m │
│ - loadStaticHooks() / releaseStaticHooks() │
│ - buzz(result) → Method.invoke(null, result) │
└──────────────────────────────────────────────────┘
Handler Discovery and Registration
Class Scanning
When source modules are loaded, AnnotatedAlert.loadStaticHooks() is called. This method:
- Calls
ClassScanner.getLoadedClasses()to get all classes loaded by Spaceport — both framework classes and user application classes. - Iterates every class, checking each method for the
@Alertannotation. - For each annotated method, creates an
AnnotatedAlertinstance with the event string, priority, class name, method name, and the annotation'spassiveflag.
Self-Registration
The AlertType constructor — AlertType(hookString, priority = 0, passive = false) — calls Alerts.notifyOf(this), which is synchronized. The passive flag is stored as a final boolean field; custom subclasses that call super(hookString, priority) keep the default passive = false and behave exactly as before. notifyOf:
- Adds the new handler as a
WeakReferenceto theregisteredlist. - Removes any
nullweak references (handlers that were garbage collected). - Sorts the entire list by priority (descending — higher priority values first).
This self-registration pattern means creating an AlertType instance automatically registers it. There is no separate "register" call.
Static Hook Management
AnnotatedAlert maintains a static list (staticHooks) of all annotation-discovered handlers. This enables:
loadStaticHooks()— Scans classes, creates instances, adds tostaticHooksreleaseStaticHooks()— Callsdispose()on each handler (setsdisabled = true, nullifies theMethodreference), then clears the list
These are called during hot-reload to tear down and rebuild the handler registry.
Event Dispatch
Alerts.invoke(hookString, context)
- Result creation: Checks if
context.resultTypeis aClass. If so, instantiates that class vianewInstance(context). Otherwise, creates anew Result(context). - Handler iteration: Walks the
registeredlist in priority order (already sorted). - Cancellation check: Before each handler, checks
result.cancelled. If true, stops immediately. - Matching:
- If the handler has a
compiledPattern(regex hook), usesMatcher.matches()against the full hookString. On match, extracts capture groups intoresult.matches. - Otherwise, uses
hookString.equalsIgnoreCase()for case-insensitive string comparison.
- If the handler has a
- Execution: Calls
handler.buzz(result). ForAnnotatedAlert, this invokes the static method via reflection:m.invoke(null, result). - Error handling: Each handler invocation is wrapped in try-catch. Exceptions are printed to stderr but do not propagate or cancel the chain.
- Called flag:
result.calledis set totruewhen a matching handler executes — unless the handler ispassive. A passive hook (hook.passive == true) runsbuzz()exactly as a normal hook — same matching, capture groups, priority position, and error handling — but skips thecalledbookkeeping (if (!hook.passive) result.called = true). This is what lets broad wildcard middleware run on every request without marking unrouted paths as handled. - Return: Returns the mutated Result.
Alerts.invokeAll(hookStrings, context)
Works like invoke but for each handler, checks it against every hookString in the list. This is used by the HTTP handler to fire both "on /path hit" and "on /path GET" in a single pass.
The key difference from calling invoke twice: the global priority order is preserved across both event names. A priority-100 handler for "on /path hit" will run before a priority-0 handler for "on /path GET".
The passive flag is honored at both dispatch sites — invoke and invokeAll guard the called assignment identically. A single hook can match more than one of the event strings passed to invokeAll; a passive hook stays passive across all of them, never setting called regardless of how many strings it matches.
HTTP Request Flow
The HttpRequestHandler (Jetty handler) processes each request as:
- Builds an
HttpContextwith request, response, parsed data, cookies, headers, method, target, dock, client, andresultType = HttpResult.class. - Calls
Alerts.invokeAll(['on <target> hit', 'on <target> <METHOD>'], context). - If
result.calledis false (no non-passive handler matched), sets response status to 404. Passive hooks deliberately leavecalleduntouched, so a global wildcard middleware (~on /(.*) hitwithpassive = true) can run on an unrouted path without suppressing this fallback. - Calls
Alerts.invoke('on page hit', context)— the catch-all that fires on every request, even after errors.
WebSocket Message Flow
The SocketHandler.onWebSocketText() method:
- Parses the incoming text as JSON.
- Silently drops heartbeat messages (handler-id
"launchpad-socket"with"pong"data). - Builds a
SocketContextwith handler, session, data, handlerId, dock, client, andresultType = SocketResult.class. - Spawns a new thread for message processing.
- In the new thread: calls
Alerts.invoke('on socket data', context). - If not cancelled, calls
Alerts.invoke('on socket <handler-id>', context).
WebSocket lifecycle events (on socket connect, on socket closed) use SocketLifecycleContext (no handlerId or data) and run on the WebSocket event thread (no separate thread).
Threading Model
| Event Type | Thread | Notes |
|---|---|---|
| HTTP alerts | Jetty handler thread | Synchronous. Handler blocks until all alerts complete. |
on page hit |
Jetty handler thread | Same thread, runs after route-specific alerts. |
| WebSocket message alerts | New thread per message | new Thread({ ... }).start(). Each message gets its own thread. |
| WebSocket lifecycle | WebSocket event thread | on socket connect and on socket closed run directly on the event thread. |
on document save |
Caller's thread | Synchronous. Runs before the save is committed. |
on document saved |
New thread | Thread.start { ... }. Runs after save completes. |
on document modified |
Caller's thread | Synchronous. Runs after save/remove. |
| Lifecycle events | Main/scanner thread | on initialize, on deinitialize, etc. |
Important: Alerts.invoke() and Alerts.invokeAll() are not synchronized. They read the registered list without locking. Only Alerts.notifyOf() (registration) is synchronized. This means handler registration during dispatch is theoretically unsafe, but in practice, registration only happens at startup and during hot-reload (which tears everything down first).
Weak References
Handlers are stored as WeakReference<AlertType> in the registered list. This design allows handlers to be garbage collected if nothing else references them.
Implications:
- If you create an
AlertTypesubclass manually (not via@Alertannotation), you must keep a strong reference to it — otherwise it may be GC'd and silently stop working. AnnotatedAlert.staticHooksholds strong references to all annotation-discovered handlers, preventing them from being collected during normal operation.- During
releaseStaticHooks(), the strong references are cleared, allowing GC. The weak references inAlerts.registeredwill become null and be cleaned up on the nextnotifyOf()call. - Null weak references are cleaned up during registration (
notifyOf), not during dispatch. Stale entries in the list during dispatch are effectively no-ops.
Regex Compilation
When an AlertType is created with a hookString starting with ~:
- The
~prefix is stripped. - All spaces in the pattern are replaced with
\s. - The pattern is compiled as a case-insensitive
java.util.regex.Pattern(Pattern.CASE_INSENSITIVE). - The compiled pattern is stored in
compiledPattern(final field).
During dispatch, compiledPattern.matcher(hookString).matches() is called. This is a full-string match — the pattern must match the entire event string, not just a substring.
Patterns are compiled once at registration time. There is no additional caching layer.
Hot-Reload Lifecycle
In debug mode, Spaceport watches source module files for changes via Beacon (a file watcher). When a change is detected:
Alerts.invoke('on deinitialize', [:])— Handlers can clean up resources.Alerts.invoke('on deinitialized', [:])— Final teardown notification.AnnotatedAlert.releaseStaticHooks()— All annotation-discovered handlers are disposed (disabled, method references nullified) and the static hooks list is cleared.- Class loaders and caches are cleared.
- Source files are re-parsed into new class loaders.
AnnotatedAlert.loadStaticHooks()— Classes are re-scanned for@Alertannotations.Alerts.invoke('on initialize', [:])— Handlers run initialization logic.Alerts.invoke('on initialized', [:])— Application is ready again.
This means the entire alert registry is rebuilt on every hot-reload. There is no incremental update.
Framework-Internal Handlers
These @Alert handlers are defined within the Spaceport framework itself:
| Class | Event | Purpose |
|---|---|---|
SourceStore |
on initialized |
Sets up file watchers for hot-reload (debug mode) |
Beacon |
on deinitialized |
Stops all file watchers |
Launchpad |
on initialize |
Sets up template file watchers (debug mode) |
Launchpad |
on /!/lp/bind hit |
Handles Launchpad reactive binding HTTP endpoints |
Launchpad |
on /!/lp/bind/u/ hit |
Handles Launchpad binding unregistration |
Launchpad |
on socket launchpad-socket |
Handles Launchpad WebSocket registration and reactive element updates |
ClientRegistry |
on initialize |
Registers CouchDB views for authentication |
Cargo |
on document saved |
Synchronizes document changes to in-memory Cargo objects |
These handlers use default priority (0), so user handlers with higher priority will run before them.
Error Handling
Exceptions thrown inside a handler's buzz() method are caught and printed to stderr. They do not:
- Propagate to the caller
- Cancel the handler chain
- Affect subsequent handlers
This means a buggy handler cannot break the dispatch loop. However, it also means errors can be silently swallowed if you're not watching stderr.
AnnotatedAlert.buzz() specifically catches IllegalArgumentException separately (for method signature mismatches) and prints a distinct error message.
Make the docs better.Edit this page on GitHub