Skip to content

JunctionRelay Notifications System Summary

Overview

This document outlines the comprehensive notification system implemented across JunctionRelay. The system provides auto-expiring notifications with intelligent categorization, database persistence, and real-time frontend delivery.

Core Components

Backend Components

  • Service_Notifications: Core notification service with pre-built methods
  • Controller_Notifications: RESTful API for notification management
  • Model_Notifications: Database model with auto-expiry support
  • Database Schema: SQLite table with automatic cleanup

Frontend Components

  • NotificationProvider: React context with glass effect UI
  • Feature Flag Integration: Configurable notification behavior
  • Auto-dismiss Logic: Intelligent timing based on notification type

Notification Types & Categories

Notification Types

Type Color Default Duration Use Case
success Green 6 seconds Successful operations
error Red 8 seconds Failed operations
warning Orange 7 seconds Caution messages
info Blue 6 seconds General information

Notification Categories

Category Purpose Feature Flag
api API operation results notifications_api_calls
auth Authentication events notifications_auth_events
cloud Cloud synchronization notifications_cloud_sync
system System events notifications_system

Auto-Expiry Configuration

Expiry Schedule by Notification Type

Notification Expiry Time Persistent Rationale
Health Report Success 60 seconds No Quick status updates
Health Report Failure 10 minutes No Errors need attention
User Login 30 minutes No Info worth keeping briefly
User Logout 15 minutes No Less important
System Updates 24 hours No Important but not urgent
API Success 15 minutes No Standard operations
API Errors 2 hours No Errors need investigation
Device Connected 30 minutes No Connection status
Device Disconnected 1 hour No More important to notice
Junction Started 30 minutes No Status information
Junction Stopped 1 hour No Important state change
Junction Errors 6 hours No Need troubleshooting
Database Backup Success 1 hour No Operational confirmation
Database Backup Failure 12 hours No Critical system issue
Cloud Sync Started 5 minutes No Temporary status
System Update Available 24 hours No Action required eventually
System Update Installed 2 hours No Important completion

Never-Expiring Notifications (Persistent = true)

Notification Rationale
Authentication Failures Security critical
Session Expired Security critical
Cloud Authentication Required Action required

Feature Flag Configuration

Master Settings

Setting Default Description
notifications_enabled true Master toggle for entire system
notifications_backend_polling true Enable server-generated notifications
notifications_polling_interval 15000 Polling frequency (milliseconds)
notifications_max_concurrent 5 Maximum visible notifications

Category Settings

Setting Default Description
notifications_api_calls true Show API operation results
notifications_auth_events true Show authentication events
notifications_cloud_sync true Show cloud synchronization
notifications_system true Show system events

Duration Settings

Setting Default Description
notifications_duration_success 6000 Success notification duration (ms)
notifications_duration_error 8000 Error notification duration (ms)

API Endpoints

Core Notification Management

Endpoint Method Purpose Rate Limit
/api/notifications/pending GET Fetch pending notifications Not yet hardened ⚠️
/api/notifications POST Create notification Not yet hardened ⚠️
/api/notifications/{id} GET Get specific notification Not yet hardened ⚠️
/api/notifications/history GET Get notification history Not yet hardened ⚠️
/api/notifications/cleanup DELETE Clean old notifications Not yet hardened ⚠️
/api/notifications/expired DELETE Clean expired notifications Not yet hardened ⚠️

Specialized Notification Endpoints

Endpoint Method Auto-Expiry Purpose
/api/notifications/health-report-sent POST 60 seconds Health report success
/api/notifications/health-report-failed POST 10 minutes Health report failure
/api/notifications/system-update POST 24 hours System update notices
/api/notifications/auth-event POST Variable Authentication events

Database Schema

Notifications Table Structure

CREATE TABLE Notifications (
    Id TEXT PRIMARY KEY,
    Type TEXT NOT NULL CHECK(Type IN ('success', 'error', 'warning', 'info')),
    Message TEXT NOT NULL,
    Title TEXT,
    Category TEXT NOT NULL CHECK(Category IN ('api', 'auth', 'cloud', 'system')),
    Duration INTEGER,
    Persistent BOOLEAN NOT NULL DEFAULT 0,
    CreatedAt DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    IsDelivered BOOLEAN NOT NULL DEFAULT 0,
    DeliveredAt DATETIME,
    ExpiresAt DATETIME  -- AUTO-EXPIRY SUPPORT
);

Database Indexes

Index Purpose
idx_notifications_pending Fast pending lookups
idx_notifications_category Category filtering
idx_notifications_created Chronological sorting
idx_notifications_expires_at Expiry cleanup
idx_notifications_pending_with_expiry Combined pending + expiry

Service Methods

Core Service Methods

// Base notification creation with expiry support
Task<string> CreateNotificationAsync(message, title?, type, category, duration?, persistent?, expiresAt?)

// Cleanup and retrieval
Task<(List<Notifications>, string?)> GetPendingNotificationsAsync(since?)
Task<int> CleanupExpiredNotificationsAsync()
Task<int> CleanupOldNotificationsAsync(daysOld)

