Skip to content

feat: add alert delivery worker with email/webhook support - #62

Closed
algojogacor wants to merge 68 commits into
Climate-Vision:mainfrom
algojogacor:feat/alert-delivery-worker
Closed

feat: add alert delivery worker with email/webhook support#62
algojogacor wants to merge 68 commits into
Climate-Vision:mainfrom
algojogacor:feat/alert-delivery-worker

Conversation

@algojogacor

Copy link
Copy Markdown
Contributor

Summary

Implements the alert delivery worker as requested in #10. Alerts created in the organization_alerts table are now automatically delivered through the configured notification channels.

What Changed

New Files

  • src/climatevision/workers/__init__.py — worker package init
  • src/climatevision/workers/alert_delivery.py — AlertDeliveryWorker background task

Modified Files

  • src/climatevision/db.py — added get_pending_alerts(), increment_delivery_attempt(), mark_alert_failed()
  • src/climatevision/api/main.py — added FastAPI lifespan integration, new GET /api/organizations/{org_id}/alerts/pending endpoint
  • .env.example — added SMTP and worker configuration variables

Solution

AlertDeliveryWorker runs as a FastAPI lifespan background task:

  1. Polls for undelivered alerts every 60 seconds (configurable via ALERT_DELIVERY_POLL_INTERVAL_SECONDS)
  2. Determines delivery channel from the subscription's notification_channel field
  3. For email: sends HTML email via SMTP (configurable via SMTP_* env vars)
  4. For webhook: POSTs JSON payload to the subscription's webhook URL
  5. Implements exponential backoff retry (max 3 attempts, configurable)
  6. Updates delivery status: delivered=1 on success, increments delivery_attempts on failure, marks as permanently failed after exhausting retries

New endpoint: GET /api/organizations/{org_id}/alerts/pending — returns undelivered alerts for monitoring/dashboard use.

Testing

  • All files pass Python syntax checks
  • Import chain verified: db → workers → api
  • SMTP delivery uses Python's built-in smtplib with TLS support
  • Webhook delivery uses urllib for zero-dependency HTTP
  • Worker lifecycle managed via asynccontextmanager lifespan hook

Acceptance Criteria

  • ✅ When an alert is created, the worker attempts delivery within 60 seconds
  • ✅ Failed deliveries are retried up to 3 times with exponential backoff
  • ✅ Delivery status is queryable via API (GET /api/organizations/{org_id}/alerts/pending)
  • ✅ Worker runs as FastAPI background task
  • ✅ Configurable via environment variables

Oshgig and others added 30 commits March 8, 2026 20:34
- Expanded config.yaml with per-analysis-type configuration for
  deforestation, ice melting, and flooding including band configs,
  alert thresholds, and model paths
- Added config/train.yaml for production training configuration
- Expanded db.py with full SQLite schema: organisations, subscriptions,
  alerts tables; API key generation; all CRUD operations
- Added requirements-install.txt for streamlined dependency installation

Co-authored-by: Adeolu Mary Oshadare <nifemi996@gmail.com>
Co-authored-by: John Edoh Onuh <onuhj47@gmail.com>
Co-authored-by: Francis Umo <Francisumoh@360yahoo.com>
Co-authored-by: Olufemi Taiwo <olufemitaiwo23@gmail.com>
Co-authored-by: Godswill Chukwu Okoroafor <godswillchukwu21@gmail.com>
- Added inference/pipeline.py: full GEE-integrated inference engine
  with NDVI computation, model loading, file and bbox inference paths,
  synthetic NDVI fallback with bbox-seeded reproducibility
- Updated inference/__init__.py to export run_inference,
  run_inference_from_file, run_inference_from_gee
- Added analysis/ module: base class, registry, and dedicated analysers
  for deforestation, flooding and ice melting detection
- Added training/ module: production trainer with EMA, checkpointing,
  early stopping, and combined loss functions (BCE + Dice + Focal)
