# Oya Drone Platform — Architecture Documentation

Comprehensive technical architecture covering system design, module
dependencies, data flow, communication protocols, state machines, database
schema, deployment patterns, scaling strategies, security, and disaster recovery
for the `@oya/core` library.

---

## Table of Contents

1. [System Architecture Overview](#1-system-architecture-overview)
2. [Module Dependency Graph](#2-module-dependency-graph)
3. [Data Flow](#3-data-flow)
4. [Communication Protocols](#4-communication-protocols)
5. [State Machines](#5-state-machines)
6. [Database Schema](#6-database-schema)
7. [Deployment Architecture](#7-deployment-architecture)
8. [Scaling](#8-scaling)
9. [Security](#9-security)
10. [Disaster Recovery](#10-disaster-recovery)

---

## 1. System Architecture Overview

The Oya drone platform is organized as a layered architecture with clear
separation of concerns. The foundation layer provides types, math utilities, and
validation. The control layer implements attitude, velocity, and position
control. The autonomy layer handles mission execution, navigation, path
planning, and obstacle avoidance. The coordination layer manages multi-drone
swarms. The perception layer covers sensors, SLAM, and pose estimation. The
cinematography layer provides shot planning, tracking, trajectories, gimbal, and
streaming. The infrastructure layer handles autopilot integration, simulation,
safety, AI/ML inference, database schema, and flight logging.

```
+===========================================================================+
|                         APPLICATION LAYER                                  |
|  Flight Management  |  Ground Control  |  Mission Planning  |  Analytics  |
+===========================================================================+
           |                  |                  |                  |
+===========================================================================+
|                       AUTOPILOT INTEGRATION                                |
|     PX4 Autopilot    |    ArduPilot    |    DJI SDK    |  MAVLink Proto   |
+===========================================================================+
           |                  |                  |                  |
+===========================================================================+
|                       CINEMATOGRAPHY LAYER                                 |
| Shot Planning | Subject Tracking | Trajectories | Gimbal | Multi-Camera  |
| Video Streaming | Camera Systems                                          |
+===========================================================================+
           |                  |                  |                  |
+===========================================================================+
|                       COORDINATION LAYER                                   |
| Swarm Coordination | Collision Avoidance | Formation Flying | Task Alloc  |
| Consensus Algorithms | Inter-Drone Communication                          |
+===========================================================================+
           |                  |                  |                  |
+===========================================================================+
|                        AUTONOMY LAYER                                      |
| Mission Execution | GPS Navigation | Path Planning | Obstacle Avoidance  |
| Indoor Positioning | Visual SLAM                                          |
+===========================================================================+
           |                  |                  |                  |
+===========================================================================+
|                        PERCEPTION LAYER                                    |
| Camera Systems | Depth Sensors | LiDAR | Audio | IMU | Multi-Sensor      |
| Pose Detection | Form Analysis | Body Reconstruction | Temporal Tracking |
+===========================================================================+
           |                  |                  |                  |
+===========================================================================+
|                       AI/ML INFRASTRUCTURE                                 |
| Model Inference | Model Optimization | Pretrained Models | Edge Deploy   |
+===========================================================================+
           |                  |                  |                  |
+===========================================================================+
|                       SAFETY & COMPLIANCE                                  |
| Geofencing | Emergency Procedures | Flight Logging | Regulatory          |
+===========================================================================+
           |                  |                  |                  |
+===========================================================================+
|                        SIMULATION LAYER                                    |
| Gazebo Integration | AirSim Integration | Physics Engine                  |
+===========================================================================+
           |                  |                  |                  |
+===========================================================================+
|                        CONTROL LAYER                                       |
| Attitude Control | Velocity Control | Position Control                    |
+===========================================================================+
           |                  |                  |                  |
+===========================================================================+
|                       FOUNDATION LAYER                                     |
| Types & Schemas | Constants | Math Utilities | Kinematics | Transforms   |
| Validation | Errors | Coordinate Transforms                               |
| Database Schema                                                            |
+===========================================================================+
```

### Design Principles

1. **Type Safety**: All data structures are defined with Zod schemas providing
   runtime validation and TypeScript types providing compile-time safety.
   Branded types (`DroneId`, `SwarmId`, `MissionId`, `WaypointId`) prevent
   accidental ID mixing.

2. **SI Units**: All physical quantities use SI units (meters, seconds, radians,
   m/s, kg) unless explicitly documented otherwise. This eliminates unit
   conversion errors at module boundaries.

3. **Stateless Computation Where Possible**: Mathematical utilities, coordinate
   transforms, and validation functions are pure functions. Stateful classes
   (controllers, trackers, state machines) clearly document their state
   management.

4. **Schema-First Design**: Database schemas, telemetry formats, and mission
   definitions are defined declaratively using Zod schemas and exported as both
   types and runtime validators.

5. **Layered Dependencies**: Lower layers never depend on higher layers. The
   foundation layer has zero internal dependencies (only `zod`).

---

## 2. Module Dependency Graph

Each source module and its direct dependencies within `@oya/core`:

```
types.ts  (external: zod)
    ^
    |
constants.ts  (no internal deps)
    ^
    |
math-utils.ts  (no internal deps)
    ^
    |
kinematics.ts  (no internal deps)
    ^
    |
coordinate-transforms.ts --> types.ts, math-utils.ts, constants.ts
    ^
    |
validation.ts --> types.ts, constants.ts
    ^
    |
errors.ts  (no internal deps)
    ^
    |
+---+---+---+---+---+---+---+---+---+---+---+---+
|   |   |   |   |   |   |   |   |   |   |   |   |
v   v   v   v   v   v   v   v   v   v   v   v   v

attitude-control.ts ---------> kinematics.ts, math-utils.ts
velocity-position-control.ts -> kinematics.ts, math-utils.ts
mission-execution.ts ---------> types.ts, math-utils.ts, constants.ts, kinematics.ts
gps-navigation.ts ------------> kinematics.ts, math-utils.ts, constants.ts
indoor-positioning.ts --------> kinematics.ts, math-utils.ts
visual-slam.ts ---------------> kinematics.ts, math-utils.ts
path-planning.ts -------------> kinematics.ts, math-utils.ts
obstacle-avoidance.ts --------> kinematics.ts, math-utils.ts
swarm-coordination.ts --------> kinematics.ts, math-utils.ts
swarm-collision-avoidance.ts -> kinematics.ts, math-utils.ts
formation-flying.ts ----------> kinematics.ts, math-utils.ts
task-allocation.ts -----------> math-utils.ts
consensus-algorithms.ts ------> math-utils.ts
inter-drone-communication.ts -> math-utils.ts
shot-planning.ts -------------> kinematics.ts, math-utils.ts
subject-tracking.ts ----------> kinematics.ts, math-utils.ts
cinematography-trajectory.ts -> kinematics.ts, math-utils.ts
multi-camera-coordination.ts -> kinematics.ts, math-utils.ts
gimbal-control.ts ------------> kinematics.ts, math-utils.ts
video-streaming.ts -----------> math-utils.ts
camera-systems.ts ------------> math-utils.ts
depth-sensors.ts -------------> kinematics.ts, math-utils.ts
lidar-integration.ts ---------> kinematics.ts, math-utils.ts
audio-systems.ts -------------> math-utils.ts
imu-orientation.ts -----------> kinematics.ts, math-utils.ts
multi-sensor-fusion.ts -------> kinematics.ts, math-utils.ts
pose-detection-2d.ts ---------> math-utils.ts
temporal-tracking.ts ---------> math-utils.ts
form-analysis.ts -------------> math-utils.ts
multi-view-fusion.ts ---------> kinematics.ts, math-utils.ts
body-reconstruction-3d.ts ----> kinematics.ts, math-utils.ts
model-inference.ts -----------> math-utils.ts
model-optimization.ts --------> math-utils.ts
pretrained-models.ts ---------> math-utils.ts
edge-deployment.ts -----------> math-utils.ts
px4-autopilot.ts -------------> kinematics.ts, math-utils.ts
ardupilot.ts -----------------> math-utils.ts
dji-sdk.ts -------------------> kinematics.ts, math-utils.ts
mavlink-protocol.ts ----------> math-utils.ts
generic-hardware.ts ----------> math-utils.ts
gazebo-integration.ts --------> kinematics.ts, math-utils.ts
airsim-integration.ts --------> kinematics.ts, math-utils.ts
geofencing.ts ----------------> kinematics.ts, math-utils.ts
emergency-procedures.ts ------> kinematics.ts, math-utils.ts
flight-logging.ts ------------> math-utils.ts
database-schema.ts -----------> (no internal deps)
```

### Key Observations

- `math-utils.ts` is the most widely imported module (used by every
  non-foundation module).
- `kinematics.ts` is the second most imported, required by anything dealing with
  3D positions, rotations, or physical dynamics.
- `types.ts` defines the Zod schemas and is imported only by modules that need
  runtime validation of domain types (mission execution, coordinate transforms,
  validation).
- No circular dependencies exist in the dependency graph.

---

## 3. Data Flow

### 3.1 Telemetry Pipeline

Telemetry flows from the drone hardware through the autopilot integration layer,
gets validated against the `TelemetrySchema`, and is distributed to consuming
subsystems.

```
+----------------+     +------------------+     +-------------------+
|  Flight        |     |  Autopilot       |     |  Telemetry        |
|  Controller    | --> |  Integration     | --> |  Schema           |
|  (PX4/AP/DJI)  |     |  (MAVLink decode)|     |  Validation (Zod) |
+----------------+     +------------------+     +-------------------+
                                                         |
                              +-----------+-----------+--+--+-----------+
                              |           |           |     |           |
                              v           v           v     v           v
                        +---------+ +---------+ +-------+ +-----+ +--------+
                        | Mission | | Swarm   | | Safety| | GCS | | Flight |
                        | Exec   | | Coord   | | Sys   | | UI  | | Logger |
                        +---------+ +---------+ +-------+ +-----+ +--------+
```

Telemetry data structure (`Telemetry` type):

| Field              | Type               | Description                        |
| ------------------ | ------------------ | ---------------------------------- |
| `droneId`          | `DroneId`          | Branded UUID v4 identifier         |
| `timestamp`        | ISO 8601 string    | Time of reading                    |
| `position`         | `Position3D`       | Lat/lon/alt (WGS84)                |
| `velocity`         | `Velocity3D`       | vx/vy/vz (m/s)                     |
| `acceleration`     | `Acceleration3D`   | ax/ay/az (m/s^2)                   |
| `orientation`      | `Orientation`      | roll/pitch/yaw (radians)           |
| `batteryState`     | `BatteryState`     | Voltage, current, SoC, temperature |
| `gpsCoordinates`   | `GPSCoordinates`   | WGS84 lat/lon/alt                  |
| `signalStrength`   | number             | dBm (-120 to 0)                    |
| `satellites`       | number             | GPS satellites in view             |
| `flightMode`       | `FlightMode`       | Current flight mode enum           |
| `droneState`       | `DroneState`       | Current operational state enum     |
| `connectionStatus` | `ConnectionStatus` | Communication link status enum     |

### 3.2 Command Pipeline

Commands flow from the ground control station or autonomous mission controller
through validation, safety checks, and the autopilot integration layer to the
flight controller.

```
+-------+     +-----------+     +-----------+     +----------------+
| GCS / | --> | Command   | --> | Safety    | --> | Autopilot      |
| Auto  |     | Validator |     | Layer     |     | Integration    |
| Pilot |     |           |     | Geofence  |     | PX4/AP/DJI     |
+-------+     +-----------+     | Failsafe  |     | MAVLink encode |
                                | Emergency |     +----------------+
                                +-----------+            |
                                                         v
                                                 +----------------+
                                                 | Flight         |
                                                 | Controller     |
                                                 +----------------+
```

Command validation chain:

1. **Schema Validation** — Zod schema ensures correct data types and ranges
2. **Geofence Check** — Target position verified within permitted airspace
3. **Altitude Check** — Altitude within regulatory and geofence limits
4. **Battery Check** — Sufficient battery for the commanded action
5. **Weather Check** — Wind and visibility within safe limits
6. **Failsafe Check** — No active failsafe conditions blocking the command
7. **Encoding** — Command serialized to MAVLink v2 frame
8. **Transmission** — Sent via UDP/TCP/Serial transport

### 3.3 Video Pipeline

Video flows from the camera through encoding, optional AI processing, and
streaming to ground stations and cloud.

```
+--------+     +----------+     +----------+     +----------+
| Camera | --> | Encoder  | --> | Stream   | --> | Display  |
| Sensor |     | H.264/5  |     | RTMP/    |     | GCS UI   |
|        |     | AV1      |     | RTSP/    |     |          |
+--------+     +----------+     | WebRTC/  |     +----------+
                    |           | SRT/HLS  |
                    v           +----------+
              +----------+
              | AI/ML    |
              | Inference|
              | (detect, |
              |  track,  |
              |  pose)   |
              +----------+
```

Encoding profiles supported:

| Codec | Class                  | Use Case                        |
| ----- | ---------------------- | ------------------------------- |
| H.264 | `H264EncodingPipeline` | Widest compatibility            |
| H.265 | `H265EncodingPipeline` | 50% better compression          |
| AV1   | `AV1EncodingPipeline`  | Best compression, newer support |

Streaming protocols:

| Protocol | Class              | Latency   | Use Case               |
| -------- | ------------------ | --------- | ---------------------- |
| RTMP     | `RTMPStreamOutput` | ~2-5s     | Live broadcast         |
| RTSP     | `RTSPServer`       | ~0.5-2s   | LAN monitoring         |
| WebRTC   | `WebRTCStreamer`   | ~0.1-0.5s | Ultra-low latency      |
| SRT      | `SRTTransport`     | ~0.5-2s   | Reliable over Internet |
| HLS      | `HLSGenerator`     | ~6-30s    | Web browser playback   |
| DASH     | `DASHGenerator`    | ~3-10s    | Adaptive bitrate       |

---

## 4. Communication Protocols

### 4.1 MAVLink v2

MAVLink v2 is the primary communication protocol between the Oya platform and
PX4/ArduPilot autopilots. The platform provides both high-level
autopilot-specific handlers and low-level protocol implementation.

```
MAVLink v2 Frame Structure:
+------+------+------+------+------+------+------+---------+------+-------+
| STX  | LEN  | INC  | CMP  | SEQ  | SYS  | COMP | MSG ID  | DATA | CRC16 |
| 0xFD | 1B   | 1B   | 1B   | 1B   | 1B   | 1B   | 3B      | 0-255| 2B    |
+------+------+------+------+------+------+------+---------+------+-------+
```

Implementation classes:

| Class                     | Role                                 |
| ------------------------- | ------------------------------------ |
| `PX4MAVLinkTransport`     | PX4-specific MAVLink v2 transport    |
| `APMAVLinkDialectHandler` | ArduPilot dialect message management |
| `MAVLinkV2Protocol`       | Low-level protocol encoding/decoding |
| `MAVLinkSerializer`       | Field-level message serialization    |
| `MAVLinkRouter`           | Message routing between system IDs   |
| `MAVLinkCustomMessage`    | Custom message definition support    |

Key constants:

| Constant             | Value    | Description                 |
| -------------------- | -------- | --------------------------- |
| `MAVLINK_V2_MAGIC`   | `0xFD`   | Start-of-frame marker       |
| `PX4_DEFAULT_SYSID`  | `1`      | PX4 default system ID       |
| `PX4_DEFAULT_COMPID` | `1`      | PX4 default component ID    |
| `GCS_SYSTEM_ID`      | exported | Ground control system ID    |
| `GCS_COMPONENT_ID`   | exported | Ground control component ID |

### 4.2 Inter-Drone Communication

For swarm operations, the platform provides multiple network transport options
for drone-to-drone communication.

```
+----------+     +-----------+     +----------+
| Drone A  | <-> | Mesh      | <-> | Drone B  |
|          |     | Network   |     |          |
+----------+     +-----------+     +----------+
                      |
                      v
               +-------------+
               | Ground      |
               | Station     |
               | Relay       |
               +-------------+
```

Transport layer options:

| Class                   | Protocol | Use Case                     |
| ----------------------- | -------- | ---------------------------- |
| `UDPBroadcast`          | UDP      | Local subnet broadcast       |
| `UDPMulticast`          | UDP      | Efficient multi-receiver     |
| `TCPReliable`           | TCP      | Guaranteed delivery          |
| `MeshNetworkTopology`   | Custom   | Ad-hoc mesh network          |
| `AODVRouter`            | AODV     | Reactive routing protocol    |
| `OLSRRouter`            | OLSR     | Proactive routing protocol   |
| `CellularNetworkBridge` | 4G/5G    | Long-range cellular fallback |
| `GroundStationRelay`    | Custom   | Ground-based relay           |

Network management:

| Class                     | Function                                     |
| ------------------------- | -------------------------------------------- |
| `AdHocNetworkFormation`   | Automatic network creation/join              |
| `MultiHopRouter`          | Route messages through intermediate drones   |
| `NetworkPartitionHandler` | Detect and handle network splits             |
| `NetworkHealingProcedure` | Automatically repair broken links            |
| `BandwidthManager`        | Allocate bandwidth across links              |
| `QoSPrioritizer`          | Priority-based message queuing               |
| `MessageCompressor`       | Compress messages for low-bandwidth links    |
| `MessageAuthenticator`    | HMAC-based message authentication            |
| `MessageEncryptor`        | AES encryption for secure channels           |
| `ChannelHopper`           | Frequency hopping for interference avoidance |

### 4.3 Streaming Protocols

| Protocol | Port     | Transport | Bidirectional | Encryption  |
| -------- | -------- | --------- | ------------- | ----------- |
| RTMP     | 1935     | TCP       | No            | RTMPS       |
| RTSP     | 554/8554 | TCP+UDP   | Yes (SETUP)   | RTSPS       |
| WebRTC   | Dynamic  | UDP (ICE) | Yes           | DTLS+SRTP   |
| SRT      | Dynamic  | UDP       | No            | AES-128/256 |
| HLS      | 80/443   | TCP       | No            | TLS         |
| DASH     | 80/443   | TCP       | No            | TLS         |

---

## 5. State Machines

### 5.1 DroneState

The `DroneState` enum defines the operational states a drone can be in.
Transitions are enforced by the flight controller and autopilot integration.

```
                    +--------+
                    |  Idle  |
                    +---+----+
                        |
                  [power on]
                        |
                        v
                  +-----------+
                  | Preflight |
                  +-----+-----+
                        |
                  [checks pass]
                        |
                        v
                    +-------+
                    | Armed |
                    +---+---+
                        |
                  [takeoff cmd]
                        |
                        v
                  +-----------+
                  | TakingOff |
                  +-----+-----+
                        |
                  [alt reached]
                        |
                        v
                    +--------+       +---------+
                    | Flying | <---> | Hovering|
                    +---+----+       +----+----+
                        |                 |
                  [land cmd]        [land cmd]
                        |                 |
                        v                 v
                   +---------+
                   | Landing |
                   +----+----+
                        |
                  [ground contact]
                        |
                        v
                   +--------+
                   | Landed |
                   +---+----+
                       |
                 [disarm cmd]
                       |
                       v
                  +----------+
                  | Disarmed |
                  +----------+

     Any state --[emergency]--> +----------+
                                | Emergency|
                                +----------+
```

### 5.2 FlightMode

```
+--------+     +------------+     +----------+
| Manual | --> | Stabilized | --> | Altitude |
+--------+     +------------+     +----+-----+
                                       |
                                       v
+------+     +--------+         +----------+
| Acro |     | Loiter | <----  | Position |
+------+     +--------+         +----+-----+
                                     |
                            +--------+--------+
                            |        |        |
                            v        v        v
                      +---------+ +------+ +--------+
                      | Mission | | Land | | Guided |
                      +---------+ +------+ +--------+
                            |
                            v
                     +--------------+
                     | ReturnToHome |
                     +--------------+
```

### 5.3 PX4SITLState

```
+--------------+     +------------+     +-----------+     +------------+
| Disconnected | --> | Connecting | --> | Connected | --> | SimRunning |
+--------------+     +------------+     +-----------+     +------------+
       ^                                     |                  |
       |                                     v                  v
       +--------- [disconnect] <-----+  +-------+         +-------+
                                     +--| Error |<--------+  Error |
                                        +-------+         +-------+
```

### 5.4 APConnectionState

```
+--------------+     +------------+     +-----------+     +--------------+
| Disconnected | --> | Connecting | --> | Connected | --> | Heartbeating |
+--------------+     +------------+     +-----------+     +------+-------+
       ^                                                         |
       |                                                  [hb timeout]
       |                                                         |
       +-------------- [max retries] <------+              +-----v----+
                                            +--------------+   Lost   |
                                                           +----------+
```

### 5.5 Mission Execution States

```
+---------+     +-----------+     +---------+     +----------+
| Pending | --> | Uploading | --> | Running | --> | Complete |
+---------+     +-----------+     +----+----+     +----------+
                                       |
                              +--------+--------+
                              |        |        |
                              v        v        v
                         +--------+ +------+ +--------+
                         | Paused | | Abort| | Failed |
                         +---+----+ +------+ +--------+
                             |
                        [resume]
                             |
                             v
                         +--------+
                         | Running|
                         +--------+
```

### 5.6 Emergency State Machine

```
+---------+     +---------+     +---------+     +-----------+
| nominal | --> | caution | --> | warning | --> | emergency |
+---------+     +---------+     +---------+     +-----+-----+
                                                      |
                              +--------+---------+----+----+
                              |        |         |         |
                              v        v         v         v
                         +---------+ +---+ +----------+ +----------+
                         |auto-land| |rth| |hover-hold| |ctrl-desc |
                         +----+----+ +---+ +----+-----+ +----+-----+
                              |        |        |             |
                              v        v        v             v
                       +-------------+ +-------------------+
                       |   resolved  | |parachute-deployed |
                       +-------------+ +-------------------+
                                              |
                                              v
                                        +----------+
                                        |motor-kill|
                                        +----------+
```

### 5.7 Swarm States

```
+------+     +---------+     +-------+     +--------+
| idle | --> | forming | --> | ready | --> | active |
+------+     +---------+     +-------+     +---+----+
                                               |
                                        +------+------+
                                        |             |
                                        v             v
                                  +-----------+  +-----------+
                                  | returning |  | emergency |
                                  +-----+-----+  +-----------+
                                        |
                                        v
                                   +--------+
                                   | landed |
                                   +--------+
```

### 5.8 Navigation States (Waypoint Navigation)

```
+------+     +----------+     +----------+     +--------+     +----------+
| Idle | --> | Navigating| --> | Approach | --> | AtWP   | --> | Complete |
+------+     +-----+----+     +----------+     +---+----+     +----------+
                   |                                |
                   v                           [next WP]
              +----------+                         |
              | Recovery |                         v
              +----------+                    +----------+
                                              |Navigating|
                                              +----------+
```

---

## 6. Database Schema

The database schema is defined declaratively in `database-schema.ts` using the
`TableSchema` interface. All schemas use PostgreSQL-compatible types with
support for PostGIS spatial types and BRIN indexes for time-series data.

### 6.1 Entity Relationship Diagram

```
+------------------+       +------------------+       +------------------+
|   pilots         |       |  drone_profiles  |       |    missions      |
+------------------+       +------------------+       +------------------+
| id (PK)          |       | id (PK)          |       | id (PK)          |
| name             |<---+  | name             |<---+  | name             |
| email (UQ)       |    |  | serial_number(UQ)|    |  | description      |
| license_number   |    |  | manufacturer     |    |  | created_by (FK)->|--+
| license_type     |    |  | model            |    |  | status           |  |
| total_flight_hrs |    |  | max_speed_ms     |    |  | constraints (J)  |  |
| total_flights    |    |  | capabilities (J) |    |  | metadata (J)     |  |
| certifications(J)|    |  | firmware_version |    |  | created_at       |  |
| active           |    |  | active           |    |  +------------------+  |
+------------------+    |  +------------------+    |         |              |
        |               |         |                |    +----+              |
        |               |         |                |    |                   |
        v               |         v                |    v                   |
+------------------+    |  +------------------+    |  +------------------+  |
| flight_records   |    |  | telemetry_points |    |  |   waypoints      |  |
+------------------+    |  +------------------+    |  +------------------+  |
| id (PK)          |    |  | id (PK)          |    |  | id (PK)          |  |
| drone_id (FK)--->|----+  | drone_id (FK)--->|----+  | mission_id (FK)->|--+
| pilot_id (FK)--->|-+    | flight_id (FK)-->|--+    | sequence         |
| mission_id (FK)->|--+   | channel          |  |    | latitude         |
| start_time       |  |   | timestamp        |  |    | longitude        |
| end_time         |  |   | value_numeric    |  |    | altitude_msl     |
| duration_sec     |  |   | value_text       |  |    | speed_ms         |
| distance_m       |  |   | value_json (J)   |  |    | action           |
| max_altitude_m   |  |   | quality          |  |    | action_params (J)|
| status           |  |   | unit             |  |    +------------------+
| events (J)       |  |   +------------------+  |
+------------------+  |                          |
        |             |   +------------------+   |
        |             |   | maintenance_recs |   |
        v             |   +------------------+   |
+------------------+  |   | id (PK)          |   |
|   incidents      |  |   | drone_id (FK)--->|---+
+------------------+  |   | type             |
| id (PK)          |  |   | description      |
| flight_id (FK)-->|--+   | performed_at     |
| drone_id (FK)--->|---+  | cost             |
| pilot_id (FK)--->|--+|  | parts_replaced(J)|
| severity         |  ||  | status           |
| type             |  ||  +------------------+
| description      |  ||
| latitude         |  ||  +------------------+   +------------------+
| longitude        |  ||  | media_metadata   |   | swarm_sessions   |
| occurred_at      |  ||  +------------------+   +------------------+
+------------------+  ||  | id (PK)          |   | id (PK)          |
                      ||  | flight_id (FK)-->|---+ name             |
                      ||  | drone_id (FK)--->|---+ formation_type   |
                      ||  | filename         |   | drone_count      |
                      ||  | media_type       |   | drone_ids (J)    |
                      ||  | resolution       |   | leader_id        |
                      ||  | storage_path     |   | status           |
                      ||  | captured_at      |   | separation_m     |
                      ||  +------------------+   +------------------+
                      ||
                      ||  +------------------+   +------------------+
                      ||  |   geofences      |   |  audit_logs      |
                      ||  +------------------+   +------------------+
                      ||  | id (PK)          |   | id (PK)          |
                      ||  | name             |   | table_name       |
                      ||  | type (circle/poly)|  | record_id        |
                      ||  | center_lat       |   | action           |
                      ||  | center_lon       |   | old_values (J)   |
                      ||  | radius_m         |   | new_values (J)   |
                      ||  | polygon_verts (J)|   | performed_by     |
                      ||  | breach_action    |   | timestamp        |
                      ||  | active           |   +------------------+
                      ||  +------------------+
                      ||
                      ||  +------------------+   +------------------+
                      |+->| calibration_recs |   | firmware_records |
                      |   +------------------+   +------------------+
                      |   | id (PK)          |   | id (PK)          |
                      +-->| drone_id (FK)    |   | drone_id (FK)    |
                          | sensor_type      |   | version          |
                          | calibrated_at    |   | release_notes    |
                          | parameters (J)   |   | installed_at     |
                          | status           |   | status           |
                          +------------------+   +------------------+
```

(J) = JSON column, (FK) = Foreign Key, (PK) = Primary Key, (UQ) = Unique

### 6.2 Table Summary

| Table                 | Rows (est.) | Key Indexes                      | Time-Series |
| --------------------- | ----------- | -------------------------------- | ----------- |
| `pilots`              | ~100        | email (unique), license          | No          |
| `drone_profiles`      | ~1,000      | serial_number (unique), model    | No          |
| `missions`            | ~10,000     | status, created_by, created_at   | No          |
| `waypoints`           | ~100,000    | mission_id + sequence (unique)   | No          |
| `flight_records`      | ~50,000     | drone_id, pilot_id, start_time   | No          |
| `telemetry_points`    | ~100M+      | drone_id + timestamp (BRIN)      | Yes         |
| `geofences`           | ~500        | active, name                     | No          |
| `maintenance_records` | ~5,000      | drone_id, type, status, date     | No          |
| `incidents`           | ~500        | flight_id, severity, status      | No          |
| `media_metadata`      | ~500,000    | flight_id, drone_id, captured_at | No          |
| `swarm_sessions`      | ~1,000      | status                           | No          |
| `calibration_records` | ~10,000     | drone_id, sensor_type            | No          |
| `firmware_records`    | ~5,000      | drone_id, version                | No          |
| `settings`            | ~1,000      | key (unique)                     | No          |
| `audit_logs`          | ~1M+        | table_name + timestamp (BRIN)    | Yes         |

### 6.3 Index Strategy

- **BRIN indexes** on `telemetry_points` and `audit_logs` for time-series
  correlation ordering. BRIN provides minimal storage overhead for naturally
  ordered data.
- **B-tree indexes** on foreign keys and frequently queried columns.
- **Unique indexes** on natural keys (serial_number, email, license).
- **Composite indexes** on common query patterns (drone_id + timestamp).

### 6.4 Spatial Data

- GPS coordinates stored as `float` (latitude, longitude, altitude)
- PostGIS `point` type available for spatial queries
- PostGIS `polygon` type available for geofence boundary queries
- Spatial indexes (GiST) recommended for geofence containment checks

---

## 7. Deployment Architecture

### 7.1 Single Node

For development, testing, and small-scale operations.

```
+---------------------------------------------------------------+
|                        Single Node                             |
|                                                                |
|  +----------+  +----------+  +----------+  +----------+       |
|  | Oya Core |  | GCS UI   |  | Database |  | Redis    |       |
|  | Service  |  | (Web)    |  | (Postgres)|  | (Cache)  |       |
|  +----------+  +----------+  +----------+  +----------+       |
|       |              |             |              |             |
|  +----+--------------+-------------+--------------+----+       |
|  |                 Node.js Runtime                     |       |
|  +-----------------------------------------------------+       |
+---------------------------------------------------------------+
```

### 7.2 Multi-Node (Production)

For fleet operations with multiple concurrent drone operations.

```
+-------------------+     +-------------------+     +-------------------+
|   GCS Clients     |     |   GCS Clients     |     |   GCS Clients     |
+--------+----------+     +--------+----------+     +--------+----------+
         |                         |                         |
         v                         v                         v
+--------+-------------------------+-------------------------+--------+
|                         Load Balancer (HAProxy/Nginx)               |
+--------+-------------------------+-------------------------+--------+
         |                         |                         |
         v                         v                         v
+--------+--------+       +--------+--------+       +--------+--------+
|  Oya Service    |       |  Oya Service    |       |  Oya Service    |
|  Instance 1     |       |  Instance 2     |       |  Instance N     |
|  (Swarm Ops)    |       |  (Mission Ctrl) |       |  (Telemetry)    |
+-----------------+       +-----------------+       +-----------------+
         |                         |                         |
         v                         v                         v
+--------+-------------------------+-------------------------+--------+
|                        Message Bus (Redis Pub/Sub)                   |
+--------+-------------------------+-------------------------+--------+
         |                         |                         |
         v                         v                         v
+--------+--------+       +--------+--------+       +--------+--------+
|  PostgreSQL     |       |  TimescaleDB    |       |  MinIO (S3)     |
|  (Primary)      |       |  (Telemetry)    |       |  (Media)        |
+-----------------+       +-----------------+       +-----------------+
```

### 7.3 Edge Deployment

For onboard compute on drones with limited resources.

```
+------------------------------------------------------------------+
|                         Drone (Onboard)                            |
|                                                                    |
|  +---------------+  +---------------+  +-----------------------+  |
|  | Flight        |  | Edge Compute  |  | Communication         |  |
|  | Controller    |  | (Jetson/Coral) |  | Module                |  |
|  | PX4/ArduPilot |  |               |  | MAVLink + Mesh        |  |
|  +-------+-------+  |  +----------+ |  +----------+------------+  |
|          |           |  | Model    | |             |               |
|          |           |  | Inference| |             |               |
|          +---------->|  +----------+ |<------------+               |
|                      |  | Detection| |                             |
|                      |  | Tracking | |                             |
|                      |  | SLAM     | |                             |
|                      +---------------+                             |
+------------------------------------------------------------------+
         |                                            |
    [MAVLink]                                   [WiFi/Cellular]
         |                                            |
         v                                            v
+------------------+                    +-------------------+
| GCS / Relay      |                    | Cloud Backend     |
+------------------+                    +-------------------+
```

Edge platforms supported:

| Platform         | CPU/GPU               | TOPS | Power  | Class     |
| ---------------- | --------------------- | ---- | ------ | --------- |
| Jetson Nano      | ARM A57 + Maxwell 128 | 0.47 | 5-10W  | Entry     |
| Jetson Orin Nano | ARM A78 + Ampere 1024 | 40   | 7-15W  | Mid-range |
| Jetson Orin NX   | ARM A78 + Ampere 2048 | 100  | 10-25W | High-end  |
| Jetson AGX Orin  | ARM A78 + Ampere 2048 | 275  | 15-60W | Maximum   |
| Coral Dev Board  | ARM A53 + TPU         | 4    | 2-4W   | Low-power |
| Coral USB Accel  | Edge TPU              | 4    | 2W     | Add-on    |
| Hailo-8          | Custom AI accelerator | 26   | 2.5W   | Efficient |
| Qualcomm RB5     | Kryo 585 + Adreno 650 | 15   | 3-7W   | Mobile    |

### 7.4 Cloud Integration

```
+-----------------------------+
|     Cloud Backend           |
|                             |
|  +--------+  +-----------+ |
|  | Fleet  |  | Analytics | |
|  | Mgmt   |  | & ML      | |
|  +--------+  +-----------+ |
|       |            |        |
|  +--------+  +-----------+ |
|  | Media  |  | Regulatory| |
|  | Store  |  | Compliance| |
|  +--------+  +-----------+ |
+-----------------------------+
```

---

## 8. Scaling

### 8.1 Horizontal Scaling

The Oya platform is designed for horizontal scaling across multiple service
instances.

**Stateless Components** (scale freely):

- Telemetry validation and routing
- Mission validation
- Coordinate transforms and math utilities
- Command encoding/decoding

**Stateful Components** (require coordination):

- Mission execution state machines
- Swarm coordination
- Subject tracking (track continuity)
- Connection managers

**Scaling Strategy**:

| Component           | Strategy                        | Max per Instance |
| ------------------- | ------------------------------- | ---------------- |
| Telemetry ingestion | Partition by drone ID           | ~1,000 drones    |
| Mission control     | One instance per active mission | ~50 missions     |
| Swarm coordination  | One instance per swarm          | ~100 drones      |
| Video streaming     | Partition by stream ID          | ~20 streams      |
| AI inference        | GPU-bound, batch across frames  | Model-dependent  |

### 8.2 Load Balancing

```
                        +-------------------+
                        |   Load Balancer   |
                        | (L4 or L7)        |
                        +---+-----+-----+---+
                            |     |     |
                            v     v     v
                        +---+ +---+ +---+
                        | S1| | S2| | SN|
                        +---+ +---+ +---+
```

- **L4 (TCP/UDP)**: For MAVLink connections (sticky sessions by source IP)
- **L7 (HTTP)**: For REST/WebSocket GCS connections
- **Consistent hashing**: For telemetry partitioning by `droneId`

### 8.3 Database Scaling

- **Read replicas**: For analytics and reporting queries
- **Table partitioning**: `telemetry_points` partitioned by time (weekly)
- **TimescaleDB**: Hypertable on `telemetry_points` for automatic time
  partitioning
- **Connection pooling**: PgBouncer for managing database connections
- **Archival**: Older telemetry data moved to cold storage (S3/MinIO)

### 8.4 Swarm Scaling

| Swarm Size | Architecture          | Communication            |
| ---------- | --------------------- | ------------------------ |
| 2-10       | Leader-follower       | Direct broadcast         |
| 10-50      | Virtual leader        | Mesh network             |
| 50-100     | Decentralized         | Cluster mesh + relay     |
| 100-500    | Hierarchical clusters | Multi-hop with AODV/OLSR |
| 500+       | Federated regions     | Ground relay backbone    |

The `MAX_SWARM_SIZE` constant defines the configured limit.

---

## 9. Security

### 9.1 Authentication

```
+--------+     +----------+     +----------+     +--------+
| Client | --> | Auth     | --> | Token    | --> | API    |
|        |     | Service  |     | Validate |     | Server |
+--------+     +----------+     +----------+     +--------+
```

- **Pilot authentication**: Username/password or certificate-based
- **Drone authentication**: Pre-shared keys or X.509 certificates
- **GCS authentication**: OAuth 2.0 / JWT tokens
- **API keys**: For programmatic access

### 9.2 Communication Encryption

| Link               | Protocol     | Encryption         |
| ------------------ | ------------ | ------------------ |
| GCS to Cloud       | HTTPS/WSS    | TLS 1.3            |
| GCS to Drone       | MAVLink v2   | MAVLink signing    |
| Drone to Drone     | Mesh network | `MessageEncryptor` |
| Video stream       | SRT/WebRTC   | AES-128/DTLS-SRTP  |
| Telemetry to Cloud | HTTPS        | TLS 1.3            |

MAVLink v2 message signing:

- `MAVLINK_IFLAG_SIGNED` flag in incompatibility flags
- SHA-256 HMAC signature appended to frame
- Prevents message tampering and replay attacks
- Implemented in `MessageAuthenticator` class

### 9.3 Authorization

Role-based access control (RBAC):

| Role             | Permissions                                          |
| ---------------- | ---------------------------------------------------- |
| Administrator    | Full access to all operations and settings           |
| Pilot-in-Command | Arm, fly, execute missions on assigned drones        |
| Mission Planner  | Create/edit missions, view telemetry (no flight ops) |
| Observer         | View-only access to telemetry and video streams      |
| Maintenance      | Update firmware, calibrate sensors, view logs        |

### 9.4 Audit Trail

The `audit_logs` table records all modifications to critical records:

```typescript
// Audit log fields:
// - table_name: which table was modified
// - record_id: UUID of the modified record
// - action: 'INSERT' | 'UPDATE' | 'DELETE'
// - old_values: JSON snapshot before change
// - new_values: JSON snapshot after change
// - performed_by: user/system identifier
// - timestamp: when the change occurred
```

### 9.5 GPS Security

| Threat         | Detection Class       | Mitigation                |
| -------------- | --------------------- | ------------------------- |
| GPS spoofing   | `GPSSpoofingDetector` | Multi-constellation check |
| GPS jamming    | `GPSJammingDetector`  | INS dead-reckoning        |
| Replay attacks | Timestamp validation  | Sequence + time check     |

---

## 10. Disaster Recovery

### 10.1 Backup Strategy

| Data Type           | Backup Frequency | Retention | Method              |
| ------------------- | ---------------- | --------- | ------------------- |
| Mission definitions | On every change  | Forever   | WAL archiving       |
| Drone profiles      | Daily            | 1 year    | pg_dump             |
| Telemetry           | Continuous       | 90 days   | TimescaleDB archive |
| Flight logs         | Per-flight       | 5 years   | S3/MinIO            |
| Media files         | On capture       | 1 year    | S3 replication      |
| Audit logs          | Continuous       | 7 years   | WAL + S3            |
| Configuration       | On change        | Forever   | Git version control |

### 10.2 Failover Architecture

```
+-------------------+           +-------------------+
|  Primary Region   |           |  Standby Region   |
|                   |           |                   |
|  +-------------+  |  stream   |  +-------------+  |
|  | PostgreSQL  |  | -------> |  | PostgreSQL  |  |
|  | Primary     |  |  (WAL)   |  | Replica     |  |
|  +-------------+  |           |  +-------------+  |
|                   |           |                   |
|  +-------------+  |  replicate|  +-------------+  |
|  | MinIO       |  | -------> |  | MinIO       |  |
|  | Primary     |  |  (sync)  |  | Replica     |  |
|  +-------------+  |           |  +-------------+  |
|                   |           |                   |
|  +-------------+  |  sentinel |  +-------------+  |
|  | Redis       |  | -------> |  | Redis       |  |
|  | Primary     |  |          |  | Replica     |  |
|  +-------------+  |           |  +-------------+  |
+-------------------+           +-------------------+
```

### 10.3 Recovery Point Objective (RPO)

| Data Type     | RPO        | Rationale                |
| ------------- | ---------- | ------------------------ |
| Telemetry     | < 1 second | Streaming replication    |
| Missions      | 0          | Synchronous replication  |
| Flight logs   | < 5 min    | Periodic upload to cloud |
| Media         | Per-flight | Uploaded after landing   |
| Configuration | 0          | Git-backed               |

### 10.4 Recovery Time Objective (RTO)

| Failure Scenario | RTO       | Recovery Procedure              |
| ---------------- | --------- | ------------------------------- |
| Service crash    | < 30s     | Container restart (systemd/k8s) |
| Database failure | < 5 min   | Promote replica                 |
| Region failure   | < 15 min  | DNS failover to standby         |
| Data corruption  | < 1 hour  | Point-in-time recovery (PITR)   |
| Total loss       | < 4 hours | Full restore from backup        |

### 10.5 In-Flight Emergency Data Preservation

During flight, critical data is preserved through multiple mechanisms:

1. **Black Box Recording** — Continuous logging of telemetry, commands, and
   events to onboard storage with circular buffer (last 30 minutes minimum)
2. **Real-Time Upload** — Telemetry streamed to ground station for persistent
   storage as it is generated
3. **Post-Emergency Analysis** — Emergency events trigger automatic upload of
   the last N minutes of black box data
4. **Flight Logging** — `flight-logging.ts` provides structured log writing with
   automatic rotation and compression

### 10.6 Model Deployment Rollback

The edge deployment system supports automatic rollback:

```
Deployment States:
  pending -> downloading -> installing -> validating -> active
                                                     -> failed -> rolled_back

Canary Deployment:
  1. Deploy new model to 10% of fleet (canary state)
  2. Monitor accuracy/latency metrics for 1 hour
  3. If metrics degrade > threshold, automatic rollback
  4. If metrics stable, promote to full fleet (active state)
```

Rollback triggers:

- Accuracy drop > 5% vs baseline
- Latency increase > 50% vs baseline
- Memory usage exceeds 90% of available
- Thermal throttling sustained > 5 minutes
- Any inference crash or NaN output
