|
| 1 | +const express = require('express'); |
| 2 | + |
| 3 | +const { isFeatureEnabled } = require('../features'); |
| 4 | +const { recordSolveHistoryRequest } = require('../metrics'); |
| 5 | +const { query } = require('../postgres'); |
| 6 | +const { stableId } = require('../postgres/dualWrite'); |
| 7 | + |
| 8 | +const DEFAULT_LIMIT = 50; |
| 9 | +const MAX_LIMIT = 100; |
| 10 | +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; |
| 11 | + |
| 12 | +const invalidRequest = (code) => { |
| 13 | + const error = new Error(code === 'invalid_cursor' ? 'Invalid cursor' : 'Invalid limit'); |
| 14 | + error.statusCode = 400; |
| 15 | + error.code = code; |
| 16 | + return error; |
| 17 | +}; |
| 18 | + |
| 19 | +const encodeCursor = ({ completedAt, id }) => Buffer.from(JSON.stringify({ |
| 20 | + completedAt: new Date(completedAt).toISOString(), |
| 21 | + id, |
| 22 | +})).toString('base64url'); |
| 23 | + |
| 24 | +const decodeCursor = (value) => { |
| 25 | + if (!value) { |
| 26 | + return null; |
| 27 | + } |
| 28 | + if (typeof value !== 'string' || value.length > 512) { |
| 29 | + throw invalidRequest('invalid_cursor'); |
| 30 | + } |
| 31 | + |
| 32 | + try { |
| 33 | + const parsed = JSON.parse(Buffer.from(value, 'base64url').toString('utf8')); |
| 34 | + const completedAt = new Date(parsed.completedAt); |
| 35 | + if (!parsed || typeof parsed.id !== 'string' || !UUID.test(parsed.id) |
| 36 | + || Number.isNaN(completedAt.getTime())) { |
| 37 | + throw new Error('invalid'); |
| 38 | + } |
| 39 | + return { completedAt, id: parsed.id }; |
| 40 | + } catch { |
| 41 | + throw invalidRequest('invalid_cursor'); |
| 42 | + } |
| 43 | +}; |
| 44 | + |
| 45 | +const parseLimit = (value) => { |
| 46 | + if (value === undefined) { |
| 47 | + return DEFAULT_LIMIT; |
| 48 | + } |
| 49 | + if (typeof value !== 'string' || !/^\d+$/.test(value)) { |
| 50 | + throw invalidRequest('invalid_limit'); |
| 51 | + } |
| 52 | + const limit = Number(value); |
| 53 | + if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_LIMIT) { |
| 54 | + throw invalidRequest('invalid_limit'); |
| 55 | + } |
| 56 | + return limit; |
| 57 | +}; |
| 58 | + |
| 59 | +const asScramble = (scrambles) => { |
| 60 | + if (typeof scrambles !== 'string') { |
| 61 | + return scrambles; |
| 62 | + } |
| 63 | + try { |
| 64 | + return JSON.parse(scrambles); |
| 65 | + } catch { |
| 66 | + return scrambles; |
| 67 | + } |
| 68 | +}; |
| 69 | + |
| 70 | +const historyQuery = ` |
| 71 | + SELECT |
| 72 | + s.id AS solve_id, |
| 73 | + s.time_ms, |
| 74 | + s.dnf, |
| 75 | + s.plus_two_penalty, |
| 76 | + s.inspection_penalty, |
| 77 | + s.auf_penalty, |
| 78 | + s.source_created_at AS completed_at, |
| 79 | + s.source_updated_at AS updated_at, |
| 80 | + a.scrambles, |
| 81 | + r.id AS room_id, |
| 82 | + rs.id AS race_session_id, |
| 83 | + rs.cube_event AS race_session_event |
| 84 | + FROM app.solves s |
| 85 | + JOIN app.attempts a ON a.id = s.attempt_id AND a.room_id = s.room_id |
| 86 | + JOIN app.race_sessions rs ON rs.id = a.race_session_id AND rs.room_id = a.room_id |
| 87 | + JOIN app.rooms r ON r.id = s.room_id |
| 88 | + JOIN app.room_participants rp |
| 89 | + ON rp.room_id = r.id AND rp.user_id = $1 AND rp.banned = false |
| 90 | + WHERE s.user_id = $1 |
| 91 | + AND ($2::timestamptz IS NULL OR (s.source_created_at, s.id) < ($2, $3::uuid)) |
| 92 | + ORDER BY s.source_created_at DESC, s.id DESC |
| 93 | + LIMIT $4 |
| 94 | +`; |
| 95 | + |
| 96 | +const solveResponse = (row) => ({ |
| 97 | + id: row.solve_id, |
| 98 | + event: row.race_session_event, |
| 99 | + timeMs: row.time_ms, |
| 100 | + penalties: { |
| 101 | + dnf: !!row.dnf, |
| 102 | + plus2: !!row.plus_two_penalty, |
| 103 | + inspection: !!row.inspection_penalty, |
| 104 | + auf: !!row.auf_penalty, |
| 105 | + }, |
| 106 | + scramble: asScramble(row.scrambles), |
| 107 | + room: { id: row.room_id }, |
| 108 | + raceSession: { id: row.race_session_id, event: row.race_session_event }, |
| 109 | + completedAt: new Date(row.completed_at).toISOString(), |
| 110 | + updatedAt: new Date(row.updated_at).toISOString(), |
| 111 | +}); |
| 112 | + |
| 113 | +const createSolveHistoryRouter = ({ |
| 114 | + enabled = isFeatureEnabled('solveHistory'), |
| 115 | + postgresQuery = query, |
| 116 | + recordMetric = recordSolveHistoryRequest, |
| 117 | + now = () => Date.now(), |
| 118 | +} = {}) => { |
| 119 | + const router = express.Router(); |
| 120 | + |
| 121 | + router.get('/', async (req, res) => { |
| 122 | + const startedAt = now(); |
| 123 | + let outcome = 'error'; |
| 124 | + let count = 0; |
| 125 | + try { |
| 126 | + if (!enabled) { |
| 127 | + outcome = 'feature_disabled'; |
| 128 | + return res.status(404).json({ |
| 129 | + code: 'feature_disabled', |
| 130 | + message: 'This feature is not available', |
| 131 | + }); |
| 132 | + } |
| 133 | + |
| 134 | + const limit = parseLimit(req.query.limit); |
| 135 | + const cursor = decodeCursor(req.query.cursor); |
| 136 | + const numericId = Number(req.user && req.user.id); |
| 137 | + if (!Number.isSafeInteger(numericId) || numericId < 1) { |
| 138 | + outcome = 'unauthorized'; |
| 139 | + return res.status(403).json({ code: 'unauthorized', message: 'Unauthorized' }); |
| 140 | + } |
| 141 | + |
| 142 | + const result = await postgresQuery(historyQuery, [ |
| 143 | + stableId('user', numericId), |
| 144 | + cursor && cursor.completedAt, |
| 145 | + cursor && cursor.id, |
| 146 | + limit + 1, |
| 147 | + ]); |
| 148 | + if (!result) { |
| 149 | + outcome = 'postgres_unavailable'; |
| 150 | + return res.status(503).json({ |
| 151 | + code: 'postgres_unavailable', |
| 152 | + message: 'Solve history is temporarily unavailable', |
| 153 | + }); |
| 154 | + } |
| 155 | + |
| 156 | + const rows = result.rows || []; |
| 157 | + const hasNextPage = rows.length > limit; |
| 158 | + const page = rows.slice(0, limit); |
| 159 | + count = page.length; |
| 160 | + outcome = 'success'; |
| 161 | + return res.json({ |
| 162 | + solves: page.map(solveResponse), |
| 163 | + nextCursor: hasNextPage ? encodeCursor({ |
| 164 | + completedAt: page[page.length - 1].completed_at, |
| 165 | + id: page[page.length - 1].solve_id, |
| 166 | + }) : null, |
| 167 | + }); |
| 168 | + } catch (err) { |
| 169 | + if (err.statusCode === 400) { |
| 170 | + outcome = err.code; |
| 171 | + return res.status(400).json({ code: err.code, message: err.message }); |
| 172 | + } |
| 173 | + outcome = 'postgres_unavailable'; |
| 174 | + return res.status(503).json({ |
| 175 | + code: 'postgres_unavailable', |
| 176 | + message: 'Solve history is temporarily unavailable', |
| 177 | + }); |
| 178 | + } finally { |
| 179 | + Promise.resolve(recordMetric({ |
| 180 | + outcome, |
| 181 | + count, |
| 182 | + latencyMs: Math.max(0, now() - startedAt), |
| 183 | + })).catch(() => {}); |
| 184 | + } |
| 185 | + }); |
| 186 | + |
| 187 | + return router; |
| 188 | +}; |
| 189 | + |
| 190 | +module.exports = { |
| 191 | + createSolveHistoryRouter, |
| 192 | + decodeCursor, |
| 193 | + encodeCursor, |
| 194 | + parseLimit, |
| 195 | +}; |
0 commit comments