-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.js
305 lines (252 loc) · 9.63 KB
/
api.js
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
import Urlon from "urlon";
import * as path from 'path';
import {
datasetBranchCommitMapping,
datasetVersionReaderInstances,
syncStatus,
syncDatasetsIfNotAlreadySyncing,
getAllowedDatasetEntryFromSlug
} from "./datasetManagement.js";
import redirectLogic from "./api-redirect-logic.js"
import { recordEvent, retrieveEvents, retrieveEvent, backupEvents, resetEvents } from "./event-analytics.js";
import DDFCsvReader from "@vizabi/reader-ddfcsv";
import { getHeapStatistics } from 'v8';
import { allowedDatasets } from "./allowedDatasets.js";
import Log from "./logger.js"
const liveSince = (new Date()).valueOf();
export default function initRoutes(api) {
/*
* Fetch events
*/
api.get("/events", async (ctx, next) => {
Log.debug("Received a request to list all events");
ctx.status = 200; //not cached through cloudflare cache rule
ctx.body = JSON.stringify(retrieveEvents());
});
/*
* Backup events
*/
api.get("/backupevents/:filename([-a-z_0-9]+)?", async (ctx, next) => {
Log.debug("Received a request to backup events");
let filename = ctx.params.filename || "manual-backup";
ctx.status = 200; //not cached through cloudflare cache rule
const backupStatus = await backupEvents({filename, timestamp: true});
ctx.body = JSON.stringify(backupStatus);
});
/*
* Reset events
*/
api.get("/resetevents", async (ctx, next) => {
Log.debug("Received a request to reset all events");
ctx.status = 200; //not cached through cloudflare cache rule
const resetStatus = await resetEvents();
ctx.body = JSON.stringify(resetStatus);
});
/*
* Check server status, allowed and available datasets
*/
api.get("/status/:dataset([-a-z_0-9]+)?", async (ctx, next) => {
let datasetSlug = ctx.params.dataset;
if (!datasetSlug) {
Log.debug("Received a general status request");
const {heapTotal, heapUsed} = process.memoryUsage();
const {heap_size_limit} = getHeapStatistics();
const toMB = (b) => Math.round(b/1024/1024);
const memory = {
limit_MB: toMB(heap_size_limit),
heapTotal_MB: toMB(heapTotal),
heapUsed_MB: toMB(heapUsed),
heapTotal_PCT:Math.round(heapTotal/heap_size_limit * 100),
heapUsed_PCT: Math.round(heapUsed/heap_size_limit * 100)
}
ctx.status = 200;
ctx.body = JSON.stringify({
server: {
name: "small-waffle",
uptime_ms: (new Date()).valueOf() - liveSince,
liveSince,
memory,
smallWaffleVersion: process.env.npm_package_version,
DDFCSVReaderVersion: DDFCsvReader.version,
DDFCSVReaderVersionInfo: DDFCsvReader.versionInfo
},
allowedDatasets,
availableDatasets: Object.keys(datasetBranchCommitMapping).length ? datasetBranchCommitMapping : "No datasets on the server"
})
} else {
Log.debug(`Received a status requests for ${datasetSlug}`);
const bcm = datasetBranchCommitMapping[datasetSlug];
if (bcm){
ctx.status = 200;
ctx.body = bcm;
} else {
ctx.throw(404, `Dataset not found: ${datasetSlug}`)
}
}
});
/*
* Sync the dataset metadata and files between disk, memory and GitHub
*/
api.get("/sync/:datasetSlug([-a-z_0-9]+)?", async (ctx, next) => {
const datasetSlug = ctx.params.datasetSlug;
const result = syncDatasetsIfNotAlreadySyncing(datasetSlug);
ctx.status = 200;
ctx.body = result;
});
/*
* Check sync progress
*/
api.get("/syncprogress", async (ctx, next) => {
ctx.status = 200;
ctx.body = syncStatus;
});
/*
* Get dataset info
*/
api.get("/info/:datasetSlug([-a-z_0-9]+)?/:branch([-a-z_0-9]+)?/:commit([-a-z_0-9]+)?", async (ctx, next) => {
const datasetSlug = ctx.params.datasetSlug;
const branch = ctx.params.branch;
const commit = ctx.params.commit;
const referer = ctx.request.headers['referer'];
Log.debug(`Received an info request for ${datasetSlug}/${branch}/${commit}`);
const {status, error, redirect, success, cacheControl} = await redirectLogic({
params: ctx.params,
queryString: ctx.queryString,
type: "info",
referer,
redirectPrefix: `/info/${datasetSlug}/`,
callback: async ({success, error})=>{
const readerInstance = datasetVersionReaderInstances[datasetSlug][branch];
if (!readerInstance)
return error("NO_READER_INSTANCE");
try {
const data = await readerInstance.getDatasetInfo();
return success(data);
} catch (err) {
return error(err);
}
}
});
ctx.status = status;
ctx.set('Cache-Control', cacheControl);
if (error) ctx.throw(status, error);
if (redirect) ctx.redirect(redirect);
if (success) ctx.body = success;
});
/*
* Get assets
*/
api.get("/open-numbers/(.*)", async (ctx, next) => {
//koa-static failed to catch an /open-numbers route, so it came here
ctx.status = 404;
ctx.body = 'Asset not found';
});
api.get("/:datasetSlug([-a-z_0-9]+)?/:branch([-a-z_0-9]+)?/:commit([-a-z_0-9]+)?/assets/:asset([-a-z_0-9.]+)?", async (ctx, next) => {
const datasetSlug = ctx.params.datasetSlug;
const branch = ctx.params.branch;
const commit = ctx.params.commit;
const asset = ctx.params.asset;
const referer = ctx.request.headers['referer'];
const eventTemplate = {type: "asset", asset, datasetSlug, branch, referer};
const {status, error, redirect, success, cacheControl} = await redirectLogic({
params: ctx.params,
queryString: ctx.queryString,
type: "asset",
referer,
redirectPrefix: `/${datasetSlug}/`,
redirectSuffix: `/assets/${asset}/`,
getValidationError: () => {
return !asset ? "ASSET_NOT_PROVIDED" : false;
},
callback: async ({redirect})=>{
const dataset = getAllowedDatasetEntryFromSlug(datasetSlug);
const assetPath = path.join("/" + dataset.id, branch, 'assets', asset);
const cacheControl = "public, s-maxage=31536000, max-age=14400";
recordEvent({...eventTemplate, status: 302, comment: "Serving asset from a resolved path", redirect: assetPath, branch, commit});
return redirect(assetPath, cacheControl);
}
});
ctx.status = status;
ctx.set('Cache-Control', cacheControl);
if (error) ctx.throw(status, error);
if (redirect) ctx.redirect(redirect);
if (success) ctx.body = success;
});
/*
* Get data
*/
api.get("/:datasetSlug([-a-z_0-9]+)?/:branch([-a-z_0-9]+)?/:commit([-a-z_0-9]+)?", async (ctx, next) => {
const datasetSlug = ctx.params.datasetSlug;
const branch = ctx.params.branch;
const commit = ctx.params.commit;
const queryString = ctx.querystring;
const referer = ctx.request.headers['referer'];
const eventTemplate = {type: "query", datasetSlug, branch, queryString, referer};
const {status, error, redirect, success, cacheControl} = await redirectLogic({
params: ctx.params,
queryString: queryString,
type: "query",
referer,
redirectPrefix: `/${datasetSlug}/`,
getValidationError: () => {
if ((typeof queryString !== "string") || queryString.length < 2)
return "NO_QUERY_PROVIDED";
try {
Urlon.parse(decodeURIComponent(queryString));
} catch (err) {
return "QUERY_PARSING_ERROR";
}
return false;
},
callback: async ({success, error})=>{
const readerInstance = datasetVersionReaderInstances[datasetSlug][branch];
if (!readerInstance)
return error("NO_READER_INSTANCE");
try {
const ddfQuery = Urlon.parse(decodeURIComponent(queryString));
if (ddfQuery.test500error)
throw "Deliberate 500 error";
if (ddfQuery.from === "datapoints" && !ddfQuery.join && (datasetSlug == "population" || datasetSlug == "povcalnet") ) {
recordEvent({...eventTemplate, status: 200, comment: "Bomb query, empty response", branch, commit});
return success({
header: ddfQuery.select.key.concat(ddfQuery.select.value),
rows: [],
version: "",
comment: "👋 this is not the query you are looking for"
})
}
const event = retrieveEvent(eventTemplate);
if (!event) Log.info(`New query to reader --- ${datasetSlug}/${commit}?${queryString}`);
const timeStart = new Date().valueOf();
//ACTUAL READER WORK IS HERE
const data = await readerInstance.read(ddfQuery);
data.version = commit;
const timeEnd = new Date().valueOf();
const timing = timeEnd - timeStart;
recordEvent({...eventTemplate, status: 200, comment: "Resolved query", branch, commit, timing});
return success(data);
} catch (err) {
return error(err);
}
}
});
ctx.status = status;
ctx.set('Cache-Control', cacheControl);
if (error) ctx.throw(status, error);
if (redirect) ctx.redirect(redirect);
if (success) ctx.body = success;
});
// api.get("(.*)", async (ctx, next) => {
// if (ctx.url.includes("#api0=true")) {
// ctx.status = 404;
// ctx.body = 'Not Found';
// Log.error(`API catch-all route '*' has aborted infinite loop of API version upgrades after 1 iteration, request ${ctx.url} got a 404`);
// return;
// }
// ctx.set('Cache-Control', "public, s-maxage=31536000, max-age=14400");
// ctx.status = 302;
// const separator = ctx.url.includes('?') ? '&' : '?';
// ctx.redirect(`/api1${ctx.url}#api0=true`);
// });
return api;
}