- Updated models/unet.py with minor architecture improvements
- Updated __init__.py package exports

Co-authored-by: Adeolu Mary Oshadare <nifemi996@gmail.com>
Co-authored-by: Francis Umo <Francisumoh@360yahoo.com>
Co-authored-by: Godswill Chukwu Okoroafor <godswillchukwu21@gmail.com>
Co-authored-by: Victor Mbachu <victor.c.mbachu@gmail.com>
- Expanded api/main.py with full production API: organisation and NGO
  management, subscription system, alert and notification endpoints,
  all three analysis types wired to inference pipeline, run history,
  file upload endpoint, health check and API key authentication
- Added run_api.sh: server startup script with venv activation,
  environment setup and uvicorn hot-reload configuration
- Added docs/API_REFERENCE.md: full endpoint reference with request
  and response schemas for all routes

Co-authored-by: Adeolu Mary Oshadare <nifemi996@gmail.com>
Co-authored-by: John Edoh Onuh <onuhj47@gmail.com>
Co-authored-by: Olufemi Taiwo <olufemitaiwo23@gmail.com>
Co-authored-by: Victor Mbachu <victor.c.mbachu@gmail.com>
Co-authored-by: Godswill Chukwu Okoroafor <godswillchukwu21@gmail.com>
- Fixed repository clone URL to Climate-Vision/ClimateVision
- Updated Quick Start to use run_api.sh instead of raw uvicorn command
- Corrected tech stack: SQLite (not PostgreSQL), Google Maps API (not Leaflet)
- Fixed API Reference doc link to docs/API_REFERENCE.md
- Updated Phase 3 roadmap to reflect Google Maps and Recharts as completed
- Fixed Star History tracking link

Co-authored-by: Adeolu Mary Oshadare <nifemi996@gmail.com>
Co-authored-by: John Edoh Onuh <onuhj47@gmail.com>
Co-authored-by: Francis Umo <Francisumoh@360yahoo.com>
Co-authored-by: Olufemi Taiwo <olufemitaiwo23@gmail.com>
Co-authored-by: Godswill Chukwu Okoroafor <godswillchukwu21@gmail.com>
Co-authored-by: Victor Mbachu <victor.c.mbachu@gmail.com>
Co-authored-by: Paul <46930375+cutewizzy11@users.noreply.github.com>
…ipts

- prepare_data.py: GEE + synthetic Sentinel-2 patch downloader with
  Dynamic World forest labels, train/val/test split, normalizer fitting
- train.py: production Attention U-Net training entry-point with YAML
  config, focal+dice loss, EMA weights, cosine LR schedule, early stopping
- run_training.py: end-to-end training + inference pipeline
- evaluate.py: per-class IoU/F1/precision/recall on held-out test set
- export_model.py: ONNX and TorchScript model export
- infer.py: CLI inference runner for single images or GEE bbox

Co-Authored-By: Emmanuel Edoh <edoh-Onuh@users.noreply.github.com>
Co-Authored-By: Godswill Okoroafor <godswillchukwu21@gmail.com>
Co-Authored-By: Gold Okpa <okpagold@gmail.com>
Co-Authored-By: Victor Mbachu <victor.c.mbachu@gmail.com>
- pipeline.py: authenticate GEE via service account key when
  GEE_SERVICE_ACCOUNT and GEE_SERVICE_ACCOUNT_KEY env vars are set;
  falls back to synthetic NDVI when GEE is unavailable instead of zeros
- .gitignore: protect secrets/ directory and *.json key files

Co-Authored-By: Gold Okpa <okpagold@gmail.com>
Notebook handles: GEE service account auth, multi-region patch download
(Amazon/Congo/Borneo), Attention U-Net training on T4 GPU, evaluation,
and checkpoint download back to local machine.

Co-Authored-By: Gold Okpa <okpagold@gmail.com>
- prepare_data.py: reads GEE_SERVICE_ACCOUNT / GEE_SERVICE_ACCOUNT_KEY
  env vars to authenticate via service account instead of requiring
  earthengine authenticate
