-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.js
More file actions
329 lines (267 loc) · 11.5 KB
/
index.js
File metadata and controls
329 lines (267 loc) · 11.5 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
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
const domainReplacements = require('./domainReplacements.json');
const fs = require('fs');
const fastify = require('fastify')({
logger: false,
rewriteUrl: (request) => {
if (domainReplacements[request.headers.host]) {
return domainReplacements[request.headers.host] + request.url;
}
return request.url;
}
});
const lcache = require('fastify-lcache');
fastify.register(lcache, {
ttlInMinutes: 0.5, // set cached data lifetime to 30 seconds
//excludeRoutes: ['/']
});
require('dotenv').config();
const getAllKeysWithParents = (obj, parentKey = '') => {
let keys = [];
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
const currentKey = parentKey ? `${parentKey}/${key}` : key;
keys.push(currentKey);
if (typeof obj[key] === 'object') {
keys = keys.concat(getAllKeysWithParents(obj[key], currentKey));
}
}
}
return keys;
}
//ensuring the plugin(s) load before we start registering endpoints
fastify.after(() => {
const only_testing = [];
const exclude_from_root = ['gtfs_sch', 'gtfs_sch_acc', 'chicago_snowplow_routes', 'atlas_routes', 'amtrak_fetch_proxy', 'mbta']; // won't be returned to lighten the load, can be overridden
let data = {};
let data_reduced = {};
let data_configs = {};
// getting folders within scripts folder
const endpoints = fs.readdirSync('./endpoints');
if (process.env.PROXY_MODE == 'true') {
const updateInProxyMode = () => {
fetch('https://store.transitstat.us/?showAll=true')
.then((result) => {
if (result !== false) {
data = result;
console.log('Finished updating in proxy mode')
console.log(`Destroying /GET`)
fastify.lcache.reset(`/GET`)
}
})
};
updateInProxyMode();
setInterval(() => { updateInProxyMode() }, process.env.PROXY_MODE_INTERVAL ?? 60000);
} else { // normal operation
// going through endpoints and setting up update jobs
endpoints.forEach(async (endpoint) => {
if (only_testing.length > 0 && !only_testing.includes(endpoint)) return;
console.log(`Loading endpoint: ${endpoint}`);
if (fs.lstatSync(`./endpoints/${endpoint}`).isDirectory()) {
console.log(`${endpoint} is a directory`);
console.log(`Reading ${endpoint} config file`)
if (!fs.existsSync(`./endpoints/${endpoint}/config.json`)) {
console.log(`No config file found for ${endpoint}, not continuing`);
return;
}
const now = new Date();
const config = JSON.parse(fs.readFileSync(`./endpoints/${endpoint}/config.json`));
if (config) data_configs[endpoint] = {
...config,
lastUpdatedUnix: now.valueOf(),
lastUpdatedISO: now.toISOString(),
lastUpdatedUSLocale: now.toLocaleString(['en-US']),
}
if (config.disabled) {
console.log(`Endpoint ${endpoint} is disabled, skipping`)
return;
}
if (config.configVersion === undefined || config.configVersion === null) {
console.log(`No config version found for ${endpoint}, not continuing`);
return;
}
// included for possible future variations in config versions
switch (config.configVersion) {
case 0:
console.log(`Config version 0 detected for ${endpoint}`);
const updateV0 = require(`./endpoints/${endpoint}/${config.script}`).update;
data[endpoint] = structuredClone(config.default)
data_reduced[endpoint] = exclude_from_root.includes(endpoint) ? `Not returned due to large size. Visit '/${endpoint}' for data.` : structuredClone(config.default);
try {
updateV0()
.then((result) => {
if (result !== false) {
data[endpoint] = result;
data_reduced[endpoint] = exclude_from_root.includes(endpoint) ? `Not returned due to large size. Visit '/${endpoint}' for data.` : result;
const keys = getAllKeysWithParents(config.default);
console.log(`Destroying /${endpoint}GET`)
fastify.lcache.reset(`/${endpoint}GET`)
keys.forEach((key) => {
console.log(`Destroying /${endpoint}/${key}GET`)
fastify.lcache.reset(`/${endpoint}/${key}GET`)
})
}
})
} catch (e) {
console.log(`error updating data for ${endpoint}`);
console.log(e);
}
setInterval(() => {
try {
updateV0()
.then((result) => {
if (result === false) return;
data[endpoint] = result;
data_reduced[endpoint] = exclude_from_root.includes(endpoint) ? `Not returned due to large size. Visit '/${endpoint}' for data.` : result;
})
} catch (e) {
console.log(`error updating data for ${endpoint}`);
console.log(e);
}
}, config.interval);
break;
case 1:
console.log(`Config version 1 detected for ${endpoint}`);
const updateV1 = require(`./endpoints/${endpoint}/${config.script}`).update;
const variables = config.variables;
data[endpoint] = structuredClone(config.default);
data_reduced[endpoint] = exclude_from_root.includes(endpoint) ? `Not returned due to large size. Visit '/${endpoint}' for data.` : structuredClone(config.default);
try {
variables.forEach((variableSet) => updateV1(...variableSet)
.then((result) => {
if (result === false) return;
data[endpoint][variableSet[0]] = result;
if (!exclude_from_root.includes(endpoint)) data_reduced[endpoint][variableSet[0]] = result;
console.log(`Destroying /${endpoint}/${variableSet[0]}GET`)
fastify.lcache.reset(`/${endpoint}/${variableSet[0]}GET`);
}))
} catch (e) {
console.log(`error updating data for ${endpoint}`);
console.log(e);
}
setInterval(() => {
try {
variables.forEach((variableSet) => updateV1(...variableSet)
.then((result) => {
if (result === false) return;
data[endpoint][variableSet[0]] = result;
if (!exclude_from_root.includes(endpoint)) data_reduced[endpoint][variableSet[0]] = result;
}))
} catch (e) {
console.log(`error updating data for ${endpoint}`);
console.log(e);
}
}, config.interval);
break;
case 2:
console.log(`Config version 2 detected for ${endpoint}`);
const updateV2 = require(`./endpoints/${endpoint}/${config.script}`).update;
data[endpoint] = structuredClone(config.default);
data_reduced[endpoint] = exclude_from_root.includes(endpoint) ? `Not returned due to large size. Visit '/${endpoint}' for data.` : structuredClone(config.default);
try {
const initialState = await fetch(`https://store.transitstat.us/${endpoint}`)
.then((res) => res.json())
.catch((e) => {
return structuredClone(config.default); // earlier failure or issue
});
data[endpoint] = initialState;
data_reduced[endpoint] = exclude_from_root.includes(endpoint) ? `Not returned due to large size. Visit '/${endpoint}' for data.` : initialState;
updateV2({ firstUpdate: true })
.then((result) => {
if (result === false) {
data[endpoint] = initialState;
data_reduced[endpoint] = exclude_from_root.includes(endpoint) ? `Not returned due to large size. Visit '/${endpoint}' for data.` : initialState;
} else {
data[endpoint] = result;
data_reduced[endpoint] = exclude_from_root.includes(endpoint) ? `Not returned due to large size. Visit '/${endpoint}' for data.` : result;
const keys = getAllKeysWithParents(config.default);
console.log(`Destroying /${endpoint}GET`)
fastify.lcache.reset(`/${endpoint}GET`)
keys.forEach((key) => {
console.log(`Destroying /${endpoint}/${key}GET`)
fastify.lcache.reset(`/${endpoint}/${key}GET`)
})
}
})
} catch (e) {
console.log(`error updating data for ${endpoint}`);
console.log(e);
}
setInterval(() => {
try {
updateV2({ firstUpdate: false })
.then((result) => {
if (result === false) return;
data[endpoint] = result;
data_reduced[endpoint] = exclude_from_root.includes(endpoint) ? `Not returned due to large size. Visit '/${endpoint}' for data.` : result;
})
} catch (e) {
console.log(`error updating data for ${endpoint}`);
console.log(e);
}
}, config.interval);
break;
default:
console.log(`No known config version detected for ${endpoint}`);
break;
}
} else {
console.log(`${endpoint} is a file, not continuing`);
}
});
}
fastify.get('*', (request, reply) => {
let path = request.url.split('?')[0];
console.log(`Returning data for ${path}`)
if (path === '/') {
reply.header('Access-Control-Allow-Origin', '*');
if (request.query?.showAll == 'true') reply.send(data)
else reply.send(data_reduced);
return;
}
//remove leading slash first
const pathArray = path.substring(1).split('/');
let dataToReturn = data;
try {
pathArray.forEach((path) => {
if (path === '') return; //trailing slash
if (path === '_ts_store_meta') {
let roughSizesOfKeys = {};
Object.keys(dataToReturn).forEach((key) => {
roughSizesOfKeys[key] = JSON.stringify(dataToReturn[key]).length
});
dataToReturn = {
roughSize: JSON.stringify(dataToReturn).length,
roughSizesOfKeys,
config: data_configs[pathArray[0]] ?? null
};
return;
};
dataToReturn = dataToReturn[path];
if (dataToReturn === undefined) {
throw new Error('Not found');
}
});
} catch (e) {
//console.log(e);
console.log('Not found:', path)
reply.header('Access-Control-Allow-Origin', '*');
reply.code(404);
reply.send('Not found');
return;
}
reply.header('Access-Control-Allow-Origin', '*');
reply.send(dataToReturn);
});
//killing the cache's default state every 5 seconds for the first minute just in case the updates didn't go through above
//this isnt needed, but tbh i dont trust this cache implementation
for (let i = 5; i <= 60; i += 5) {
setTimeout(() => {
console.log('Hard resetting cache')
fastify.lcache.reset();
}, i * 1000)
}
});
fastify.listen({ port: process.env.PORT ?? 3000, host: '0.0.0.0', }, (err, address) => {
if (err) throw err
console.log(`Server is now listening on ${address}`);
})