# Sequence Flows (Prototype Reference)

Status:
- Reference-only extraction from prototype behavior.
- Not the canonical target-state flow for implementation.

Canonical target-state sources:
- `doc/api/openapi.draft.yaml`
- `doc/api/asyncapi.draft.yaml`
- `doc/architecture/State_Machines.md`
- `doc/architecture/Inter_Service_Communication.md`

## 1. Login and Bootstrap
```mermaid
sequenceDiagram
  participant U as User
  participant FE as Frontend
  participant BE as Backend

  U->>FE: Enter username/password
  FE->>BE: POST /api/auth/login
  BE-->>FE: token + user profile
  FE->>FE: store token (localStorage)
  FE->>BE: GET /api/users/me
  FE->>BE: GET /api/nodes
  FE->>BE: GET /api/allocations
  BE-->>FE: profile + inventory + allocations
```

## 2. Provision Node
```mermaid
sequenceDiagram
  participant U as User
  participant FE as Frontend
  participant BE as Backend
  participant N as GPU Node (SSH)

  U->>FE: Click Provision
  FE->>BE: POST /api/provision/:nodeId
  BE->>BE: validate node/status/balance
  BE->>BE: generate ssh keypair
  BE->>N: SSH setup user + authorized_keys
  N-->>BE: success/failure
  BE->>BE: write allocation + usage + node assignment
  BE-->>FE: 201 allocation
```

## 3. Release Allocation
```mermaid
sequenceDiagram
  participant U as User/Admin
  participant FE as Frontend
  participant BE as Backend
  participant N as GPU Node (SSH)

  U->>FE: Confirm release
  FE->>BE: POST /api/allocations/:id/release
  BE->>BE: mark allocation released/end usage/unassign node
  BE->>N: SSH remove key + lock password (best effort)
  N-->>BE: success/failure
  BE-->>FE: ok
```

## 4. Billing Loop (every 60s)
```mermaid
sequenceDiagram
  participant T as Timer
  participant BE as Backend
  participant WS as WebSocket Clients

  T->>BE: runBillingCycleAndEnforceLimits()
  BE->>BE: find active usage records
  BE->>BE: compute cost and decrement balances
  BE->>BE: if depleted -> release active allocations
  BE->>WS: send low_balance_warning/balance_depleted
```

## 5. Stripe Top-up and Webhook
```mermaid
sequenceDiagram
  participant U as User
  participant FE as Frontend
  participant BE as Backend
  participant ST as Stripe

  U->>FE: Enter amount, click Add Funds
  FE->>BE: POST /api/stripe/create-charge-session
  BE->>ST: create checkout session
  ST-->>BE: checkout URL
  BE-->>FE: URL
  FE->>ST: redirect to checkout
  ST->>BE: POST /api/stripe/webhook
  BE->>BE: verify signature + dedupe event id
  BE->>BE: credit internal balance
  ST->>FE: redirect back with payment status query
```