Pre-Built Notification Methods

Health & Cloud Operations

  • NotifyHealthReportSentAsync() - 60s expiry
  • NotifyHealthReportFailedAsync() - 10min expiry
  • NotifyCloudSyncStartedAsync() - 5min expiry
  • NotifyCloudAuthenticationRequiredAsync() - Never expires

Authentication Events

  • NotifyUserLoginAsync(username) - 30min expiry
  • NotifyUserLogoutAsync(username) - 15min expiry
  • NotifyAuthFailureAsync(reason) - Never expires
  • NotifySessionExpiredAsync() - Never expires

System Operations

  • NotifySystemUpdateAvailableAsync(version) - 24hr expiry
  • NotifySystemUpdateInstalledAsync(version) - 2hr expiry
  • NotifyDatabaseBackupAsync(success, details) - 1hr/12hr expiry

Device & Junction Operations

  • NotifyDeviceConnectedAsync(deviceName) - 30min expiry
  • NotifyDeviceDisconnectedAsync(deviceName) - 1hr expiry
  • NotifyJunctionStartedAsync(junctionName) - 30min expiry
  • NotifyJunctionStoppedAsync(junctionName) - 1hr expiry
  • NotifyJunctionErrorAsync(junctionName, error) - 6hr expiry

API Operations

  • NotifyApiSuccessAsync(operation, details) - 15min expiry
  • NotifyApiErrorAsync(operation, error) - 2hr expiry

Frontend Implementation

Glass Effect Styling

  • 80% opacity for translucent appearance
  • Backdrop blur with saturation for modern glass effect
  • Subtle borders and highlights for enhanced definition
  • Text shadows for readability on transparent backgrounds

Auto-Dismiss Logic

  • Type-based durations from feature flags
  • Manual dismiss via close button
  • Automatic cleanup when polling for new notifications
  • Smooth animations for show/hide transitions

Feature Flag Integration

  • Category filtering based on user preferences
  • Master toggle to disable entire system
  • Configurable durations per notification type
  • Max concurrent limit to prevent UI clutter

Memory Management

Auto-Cleanup Mechanisms

  1. Frontend Auto-Dismiss: Notifications disappear based on duration
  2. API Polling Cleanup: Expired notifications removed during /pending calls
  3. Database Cleanup: Manual endpoint for expired notification removal
  4. Scheduled Cleanup: Background service for old notification removal

Cleanup Schedule

Cleanup Type Frequency Target
Frontend Auto-Dismiss Per duration Individual notifications
API Polling Cleanup Per request Expired notifications
Manual Cleanup On-demand Old and expired notifications
Database Maintenance Configurable Delivered notifications >30 days

Security & Performance

Database Performance

  • Indexed queries for fast lookups
  • Automatic expiry prevents table bloat
  • Efficient cleanup with combined conditions
  • Minimal storage with compact schema

Rate Limiting Status

Endpoint Status
All notification endpoints Not yet hardened ⚠️

Future Security Considerations

  • Implement rate limiting per user/IP
  • Add request size validation
  • Consider notification spam prevention
  • Monitor notification creation patterns

Usage Examples

Backend Usage

// Health report with auto-expiry
await _notificationService.NotifyHealthReportSentAsync("Sent 5 devices to cloud");

// Custom notification with specific expiry
await _notificationService.CreateNotificationAsync(
    "Custom message",
    "Custom Title",
    NotificationType.Warning,
    NotificationCategory.System,
    expiresAt: DateTime.UtcNow.AddMinutes(30)
);

Frontend Usage

// Show notification programmatically
const { showSuccess, showError } = useNotifications();

showSuccess("Operation completed", "Success", "api");
showError("Something went wrong", "Error", "api", 0); // Persistent

API Usage

# Create custom notification
POST /api/notifications
{
  "message": "Custom notification",
  "type": "info",
  "category": "system",
  "expiresAt": "2024-08-12T16:00:00Z"
}

# Get pending notifications (auto-cleans expired)
GET /api/notifications/pending

# Manual cleanup of expired notifications  
DELETE /api/notifications/expired

Migration Benefits

Before Auto-Expiry

  • ❌ Health reports accumulated indefinitely
  • ❌ Users flooded with old notifications on login
  • ❌ Manual cleanup required
  • ❌ Database bloat over time

After Auto-Expiry

  • ✅ Notifications auto-expire based on importance
  • ✅ Clean UI with only relevant notifications
  • ✅ Automatic database maintenance
  • ✅ Better user experience with glass effect UI
  • ✅ Configurable behavior via feature flags

Future Enhancements

Phase 2 Candidates

  1. Rate Limiting: Implement proper rate limiting on notification endpoints
  2. WebSocket Push: Real-time notifications without polling
  3. User Preferences: Per-user notification settings
  4. Notification History: Enhanced history with filtering
  5. Email Integration: Critical notifications via email
  6. Mobile Push: Integration with mobile push notifications

Monitoring Recommendations

  • Track notification creation patterns
  • Monitor auto-expiry effectiveness
  • Alert on notification system errors
  • Measure user engagement with notifications
  • Track feature flag usage patterns