Repository navigation
Expand file tree
/
Copy pathacled.js
More file actions
200 lines (178 loc) · 5.42 KB
/
Copy pathacled.js
File metadata and controls
200 lines (178 loc) · 5.42 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
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
// ACLED API proxy - keeps token server-side only
// Token is stored in ACLED_ACCESS_TOKEN (no VITE_ prefix)
import { getCorsHeaders, isDisallowedOrigin } from './_cors.js';
import { getCachedJson, setCachedJson } from './_upstash-cache.js';
import { recordCacheTelemetry } from './_cache-telemetry.js';
import { createIpRateLimiter } from './_ip-rate-limit.js';
export const config = { runtime: 'edge' };
const CACHE_KEY = 'acled:protests:v2';
const CACHE_TTL_SECONDS = 10 * 60;
const CACHE_TTL_MS = CACHE_TTL_SECONDS * 1000;
// In-memory fallback cache when Redis is unavailable.
let fallbackCache = { data: null, timestamp: 0 };
const RATE_LIMIT = 10; // requests per minute
const RATE_WINDOW_MS = 60 * 1000;
const rateLimiter = createIpRateLimiter({
limit: RATE_LIMIT,
windowMs: RATE_WINDOW_MS,
maxEntries: 5000,
});
function getClientIp(req) {
return req.headers.get('x-forwarded-for')?.split(',')[0] ||
req.headers.get('x-real-ip') ||
'unknown';
}
function toErrorMessage(error) {
if (error instanceof Error) return error.message;
return String(error || 'unknown error');
}
export default async function handler(req) {
const corsHeaders = getCorsHeaders(req, 'GET, OPTIONS');
if (req.method === 'OPTIONS') {
if (isDisallowedOrigin(req)) {
return new Response(null, { status: 403, headers: corsHeaders });
}
return new Response(null, { status: 204, headers: corsHeaders });
}
if (req.method !== 'GET') {
return Response.json({ error: 'Method not allowed', data: [] }, {
status: 405,
headers: corsHeaders,
});
}
if (isDisallowedOrigin(req)) {
return Response.json({ error: 'Origin not allowed', data: [] }, {
status: 403,
headers: corsHeaders,
});
}
const ip = getClientIp(req);
if (!rateLimiter.check(ip)) {
return Response.json({ error: 'Rate limited', data: [] }, {
status: 429,
headers: {
...corsHeaders,
'Retry-After': '60',
},
});
}
const token = process.env.ACLED_ACCESS_TOKEN;
if (!token) {
return Response.json({
error: 'ACLED not configured',
data: [],
configured: false,
}, {
status: 200,
headers: corsHeaders,
});
}
const now = Date.now();
const cached = await getCachedJson(CACHE_KEY);
if (cached && typeof cached === 'object' && Array.isArray(cached.data)) {
recordCacheTelemetry('/api/acled', 'REDIS-HIT');
return Response.json(cached, {
status: 200,
headers: {
...corsHeaders,
'Cache-Control': 'public, max-age=300',
'X-Cache': 'REDIS-HIT',
},
});
}
if (fallbackCache.data && now - fallbackCache.timestamp < CACHE_TTL_MS) {
recordCacheTelemetry('/api/acled', 'MEMORY-HIT');
return Response.json(fallbackCache.data, {
status: 200,
headers: {
...corsHeaders,
'Cache-Control': 'public, max-age=300',
'X-Cache': 'MEMORY-HIT',
},
});
}
try {
const endDate = new Date().toISOString().split('T')[0];
const startDate = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
const params = new URLSearchParams({
event_type: 'Protests',
event_date: `${startDate}|${endDate}`,
event_date_where: 'BETWEEN',
limit: '500',
_format: 'json',
});
const response = await fetch(`https://acleddata.com/api/acled/read?${params}`, {
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`,
},
});
if (!response.ok) {
const text = await response.text();
return Response.json({
error: `ACLED API error: ${response.status}`,
details: text.substring(0, 200),
data: [],
}, {
status: response.status,
headers: corsHeaders,
});
}
const rawData = await response.json();
const events = Array.isArray(rawData?.data) ? rawData.data : [];
const sanitizedEvents = events.map((e) => ({
event_id_cnty: e.event_id_cnty,
event_date: e.event_date,
event_type: e.event_type,
sub_event_type: e.sub_event_type,
actor1: e.actor1,
actor2: e.actor2,
country: e.country,
admin1: e.admin1,
location: e.location,
latitude: e.latitude,
longitude: e.longitude,
fatalities: e.fatalities,
notes: typeof e.notes === 'string' ? e.notes.substring(0, 500) : undefined,
source: e.source,
tags: e.tags,
}));
const result = {
success: true,
count: sanitizedEvents.length,
data: sanitizedEv
531A
ents,
cached_at: new Date().toISOString(),
};
fallbackCache = { data: result, timestamp: now };
void setCachedJson(CACHE_KEY, result, CACHE_TTL_SECONDS);
recordCacheTelemetry('/api/acled', 'MISS');
return Response.json(result, {
status: 200,
headers: {
...corsHeaders,
'Cache-Control': 'public, max-age=300',
'X-Cache': 'MISS',
},
});
} catch (error) {
if (fallbackCache.data) {
recordCacheTelemetry('/api/acled', 'STALE');
return Response.json(fallbackCache.data, {
status: 200,
headers: {
...corsHeaders,
'Cache-Control': 'public, max-age=60',
'X-Cache': 'STALE',
},
});
}
recordCacheTelemetry('/api/acled', 'ERROR');
return Response.json({
error: `Fetch failed: ${toErrorMessage(error)}`,
data: [],
}, {
status: 500,
headers: corsHeaders,
});
}
}