- notebook: sets env vars with absolute key path in Cell 3 so all
  subprocess calls in Cells 5 and 6 inherit them automatically

Co-Authored-By: Gold Okpa <okpagold@gmail.com>
Split each region into 0.5° tiles at 30m resolution instead of
downloading the whole bbox at 10m (which hit GEE's pixel grid cap).
Each tile is ~1850x1850px — well under the 32768 limit.
Patches are accumulated across tiles until max_patches is reached.

Co-Authored-By: Gold Okpa <okpagold@gmail.com>
…E limit

Previous 30m/0.5° tiles were ~130MB each, exceeding GEE's 48MB cap.
At 100m resolution each 0.25° tile is ~1.5MB — well within limits.
Also fixes NameError on profile when all tiles failed, and adds a
clear error exit when no patches are extracted.

Co-Authored-By: Gold Okpa <okpagold@gmail.com>
… config

- App.tsx: main application shell with routing, global state and
  sidebar navigation between Dashboard, Analysis, NGO and Settings
- api.ts: typed API client for all backend endpoints (predict, runs,
  organizations, alerts, analysis-types) with error handling
- types.ts: shared TypeScript interfaces for Run, Organization,
  Alert, NDVIStats, InferenceResult and API responses
- styles.css: design-system CSS variables (cv-* tokens), component
  base styles, skeleton loader, scrollbar and animation utilities
- tailwind.config.js: extended theme with cv-* color palette, shadow
  tokens, and custom font stack matching the dark forest UI
- main.tsx: React 18 createRoot entry-point with StrictMode
- index.html: updated meta tags, font preload and app title
- package.json: added lucide-react, recharts, react-router-dom deps
- .env.example: documents VITE_GOOGLE_MAPS_API_KEY and VITE_API_BASE_URL

Co-Authored-By: Emmanuel Edoh <edoh-Onuh@users.noreply.github.com>
Co-Authored-By: Adeolu Mary Oshadare <nifemi996@gmail.com>
Co-Authored-By: Gold Okpa <okpagold@gmail.com>
Co-Authored-By: Victor Mbachu <victor.c.mbachu@gmail.com>
- Validate bbox has exactly 4 values [west, south, east, north]
- Enforce longitude bounds (-180 to 180) and latitude bounds (-90 to 90)
- Ensure west < east and south < north
- Validate date strings follow YYYY-MM-DD format
- Ensure start_date is earlier than end_date
- Add offset query parameter for cursor-based pagination
- Return total record count alongside results for frontend page controls
- Restructure response to {total, limit, offset, runs} envelope
- Refactor WHERE clause building to avoid SQL injection via safe parameterisation
- Returns total run count, completed runs in last 7 days
- Breakdown by status (pending, running, completed, failed)
- Breakdown by analysis type (deforestation, ice_melting, flooding)
- Alert summary: total alerts and unacknowledged count
- Feeds directly into the frontend Dashboard KPI summary cards
- Log every request: method, path, status code, duration_ms, client IP
- Attach X-Response-Time-Ms header to all responses for frontend monitoring
- Uses Starlette BaseHTTPMiddleware for non-blocking request interception
- Helps trace slow endpoints and detect unusual access patterns in production
- Reduce from 874 lines to ~100 lines (~5000 words to 596 words)
- Move installation to top (line 18) - visible without scrolling
- Replace imaginary API examples with real working curl + uvicorn commands
- Replace fabricated benchmarks with honest in-progress markers
- Remove community growth strategy, team descriptions, and execution plan
- Add satellite band details to analysis types table
- Keep citation, contributing, and docs links
…lufemi-improvements

feat(api): Olufemi - API validation, pagination, stats & audit logging
- Add React components: Map, Charts, Layout, UI elements
- Add contexts: AppContext, ToastContext
- Add hooks: useGeocoding, useRunPolling
- Add pages: Analytics, NewAnalysis, RunHistory, Settings, Upload
- Update SETUP_COMPLETE.md

Co-authored-by: Adeolu Mary Oshadare <nifemi996@gmail.com>
Co-authored-by: John Edoh Onuh <onuhj47@gmail.com>
Co-authored-by: Francis Umo <Francisumoh@360yahoo.com>
Co-authored-by: Olufemi Taiwo <olufemitaiwo23@gmail.com>
Co-authored-by: Godswill Chukwu Okoroafor <godswillchukwu21@gmail.com>
Co-authored-by: Victor Mbachu <victor.c.mbachu@gmail.com>
Co-authored-by: Paul <46930375+cutewizzy11@users.noreply.github.com>
Co-authored-by: Gold Okpa <okpagold@gmail.com>
Prevent accidental commits of large .pth model files that exceed GitHub's 100MB limit.
Add centralized constants for API config, map settings, analysis types, polling intervals, and UI configurations.
Goldokpa and others added 18 commits March 31, 2026 19:07
…mate-Vision#7)

* feat(data): add GEE tile downloader with analysis-aware band selection

- Downloads real Sentinel-2 composites via Google Earth Engine
- Reads required bands from config.yaml per analysis_type
- Includes SCL band for downstream cloud masking
- Synthetic fallback with explicit is_synthetic flag when GEE unavailable
- Fix .gitignore so src/climatevision/data/ is no longer ignored

* feat(data): add analysis-specific Sentinel-2 band mapping utilities

- get_bands_for_analysis() reads correct bands from config.yaml
- get_band_indices() maps band names to canonical 13-band stack positions
- is_analysis_enabled() and list_enabled_analysis_types() for config validation
- Includes SCL band helpers for downstream cloud masking

* feat(data): integrate SCL cloud masking and export new pipeline modules

- apply_scl_cloud_mask() masks cloudy pixels using Sentinel-2 SCL band
- Default clear labels: vegetation, bare soils, water, snow
- Update __init__.py to expose gee_downloader and band_mapping utilities

* refactor(data): address PR review feedback

- Remove duplicated config logic in gee_downloader.py; import from band_mapping
- Cache config.yaml load in band_mapping.py via lru_cache
- Read synthetic tile size from config.yaml instead of hardcoding 256
- Remove unused json import in gee_downloader.py
- Add shape validation in apply_scl_cloud_mask

---------

Co-authored-by: Adeolu Mary Oshadare <adeolu@placeholder.com>
…ing (Climate-Vision#8)

* feat(inference): make pipeline analysis-aware with dynamic model loading

- _load_model() now accepts analysis_type and reads in_channels/num_classes from config.yaml
- Per-analysis-type model cache prevents cross-contamination between deforestation/ice/flood models
- _find_best_checkpoint() prefers config.yaml weight path per analysis type
- run_inference() accepts analysis_type, pads/crops to correct n_channels, and returns dynamic class counts
- run_inference_from_file() and run_inference_from_gee() propagate analysis_type parameter

* feat(api): wire analysis_type into prediction endpoints

- Pass body.analysis_type to run_inference_from_gee() in /api/predict
- Pass analysis_type to run_inference_from_file() in /api/predict/upload
- Enables the API to load the correct model and return correct class counts per analysis type

---------

Co-authored-by: Olufemi Taiwo <Olufemitaiwo23@gmail.com>
… flag, add config health validation

- Add cv_dev development key bypass for local testing
- Require X-API-Key on all mutation endpoints (POST predict, orgs, alerts, subscriptions)
- Surface is_synthetic at root of inference response for frontend demo banners
- Expand /api/health to validate config alignment (bands vs in_channels, classes vs num_classes)
- Add FastAPI test client fixture
- Create CI workflow for Python (flake8, pytest) and frontend (npm build)
- Bootstrap tests/ directory structure
- Parametrize UNet init for all 3 analysis types (4ch/2cl, 4ch/3cl, 3ch/3cl)
- Validate forward pass output shapes
- Add Siamese change detection forward shape test
- Link to 6 active good-first-issue and help-wanted issues
- Add claim workflow for new contributors
- Include time estimates and skill-building map
- ../components/map/ -> ../components/Map/
- Fixes vite build failure on Linux (case-sensitive filesystem)
- Fixes pip install failure for gdal and rasterio on Ubuntu runners
- Adds libgdal-dev, gdal-bin, libgl1-mesa-glx
- gdal Python package requires exact system GDAL version matching
- rasterio covers all GDAL functionality we actually use
- Simplify CI system deps to libgl1 only (for opencv runtime)
- Fixes ModuleNotFoundError: No module named 'climatevision'
- pip install -e . registers src/ as an importable package
- ForestDataset with DataLoader support
- Training/validation augmentation pipelines
- Synthetic tile generation for demo/fallback mode
- Add DONE/PENDING task list for April 2026 sprint
- Include actual .github/workflows/ci.yml code in role doc
- Update local CI check commands to match current workflow
- Add AlertDeliveryWorker background task with FastAPI lifespan integration
- Implement email delivery via SMTP with TLS support
- Implement webhook delivery via HTTP POST
- Add exponential backoff retry logic (max 3 attempts)
- Add DB functions: get_pending_alerts, increment_delivery_attempt, mark_alert_failed
- Add GET /api/organizations/{org_id}/alerts/pending endpoint
- Update .env.example with SMTP and worker configuration

Closes Climate-Vision#10
@Oshgig

Oshgig commented May 16, 2026

Copy link
Copy Markdown
Collaborator

Great work @algojogacor — the architecture here is solid. Using a FastAPI lifespan context manager as the worker host is the right call over BackgroundTasks, since it survives cleanly across the server lifecycle rather than being tied to individual request triggers. The exponential backoff, delivery status tracking, and zero-dependency approach (smtplib + urllib) are all good choices.

One thing is blocking merge:

Tests are missing. The test section says "all files pass Python syntax checks" — that's not a test suite. Before this can land I need at least:

  1. A unit test for the retry/backoff logic (mock smtplib.SMTP to raise, verify delivery_attempts increments and the worker stops at MAX_RETRIES).
  2. A test for the GET /api/organizations/{org_id}/alerts/pending endpoint (use TestClient, seed a pending alert, verify the response shape).

The rest of the PR is in great shape. Add those tests and I'll approve.

Note to @Presmanes3: I'm closing #57 in favour of this PR — please see the comment there.

@femi23 femi23 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for taking on alert delivery, @algojogacor — this is a substantial and well-structured contribution, and it touches a lot of the production paths I care about for inference→alert. CI is green and the lifespan integration is the right shape. A few blocking issues to address before we can land it though:

Blockers

1. _send_webhook references urllib.parse which is never imported. In alert_delivery.py the imports are:

import urllib.request
import urllib.error

but the helper calls urllib.parse.urlencode(payload). This will raise AttributeError: module 'urllib' has no attribute 'parse' the first time the function runs. Either import urllib.parse explicitly or drop the helper (see #2).

2. _send_webhook is dead code and uses the wrong encoder. _process_pending_alerts builds the webhook request inline and never calls the helper. The helper also uses urlencode (form encoding) for what should be a JSON body — that wouldn't work even with the import fix. Please either: (a) delete _send_webhook and keep the inline path, or (b) refactor the inline path to call a corrected helper that does json.dumps(...).encode(). (b) is cleaner.

3. SSRF risk on webhook URLs. urllib.request.urlopen(webhook_url, ...) will happily fetch http://localhost, http://169.254.169.254/... (AWS metadata), file:///etc/passwd, etc. Webhook URLs come from API subscribers, so this is reachable. Please add a small URL validator that:

  • requires https:// (or http:// only for non-loopback, non-private IPs)
  • rejects RFC1918 / loopback / link-local destinations after DNS resolution
    This aligns with the OWASP middleware that landed in #34.

4. Backoff blocks the whole batch. Inside _process_pending_alerts:

if attempts > 0:
    delay = min(2 ** attempts, 300)
    await asyncio.sleep(delay)

This sleeps inline before processing each retried alert, so one alert at attempt 2 stalls every other alert for 4s, attempt 3 stalls 8s, etc. With a backlog this serialises into many minutes per cycle and starves the rest of the queue. Two reasonable fixes:

  • store next_attempt_at on the row and have get_pending_alerts filter by next_attempt_at <= now() — no in-process sleeping, and survives restarts
  • or, at minimum, run the per-alert sleeps via asyncio.gather(...) so they're concurrent
    I'd prefer the first.

Should-fix before merge

5. No tests. This is the largest worker we've added — please include at least:

  • a unit test for _send_email with smtplib.SMTP mocked
  • a unit test for the webhook path with urllib.request.urlopen patched
  • a test that asserts start()/stop() is idempotent and stop() cancels cleanly within the 30s budget

6. get_pending_alerts import inside the function. In db.py:

def get_pending_alerts(...):
    import sqlite3
    with get_connection() as conn:

The sqlite3 import is unused — please drop it.

7. mark_alert_failed doesn't set a terminal flag. Right now "failed" alerts are indistinguishable from "still pending but past max attempts" — both are delivered=0, attempts>=max. Long-term we'll want a delivery_status enum (pending|delivered|failed). Not a hard blocker, but please add a TODO comment in mark_alert_failed so we don't lose it.

Nits

  • _get_smtp_config() defaults from_email to SMTP_USERNAME which may be a login like alerts@gmail.com — fine but worth documenting in .env.example as "often must match SMTP_USERNAME for some providers".
  • The HTML template injects {subject} and {body} into an f-string without escaping. Low risk since they come from our DB, but if any alert message ever carries user-controlled text we have XSS in emails. Either run them through html.escape() or add a comment that the upstream is trusted.
  • lifespan is a closure inside create_app() — fine, but please add a comment that the worker instance is intentionally per-app so test factories get isolation.

Once the four blockers are addressed I'll re-review quickly. Thanks again for the careful work here — looking forward to landing this.

@Goldokpa

Copy link
Copy Markdown
Member

📢 Heads-up: repo history was rewritten today (2026-05-18)

We force-pushed a cleaned history across all branches to remove an internal directory from past commits. Your code and this PR are unaffected — only the commit SHAs underneath have shifted. GitHub will re-render the diff against the new base automatically.

If you have a local clone, please bring it back in sync before pushing anything else:

# Option A (simplest): fresh start
git clone https://github.com/Climate-Vision/ClimateVision.git

# Option B: rebase the existing PR branch in your fork
git fetch origin
git checkout <your-branch>
git rebase origin/main          # likely no conflicts
git push --force-with-lease

Do not git pull on an existing clone — it will produce a messy non-fast-forward state. Either re-clone, or rebase explicitly as above.

Apologies for the interruption — really appreciate your patience here. If anything looks off after rebasing, leave a comment and I'll help unblock right away. Thanks for contributing 🙏

@Goldokpa
Goldokpa self-requested a review as a code owner June 26, 2026 11:33
obielin added a commit that referenced this pull request Jun 26, 2026
feat: alert delivery worker with email/webhook support (#62, rebased)
@obielin

obielin commented Jun 26, 2026

Copy link
Copy Markdown
Collaborator

Merged into main via #105 (rebased onto current main after the history update; .env.example and main.py conflicts resolved, your commits/authorship preserved). Thanks @algojogacor!

@obielin obielin closed this Jun 26, 2026
Goldokpa pushed a commit that referenced this pull request Jun 26, 2026
feat: alert delivery worker with email/webhook support (#62, rebased)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants