All files / lib mutationOutbox.ts

38.46% Statements 70/182
30.88% Branches 21/68
36.95% Functions 17/46
46.66% Lines 63/135

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221                      57x 57x   2x     2x               111x 109x 6x                                   10x 10x       6x 6x                     56x 55x                                       2x 2x             4x 4x 4x 4x 4x         55x       55x 54x               3x       3x 3x 3x   2x 1x             1x 1x 1x     2x     1x 1x               4x   4x 4x   3x 3x   3x   3x 3x   55x 55x       55x 3x   3x 3x 55x 3x   3x 2x 2x 1x 1x     1x 1x               3x 3x         3x 2x     3x                                            
/**
 * @see frontend/docs/UX/layer-contracts/L1-data-layer.md §9.4
 *
 * IndexedDB-pohjainen outbox offline-mutaatioille.
 * Tallentaa mutaatiot järjestyksessä, lähettää yhteyden palautuessa.
 *
 * Liittyy periaatteisiin: 5, 8
 */
 
import { get, set } from 'idb-keyval'
import type { QueryClient } from '@tanstack/react-query'
import { apiClient } from '@/lib/axios'
import { getOnlineDetector } from '@/lib/onlineDetector'

const OUTBOX_KEY = 'mutation-outbox'

type OutboxListener = () => void
const outboxListeners = new Set<OutboxListener>()
 
export function subscribeOutbox(listener: OutboxListener): () => void {
  outboxListeners.add(listener)
  return () => {
    outboxListeners.delete(listener)
  }
}
 
function notifyOutboxListeners(): void {
  for (const listener of outboxListeners) {
    listener()
  }
}
 
export interface OutboxEntry {
  id: string
  entityPath: string
  op: 'CREATE' | 'UPDATE' | 'DELETE'
  payload: unknown
  idempotencyKey: string
  createdAt: number
  attempts: number
  lastError?: string
  status: 'PENDING' | 'PROCESSING' | 'FAILED'
}

async function readOutbox(): Promise<OutboxEntry[]> {
  const raw = await get<OutboxEntry[]>(OUTBOX_KEY)
  return raw ?? []
}

async function writeOutbox(entries: OutboxEntry[]): Promise<void> {
  await set(OUTBOX_KEY, entries)
  notifyOutboxListeners()
}

export async function addToOutbox(
  entry: Omit<OutboxEntry, 'attempts' | 'lastError' | 'status'>,
): Promise<void> {
  const outbox = await readOutbox()
  const existing = outbox.filter(
    (e) =>
      !(
        e.entityPath === entry.entityPath &&
        e.op === 'DELETE' &&
        entry.op === 'CREATE'
      ),
  )
  existing.push({
    ...entry,
    attempts: 0,
    status: 'PENDING' as const,
  })
  await writeOutbox(existing)
}

export async function getOutboxEntries(
  status?: OutboxEntry['status'],
): Promise<OutboxEntry[]> {
  const outbox = await readOutbox()
  if (!status) return outbox
  return outbox.filter((e) => e.status === status)
}

export async function removeFromOutbox(id: string): Promise<void> {
  const outbox = await readOutbox()
  await writeOutbox(outbox.filter((e) => e.id !== id))
}

export async function updateOutboxEntry(
  id: string,
  updates: Partial<Pick<OutboxEntry, 'attempts' | 'lastError' | 'status'>>,
): Promise<void> {
  const outbox = await readOutbox()
  const idx = outbox.findIndex((e) => e.id === id)
  Iif (idx === -1) return
  outbox[idx] = { ...outbox[idx], ...updates }
  await writeOutbox(outbox)
}
 
export async function getPendingDeleteEntriesFromOutbox(): Promise<
  Array<{ entityPath: string; id: string }>
>I {
  const outbox = await readOutbox()
  return outbox
    .filter((e) => e.op === 'DELETE' && e.status !== 'FAILED')
    .map((e) => {
 E     const payload = e.payload as { id: string }
      return { entityPath: e.entityPath, id: payload.id }
    })
}

async function executeOutboxEntry(
  entry: OutboxEntry,
): Promise<{ success: boolean; error?: string }> {
  const headers: Record<string, string> = {
    'Idempotency-Key': entry.idempotencyKey,
  }

  try {
    const { entityPath, op, payload } = entry
    switch (op) {
      case 'CREATE':
        await apiClient.post(entityPath, payload, { headers })
        break
      case 'UPDATE': {
        const { id, ...body } = payload as { id: string; [key: string]: unknown }
        await apiClient.put(`${entityPath}/${id}`, body, { headers })
        break
      }
      case 'DELETE': {
        const { id } = payload as { id: string }
        await apiClient.delete(`${entityPath}/${id}`, { headers })
        break
      }
    }
    return { success: true }
  } catch (err) {
    const message =
      err instanceof Error ? err.message : 'Unknown outbox replay error'
    return { success: false, error: message }
  }
}
 
export async function replayOutbox(
  queryClient: QueryClient,
  onDeleteReplaySuccess?: (entityPath: string, id: string) => void,
): Promise<{ failed: number; total: number }> {
  Iif (!getOnlineDetector().isOnline()) return { failed: 0, total: 0 }
 
  const outbox = await readOutbox()
  if (outbox.length === 0) return { failed: 0, total: 0 }

  const pending = outbox.filter(
    (e) => e.status === 'PENDING' || e.status === 'FAILED',
  )
  Iif (pending.length === 0) return { failed: 0, total: 0 }
 
  const hasPending = pending.some((e) => e.status === 'PENDING')
  Iif (!hasPending) {
    for (const entry of pending) {
      await removeFromOutbox(entry.id)
    }
    return { failed: 0, total: pending.length }
  }
 
  let failed = 0
  const touchedPaths = new Set<string>()

  for (const entry of pending) {
    await updateOutboxEntry(entry.id, { status: 'PROCESSING' })
    const result = await executeOutboxEntry(entry)
    touchedPaths.add(entry.entityPath)
 
    if (result.success) {
      await removeFromOutbox(entry.id)
      if (entry.op === 'DELETE') {
        const payload = entry.payload as { id: string }
        onDeleteReplaySuccess?.(entry.entityPath, payload.id)
      }
    } else {
      failed++
      await updateOutboxEntry(entry.id, {
        status: 'FAILED',
        attempts: entry.attempts + 1,
        lastError: result.error,
      })
    }
  }
 
  for (const path of touchedPaths) {
    queryClient.invalidateQueries({ queryKey: [path] })
  }
 
  // Per-component SSE reconnect is handled by Phase 1 backoff/lost-retry timers (§9.5).
  // No separate SSE coordinator is needed.
  if (failed === 0) {
    await queryClient.refetchQueries({ stale: true })
  }
 
  return { failed, total: pending.length }
}
 
export function startOutboxReplay(
  queryClient: QueryClient,
  onDeleteReplaySuccess?: (entityPath: string, id: string) => void,
): () => void {
  replayOutbox(queryClient, onDeleteReplaySuccess)
 
  const detector = getOnlineDetector()
 
  async function onOnline() {
    await replayOutbox(queryClient, onDeleteReplaySuccess)
  }
 
  const unsubscribe = detector.subscribe(() => {
    if (detector.isOnline()) {
      void onOnline()
    }
  })
 
  return unsubscribe
}