diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts index 5f278d0..808bb85 100644 --- a/docs/.vitepress/config.mts +++ b/docs/.vitepress/config.mts @@ -1,16 +1,15 @@ -import { defineConfig } from 'vitepress' +import { defineConfig } from "vitepress"; export default defineConfig({ title: "MvuviGo Technical Documentation", - base: '/pixels-technical-documentation/', - description: "Technical architecture and system design for the MvuviGo maritime safety platform", - - head: [ - ['link', { rel: 'stylesheet', href: '/custom.css' }] - ], + base: "/pixels-technical-documentation/", + description: + "Technical architecture and system design for the MvuviGo maritime safety platform", + + head: [["link", { rel: "stylesheet", href: "/custom.css" }]], themeConfig: { - logo: '/logo.png', + logo: "/logo.png", nav: [ { text: "Home", link: "/" }, { text: "Overview", link: "/overview/" }, @@ -35,9 +34,18 @@ export default defineConfig({ collapsed: true, items: [ { text: "Introduction", link: "/architecture/" }, - { text: "Architecture Principles", link: "/architecture/architecture-principles" }, - { text: "System Architecture", link: "/architecture/system-architecture" }, - { text: "Component Diagram", link: "/architecture/component-diagram" }, + { + text: "Architecture Principles", + link: "/architecture/architecture-principles", + }, + { + text: "System Architecture", + link: "/architecture/system-architecture", + }, + { + text: "Component Diagram", + link: "/architecture/component-diagram", + }, { text: "Data Flow", link: "/architecture/data-flow" }, ], }, @@ -71,7 +79,10 @@ export default defineConfig({ { text: "Repositories", link: "/repository/" }, { text: "Backend Repository", link: "/repository/backend-repo" }, { text: "Frontend Repository", link: "/repository/frontend-repo" }, - { text: "IoT Server Repository", link: "/repository/iot-server-repo" }, + { + text: "IoT Server Repository", + link: "/repository/iot-server-repo", + }, ], }, { @@ -79,8 +90,14 @@ export default defineConfig({ collapsed: true, items: [ { text: "Introduction", link: "/communication/" }, - { text: "RFID and Station Hardware", link: "/communication/rfid-and-station-hardware" }, - { text: "LoRa Relay and Mesh", link: "/communication/lora-relay-and-mesh" }, + { + text: "RFID and Station Hardware", + link: "/communication/rfid-and-station-hardware", + }, + { + text: "LoRa Relay and Mesh", + link: "/communication/lora-relay-and-mesh", + }, { text: "SMS Integration", link: "/communication/sms-integration" }, { text: "GPS Tracking", link: "/communication/gps-tracking" }, ], @@ -92,9 +109,15 @@ export default defineConfig({ { text: "Introduction", link: "/frontend/" }, { text: "Architecture", link: "/frontend/architecture" }, { text: "Routing", link: "/frontend/routing" }, - { text: "Pages and Components", link: "/frontend/pages-and-components" }, + { + text: "Pages and Components", + link: "/frontend/pages-and-components", + }, { text: "State Management", link: "/frontend/state-management" }, - { text: "Forms and Validation", link: "/frontend/forms-and-validation" }, + { + text: "Forms and Validation", + link: "/frontend/forms-and-validation", + }, { text: "API Integration", link: "/frontend/api-integration" }, { text: "Authentication", link: "/frontend/authentication" }, { text: "Maps and Real-time", link: "/frontend/maps-and-real-time" }, @@ -110,24 +133,42 @@ export default defineConfig({ { text: "Introduction", link: "/security/" }, { text: "Access Control", link: "/security/access-control" }, { text: "Data Protection", link: "/security/data-protection" }, - { text: "Logging and Monitoring", link: "/security/logging-and-monitoring" }, + { + text: "Logging and Monitoring", + link: "/security/logging-and-monitoring", + }, { text: "Failure Handling", link: "/security/failure-handling" }, ], }, { - text: "Setup", + text: "Developer Setup", collapsed: true, items: [ - { text: "Deployment and Contribution", link: "/deployment/" }, - { text: "Deployment", link: "/deployment/deployment" }, - { text: "Branching and Pull Requests", link: "/deployment/branching-and-prs" }, - { text: "Code Contribution", link: "/deployment/code-contribution" }, + { text: "Onboarding", link: "/setup/" }, + { text: "Prerequisites", link: "/setup/prerequisites" }, { text: "Installation", link: "/setup/installation" }, - { text: "Run Locally", link: "/setup/run-locally" }, + { + text: "Environment Variables", + link: "/setup/environment-variables", + }, { text: "Database Setup", link: "/setup/database-setup" }, - { text: "Environment Variables", link: "/setup/environment-variables" }, + { text: "Run Locally", link: "/setup/run-locally" }, ], }, + { + text: "Deployment and Contribution", + collapsed: true, + items: [ + { text: "Introduction", link: "/deployment/" }, + { text: "Deployment", link: "/deployment/deployment" }, + { + text: "Branching and Pull Requests", + link: "/deployment/branching-and-prs", + }, + { text: "Code Contribution", link: "/deployment/code-contribution" }, + ], + }, + { text: "Workflows", collapsed: true, @@ -135,7 +176,10 @@ export default defineConfig({ { text: "Introduction", link: "/workflows/" }, { text: "Trip Tracking", link: "/workflows/trip-tracking" }, { text: "SOS Alert Flow", link: "/workflows/sos-alert-flow" }, - { text: "Rescue Coordination", link: "/workflows/rescue-coordination" }, + { + text: "Rescue Coordination", + link: "/workflows/rescue-coordination", + }, ], }, { @@ -151,4 +195,4 @@ export default defineConfig({ }, ], }, -}) +}); diff --git a/docs/database/index.md b/docs/database/index.md index 0203af4..7fd9a3b 100644 --- a/docs/database/index.md +++ b/docs/database/index.md @@ -1,6 +1,6 @@ # Database -MvuviGo stores everything in a **PostgreSQL** database named `MvuviGo`. The backend (`pixels-backend`) talks to it through **SQLAlchemy** models, and the schema is versioned with **Alembic** migrations. +MvuviGo stores its application data in **PostgreSQL**. For local development, this documentation uses the database name `mvuvigo`; the backend (`pixels-backend`) accesses it through **SQLAlchemy**, and the schema is versioned with **Alembic** migrations. ## What the database holds @@ -14,11 +14,18 @@ MvuviGo stores everything in a **PostgreSQL** database named `MvuviGo`. The back ## In this section - [Entity relationship diagram](./er-diagram.md): how the tables connect. + - [Key entities](./key-entities.md): what each table stores and how an alert moves through them. - [Constraints](./constraints.md): keys, unique rules, required columns and allowed values. - [Migrations](./migrations.md): how the schema is versioned and changed with Alembic. - [Seed data](./seed-data.md): the data a fresh database needs and how it is loaded. +- [Constraints](./constraints.md): keys, unique rules, required columns and allowed values. + +- [Migrations](./migrations.md): how the schema is versioned and changed with Alembic. + +- [Seed data](./seed-data.md): the data a fresh database needs and how it is loaded. + ## Working with the database locally The local database runs on `localhost:5432`. To create or update the tables, run the migrations from the backend repo: @@ -27,6 +34,6 @@ The local database runs on `localhost:5432`. To create or update the tables, run alembic upgrade head ``` -If you get an error such as `relation "islands" already exists`, the tables were created before Alembic was set up on your machine. Either drop and recreate your local database, or mark the existing schema as up to date with `alembic stamp head` and then upgrade. +If you get an error such as `relation "islands" already exists`, the tables may have been created before Alembic was set up. For a disposable local database, recreate it and apply migrations from the beginning. `alembic stamp head` only records a version; use it only after verifying that the existing schema exactly matches that revision. Never drop or stamp a shared or production database as a troubleshooting shortcut. Every change to a SQLAlchemy model needs a new migration. Do not edit the database by hand and leave the models behind. \ No newline at end of file diff --git a/docs/database/migrations.md b/docs/database/migrations.md index 5c38343..0e36f07 100644 --- a/docs/database/migrations.md +++ b/docs/database/migrations.md @@ -5,9 +5,13 @@ The schema is versioned with **Alembic** in `pixels-backend`. The SQLAlchemy mod ## Rules - Every change to a SQLAlchemy model needs a new migration. + - Never edit the database by hand and leave the models behind. + - Keep one concern per migration, and keep it in the same PR as the model change. + - Read every generated migration before committing it. Autogenerate can miss renames and constraints. + - Write a working `downgrade` for every migration so it can be undone. ## Commands @@ -28,13 +32,20 @@ Migration files live in the Alembic `versions` folder (**TO CONFIRM** the path i ## Adding a migration 1. Change the model in `pixels-backend`. -2. Run `alembic revision --autogenerate -m "describe the change"`. -3. Open the new file and check the `upgrade` and `downgrade` steps. -4. Run `alembic upgrade head` on your local database. -5. Run `alembic downgrade -1` and then `alembic upgrade head` again to prove both directions work. -6. Run the backend tests (`pytest`). -7. Commit the model change and the migration together. -8. Update [Key entities](./key-entities.md), [Constraints](./constraints.md) and the [entity relationship diagram](./er-diagram.md) if the schema changed. + +1. Run `alembic revision --autogenerate -m "describe the change"`. + +1. Open the new file and check the `upgrade` and `downgrade` steps. + +1. Run `alembic upgrade head` on your local database. + +1. Run `alembic downgrade -1` and then `alembic upgrade head` again to prove both directions work. + +1. Run the backend tests (`pytest`). + +1. Commit the model change and the migration together. + +1. Update [Key entities](./key-entities.md), [Constraints](./constraints.md) and the [entity relationship diagram](./er-diagram.md) if the schema changed. ## Common problems @@ -44,10 +55,14 @@ Migration files live in the Alembic `versions` folder (**TO CONFIRM** the path i | Adding a unique constraint fails | The table already contains duplicate values. | Clean the duplicates first, for example in the migration itself, then upgrade again. | | The app and the migrations disagree about the data | Alembic and the application are connected to different databases. | Make sure the connection setting in `.env` and the default in the application's database code name the same database. | -PostgreSQL treats names that differ only in capitals, such as `MvuviGo` and `mvuvigo`, as different databases when the name was created with quotes. The documented name is `MvuviGo`. **TO CONFIRM** the exact spelling every environment must use, and use it everywhere. +For local development, use the lower-case database name `mvuvigo` consistently in the database creation command and `DATABASE_URL`. PostgreSQL folds unquoted identifiers to lower case; a database created with a quoted mixed-case name is a different name and requires a matching connection string. Confirm the target database before running any migration. + +Do not use `alembic stamp head` as a general fix for migration errors. It changes Alembic's recorded version without applying or validating the schema. Use it only after verifying that the existing database exactly matches the target revision; otherwise, recreate a disposable local database and apply migrations from the beginning. Never use this shortcut on a shared or production database. ## Production - Take a database backup before every production migration. + - Run `alembic upgrade head` on every deploy, after the backup and before the new backend starts. + - Follow [Rollback and recovery](../deployment/deployment.md#rollback-and-recovery) if a migration has to be undone. diff --git a/docs/database/seed-data.md b/docs/database/seed-data.md index 7397901..e1e6d81 100644 --- a/docs/database/seed-data.md +++ b/docs/database/seed-data.md @@ -1,33 +1,41 @@ # Seed Data -Seed data is the information a fresh database needs before the system is useful. Everything else is created by people using the dashboard and by the wristbands and stations. +Seed data is information needed to make a fresh database useful. The project documentation identifies island reference records and an initial station-operator account as potential setup needs, while sample fishers, wristbands, trips, locations and alerts are for local development or demos. -## What needs seeding -| Table | Why | Needed in production | +## Data categories + +| Data | Documented purpose | Handling guidance | | --- | --- | --- | -| `islands` | Reference data for the fishing areas: `island_name`, `island_latitude` and `island_longitude`. | Yes | -| `station_operators` | At least one operator must exist to log in and register fishers. The password is stored as a hash, never in plain text. | Yes, the first operator only | -| `fishers`, `wristbands`, `trips`, `locations` | Sample records for local development and demos. | No | -| `distressed_fisher_alerts`, `alert_responders` | Sample alerts for local development and demos. | No | +| Islands | Reference names and coordinates used by the product | Use an approved, sourced dataset. The exact list and source are not included here. | +| First station operator | Allows an authorized operator to access the dashboard | Create through the backend's secured account-creation process; never store a plaintext password in a seed file. Confirm the actual bootstrap flow in the backend repository. | +| Fishers, wristbands, trips and locations | Local development or demo records | Use invented identities and synthetic coordinates only. | +| SOS alerts and responders | Local workflow demonstration | Use synthetic events in a local/test environment; never replay test alerts to real responders. | + +## Verify the seeding mechanism + +From the backend repository root, before changing a database: + +1. Read the repository README and inspect `pyproject.toml` for documented scripts or commands. -The list of islands to load: **TO CONFIRM**. +1. Inspect the Alembic migrations and search the repository for seed/fixture files or commands. Do not assume a filename or entry point. -## How seed data is loaded +1. Confirm whether reference data is created by a migration, an idempotent script, an API workflow or a manual approved process. -**TO CONFIRM:** whether seed data is loaded by a script, by a migration or by hand, and the exact command. Document it here once decided, for example: +1. If a script exists, verify that it is safe to run more than once and that it cannot target production by accident. -```bash -# TO CONFIRM: replace with the real command -python -``` +1. Run it only against a disposable local/test database, then verify the resulting rows and record the exact command and source dataset here. -If there is no seed mechanism yet, state "none" here and list how the first operator and the islands are created. +If the checked-out application repository has no seed mechanism, document that explicitly and describe the approved local setup path for the first operator and reference data. Keep this page synchronized with any later script or migration change. ## Rules -- A seed script must be safe to run twice. Check for existing rows before inserting. -- Never load development sample data into production. -- Sample data uses invented names and phone numbers, never real people. -- Do not commit real passwords or real operator accounts. Create the first production operator through a secured step and store its credentials in the host's secret store. -- Backend tests create their own data and roll it back, so they do not depend on seed data. +- Keep development seed data separate from production data. + +- Use synthetic names, phone numbers and locations; do not copy real fisher records into a test environment. + +- Never seed plaintext passwords, API keys, tokens or provider credentials. + +- Make repeatable seed operations idempotent or clearly document that they are one-time operations. + +- Backend tests should use isolated test fixtures rather than depending on a developer's local seed dataset. diff --git a/docs/frontend/build-and-tooling.md b/docs/frontend/build-and-tooling.md index cb64ad9..be6acf7 100644 --- a/docs/frontend/build-and-tooling.md +++ b/docs/frontend/build-and-tooling.md @@ -16,7 +16,7 @@ Run these from the `pixels-frontend` folder: | Command | What it does | | --- | --- | -| `npm install` | Install dependencies | +| `npm ci` | Install the exact dependencies recorded in `package-lock.json` | | `npm run dev` | Start the development server on port 3000 | | `npm run build` | Create the optimised production build | | `npm run start` | Serve the production build | @@ -32,7 +32,10 @@ Variables that start with `NEXT_PUBLIC_` are included in the browser bundle, so ## Build process -1. `npm install` installs dependencies from `package-lock.json`. -2. `npm run build` compiles the pages, bundles the JavaScript and CSS, and generates the static assets. -3. The build fails on compile errors, so fix them before release. -4. `npm run start` serves the result for a final check. +1. `npm ci` installs the exact dependencies recorded in `package-lock.json`. + +1. `npm run build` compiles the pages, bundles the JavaScript and CSS, and generates the static assets. + +1. The build fails on compile errors, so fix them before release. + +1. `npm run start` serves the result for a final check. diff --git a/docs/index.md b/docs/index.md index 7002b85..061c9eb 100644 --- a/docs/index.md +++ b/docs/index.md @@ -12,28 +12,28 @@ import { withBase } from 'vitepress'

MvuviGo

-

When the horizon is your office, connectivity is survival. MvuviGo delivers relentless tracking and emergency response for those who make their living on the Lake Victoria waters.

+

MvuviGo helps small-scale fishers on Lake Victoria raise an SOS and coordinate a human-led local response when mobile coverage may be unreliable.

- Get Started + Developer Onboarding Explore the Platform
-

Unbroken Connectivity

-

Leveraging custom LoRa mesh networks and edge hardware to keep communication alive when cellular signals drop off the map.

+

Long-range first alert

+

The system is designed to send an initial SOS over long-range radio without depending on mobile coverage. Availability still depends on working devices, station reach and power.

-

Seamless Fleet Management

-

A comprehensive dashboard for station operators to register vessels, assign RFID wristbands, and monitor active trips in real time.

+

Landing-site coordination

+

Operators register fishers and pair devices, then use the dashboard to review emergency information and coordinate a response.

-

Rapid Response Protocol

-

Instant distress alerts that route directly to the nearest rescue responders, turning critical emergencies into coordinated actions.

+

Human-led response

+

Emergency alerts and available location information support nearby participating fishers and the landing-site operator. People decide whether and how to respond.

@@ -43,7 +43,7 @@ import { withBase } from 'vitepress' Learn more about MvuviGo on our Website. diff --git a/docs/overview/product-definition.md b/docs/overview/product-definition.md index e3e3aa6..5d01b37 100644 --- a/docs/overview/product-definition.md +++ b/docs/overview/product-definition.md @@ -7,13 +7,15 @@ Lake Victoria supports the livelihoods of many small-scale fishers who spend lon When that happens, three things go wrong: 1. **The fisher has no dependable way to call for help.** Many fishers do not have a reliable way to raise an alarm, and mobile coverage on the water cannot be assumed. -2. **Nobody nearby knows where the boat is.** Other fishers and the landing site may not learn that help is needed, or where. -3. **Response is slow and informal.** Rescue depends on fellow fishers noticing and having a boat and fuel available. Searches can take a long time, and little is recorded afterward. + +1. **Nobody nearby knows where the boat is.** Other fishers and the landing site may not learn that help is needed, or where. + +1. **Response is slow and informal.** Rescue depends on fellow fishers noticing and having a boat and fuel available. Searches can take a long time, and little is recorded afterward. Other measures address parts of the problem but not this gap: | Measure | What it does | What it leaves open | -|---|---|---| +| --- | --- | --- | | Weather forecasts and alerts | Warn areas of dangerous conditions | Do not tell anyone a specific boat is in trouble | | Life jackets and safety training | Reduce the risk of drowning | Do not summon help | | Satellite emergency beacons | Alert distant national authorities | Costly, and do not alert nearby fishers | @@ -27,8 +29,11 @@ MvuviGo shortens the delay between **a boat getting into trouble** and **someone It does this by combining four capabilities: - a one-button **alarm** that works without mobile coverage; + - an immediate **alert** to the landing site and to the nearby fishers best placed to help; + - **guidance** that helps responders find the distressed boat as it and they move; + - **coordination and a record** managed by a person at the landing site. The product boundary is **emergency detection, local notification, response coordination and incident recording**. @@ -36,7 +41,7 @@ The product boundary is **emergency detection, local notification, response coor ## Target users | User | Who they are | What they need from MvuviGo | Constraints that shape the design | -|---|---|---|---| +| --- | --- | --- | --- | | **Fisher in distress** | A small-scale fisher who may be far from shore | Raise an alarm quickly, with a usable location, without a smartphone | Cannot rely on mobile coverage. Location is shared on SOS, not continuously | | **Responding fisher** | A participating fisher on a nearby boat | Know that someone needs help, where they are, and how to reach them as positions change | Often has only a basic feature phone, so guidance arrives as simple messages | | **Landing-site operator** | The person at the landing site who runs the station | One view of the emergency, who is nearby and how far away, and a way to record the outcome | Coordinates by phone. Needs to be available when boats are out | @@ -46,13 +51,13 @@ Others are affected but are not direct users: boat owners and landing-site organ ## Main use cases | # | Use case | What happens | Outcome | -|---|---|---|---| +| --- | --- | --- | --- | | 1 | **Raise an alarm** | A fisher in danger presses the SOS button. The device captures the latest available GPS location and sends the alert over radio | The landing site and nearby participating fishers know that help is needed and where | -| 2 | **Respond to an alarm** | A nearby fisher is alerted, their position is shared, and they receive directions to the distressed boat. Directions refresh every 30 seconds as boats move | The responder can decide whether and how to help and adjust their route | +| 2 | **Respond to an alarm** | During an active response, a nearby fisher is alerted, their position is shared, and they receive directions to the distressed boat. Directions are intended to refresh every 30 seconds as positions change | The responder can decide whether and how to help and adjust their route | | 3 | **Coordinate from shore** | The operator sees the distressed boat, nearby boats and distances on a dashboard, then contacts responders by normal phone call | Response is organised by a person with the full picture | | 4 | **Record the incident** | The operator records the incident, responses, status and outcome | A record exists for follow-up and for improving safety | | 5 | **Set up participation** | The operator registers a fisher and pairs a device to them | Alerts are tied to the right person | ## Core functionality in one paragraph -A fisher carries a device. Pressing its button sends an SOS with the fisher's identity and latest location by long-range radio to the landing station and nearby participating devices. Nearby boats share their positions. The landing-site dashboard shows the distressed boat, nearby boats and distances, and AI-generated directions are sent to responders' feature phones, refreshed as positions change. The operator coordinates the response and records the outcome. See [System Overview](system-overview.md) for how this works step by step. +A fisher carries a device. Pressing its button sends an SOS with the fisher's identity and latest available location by long-range radio to the landing station and nearby participating devices. During an active response, nearby boats share their positions. The landing-site dashboard shows the distressed boat, nearby boats and distances, and AI-generated directions are sent to responders' feature phones, with updates intended to follow changing positions. The operator coordinates the response and records the outcome. This active-response flow is not continuous location tracking during ordinary trips. See [System Overview](./system-overview.md) for how it works step by step. diff --git a/docs/security/failure-handling.md b/docs/security/failure-handling.md index ebca98a..83ee877 100644 --- a/docs/security/failure-handling.md +++ b/docs/security/failure-handling.md @@ -1,15 +1,67 @@ -# Failure Handling +# Failure Handling and Incident Response -In a maritime environment, network connections drop frequently. MvuviGo is designed to fail gracefully. +MvuviGo supports a safety-critical workflow, but it does not replace the landing site's approved emergency procedures or formal search-and-rescue services. During an active SOS, human safety and communication take priority over restoring software. This checklist is a documentation-level guide; the system owner must validate it with the landing-site operator, security/privacy owner and service operators before adopting it as an operational runbook. -## Database Failures -* **FastAPI:** If the connection to PostgreSQL drops, SQLAlchemy tests and recreates the connection automatically before executing a query. -* **Node.js:** Uses a `pg.Pool`. If a database query fails, the error is caught and logged without crashing the server, allowing it to process the next MQTT message. +## Documented failure behavior -## Network Failures (Edge Layer) -* **LoRa Fallback:** If a landing station loses internet, it stores the GPS and SOS packets locally. Once the internet connection is restored, it flushes the stored data to the MQTT broker. -* **Offline Frontend:** If the web dashboard loses connection to the backend, the frontend displays an error toast ("Failed to fetch") rather than crashing the entire UI. +The existing system documentation describes the following behaviors. Confirm each against the current service code, device tests and deployed configuration before relying on it in an emergency. -## Email Failures -* If the SMTP server is down or credentials are invalid, the `request-code` endpoint will return an error. -* For local development, developers can set `EMAIL_DELIVERY=console` in the `.env` file to bypass SMTP entirely and read the OTP from the terminal logs. \ No newline at end of file +### Database failures + +- **FastAPI:** the architecture documentation describes SQLAlchemy reconnecting after a dropped PostgreSQL connection. Verify retry behavior and limits in the backend implementation. + +- **Node.js gateway:** the repository documentation describes handling database query errors without terminating the server. Verify queueing, retry, duplicate handling and message-loss behavior in the IoT implementation. + +### Network failures + +- **Landing station offline:** the architecture documentation describes locally storing GPS/SOS packets and forwarding them when internet connectivity returns. Verify storage capacity, power-loss behavior, replay ordering and duplicate suppression on the actual hardware before treating this as a guarantee. + +- **Dashboard disconnected:** the frontend documentation describes presenting an error rather than crashing. An error display does not prove that an SOS was received or that a location is current. Switch to the site's approved human coordination fallback. + +### Email and one-time-code failures + +If the configured email provider is unavailable, operator authentication or account recovery may fail. For local development only, the docs describe `EMAIL_DELIVERY=console` as a way to print one-time codes. Never enable console OTP delivery in production or expose authentication codes in shared logs. + +## Active SOS: operator checklist + +1. **Use the local emergency procedure first.** Acknowledge the report through the approved operator process and use normal phone/radio channels to coordinate people. Do not wait for an AI direction, dashboard refresh or successful software recovery before acting. + +1. **Record what is known and how fresh it is.** Note the incident identifier, time received, source, latest available position and its timestamp/age if known. Clearly label missing, stale or simulated locations; never present an old position as current. + +1. **Confirm the human fallback.** If the dashboard, internet, MQTT, SMS or automated directions are unavailable, contact the relevant people using the landing site's established communication method and escalate to formal rescue services according to local procedure. + +1. **Do not create duplicate live alerts to test recovery.** Use a designated test environment for troubleshooting. Preserve existing incident records and follow the approved process for corrections. + +1. **After service returns, reconcile cautiously.** Confirm which events were received, delayed or lost before replaying queued messages. Replay only under a documented process that prevents duplicate alerts and database records. + +1. **Close the operational record.** Record response actions, communications, service interruptions, outcome and follow-up owner in the approved incident record. Do not put unnecessary personal data in general-purpose technical logs. + +## Security or privacy incident checklist + +1. **Recognize and report.** Record when and where the issue was noticed, affected service/environment, and a brief description. Notify the designated security/privacy owner using the contact path in the approved incident plan. + +1. **Protect people and preserve evidence.** Keep an active response moving through human channels. Preserve relevant logs and timestamps with access restricted; do not delete, edit or broadly copy evidence to troubleshoot. + +1. **Contain with the service owner.** If credentials are exposed, revoke or rotate them through the owning system and assess what they could access. Isolate a component only when the responsible operator has assessed the safety impact and the human fallback is active. + +1. **Limit personal and location data.** Share only the minimum necessary information with authorized responders. Do not paste access tokens, passwords, phone numbers or precise fisher locations into tickets, chat, screenshots or public issue reports. + +1. **Recover and verify.** Restore from a known-good configuration or backup using the service's approved runbook. Check service health, database integrity, authentication and event processing in a test environment before returning it to operational use. + +1. **Document and review.** Record the timeline, affected data/services, containment and recovery actions, decision owners and follow-up tasks. The responsible organization must determine any required external notifications under its incident policy and applicable law. + +## Complete before operational use + +This documentation archive does not identify named on-call contacts or a formal incident plan. The service owner must add and maintain the following in an access-controlled operational runbook: + +- primary and backup operator/security/privacy contacts and escalation path; + +- local emergency and formal rescue escalation procedure for each deployment site; + +- approved degraded-mode procedure when internet, dashboard, radio, MQTT or SMS fails; + +- who can rotate secrets, restore databases and approve message replay; + +- log access, retention, backup/restore ownership and incident record location; + +- a safe, scheduled test of fallback communications and backup restoration. \ No newline at end of file diff --git a/docs/security/index.md b/docs/security/index.md index 0110959..59d2580 100644 --- a/docs/security/index.md +++ b/docs/security/index.md @@ -1,14 +1,14 @@ # Security and Reliability -The MvuviGo platform handles life-critical data. The security architecture is designed to protect fisher identities, ensure only authorized station operators can access the dashboard, and maintain system availability even when parts of the network fail. +The MvuviGo platform handles sensitive identity and location data in a safety-critical context. The controls on this page describe the documented security design; they are not, by themselves, evidence that a control is implemented, deployed or independently tested. Confirm actual controls in the application code, hosting configuration and operational procedures before relying on them. ## System Security Zones -MvuviGo Secure System Architecture Diagram -The platform is divided into three distinct security zones to prevent unauthorized access and contain potential breaches: +The documented architecture divides the platform into three security zones. Verify the deployed network boundaries and controls with the service owner: 1. **Perimeter Layer:** Handles public internet traffic. A Web Application Firewall and API Gateway protect the backend. Unauthenticated traffic is dropped here. -2. **Application Zone:** Contains the FastAPI backend, Node.js IoT server, and Auth Services. -3. **Data Zone:** A private subnet where the PostgreSQL database resides. It is completely inaccessible from the public internet and only accepts connections from the Application Zone. + +1. **Application Zone:** Contains the FastAPI backend, Node.js IoT server, and Auth Services. + +1. **Data Zone:** A private subnet where the PostgreSQL database resides. It is completely inaccessible from the public internet and only accepts connections from the Application Zone. ## Incident Handling & Monitoring + Because MvuviGo is a safety-critical system, detecting and responding to incidents is a core requirement. -* **Logging:** Both FastAPI and Node.js use structured JSON logging. Every request, authentication attempt, and MQTT payload is logged with a timestamp and IP address. -* **Detection:** The system monitors for unusual patterns, such as repeated `401 Unauthorized` responses (indicating a brute-force attack) or invalid MQTT payloads. -* **Response:** If the database goes offline, the API returns a `503 Service Unavailable` to protect data integrity. If an SOS alert fails to process, it is logged as a `CRITICAL` incident for immediate manual review. -* **Credential Rotation:** All database passwords, SMTP credentials, and JWT private keys are stored in environment variables (`.env` or Heroku Config Vars). They can be rotated without changing a single line of code. -* **Recovery:** Database backups are handled via the hosting provider (e.g., Heroku Postgres automated backups) to ensure data can be restored in the event of corruption. +- **Logging:** Collect only the information needed to operate and investigate the service. Protect logs and minimize fisher identifiers and precise location data; see [Logging and Monitoring](/security/logging-and-monitoring). + +- **Detection:** Define and test alerts for service failures, suspicious authentication activity and invalid device messages. The monitoring provider, alert recipients and thresholds must be confirmed for each deployment. + +- **Response:** During an active SOS, use the approved human coordination fallback if the dashboard, database or messaging path fails. Follow the [Failure Handling and Incident Response checklist](/security/failure-handling). + +- **Credential rotation:** Keep local secrets out of source control and production secrets in the deployment's approved secret store. Confirm the actual store, access owners and rotation procedure for each service. + +- **Recovery:** Confirm backup ownership, schedule, retention and restore procedure with the database provider. Test restoration before relying on a backup; provider-specific arrangements are not established in this documentation archive. ## Explore Security Topics -* **[Access Control](/security/access-control)** - Authentication, JWT tokens, and session expiration. -* **[Data Protection](/security/data-protection)** - Password hashing, encryption in transit, and database protection. -* **[Application Security](/security/application-security)** - Rate limiting, CORS, input validation, and integration security. -* **[Failure Handling](/security/failure-handling)** - How the system gracefully handles network drops and device disconnects. \ No newline at end of file +- [**Access Control**](/security/access-control) - Authentication, JWT tokens, and session expiration. + +- [**Data Protection**](/security/data-protection) - Password hashing, encryption in transit, and database protection. + +- [**Application Security**](/security/application-security) - Rate limiting, CORS, input validation, and integration security. + +- [**Failure Handling**](/security/failure-handling) - How the system gracefully handles network drops and device disconnects. \ No newline at end of file diff --git a/docs/security/logging-and-monitoring.md b/docs/security/logging-and-monitoring.md index 8ad984f..5137ff4 100644 --- a/docs/security/logging-and-monitoring.md +++ b/docs/security/logging-and-monitoring.md @@ -1,17 +1,43 @@ # Logging and Monitoring -To ensure the system is running smoothly and to investigate issues during rescue operations, MvuviGo implements structured logging. +Logs can support debugging and incident review, but MvuviGo handles identity and location data. The statements below reflect the existing technical documentation; verify actual log fields, access controls and retention against the running services before relying on them. -## Backend Logging (FastAPI) -* Every request is logged with its HTTP method, path, and response status code. -* When an OTP is generated, a log is printed (in development mode) so developers can test without an email server. -* Rate limit violations are logged automatically. +## Documented logging behavior -## IoT Server Logging (Node.js) -The Node.js server uses Fastify's built-in logger (Pino). It logs: -* `MQTT connected to HiveMQ`: When the server connects to the broker. -* `Trip started/completed`: When a fisher checks in or out via RFID. -* `SOS alert triggered`: When a panic button is pressed, including the Fisher ID and GPS coordinates. +| Component | Behavior described in the current docs | Verification needed | +| --- | --- | --- | +| FastAPI backend | Request method, path and response status are logged; OTPs may be printed in development mode; rate-limit violations are logged | Confirm that secrets, bearer tokens, request bodies and personal data are excluded or appropriately redacted in each environment. Confirm who can access logs and how long they are retained. | +| Node.js IoT gateway | The docs describe MQTT connection, trip start/completion and SOS events being logged. They state SOS records may include fisher ID and GPS coordinates. | Verify the actual fields, purpose, access control and retention. Avoid exact coordinates and directly identifying fields in general-purpose logs unless necessary, authorized and protected. Prefer an incident/correlation ID and keep operational record details in the approved system. | +| Dashboard | Client errors may appear in the browser console; host/server logging depends on deployment | Ensure production errors do not expose tokens, personal records or location details to unauthorized users. | -## Alert Monitoring -When an SOS is triggered, the Node.js server immediately logs the event and inserts it into the `distressed_fisher_alerts` table. The Web Dashboard polls the FastAPI backend, which highlights the active alert on the map in red, ensuring operators do not miss it. \ No newline at end of file +## Safe logging requirements + +- Never log passwords, private keys, full authentication tokens, one-time codes in production, or complete request bodies containing personal data. + +- Minimize fisher identifiers and precise location data in application and monitoring logs. Where event correlation is needed, prefer a non-sensitive incident identifier. + +- Restrict log access to personnel with an operational need. Keep access auditable and set retention through the organization's approved data-protection policy. + +- Redact logs before sharing them in a ticket, pull request, chat or public issue. Avoid screenshots containing phone numbers or map coordinates. + +- Treat logs as evidence during a security or SOS incident: preserve relevant records, record timestamps, and do not edit or delete them as a troubleshooting shortcut. + +## Operational monitoring + +The deployment documentation recommends watching service uptime, HTTP 5xx rates and response times, database capacity/connections/backup success, and build or deployment failures. The monitoring platform, alert recipients and retention periods are not identified in the supplied project archive; document the actual tools and responsible contacts in the deployment runbook before relying on automated alerting. + +For an active SOS, a missing dashboard update, stale location, failed SMS or service-health alert must be treated as a possible service failure—not proof that no emergency exists. Operators should use the approved human coordination fallback in [Failure Handling and Incident Response](./failure-handling.md). + +## Verification checklist + +Before a release or operational trial, confirm: + +- [ ] Production logging does not expose passwords, OTPs, bearer tokens or private keys. + +- [ ] Location and identity fields are minimized, access-controlled and retained only as approved. + +- [ ] Owners can locate relevant logs and know the retention and escalation process. + +- [ ] Health checks and monitoring distinguish current, stale and missing location data. + +- [ ] A human fallback remains available if monitoring, dashboard or messaging fails. \ No newline at end of file diff --git a/docs/setup/database-setup.md b/docs/setup/database-setup.md index 7723daf..aefafdb 100644 --- a/docs/setup/database-setup.md +++ b/docs/setup/database-setup.md @@ -1,10 +1,52 @@ - ---- # Database Setup -MvuviGo uses PostgreSQL. The FastAPI backend handles the database schema and migrations using Alembic, while the IoT server only reads and writes data. +The backend uses PostgreSQL and Alembic migrations. Use a **throwaway local development database** for these steps. Never run database creation, seed or migration commands against a production or shared database unless an authorized release procedure explicitly requires it. + +## 1. Start PostgreSQL and create a local database + +Ensure the PostgreSQL service is running. The example below assumes a local PostgreSQL role named `postgres` and a database named `mvuvigo`: + +```bash +psql -h localhost -U postgres -c "CREATE DATABASE mvuvigo;" +``` + +If your local role is different, substitute it. If `mvuvigo` already exists, do not create it again; verify that it is the intended local database before proceeding. + +## 2. Set the backend connection string + +In `pixels-backend/.env`, configure the `DATABASE_URL` using the local username and password. The documented SQLAlchemy URL format is: + +``` +DATABASE_URL=postgresql+psycopg://local_user:local_password@localhost:5432/mvuvigo +``` + +Replace `local_user` and `local_password` with the local PostgreSQL role and password. URL-encode reserved characters in a password if required by the connection-string parser. Use the backend repository's own configuration documentation as authoritative. Do not paste a real password into source files or commit the `.env` file. + +## 3. Verify the database is reachable + +```bash +psql -h localhost -U local_user -d mvuvigo -c "SELECT 1;" +``` + +A successful check returns a one-row result containing `1`. Replace `local_user` with your local PostgreSQL role. If the command fails, confirm PostgreSQL is running, the role/password are correct, and the database name in this command matches `DATABASE_URL`. + +## 4. Apply migrations + +From the backend repository root, after installing its dependencies and configuring its local environment, run: + +```bash +uv run alembic upgrade head +``` + +The migration command must target the same local database as the backend. Check the backend's README and Alembic configuration if the command differs in the checked-out version. To inspect the migration state, the documented commands are: + +```bash +uv run alembic current +uv run alembic history --verbose +``` + +## Existing schema or migration errors -## 1. Create the Database -Ensure PostgreSQL is running, then open your terminal and create an empty database: +If Alembic reports that a table already exists, the schema may have been created outside the migration history. For a disposable local database, the safest option is usually to recreate that local database and apply migrations from the beginning. `alembic stamp head` only records a migration version; it does **not** create or validate tables. Use it only when you have independently verified that the existing schema exactly matches the migration at that revision. -psql -h localhost -U postgres -c "CREATE DATABASE mvuvigo \ No newline at end of file +Do not drop a database or stamp migration state in a shared environment. See [Database Migrations](../database/migrations.md) for the project migration workflow. \ No newline at end of file diff --git a/docs/setup/environment-variables.md b/docs/setup/environment-variables.md index 1faaf8f..5f8602a 100644 --- a/docs/setup/environment-variables.md +++ b/docs/setup/environment-variables.md @@ -1,22 +1,51 @@ - ---- # Environment Variables -All secrets and environment-specific configurations are stored in `.env` files. These files are gitignored and must be created manually on your local machine. +Use environment variables for local configuration and secrets. This page records only names already present in the documentation; the application repositories were not included in this documentation archive, so this is **not a complete or independently verified configuration schema**. Before starting a service, compare every setting with that repository's `.env.example`, README and configuration code. -## 1. Backend (`pixels-backend/.env`) -Create a `.env` file in the `pixels-backend` root directory: +## Backend: `pixels-backend/.env` -DATABASE_URL=postgresql+psycopg://postgres:postgres@localhost:5432/mvuvigo -JWT_ALGORITHM=RS256 +Create this file in the backend repository root, if these names are supported by the checked-out backend version: -### Set to "console" to print OTPs to the terminal instead of sending emails +``` +DATABASE_URL=postgresql+psycopg://:@localhost:5432/mvuvigo +JWT_ALGORITHM=RS256 EMAIL_DELIVERY=console +``` -### Only required if EMAIL_DELIVERY=smtp -```env -SMTP_HOST=smtp.gmail.com +Replace the database placeholders with credentials for your local PostgreSQL instance. `EMAIL_DELIVERY=console` is documented as a local option for printing one-time codes to the terminal instead of sending email. SMTP settings are only needed if the backend is explicitly configured to use SMTP: + +``` +SMTP_HOST= SMTP_PORT=587 -SMTP_USER=your_email@gmail.com -SMTP_PASSWORD=your_app_password -SMTP_FROM=your_email@gmail.com \ No newline at end of file +SMTP_USER= +SMTP_PASSWORD= +SMTP_FROM= +``` + +The exact JWT key settings and any other required backend variables are not established by the documentation archive. Do not assume that setting `JWT_ALGORITHM` alone is sufficient for RS256 signing; follow the backend's current setup instructions and use development-only keys if required. + +## Frontend: `pixels-frontend/.env.local` + +The frontend documentation specifies this variable for the local API host: + +``` +NEXT_PUBLIC_API_URL=http://localhost:8000 +``` + +The frontend client is documented to append `/api/v1` and the endpoint path to this base URL. `NEXT_PUBLIC_` values are included in browser-delivered code: put only public configuration here, never passwords, signing keys, tokens or provider secrets. Restart the frontend development server after changing its environment file. + +**Compatibility check:** the API reference also documents some paths under `/api/`, some under `/api/v1/`, and some without a prefix. Confirm the checked-out frontend's requests and backend's mounted routes match before concluding the full integration is configured. + +## IoT gateway: `pixels-iot` + +This documentation archive does not establish the IoT gateway's exact variable names, MQTT broker URL, topics, database access settings or certificate paths. Do not copy values from another environment. Read the gateway repository's `.env.example`, README and configuration code. Use a test broker and test credentials only. + +## Secret-handling rules + +- Keep `.env` and `.env.local` out of version control. Check each repository's `.gitignore` before adding local configuration. + +- Do not commit real passwords, private keys, bearer tokens, broker credentials, phone numbers or fisher location data. + +- If a secret is exposed in a commit, log or chat, treat it as compromised and rotate it through the owning service. + +- Use separate credentials for development, staging and production; never point a local test at production data. \ No newline at end of file diff --git a/docs/setup/index.md b/docs/setup/index.md index 336c843..e4a9034 100644 --- a/docs/setup/index.md +++ b/docs/setup/index.md @@ -1,17 +1,62 @@ -# Setup & Installation +# Developer Setup and Local Onboarding -Welcome to the MvuviGo setup guide. The MvuviGo platform consists of three separate applications that work together: -1. **The Backend (`pixels-backend`)**: The FastAPI core API. -2. **The Frontend (`pixels-frontend`)**: The Next.js operator dashboard. -3. **The IoT Server (`pixels-iot`)**: The Node.js MQTT gateway. +This guide takes a contributor from prerequisites to a locally running MvuviGo development environment. MvuviGo's application is split across three repositories; this VitePress documentation site is a separate fourth repository and is not one of the runtime services. -To have the full system running locally, you will need to set up all three. +## Choose your goal -## Setup Guides -Follow these guides in order to get your local environment ready: +| Goal | Start here | Result | +|---|---|---| +| Read or edit this documentation site | Follow the [documentation-site quick start](#run-the-documentation-site) | Local VitePress site and a production-build check | +| Develop the MvuviGo platform | Continue with the guides below | Local backend and dashboard; the IoT gateway requires its own repository-specific configuration | -* **[Prerequisites](/setup/prerequisites)** - What you need installed on your computer before starting. -* **[Installation](/setup/installation)** - How to clone the repositories and install dependencies. -* **[Environment Variables](/setup/environment-variables)** - How to configure the `.env` files for each service. -* **[Database Setup](/setup/database-setup)** - How to initialize PostgreSQL and run migrations. -* **[Run Locally](/setup/run-locally)** - How to start all three servers and view the dashboard. \ No newline at end of file +## Recommended onboarding sequence + +1. Read [Prerequisites](./prerequisites.md) and confirm the required tools are installed. +2. Follow [Installation](./installation.md) to clone the application repositories. +3. Configure local-only values using [Environment Variables](./environment-variables.md). Check each application's own `.env.example`, README and settings before treating any variable list as complete. +4. Create a throwaway local PostgreSQL database and apply migrations using [Database Setup](./database-setup.md). +5. Follow [Run Locally](./run-locally.md) to start the backend and dashboard, then configure the IoT gateway only from its documented scripts and settings. +6. Run the [backend tests](../testing/backend-tests.md), the frontend production build, and the smoke checks in the local-run guide. + +## Run the documentation site + +From the root of the `pixels-technical-documentation` repository, install the locked dependencies and start VitePress: + +```bash +npm ci +npm run docs:dev +``` + +Open the URL printed in the terminal. To verify the production build and preview it locally: + +```bash +npm run docs:build +npm run docs:preview +``` + +## Components and prerequisites + +| Component | Repository | Main role | Local requirement | +|---|---|---|---| +| Backend API | `pixels-backend` | FastAPI service, database models and migrations | Python and `uv`; PostgreSQL | +| Operator dashboard | `pixels-frontend` | Next.js web application | Node.js and npm | +| IoT gateway | `pixels-iot` | Node.js service that handles MQTT/device traffic | Node.js and the gateway's configured broker, credentials and certificates | +| Documentation | `pixels-technical-documentation` | VitePress documentation site | Node.js and npm | + +## Before you begin + +- Use local development credentials and a local database only. Never use production credentials or send test SOS messages to real responders. +- Do not commit `.env`, `.env.local`, private keys, access tokens, broker credentials or real fisher information. +- The documentation archive does not contain the three application repositories. For service-specific variables, run commands or hardware behavior, verify the current README, package scripts, `.env.example` and source code in that service's repository. +- Running the backend and dashboard locally does not by itself simulate an on-water SOS or validate the radio, MQTT, SMS or rescue workflow. Those integrations require the relevant test configuration and, where applicable, hardware or an approved simulator. + +## Ready-to-run checklist + +- [ ] Required tools are installed and versions meet the application repositories' requirements. +- [ ] All required repositories are accessible and cloned. +- [ ] PostgreSQL is running and the local database connection works. +- [ ] Backend environment values are set from the backend's documented configuration. +- [ ] Database migrations complete successfully. +- [ ] Backend health check returns the documented success response. +- [ ] Dashboard loads and points at the local backend. +- [ ] Backend tests pass and the frontend production build completes. diff --git a/docs/setup/installation.md b/docs/setup/installation.md index 73ec883..3cdaccc 100644 --- a/docs/setup/installation.md +++ b/docs/setup/installation.md @@ -1,11 +1,63 @@ # Installation -MvuviGo is split across three repositories. You will need to clone all of them. +MvuviGo's runtime platform is maintained in three separate repositories. Clone the services you need; you do not need to clone every repository to edit one component. These commands use the repository URLs recorded in this documentation. GitHub access may require membership or permissions. -## 1. Clone the Repositories -Open your terminal and run: +## 1. Clone the application repositories + +From a workspace directory where you want the repositories created: ```bash git clone https://github.com/akirachix/pixels-backend.git git clone https://github.com/akirachix/pixels-frontend.git -git clone https://github.com/akirachix/pixels-iot.git \ No newline at end of file +git clone https://github.com/akirachix/pixels-iot.git +``` + +The commands create sibling directories named `pixels-backend`, `pixels-frontend` and `pixels-iot`. If you only need one component, clone only that repository. + +## 2. Inspect each service before installing dependencies + +```bash +cd pixels-backend +git status --short +``` + +Read the repository's `README.md`, `pyproject.toml` and any `.env.example` before installing or configuring it. Return to the workspace root before entering another repository. For the frontend and IoT gateway, use their `README.md`, `package.json`, lockfile and `.env.example` as the source of truth for scripts, Node.js versions and configuration. + +## 3. Install service dependencies + +### Backend + +The current project documentation identifies `uv` as the backend environment/dependency tool. From the backend repository root, use the command documented by its `pyproject.toml` and README; the expected project workflow is: + +```bash +uv sync +``` + +If the repository documents a different setup command, use that repository's instructions. + +### Frontend and IoT gateway + +In each Node.js repository that includes a `package-lock.json`, install its locked dependencies with: + +```bash +npm ci +``` + +Run this separately from the `pixels-frontend` and `pixels-iot` directories. If a repository uses a different package manager or has no npm lockfile, follow its own README rather than generating or replacing a lockfile by assumption. + +## 4. Continue setup + +- Configure only local values as described in [Environment Variables](./environment-variables.md). + +- Create the local database and run backend migrations using [Database Setup](./database-setup.md). + +- Start available services using [Run Locally](./run-locally.md). + +## Common installation problems + +| Symptom | Next step | +| --- | --- | +| `Repository not found` or permission denied | Confirm the URL, GitHub account and repository access. Do not embed a personal access token in the clone URL. | +| `uv: command not found` | Install `uv` using its official installation instructions, reopen the terminal and run `uv --version`. | +| `npm ci` reports a Node.js engine/version error | Check the repository's `engines` field and use its documented Node.js version. Keep the committed lockfile. | +| Dependencies install but a service will not start | Read that repository's startup scripts, `.env.example` and README; do not guess an entry point or environment variable. | \ No newline at end of file diff --git a/docs/setup/prerequisites.md b/docs/setup/prerequisites.md index 0e7cb7c..2694a57 100644 --- a/docs/setup/prerequisites.md +++ b/docs/setup/prerequisites.md @@ -1,25 +1,31 @@ # Prerequisites -Before you can run MvuviGo locally, you need the following tools installed on your machine. - -## Required Software - -1. **Python 3.11+** - * Required for the FastAPI backend. - * You also need `uv` installed for fast Python package management. (`curl -LsSf https://astral.sh/uv/install.sh | sh`) -2. **Node.js (v20 or v22)** - * Required for both the Next.js frontend and the Node.js IoT server. - * `npm` comes pre-installed with Node.js. -3. **PostgreSQL** - * Required for the main database. - * Ensure the PostgreSQL service is running on your machine (usually on port 5432). -4. **Git** - * Required to clone the repositories. - -## Optional Tools -* **Postman**: For testing the FastAPI endpoints manually. -* **MqttX**: A desktop client for publishing and subscribing to MQTT topics to simulate hardware devices. -* **OpenSSL**: Required to generate the RSA keys for JWT authentication (usually pre-installed on Linux/macOS). - -## Hardware Requirements -* At least 8GB of RAM is recommended, as running PostgreSQL, Next.js, FastAPI, and Node.js simultaneously can be resource-intensive. \ No newline at end of file +Install the tools needed by the component you intend to work on. The version requirements below reflect the current project documentation; confirm them against the relevant repository's README and dependency files before upgrading or changing a shared development environment. + +## Required for the platform + +| Tool | Used by | Documented requirement or check | +| --- | --- | --- | +| Git | All repositories | `git --version` | +| Python | `pixels-backend` | Python 3.11 or newer; check with `python3 --version` | +| `uv` | `pixels-backend` | Python package/environment manager; check with `uv --version` | +| Node.js and npm | `pixels-frontend`, `pixels-iot` and this docs site | The current docs specify Node.js 20 or 22; check with `node --version` and `npm --version`. Confirm the active repository's `engines` field if present. | +| PostgreSQL | Backend persistence | A local development service reachable by the backend; check with `psql --version` | + +The backend README or project metadata is authoritative for its Python and `uv` requirements. The frontend and IoT repository lockfiles and `package.json` scripts are authoritative for their Node.js commands. + +## Optional tools + +- **Postman** for manual API requests; see [Postman Examples](../testing/postman-examples.md). + +- **MQTTX** or another MQTT client to inspect or simulate messages only when the IoT repository documents the required broker, topics and payloads. Do not publish test data to a production broker. + +- **OpenSSL** if the backend's setup instructions require local RSA key generation. Do not generate or reuse production keys for local development. + +## Hardware and integration testing + +A laptop-only setup can validate the API and dashboard, but it cannot prove the full device-to-rescue path. Testing LoRa, RFID, GPS, MQTT, SMS delivery or an SOS response may require the appropriate device, test broker, gateway credentials, provider sandbox or a project-approved simulator. Use a test environment and test identities only. + +## Resource guidance + +Running PostgreSQL, the backend, dashboard and IoT gateway together uses more memory than running one service. The project documentation recommends at least 8 GB of RAM for the complete local stack; a smaller setup may still run selected services individually. \ No newline at end of file diff --git a/docs/setup/run-locally.md b/docs/setup/run-locally.md index af8b893..5aaa1ba 100644 --- a/docs/setup/run-locally.md +++ b/docs/setup/run-locally.md @@ -1,11 +1,108 @@ +# Run Locally ---- +## Before starting -# Run Locally +1. Check out the application source in a separate workspace. For example, if you do not already have these folders, run: + + ```bash + mkdir -p ~/Projects/MvuviGo + cd ~/Projects/MvuviGo + git clone https://github.com/akirachix/pixels-backend.git + git clone https://github.com/akirachix/pixels-frontend.git + ``` + + Clone `pixels-iot` only if you need the gateway. If GitHub reports that a repository is unavailable or access is denied, confirm the URL and ask the project maintainer for repository access. Do not run `git clone` again inside an existing checkout. + +1. Complete [Installation](./installation.md), [Environment Variables](./environment-variables.md) and [Database Setup](./database-setup.md). -To run the MvuviGo platform, you need to start all three servers simultaneously. It is recommended to use the three terminal windows you opened during installation. +1. Confirm the backend's required variables against its `.env.example` and README. The examples here are limited to what the documentation records. -## Terminal 1: FastAPI Backend +1. Ensure the local PostgreSQL database is reachable and migrations have completed. +## Terminal 1: Backend API + +From the workspace root: + +```bash cd pixels-backend -uv run --no-sync uvicorn main:app --reload \ No newline at end of file +uv sync +uv run alembic upgrade head +uv run uvicorn main:app --reload --host 127.0.0.1 --port 8000 +``` + +The documented backend entry point is `main:app`. If the checked-out backend README specifies a different entry point or startup command, follow it. Keep this development server bound to localhost; do not use `--reload` in production. + +## Terminal 2: Operator dashboard + +In a second terminal, from the workspace root: + +```bash +cd pixels-frontend +npm ci +``` + +Create or update `pixels-frontend/.env.local` with the local backend host documented for the client: + +``` +NEXT_PUBLIC_API_URL=http://localhost:8000 +``` + +Then start the frontend: + +```bash +npm run dev +``` + +Open the URL printed in the terminal (the frontend documentation identifies port `3000` as the development port). If the app cannot reach the API, check the configured base URL and the route-prefix compatibility note in [Environment Variables](./environment-variables.md). + +## Terminal 3: IoT gateway (when needed) + +The IoT gateway requires a Node.js runtime and may require an MQTT broker, credentials and certificates. The docs archive does not verify its `package.json` scripts or required variables. In the `pixels-iot` repository: + +1. Read its README and `.env.example`. + +1. Confirm the documented Node.js version and startup script. + +1. Use `npm ci` only if `package-lock.json` is present. + +1. Configure a test broker and test credentials, then run only the repository's documented development script. + +Do not infer a start command from the filename or connect the gateway to a production broker. Device-level tests may also require the approved hardware or simulator. + +## Smoke checks + +### 1. Check the backend health route + +```bash +curl -i http://127.0.0.1:8000/health +``` + +The API reference documents `GET /health` as an unauthenticated endpoint returning `200` with a JSON object. If the route is unavailable, check that the backend process started without errors and that the checked-out source matches the API documentation. + +### 2. Check the dashboard + +- Open the local URL printed by `npm run dev`. + +- Confirm the sign-in page renders without a terminal compilation error or browser-console error. + +- Confirm the browser is configured to call the intended local backend. Do not treat a rendered page alone as proof that protected API calls work. + +### 3. Check development quality gates + +From the backend repository root: + +```bash +uv run --no-sync pytest +``` + +From the frontend repository root: + +```bash +npm run build +``` + +Use each repository's README if its test or build command has changed. See [Testing and Troubleshooting](../testing/) for additional checks. + +## What this local setup does not prove + +A successful backend health check and dashboard build do not demonstrate the complete rescue path. They do not by themselves verify device GPS, RFID, LoRa transmission, MQTT delivery, SMS provider delivery, responder availability, location freshness or operational response. Validate those separately in an approved test setup and clearly distinguish simulated data from real events. \ No newline at end of file diff --git a/docs/testing/common-issues.md b/docs/testing/common-issues.md index 8f274ed..0b3b4cf 100644 --- a/docs/testing/common-issues.md +++ b/docs/testing/common-issues.md @@ -1,27 +1,86 @@ # Common Issues -While working on the MvuviGo project, you may run into environment, dependency, or pipeline issues. This page documents the most common errors our team has encountered, what causes them, and how to resolve them so you can get back to building. +Use the service's own README and error output as the source of truth. The commands below are intended for local development only. Before sharing logs, remove passwords, tokens, private keys, phone numbers and precise fisher locations. +## Backend and database -## 1. Backend & Python Issues +### `uv: command not found` -### "ModuleNotFoundError: No module named '...'" -**Cause:** You pulled the latest backend code, but your local virtual environment is missing a newly added Python package. -**Resolution:** -1. Ensure your virtual environment is activated (you should see `(env)` in your terminal prompt). -2. Install the updated dependencies: - ```bash - pip install -r requirements.txt +Install `uv` using its official installation instructions, open a new terminal, and verify with `uv --version`. Confirm you are in the `pixels-backend` repository before running backend commands. -# Frontend Common Issues +### Python dependency or import errors -While developing the MvuviGo Web Dashboard and Mobile applications, you may run into environment, build, or dependency issues. This page documents the most common frontend errors our team has encountered, what causes them, and how to resolve them. +From the backend root, check the Python version required by the repository and run its documented dependency sync command (currently documented as `uv sync`). Do not install packages globally to work around a project environment issue. -## Dependency & Environment Issues +### Database connection refused or authentication failed + +1. Confirm PostgreSQL is running and reachable on the host and port in `DATABASE_URL`. + +1. Check the local database name, role and password; do not paste the password into an issue or chat. + +1. Test the same local database with `psql` as shown in [Database Setup](../setup/database-setup.md). + +1. Ensure the backend loaded the intended `.env` and never points at production or shared data. + +### Alembic reports that a table already exists + +The local schema may predate Alembic. For a disposable local database, recreate it and run migrations from the beginning. Do not use `alembic stamp head` unless you have verified the existing schema exactly matches that migration. Never drop or stamp a shared database to clear an error. + +### Backend starts but the health request fails + +Check the startup output, port and entry point, then try the documented route: -### "npm install" Fails or `node_modules` are Corrupted -**Cause:** Your local `node_modules` folder or `package-lock.json` is out of sync with the `package.json`. This often happens when switching branches or pulling new code with different dependencies. -**Resolution:** Delete your existing modules and lockfile, then reinstall everything cleanly: ```bash -rm -rf node_modules package-lock.json -npm install \ No newline at end of file +curl -i http://127.0.0.1:8000/health +``` + +The API reference documents `/health` without a prefix. A connection-refused error usually means the server is not running on that address/port; an HTTP error means the route or application returned a response that needs investigation. + +## Frontend + +### `npm ci` fails + +Check `node --version`, `npm --version`, and the frontend repository's documented Node.js version. Run `npm ci` from the directory containing the committed `package-lock.json`. Keep the lockfile; do not remove it as a first troubleshooting step. + +### Dashboard loads but API calls fail + +- Confirm the backend is running and `NEXT_PUBLIC_API_URL` is set to the local backend host (the frontend guide documents `http://localhost:8000` ). + +- Confirm the value does not already include `/api/v1`; the documented client appends that prefix itself. + +- Restart the frontend after changing `.env.local`. + +- Check the browser network panel for the exact requested URL, status and CORS error. + +- Compare the URL with the API reference. This docs set records mixed API prefixes, so confirm the actual frontend and backend routes are compatible in the checked-out repositories. + +### Frontend build fails + +Run `npm run build` from the frontend repository root and resolve the first reported compile or type error. Check for missing environment configuration and use the script defined in that repository's `package.json`. + +## IoT and field integrations + +### MQTT connection or certificate errors + +Use the IoT repository's documented broker URL, credentials, certificate path and topic names. Confirm system time and test-environment access. Never disable TLS or use a production broker to make a local test pass. + +### No SMS, SOS or location update appears + +A web dashboard or health check does not validate the radio-to-cloud path. Confirm whether the test uses hardware or a documented simulator, check each service's logs with sensitive fields redacted, and distinguish stale or simulated positions from current positions. Do not contact real responders unless an authorized operational test is in progress. + +## Documentation site + +### VitePress page or link is missing + +From this documentation repository root, run: + +```bash +npm ci +npm run docs:build +``` + +Check the spelling and case of the Markdown filename and the route in `docs/.vitepress/config.mts`. Preview using `npm run docs:preview` and the URL printed in the terminal. Do not assume an unbuilt page is available in the published site. + +## Reporting a reproducible issue + +Include the repository and branch, operating system, tool versions, the command or request, expected behavior, actual behavior, and a redacted error excerpt. Do not include secrets or personal fisher information. For an SOS-related problem, preserve incident evidence through the project's approved operational process rather than deleting or replaying live records. \ No newline at end of file diff --git a/docs/testing/postman-examples.md b/docs/testing/postman-examples.md index 6012ebb..f161444 100644 --- a/docs/testing/postman-examples.md +++ b/docs/testing/postman-examples.md @@ -1,147 +1,60 @@ - # Postman Examples -Postman is used to test MvuviGo API endpoints, verify responses, and identify errors. - -## 1. Set Up Postman - -1. Start the FastAPI backend. -2. Open Postman and create a collection named `MvuviGo API Tests`. -3. Use `http://localhost:8000` as the base URL. - -## 2. Test GET Requests - -Use GET to retrieve data from an endpoint. - -**Example: Retrieve Fishers** - -```http -GET http://localhost:8000/api/fishers -``` +Use Postman to inspect the documented API in a local or approved test environment. The route examples below are taken from the MvuviGo API reference. Do not use real fisher data or send SOS test requests to a live service. -Click **Send** and verify the status code and returned data. +## 1. Set up a collection and variables -## 3. Test POST Requests - -Use POST to create a new record. - -**Example: Create a Fisher** - -```http -POST http://localhost:8000/api/fishers -Content-Type: application/json -``` - -Under **Body → raw → JSON**, enter: - -```json -{ - "name": "Test Fisher", - "phone_number": "0700000000" -} -``` +1. Create a collection named `MvuviGo Local API`. -Click **Send** and verify that the record is created successfully. +1. Add collection variables: + - `baseUrl`: `http://localhost:8000` + - `accessToken`: leave empty until you have obtained a token through the documented authentication flow. -## 4. Test PUT Requests +1. Use the endpoint paths exactly as written in [API Endpoints](../api/endpoints.md). Some resources use different prefixes and trailing-slash conventions. -Use PUT to replace or update a resource, depending on the API implementation. +## 2. Verify API availability -**Example: Update a Fisher** +Create a request: -```http -PUT http://localhost:8000/api/fishers/1 -Content-Type: application/json ``` - -Example body: - -```json -{ - "name": "Updated Fisher", - "phone_number": "0712345678" -} +GET {{baseUrl}}/health ``` -Click **Send** and verify that the response reflects the updated information. +The API reference documents this route as unauthenticated. Expected result: `200` and a JSON object. This check confirms only that the API health route responds; it does not validate the database, MQTT, SMS or rescue workflow unless the implementation explicitly includes those checks. -## 5. Test PATCH Requests +## 3. Check an authenticated read endpoint -Use PATCH to update specific fields of an existing record. +After completing the flow in [API Authentication](../api/authentication.md), set `accessToken` to the issued access token and create: -**Example: Update a Fisher's Phone Number** - -```http -PATCH http://localhost:8000/api/fishers/1 -Content-Type: application/json ``` - -Example body: - -```json -{ - "phone_number": "0712345678" -} +GET {{baseUrl}}/api/fishers/?skip=0&limit=100 +Authorization: Bearer {{accessToken}} +Accept: application/json ``` -Verify that the phone number changes and other fields remain unchanged. - -## 6. Test DELETE Requests +The API reference documents this path as requiring Bearer authentication. Expected result for a valid token is `200` with a JSON array. An unauthenticated or invalid-token request should be rejected according to the authentication behavior documented by the backend. -Use DELETE to remove an existing record. +For sensitive or empty test databases, prefer a read-only request. Do not create or delete production records for a manual test. -**Example: Delete a Fisher** - -```http -DELETE http://localhost:8000/api/fishers/1 -``` +## 4. Test validation safely -Click **Send** and check the response status code. Send a GET request for the same ID to verify that the record has been removed. +To test a protected endpoint's authentication behavior, repeat the read request without the `Authorization` header and record the actual status and response body. To test request validation, use a disposable local environment and choose an endpoint whose request schema is documented in [Schemas](../api/schemas.md). Avoid sending malformed requests to a live service. -## 7. Test Authentication +## 5. Check responses -1. Send a request to the login endpoint. -2. Copy the access token from the response. -3. Open **Authorization** and select **Bearer Token**. -4. Paste the token and send a request to a protected endpoint. -5. Repeat without a token to check whether unauthorized access is rejected. +Record the method, full path, environment, status code, response time, and a redacted response excerpt. The endpoint reference documents common success patterns, including `200` for reads/actions, `201` for creates and `204` for deletes; always use the specific endpoint's documented response rather than assuming every request returns the same status. -## 8. Test Invalid Inputs - -Test requests with: -- Missing required fields -- Incorrect data types -- Invalid record IDs -- Missing or invalid authentication tokens - -Verify that the API returns appropriate error responses. - -| Status Code | Meaning | -|---|---| -| 200 | Request successful | -| 201 | Resource created | -| 204 | Request successful, no response body | -| 401 | Unauthorized | -| 404 | Resource not found | -| 422 | Validation error | -| 500 | Internal server error | - -## 9. Validate Responses - -Under **Scripts → Post-response**, add assertions: +Example Postman post-response checks for the health request: ```javascript -pm.test("Status code is 200", () => { - pm.response.to.have.status(200); +pm.test("Health route returns 200", () => { + pm.response.to.have.status(200); }); - pm.test("Response is JSON", () => { - pm.response.to.be.json; + pm.response.to.be.json; }); ``` -Adjust the expected status code to match the endpoint. For example, a successful DELETE request may return `200` or `204`. - -## 10. Record Test Results +## 6. Record a reproducible failure -For failed requests, record the endpoint, test data, expected result, actual result, and steps to reproduce the issue. Retest after fixes to confirm that the endpoint works correctly. +For a failed request, record the API version or commit, method and route, test environment, redacted request shape, expected result, actual result, and steps to reproduce. Do not include bearer tokens, passwords, phone numbers or precise fisher locations. See [Common Issues](./common-issues.md) for local diagnostics. \ No newline at end of file