Skip to content

Handover API Specification ​

Purpose & Scope ​

This specification covers the API endpoints and data models required to support the protector handover functionality. The handover system allows for secure transfer of worksite protection between two protectors while maintaining audit trails and preventing conflicts.

Requirements Implemented ​

Architecture Decisions ​

Architecture Overview ​

The handover system consists of:

  1. Handover Entity: Database model for tracking handover sessions
  2. API Endpoints: REST endpoints for handover management
  3. Heartbeat System: Session maintenance and timeout handling
  4. Status Polling: Real-time updates for both protectors

Implementation Details ​

Core Components ​

  • HandoverService: Business logic for handover operations
  • HandoverController: API endpoint management
  • HandoverRepository: Data access layer
  • HeartbeatService: Session timeout management

Data Flow ​

  1. Outgoing protector initiates handover → Creates handover entity
  2. Outgoing protector scans incoming protector's QR → Updates handover entity
  3. Incoming protector accepts → Updates handover entity status
  4. Heartbeat system maintains session validity (5-10 second intervals, see ADR-007)
  5. Final confirmation follows an "A-B-A" flow to ensure both parties are online:
    • The outgoing Protector (A) sends regular heartbeats.
    • The incoming Protector (B) sends their acceptance.
    • The system waits for the next heartbeat from Protector A before finalising the handover, thus confirming both were online.

State Management ​

  • Pending: Handover initiated, waiting for incoming protector
  • Completed: Handover successfully completed
  • Cancelled: Handover cancelled (timeout, manual cancellation, or offline)

API Contracts / Interfaces ​

Public APIs ​

Create Handover ​

http
POST /api/handover
Content-Type: application/json

{
  "siteId": "uuid",
  "outgoingUserId": "uuid",
  "incomingUserId": "uuid"
}

Response:

json
{
  "id": "uuid",
  "siteId": "uuid",
  "outgoingUserId": "uuid",
  "incomingUserId": "uuid",
  "startDate": "2025-08-20T10:00:00Z",
  "endDate": null,
  "status": "pending",
  "createdAt": "2025-08-20T10:00:00Z",
  "updatedAt": "2025-08-20T10:00:00Z"
}

Get Handover ​

http
GET /api/handover/{id}

Update Handover Status ​

http
PATCH /api/handover/{id}
Content-Type: application/json

{
  "status": "completed" | "cancelled",
  "endDate": "2025-08-20T10:30:00Z" // Optional, set on completion
}

Send Heartbeat ​

http
POST /api/handover/{id}/heartbeat

Response:

json
{
  "success": true,
  "lastHeartbeat": "2025-08-20T10:15:00Z",
  "nextExpected": "2025-08-20T10:15:30Z"
}

Get Handover by Site ​

http
GET /api/site/{siteId}/handover

Response:

json
{
  "currentHandover": {
    "id": "uuid",
    "status": "pending",
    "outgoingUserId": "uuid",
    "incomingUserId": "uuid",
    "startDate": "2025-08-20T10:00:00Z"
  },
  "recentHandovers": [
    {
      "id": "uuid",
      "status": "completed",
      "outgoingUserId": "uuid",
      "incomingUserId": "uuid",
      "startDate": "2025-08-20T08:00:00Z",
      "endDate": "2025-08-20T10:00:00Z"
    }
  ]
}

Internal APIs ​

  • Heartbeat Monitoring: Background service that monitors heartbeat timeouts
  • Status Synchronisation: Service for updating handover status across components

Data Models ​

Handover Entity ​

csharp
public class Handover : IEntity
{
    public Guid Id { get; set; }
    public required Guid SiteId { get; set; }
    public required Guid OutgoingUserId { get; set; }
    public required Guid IncomingUserId { get; set; }
    public HandoverStatus Status { get; set; }
    public DateTime CreatedAt { get; set; }
    public DateTime UpdatedAt { get; set; }
    public DateTime? LastHeartbeat { get; set; }
}

public enum HandoverStatus
{
    Pending,
    Completed,
    Cancelled
}

Handover Request DTOs ​

csharp
public class CreateHandoverRequest
{
    public required Guid SiteId { get; set; }
    public required Guid OutgoingUserId { get; set; }
    public required Guid IncomingUserId { get; set; }
}

public class UpdateHandoverRequest
{
    public HandoverStatus? Status { get; set; }
    public DateTime? EndDate { get; set; }
}

Integration Points ​

External Dependencies ​

  • Site Service: For updating worksite protector assignments
  • User Service: For validating protector identities
  • Audit Service: For logging handover events

Consumers ​

  • Frontend Apps: For handover UI flows
  • Background Services: For heartbeat monitoring and cleanup
  • Reporting Services: For handover analytics and audit trails

Error Handling ​

Error Types ​

  • Validation Errors: Invalid user IDs, site not found, etc.
  • Business Rule Violations: Site already in handover, user not authorized, etc.
  • System Errors: Database failures, timeout issues, etc.

Error Responses ​

json
{
  "error": "Handover already in progress for this site",
  "code": "HANDOVER_CONFLICT",
  "details": {
    "existingHandoverId": "uuid",
    "status": "pending"
  }
}

Fallback Behaviour ​

  • Heartbeat Timeout: Automatic cancellation and notification to both parties
  • Network Issues: Clear error messages with retry options
  • System Failures: Graceful degradation with manual intervention options

Performance Requirements ​

Response Times ​

  • API Endpoints: < 200ms for standard operations
  • Heartbeat Processing: < 100ms for heartbeat updates
  • Status Polling: < 500ms for real-time updates

Scalability ​

  • Concurrent Handovers: Support for multiple simultaneous handovers
  • Heartbeat Frequency: 5-10 seconds (see ADR-007 for detailed rationale)
  • Database Performance: Efficient queries for handover status and history

Resource Usage ​

  • Memory: Minimal memory footprint for active handovers
  • Database: Efficient indexing on siteId, status, and timestamps
  • Network: Optimised polling and heartbeat mechanisms

Security Considerations ​

Authentication ​

  • JWT Tokens: All endpoints require valid authentication
  • User Validation: Verify that users are authorized for the specified site

Authorization ​

  • Site Access: Users must have access to the site being handed over
  • Protector Role: Users must have protector permissions
  • Handover Initiation: Only current site protector can initiate handover

Data Protection ​

  • Audit Logging: All handover actions are logged with user context
  • Data Validation: Input validation and sanitisation for all endpoints
  • Access Control: Users can only access handovers they're involved in

Testing Strategy ​

Unit Testing ​

  • Service Layer: Test business logic and validation rules
  • Repository Layer: Test data access and entity management
  • Controller Layer: Test API endpoint behaviour

Integration Testing ​

  • API Endpoints: Test complete request/response cycles
  • Database Operations: Test entity creation, updates, and queries
  • External Services: Test integration with site and user services

End-to-End Testing ​

  • Complete Handover Flow: Test full handover process from initiation to completion
  • Offline Scenarios: Test heartbeat timeout and cancellation flows
  • Error Conditions: Test various failure scenarios and recovery

Deployment ​

Configuration ​

  • Heartbeat Intervals: 5 seconds, see ADR-007
  • Database Settings: Connection strings and performance tuning
  • Logging Levels: Configurable logging for debugging and monitoring

Dependencies ​

  • Database: PostgreSQL with proper indexing
  • Message Queue: For background heartbeat processing (optional)
  • Caching: Redis for session state (optional)

Monitoring ​

  • Health Checks: API endpoint health and database connectivity
  • Metrics: Handover success rates, completion times, and error rates
  • Alerts: Notifications for failed handovers or system issues

References ​

Internal use only