-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathimport.js
More file actions
329 lines (301 loc) · 10.8 KB
/
import.js
File metadata and controls
329 lines (301 loc) · 10.8 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
import {fileURLToPath} from 'node:url'
import pgFormat from 'pg-format'
import {ok} from 'node:assert'
import {
readdir,
writeFile,
} from 'node:fs/promises'
import {
digestString,
digestFile,
pSpawn,
formatDbName,
getPgConfig,
getPgEnv,
connectToMetaDatabase,
successfulImportsTableName,
ensureSuccesfulImportsTableExists,
queryImports,
recordSuccessfulImport,
removeDbFromLatestSuccessfulImports,
} from './index.js'
// expose npm-installed local CLI tools to child processes
import {createRequire} from 'node:module'
import {
dirname,
join as pathJoin,
} from 'node:path'
// todo: use import.meta.resolve once it is stable?
// see https://nodejs.org/docs/latest-v20.x/api/esm.html#importmetaresolvespecifier
const require = createRequire(import.meta.url)
const GTFS_VIA_POSTGRES_PKG = require.resolve('gtfs-via-postgres/package.json')
const NPM_BIN_DIR = dirname(dirname(GTFS_VIA_POSTGRES_PKG)) + '/.bin'
const PATH_TO_IMPORT_SCRIPT = fileURLToPath(new URL('import.sh', import.meta.url).href)
const PATH_TO_DOWNLOAD_SCRIPT = fileURLToPath(new URL('download.sh', import.meta.url).href)
const importGtfsAtomically = async (cfg) => {
const {
logger,
downloadScriptVerbose,
connectDownloadScriptToStdout,
importScriptVerbose,
connectImportScriptToStdout,
databaseNamePrefix,
schemaName,
pathToImportScript,
pathToDownloadScript,
pathToDsnFile,
gtfsDownloadUrl,
gtfsDownloadUserAgent,
tmpDir,
gtfstidyBeforeImport,
determineDbsToRetain,
continueOnFailureDeletingOldDb,
gtfsPostprocessingDPath,
} = {
logger: console,
downloadScriptVerbose: true,
connectDownloadScriptToStdout: true,
importScriptVerbose: true,
connectImportScriptToStdout: true,
schemaName: process.env.GTFS_IMPORTER_SCHEMA || null,
pathToImportScript: process.env.GTFS_IMPORT_SCRIPT || PATH_TO_IMPORT_SCRIPT,
pathToDownloadScript: process.env.GTFS_DOWNLOAD_SCRIPT || PATH_TO_DOWNLOAD_SCRIPT,
pathToDsnFile: process.env.GTFS_IMPORTER_DSN_FILE || null,
gtfsDownloadUrl: null,
gtfsDownloadUserAgent: null,
tmpDir: process.env.GTFS_TMP_DIR || '/tmp/gtfs',
gtfstidyBeforeImport: null, // or `true` or `false`
determineDbsToRetain: (latestSuccessfulImports, oldDbs) => {
return latestSuccessfulImports.slice(0, 2).map(_import => _import.dbName)
},
continueOnFailureDeletingOldDb: process.env.GTFS_IMPORTED_CONTINUE_ON_FAILURE_DELETING_OLD_DB === 'true',
gtfsPostprocessingDPath: process.env.GTFS_POSTPROCESSING_D_PATH || '/etc/gtfs/postprocessing.d',
...cfg,
}
ok(databaseNamePrefix, 'missing/empty cfg.databaseNamePrefix')
ok(pathToImportScript, 'missing/empty cfg.pathToImportScript')
ok(gtfsDownloadUrl, 'missing/empty cfg.gtfsDownloadUrl')
ok(gtfsDownloadUserAgent, 'missing/empty cfg.gtfsDownloadUserAgent')
const result = {
downloadDurationMs: null,
deletedDatabases: [], // [dbName]
retainedDatabases: null, // [dbName]
importSkipped: false,
newImport: null, // or {dbName, importedAt, feedDigest}
importDurationMs: null,
}
// todo: DRY with lib.sh
const zipPath = `${tmpDir}/gtfs.zip`
logger.info(`downloading data to "${zipPath}"`)
const _t0Download = performance.now()
await pSpawn(pathToDownloadScript, [], {
stdio: [
'inherit',
connectDownloadScriptToStdout ? 'inherit' : 'ignore',
'inherit',
],
env: {
...process.env,
GTFS_TMP_DIR: tmpDir,
GTFS_DOWNLOAD_URL: gtfsDownloadUrl,
GTFS_DOWNLOAD_USER_AGENT: gtfsDownloadUserAgent,
GTFS_DOWNLOAD_VERBOSE: downloadScriptVerbose ? 'true' : 'false',
},
})
result.downloadDurationMs = performance.now() - _t0Download
const pgConfig = await getPgConfig(cfg)
const pgEnv = getPgEnv(pgConfig)
// `CREATE/DROP DATABASE` can't be run within the transation, so we need need a separate client for it.
// Thus, a newly created database also won't be removed if the transaction fails or is aborted, so we
// have to drop it manually when cleaning up failed/aborted imports.
const dbMngmtClient = await connectToMetaDatabase(cfg)
const client = await connectToMetaDatabase(cfg)
await ensureSuccesfulImportsTableExists({
db: client,
})
await client.query('BEGIN')
try {
logger.info(`obtaining exclusive lock on "${successfulImportsTableName}", so that only one import can be running`)
// https://www.postgresql.org/docs/14/explicit-locking.html#LOCKING-TABLES
// > Conflicts with the ROW SHARE, ROW EXCLUSIVE, SHARE UPDATE EXCLUSIVE, SHARE, SHARE ROW EXCLUSIVE, EXCLUSIVE, and ACCESS EXCLUSIVE lock modes. This mode allows only concurrent ACCESS SHARE locks, i.e., only reads from the table can proceed in parallel with a transaction holding this lock mode.
//> Only an ACCESS EXCLUSIVE lock blocks a SELECT (without FOR UPDATE/SHARE) statement.
await client.query(pgFormat('LOCK TABLE %I IN EXCLUSIVE MODE NOWAIT', successfulImportsTableName))
logger.debug('checking previous imports')
let {
latestSuccessfulImports,
allDbs,
} = await queryImports({
databaseNamePrefix,
db: client,
})
let prevImport = null
if (latestSuccessfulImports.length > 0) {
logger.info(`there are ${latestSuccessfulImports.length} (most recent) successful imports recorded in the bookkeeping DB: ${latestSuccessfulImports.map(imp => imp.dbName)}`)
prevImport = latestSuccessfulImports[0]
}
logger.debug('all DBs, including old/unfinished imports: ' + allDbs.join(', '))
for (let i = 0; i < latestSuccessfulImports.length; i++) {
const prevImport = latestSuccessfulImports[i]
if (!allDbs.includes(prevImport.dbName)) {
logger.warn(`The "${successfulImportsTableName}" table points to a DB "${prevImport.dbName}" which does not exist. This indicates either a bug in postgis-gtfs-importer, or that its state has been tampered with!`)
// remove from list
latestSuccessfulImports.splice(i, 1)
i--
}
}
{
const dbsToRetain = determineDbsToRetain(latestSuccessfulImports, allDbs)
ok(Array.isArray(dbsToRetain), 'determineDbsToRetain() must return an array')
logger.debug('dbs to retain: ' + dbsToRetain.join(', '))
result.retainedDatabases = dbsToRetain
for (const dbName of allDbs) {
if (dbsToRetain.includes(dbName)) {
continue;
}
const isRecentSuccessfulImport = latestSuccessfulImports.some(imp => imp.dbName === dbName)
if (isRecentSuccessfulImport) {
logger.info(`dropping database "${dbName}" containing a (recent) successful import`)
} else {
logger.info(`dropping database "${dbName}" containing an older or unfinished import`)
}
// todo: `WITH (FORCE)`? – https://stackoverflow.com/a/68982312/1072129
try {
await dbMngmtClient.query(pgFormat('DROP DATABASE %I', dbName))
result.deletedDatabases.push(dbName)
} catch (err) {
if (continueOnFailureDeletingOldDb) {
logger.warn({
error: err,
dbName,
}, `failed to delete old database "${dbName}"`)
} else {
throw err
}
}
if (isRecentSuccessfulImport) {
await removeDbFromLatestSuccessfulImports({
db: client,
dbName,
})
}
}
}
const zipDigest = await digestFile(zipPath)
let feedDigest = zipDigest
// if $GTFS_POSTPROCESSING_D_PATH contains files, hash them into `feedDigest`
if (gtfsPostprocessingDPath !== null) {
let files = []
// todo: DRY this with the postprocessing logic in import.js
try {
const allFiles = await readdir(gtfsPostprocessingDPath)
// Bash `*` globs ignore dotfiles
files = allFiles.filter(filename => filename[0] !== '.')
} catch (err) {
// allow the postprocessing.d directory to be missing
if (err.code !== 'ENOENT') {
throw err
}
}
if (files.length > 0) {
let filesDigest = ''
logger.debug(`adding ${files.length} files' hashes to feed_digest`)
for (const file of files) {
const path = pathJoin(gtfsPostprocessingDPath, file)
filesDigest += await digestFile(path)
}
feedDigest = digestString(feedDigest + filesDigest)
}
}
const importedAt = (Date.now() / 1000 | 0)
const dbName = formatDbName({
databaseNamePrefix,
importedAt,
feedDigest,
})
if (prevImport?.feedDigest === feedDigest) {
result.importSkipped = true
logger.info('GTFS feed digest has not changed, skipping import')
return result
}
result.newImport = {
dbName,
importedAt,
feedDigest,
}
logger.debug(`creating database "${dbName}"`)
await dbMngmtClient.query(pgFormat('CREATE DATABASE %I', dbName))
logger.info(`importing data into "${dbName}"`)
const _importEnv = {
...process.env,
...pgEnv,
PATH: NPM_BIN_DIR + ':' + process.env.PATH,
PGDATABASE: dbName,
GTFS_TMP_DIR: tmpDir,
GTFS_IMPORTER_VERBOSE: importScriptVerbose ? 'true' : 'false',
GTFS_FEED_DIGEST: feedDigest,
}
if (schemaName !== null) {
_importEnv.GTFS_IMPORTER_SCHEMA = schemaName
}
if (gtfstidyBeforeImport !== null) {
_importEnv.GTFSTIDY_BEFORE_IMPORT = String(gtfstidyBeforeImport)
}
if (gtfsPostprocessingDPath !== null) {
_importEnv.GTFS_POSTPROCESSING_D_PATH = gtfsPostprocessingDPath
}
const _t0Import = performance.now()
await pSpawn(pathToImportScript, [], {
stdio: [
'inherit',
connectImportScriptToStdout ? 'inherit' : 'ignore',
'inherit',
],
env: _importEnv,
})
result.importDurationMs = performance.now() - _t0Import
logger.debug(`import succeeded in ${Math.round(result.importDurationMs / 1000)}s`)
logger.info(`marking the import into "${dbName}" as the latest`)
await recordSuccessfulImport({
db: client,
successfulImport: {
dbName,
importedAt,
feedDigest,
},
})
if (pathToDsnFile !== null) {
// https://www.pgbouncer.org/config.html#section-databases
// https://www.postgresql.org/docs/15/libpq-connect.html#id-1.7.3.8.3.5
const {
PGHOST,
PGPORT,
POSTGREST_USER,
POSTGREST_PASSWORD,
} = process.env
ok(PGHOST, 'missing/empty $PGHOST')
ok(PGPORT, 'missing/empty $PGPORT')
// todo: why `POSTGREST_`? rename to e.g. `PGBOUNCER_`?
ok(POSTGREST_USER, 'missing/empty $POSTGREST_USER')
ok(POSTGREST_PASSWORD, 'missing/empty $POSTGREST_PASSWORD')
const dsn = `gtfs=host=${PGHOST} port=${PGPORT} dbname=${dbName} user=${POSTGREST_USER} password=${POSTGREST_PASSWORD}`
const logDsn = `gtfs=host=${PGHOST} port=${PGPORT} dbname=${dbName} user=${POSTGREST_USER} password=${POSTGREST_PASSWORD.slice(0, 2)}…${POSTGREST_PASSWORD.slice(-2)}`
logger.debug(`writing "${logDsn}" into env file ${pathToDsnFile}`)
await writeFile(pathToDsnFile, dsn)
}
logger.info(`import succeeded, committing all changes to "${successfulImportsTableName}"!`)
await client.query('COMMIT')
} catch (err) {
logger.warn('an error occured, rolling back')
// The newly created DB will remain, potentially with data inside. But it will be cleaned up during the next run.
await client.query('ROLLBACK')
throw err
} finally {
dbMngmtClient.end()
client.end()
}
logger.debug('done!')
return result
}
export {
importGtfsAtomically,
}