Repository navigation
Expand file tree
/
Copy pathserver.ts
More file actions
97 lines (82 loc) · 2.52 KB
/
Copy pathserver.ts
File metadata and controls
97 lines (82 loc) · 2.52 KB
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
import express from 'express'
import cors from 'cors'
import * as fs from 'fs'
import path from 'path'
import { getLatestExportedState } from './core/exportState.js'
function isObjectRecord(input: unknown): input is Record<string, unknown> {
return typeof input === 'object' && input !== null && !Array.isArray(input)
}
function serializeState(value: unknown): string {
return JSON.stringify(
value,
(_key, nestedValue) => (typeof nestedValue === 'bigint' ? nestedValue.toString() : nestedValue),
)
}
function sendJsonSafely(res: express.Response, payload: unknown) {
try {
const serialized = serializeState(payload)
res.type('application/json').send(serialized)
} catch (err) {
console.error('STATE SERIALIZATION ERROR:', err)
res.json({ status: 'starting' })
}
}
export function startServer() {
console.log('STARTING EXPRESS')
const app = express()
app.use(cors())
const STATE_FILE = path.resolve('latest_state.json')
const PORT = Number(process.env.PORT) || 3000
const HOST = '0.0.0.0'
const COMMIT_SHA =
process.env.RAILWAY_GIT_COMMIT_SHA ||
process.env.GITHUB_SHA ||
process.env.VERCEL_GIT_COMMIT_SHA ||
'unknown'
app.get('/', (_req, res) => {
res.send('Backend alive')
})
app.get('/state', (_req, res) => {
const inMemoryState = getLatestExportedState()
if (isObjectRecord(inMemoryState)) {
sendJsonSafely(res, inMemoryState)
return
}
if (inMemoryState !== null) {
console.warn('STATE WARN: in-memory state malformed, falling back to file')
}
try {
const data = fs.readFileSync(STATE_FILE, 'utf-8')
const parsed: unknown = JSON.parse(data)
if (isObjectRecord(parsed)) {
sendJsonSafely(res, parsed)
return
}
console.warn('STATE WARN: file state malformed, returning starting status')
res.json({ status: 'starting' })
} catch (err) {
console.error('STATE ERROR:', err)
res.json({ status: 'starting' })
}
})
console.log('BOOT INFO:', {
commit: COMMIT_SHA,
node: process.version,
cwd: process.cwd(),
portEnv: process.env.PORT ?? 'undefined',
resolvedPort: PORT,
host: HOST,
stateFile: STATE_FILE,
startedAt: new Date().toISOString(),
})
const server = app.listen(PORT, HOST, () => {
console.log('API running on', PORT, 'on', HOST)
})
server.on('error', (error) => {
console.error('SERVER LISTEN ERROR:', error)
process.exit(1)
})
setTimeout(() => {
console.log('Self-test: server should be live now')
}, 2000)
}