-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathserver.js
More file actions
143 lines (121 loc) · 4.82 KB
/
Copy pathserver.js
File metadata and controls
143 lines (121 loc) · 4.82 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
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
import dotenv from 'dotenv';
import express from 'express';
import { fireAndForget, postJson, putJson } from '../shared/http.js';
import { verifyInternalSignedRequest } from '../shared/internalSignature.js';
import { isInterruptedEvent, isStartEvent, isStopEvent } from '../shared/regions.js';
import { captureRawBody } from '../shared/zoomSignature.js';
import { createRtmsObservabilityLogger } from '../shared/rtmsObservabilityLogger.js';
dotenv.config();
const app = express();
const port = Number(process.env.SPOKE_PORT || 4200);
const regionCode = process.env.SPOKE_REGION || 'IAD';
const regionalStoreUrl = process.env.REGIONAL_STORE_URL || process.env.CENTRAL_STORE_URL || 'http://127.0.0.1:4100';
const internalWebhookSecret = process.env.INTERNAL_WEBHOOK_SECRET || process.env.SPOKE_WEBHOOK_SECRET;
const internalTimestampToleranceSeconds = Number(process.env.INTERNAL_WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS || 300);
const computeEndpoints = parseComputeEndpoints();
const localEvents = [];
let nextComputeIndex = 0;
const logger = createRtmsObservabilityLogger({
service: 'regional-webhook-spoke',
regionCode,
nodeId: process.env.NODE_ID || `spoke-${regionCode}-${process.pid}`,
level: process.env.SERVICE_LOG_LEVEL || process.env.RTMS_LOG_LEVEL || 'info',
console: process.env.SERVICE_LOG_CONSOLE !== 'false'
});
app.use(express.json({ verify: captureRawBody, limit: '10mb' }));
app.get('/health', (_req, res) => {
res.json({
ok: true,
service: 'regional-webhook-spoke',
regionCode,
internalSignatureVerification: 'required',
internalTimestampToleranceSeconds,
regionalStoreUrl,
computeEndpoints
});
});
app.get('/local/events', (_req, res) => {
res.json({ events: localEvents.slice(-200) });
});
app.post('/spoke/webhook', (req, res) => {
const envelope = req.body || {};
const verification = verifyInternalSignedRequest(req, internalWebhookSecret, {
toleranceSeconds: internalTimestampToleranceSeconds
});
if (!verification.ok) {
const status = verification.reason === 'missing_internal_webhook_secret' ? 500 : 401;
logger.warn(`[03-regional-webhook-spoke] rejected internal webhook reason=${verification.reason}`);
return res.status(status).json({ error: 'invalid_internal_webhook', reason: verification.reason });
}
if (!envelope.streamId || !envelope.event) {
return res.status(400).json({ error: 'missing_event_or_stream_id' });
}
remember(envelope);
res.sendStatus(202);
fireAndForget(handleRegionalEnvelope(envelope), `regional dispatch ${envelope.streamId || 'unknown'}`);
});
async function handleRegionalEnvelope(envelope) {
await persistRegionalEnvelope(envelope);
await dispatchToCompute(envelope);
}
async function persistRegionalEnvelope(envelope) {
if (!envelope.streamId || !envelope.event) return;
if (isStartEvent(envelope.event)) {
await putJson(`${regionalStoreUrl}/streams/${encodeURIComponent(envelope.streamId)}/route`, {
regionCode,
selectedRegionCode: envelope.regionCode || regionCode,
productType: envelope.productType,
rtmsId: envelope.rtmsId,
envelope,
webhook: envelope.webhook || { event: envelope.event, payload: envelope.payload }
}, { timeoutMs: 3000 });
return;
}
if (isStopEvent(envelope.event)) {
await postJson(`${regionalStoreUrl}/streams/${encodeURIComponent(envelope.streamId)}/state`, {
state: 'stop_requested',
stopEnvelope: envelope
}, { timeoutMs: 3000 });
return;
}
if (isInterruptedEvent(envelope.event)) {
await postJson(`${regionalStoreUrl}/streams/${encodeURIComponent(envelope.streamId)}/state`, {
state: 'recovery_requested',
recoveryEnvelope: envelope,
recoveryRequestedAt: new Date().toISOString()
}, { timeoutMs: 3000 });
}
}
async function dispatchToCompute(envelope) {
if (computeEndpoints.length === 0) {
throw new Error('No compute endpoints configured');
}
const endpoint = computeEndpoints[nextComputeIndex % computeEndpoints.length];
nextComputeIndex += 1;
logger.info(`[03-regional-webhook-spoke] stream=${envelope.streamId} -> ${endpoint}`);
await postJson(endpoint, envelope, { timeoutMs: 3000 });
}
function remember(envelope) {
localEvents.push({
event: envelope.event,
streamId: envelope.streamId,
regionCode: envelope.regionCode,
receivedAt: new Date().toISOString()
});
if (localEvents.length > 1000) {
localEvents.splice(0, localEvents.length - 1000);
}
}
function parseComputeEndpoints() {
if (!process.env.COMPUTE_ENDPOINTS) {
return ['http://127.0.0.1:4300/compute/webhook'];
}
try {
return JSON.parse(process.env.COMPUTE_ENDPOINTS);
} catch (error) {
throw new Error(`Invalid COMPUTE_ENDPOINTS JSON: ${error.message}`);
}
}
app.listen(port, () => {
logger.info(`[03-regional-webhook-spoke] ${regionCode} listening on http://127.0.0.1:${port}/spoke/webhook`);
});