Repository navigation
Expand file tree
/
Copy pathucdp.js
More file actions
145 lines (127 loc) · 4.41 KB
/
Copy pathucdp.js
File metadata and controls
145 lines (127 loc) · 4.41 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
// UCDP (Uppsala Conflict Data Program) proxy
// Returns conflict classification per country with intensity levels
// No auth required - public API
export const config = { runtime: 'edge' };
import { getCachedJson, setCachedJson } from './_upstash-cache.js';
import { recordCacheTelemetry } from './_cache-telemetry.js';
const CACHE_KEY = 'ucdp:country-conflicts:v2';
const CACHE_TTL_SECONDS = 24 * 60 * 60; // 24 hours (annual data)
const CACHE_TTL_MS = CACHE_TTL_SECONDS * 1000;
const RESPONSE_CACHE_CONTROL = 'public, max-age=3600';
// In-memory fallback when Redis is unavailable.
let fallbackCache = { data: null, timestamp: 0 };
function isValidResult(data) {
return Boolean(
data &&
typeof data === 'object' &&
Array.isArray(data.conflicts)
);
}
function toErrorMessage(error) {
if (error instanceof Error) return error.message;
return String(error || 'unknown error');
}
export default async function handler(req) {
const now = Date.now();
const cached = await getCachedJson(CACHE_KEY);
if (isValidResult(cached)) {
recordCacheTelemetry('/api/ucdp', 'REDIS-HIT');
return Response.json(cached, {
status: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Cache-Control': RESPONSE_CACHE_CONTROL,
'X-Cache': 'REDIS-HIT',
},
});
}
if (isValidResult(fallbackCache.data) && now - fallbackCache.timestamp < CACHE_TTL_MS) {
recordCacheTelemetry('/api/ucdp', 'MEMORY-HIT');
return Response.json(fallbackCache.data, {
status: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Cache-Control': RESPONSE_CACHE_CONTROL,
'X-Cache': 'MEMORY-HIT',
},
});
}
try {
// Fetch all pages of conflicts
let allConflicts = [];
let page = 0;
let totalPages = 1;
while (page < totalPages) {
const response = await fetch(`https://ucdpapi.pcr.uu.se/api/ucdpprioconflict/24.1?pagesize=100&page=${page}`, {
headers: { 'Accept': 'application/json' },
});
if (!response.ok) {
throw new Error(`UCDP API error: ${response.status}`);
}
const rawData = await response.json();
totalPages = rawData.TotalPages || 1;
const conflicts = rawData.Result || [];
allConflicts = allConflicts.concat(conflicts);
page++;
}
// Fields are snake_case: conflict_id, location, side_a, side_b, year, intensity_level, type_of_conflict
const countryConflicts = {};
for (const c of allConflicts) {
const name = c.location || '';
const year = parseInt(c.year, 10) || 0;
const intensity = parseInt(c.intensity_level, 10) || 0;
const entry = {
conflictId: parseInt(c.conflict_id, 10) || 0,
conflictName: c.side_b || '',
location: name,
year,
intensityLevel: intensity,
typeOfConflict: parseInt(c.type_of_conflict, 10) || 0,
startDate: c.start_date,
startDate2: c.start_date2,
sideA: c.side_a,
sideB: c.side_b,
region: c.region,
};
// Keep most recent / highest intensity per location
if (!countryConflicts[name] || year > countryConflicts[name].year ||
(year === countryConflicts[name].year && intensity > countryConflicts[name].intensityLevel)) {
countryConflicts[name] = entry;
}
}
const result = {
success: true,
count: Object.keys(countryConflicts).length,
conflicts: Object.values(countryConflicts),
cached_at: new Date().toISOString(),
};
fallbackCache = { data: result, timestamp: now };
void setCachedJson(CACHE_KEY, result, CACHE_TTL_SECONDS);
recordCacheTelemetry('/api/ucdp', 'MISS');
return Response.json(result, {
status: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Cache-Control': RESPONSE_CACHE_CONTROL,
'X-Cache': 'MISS',
},
});
} catch (error) {
if (isValidResult(fallbackCache.data)) {
recordCacheTelemetry('/api/ucdp', 'STALE');
return Response.json(fallbackCache.data, {
status: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Cache-Control': 'public, max-age=600',
'X-Cache': 'STALE',
},
});
}
recordCacheTelemetry('/api/ucdp', 'ERROR');
return Response.json({ error: `Fetch failed: ${toErrorMessage(error)}`, conflicts: [] }, {
status: 500,
headers: { 'Access-Control-Allow-Origin': '*' },
});
}
}