1 /* eslint-disable security/detect-object-injection */
4 const pgpInitOptions
= {
8 const path
= require('path');
9 const pgp
= require('pg-promise')(pgpInitOptions
);
10 const svh
= require('../schema-version-helper');
11 const Database
= require('../base');
12 const DBErrors
= require('../errors');
13 const Listener
= require('./listener');
14 const common
= require('../../common');
16 const _fileScope
= common
.fileScope(__filename
);
18 const PGTypeIdINT8
= 20; // Type Id 20 == INT8 (BIGINT)
19 const PGTYpeIdINT8Array
= 1016; //Type Id 1016 == INT8[] (BIGINT[])
20 pgp
.pg
.types
.setTypeParser(PGTypeIdINT8
, BigInt
); // Type Id 20 = INT8 (BIGINT)
21 const parseBigIntArray
= pgp
.pg
.types
.getTypeParser(PGTYpeIdINT8Array
); // Type Id 1016 = INT8[] (BIGINT[])
22 pgp
.pg
.types
.setTypeParser(PGTYpeIdINT8Array
, (a
) => parseBigIntArray(a
).map(BigInt
));
24 const schemaVersionsSupported
= {
37 class DatabasePostgres
extends Database
{
38 constructor(logger
, options
, _pgp
= pgp
) {
39 super(logger
, options
);
41 this.db
= _pgp(options
.db
.connectionString
);
42 this.schemaVersionsSupported
= schemaVersionsSupported
;
44 // Suppress QF warnings when running tests
45 this.noWarnings
= options
.db
.noWarnings
;
47 if (options
.db
.cacheEnabled
) {
48 this.listener
= new Listener(logger
, this.db
, {
49 ...options
.db
.listener
,
50 channel: 'topic_changed',
51 dataCallback: this._topicChanged
.bind(this),
52 connectionEstablishedCallback: this._listenerEstablished
.bind(this),
53 connectionLostCallback: this._listenerLost
.bind(this),
58 const queryLogLevel
= options
.db
.queryLogLevel
;
60 pgpInitOptions
.query
= (event
) => {
61 // Quell outgoing pings
62 if (event
?.query
?.startsWith('NOTIFY')) {
65 this.logger
[queryLogLevel
](_fileScope('pgp:query'), '', { ...common
.pick(event
|| {}, ['query', 'params']) });
70 pgpInitOptions
.error
= (err
, event
) => {
71 this.logger
.error(_fileScope('pgp:error'), '', { err
, event
});
73 // TODO: close connection on err.code === '57P03' database shutting down
76 // Deophidiate column names in-place, log results
77 pgpInitOptions
.receive
= ({ data
, result
, ctx: event
}) => {
78 const exemplaryRow
= data
[0];
79 for (const prop
in exemplaryRow
) {
80 const camel
= Database
._camelfy(prop
);
81 if (!(camel
in exemplaryRow
)) {
82 for (const d
of data
) {
89 // Quell outgoing pings
90 if (result
&& result
.command
=== 'NOTIFY') {
94 const resultLog
= common
.pick(result
|| {}, ['command', 'rowCount', 'duration']);
95 this.logger
[queryLogLevel
](_fileScope('pgp:result'), '', { query: event
.query
, ...resultLog
});
99 // Expose these for test coverage
100 this.pgpInitOptions
= pgpInitOptions
;
103 this._initStatements(_pgp
);
107 _queryFileHelper(_pgp
) {
109 const _scope
= _fileScope('_queryFile');
110 /* istanbul ignore next */
113 ...(this.noWarnings
&& { noWarnings: this.noWarnings
}),
115 const qf
= new _pgp
.QueryFile(file
, qfParams
);
117 this.logger
.error(_scope
, 'failed to create SQL statement', { error: qf
.error
, file
});
125 async
initialize(applyMigrations
= true) {
126 const _scope
= _fileScope('initialize');
127 this.logger
.debug(_scope
, 'called', { applyMigrations
});
128 if (applyMigrations
) {
129 await
this._initTables();
131 await
super.initialize();
133 await
this.listener
.start();
138 async
_initTables(_pgp
) {
139 const _scope
= _fileScope('_initTables');
140 this.logger
.debug(_scope
, 'called', {});
142 const _queryFile
= this._queryFileHelper(_pgp
|| this._pgp
);
144 // Migrations rely upon this table, ensure it exists.
145 const metaVersionTable
= '_meta_schema_version';
147 const tableExists
= async (name
) => this.db
.oneOrNone('SELECT table_name FROM information_schema.tables WHERE table_name=$(name)', { name
});
148 let metaExists
= await
tableExists(metaVersionTable
);
150 const fPath
= path
.join(__dirname
, 'sql', 'schema', 'init.sql');
151 const initSql
= _queryFile(fPath
);
152 const results
= await
this.db
.multiResult(initSql
);
153 this.logger
.debug(_scope
, 'executed init sql', { results
});
154 metaExists
= await
tableExists(metaVersionTable
);
155 /* istanbul ignore if */
157 throw new DBErrors
.UnexpectedResult(`did not create ${metaVersionTable} table`);
159 this.logger
.info(_scope
, 'created schema version table', { metaVersionTable
});
163 const currentSchema
= await
this._currentSchema();
164 const migrationsWanted
= svh
.unappliedSchemaVersions(__dirname
, currentSchema
, this.schemaVersionsSupported
);
165 this.logger
.debug(_scope
, 'schema migrations wanted', { migrationsWanted
});
166 for (const v
of migrationsWanted
) {
167 const fPath
= path
.join(__dirname
, 'sql', 'schema', v
, 'apply.sql');
169 const migrationSql
= _queryFile(fPath
);
170 this.logger
.debug(_scope
, 'applying migration', { version: v
});
171 const results
= await
this.db
.multiResult(migrationSql
);
172 this.logger
.debug(_scope
, 'migration results', { results
});
173 this.logger
.info(_scope
, 'applied migration', { version: v
});
175 this.logger
.error(_scope
, 'migration failed', { error: e
, fPath
, version: v
});
182 _initStatements(_pgp
) {
183 const _scope
= _fileScope('_initStatements');
184 const _queryFile
= this._queryFileHelper(_pgp
);
185 this.statement
= _pgp
.utils
.enumSql(path
.join(__dirname
, 'sql'), {}, _queryFile
);
186 this.logger
.debug(_scope
, 'statements initialized', { statements: Object
.keys(this.statement
).length
});
190 async
healthCheck() {
191 const _scope
= _fileScope('healthCheck');
192 this.logger
.debug(_scope
, 'called', {});
193 const c
= await
this.db
.connect();
195 return { serverVersion: c
.client
.serverVersion
};
199 async
_currentSchema() {
200 return this.db
.one('SELECT major, minor, patch FROM _meta_schema_version ORDER BY major DESC, minor DESC, patch DESC LIMIT 1');
204 async
_closeConnection() {
205 const _scope
= _fileScope('_closeConnection');
208 await
this.listener
.stop();
210 await
this._pgp
.end();
212 this.logger
.error(_scope
, 'failed', { error: e
});
218 /* istanbul ignore next */
219 async
_purgeTables(really
= false) {
220 const _scope
= _fileScope('_purgeTables');
223 await
this.db
.tx(async (t
) => {
226 // 'topic_fetch_in_progress',
228 // 'verification_in_progress',
230 // 'subscription_delivery_in_progress',
231 ].map(async (table
) => t
.query('TRUNCATE TABLE $(table:name) CASCADE', { table
})));
235 this.logger
.error(_scope
, 'failed', { error: e
});
241 // eslint-disable-next-line class-methods-use-this
242 _engineInfo(result
) {
244 changes: result
.rowCount
,
245 lastInsertRowid: result
.rows
.length
? result
.rows
[0].id : undefined,
246 duration: result
.duration
,
251 // eslint-disable-next-line class-methods-use-this
253 return common
.pick(result
, ['command', 'rowCount', 'duration']);
258 * Receive notices when topic entry is updated.
259 * Clear relevant cache entry.
260 * @param {string} payload topic changed event
262 _topicChanged(payload
) {
263 const _scope
= _fileScope('_topicChanged');
264 if (payload
!== 'ping') {
265 this.logger
.debug(_scope
, 'called', { payload
});
266 this.cache
.delete(payload
);
272 * Called when a listener connection is opened.
275 _listenerEstablished() {
276 const _scope
= _fileScope('_listenerEstablished');
277 this.logger
.debug(_scope
, 'called', {});
278 this.cache
= new Map();
283 * Called when a listener connection is closed.
287 const _scope
= _fileScope('_listenerLost');
288 this.logger
.debug(_scope
, 'called', {});
294 * Return a cached entry, if available.
296 * @returns {object=} cached data
299 const _scope
= _fileScope('_cacheGet');
300 if (this.cache
?.has(key
)) {
301 const cacheEntry
= this.cache
.get(key
);
302 this.logger
.debug(_scope
, 'found cache entry', { key
, ...common
.pick(cacheEntry
, ['added', 'hits', 'lastHit']) });
303 cacheEntry
.hits
+= 1;
304 cacheEntry
.lastHit
= new Date();
305 return cacheEntry
.data
;
311 * Store an entry in cache, if available.
313 * @param {*} data data
315 _cacheSet(key
, data
) {
316 const _scope
= _fileScope('_cacheSet');
318 this.cache
.set(key
, {
324 this.logger
.debug(_scope
, 'added cache entry', { key
});
330 return this.db
.task(async (t
) => fn(t
));
334 // eslint-disable-next-line class-methods-use-this
335 async
transaction(dbCtx
, fn
) {
336 return dbCtx
.txIf(async (t
) => fn(t
));
340 async
authenticationSuccess(dbCtx
, identifier
) {
341 const _scope
= _fileScope('authenticationSuccess');
342 this.logger
.debug(_scope
, 'called', { identifier
});
346 result
= await dbCtx
.result(this.statement
.authenticationSuccess
, { identifier
});
347 if (result
.rowCount
!= 1) {
348 throw new DBErrors
.UnexpectedResult('did not update authentication success event');
351 this.logger
.error(_scope
, 'failed', { error: e
, identifier
});
357 async
authenticationGet(dbCtx
, identifier
) {
358 const _scope
= _fileScope('authenticationGet');
359 this.logger
.debug(_scope
, 'called', { identifier
});
363 auth
= await dbCtx
.oneOrNone(this.statement
.authenticationGet
, { identifier
});
366 this.logger
.error(_scope
, 'failed', { error: e
, identifier
});
372 async
authenticationUpsert(dbCtx
, identifier
, credential
) {
373 const _scope
= _fileScope('authenticationUpsert');
374 const scrubbedCredential
= '*'.repeat((credential
|| '').length
);
375 this.logger
.debug(_scope
, 'called', { identifier
, scrubbedCredential
});
379 result
= await dbCtx
.result(this.statement
.authenticationUpsert
, { identifier
, credential
});
380 if (result
.rowCount
!= 1) {
381 throw new DBErrors
.UnexpectedResult('did not upsert authentication');
384 this.logger
.error(_scope
, 'failed', { error: e
, identifier
, scrubbedCredential
});
390 async
subscriptionsByTopicId(dbCtx
, topicId
) {
391 const _scope
= _fileScope('subscriptionsByTopicId');
392 this.logger
.debug(_scope
, 'called', { topicId
});
396 count
= await dbCtx
.manyOrNone(this.statement
.subscriptionsByTopicId
, { topicId
});
399 this.logger
.error(_scope
, 'failed', { error: e
, topicId
});
405 async
subscriptionCountByTopicUrl(dbCtx
, topicUrl
) {
406 const _scope
= _fileScope('subscriptionCountByTopicUrl');
407 this.logger
.debug(_scope
, 'called', { topicUrl
});
411 count
= await dbCtx
.one(this.statement
.subscriptionCountByTopicUrl
, { topicUrl
});
414 this.logger
.error(_scope
, 'failed', { error: e
, topicUrl
});
420 async
subscriptionDelete(dbCtx
, callback
, topicId
) {
421 const _scope
= _fileScope('subscriptionDelete');
422 this.logger
.debug(_scope
, 'called', { callback
, topicId
});
425 const result
= await dbCtx
.result(this.statement
.subscriptionDelete
, { callback
, topicId
});
426 return this._engineInfo(result
);
428 this.logger
.error(_scope
, 'failed', { error: e
, callback
, topicId
});
434 async
subscriptionDeleteExpired(dbCtx
, topicId
) {
435 const _scope
= _fileScope('subscriptionDeleteExpired');
436 this.logger
.debug(_scope
, 'called', { topicId
});
439 const result
= await dbCtx
.result(this.statement
.subscriptionDeleteExpired
, { topicId
});
440 this.logger
.debug(_scope
, 'success', { topicId
, deleted: result
.rowCount
});
441 return this._engineInfo(result
);
443 this.logger
.error(_scope
, 'failed', { error: e
, topicId
});
449 async
subscriptionDeliveryClaim(dbCtx
, wanted
, claimTimeoutSeconds
, claimant
) {
450 const _scope
= _fileScope('subscriptionDeliveryClaim');
451 this.logger
.debug(_scope
, 'called', { wanted
, claimTimeoutSeconds
, claimant
});
454 const claims
= await dbCtx
.txIf(async (txCtx
) => {
455 return txCtx
.manyOrNone(this.statement
.subscriptionDeliveryClaim
, { claimant
, wanted
, claimTimeoutSeconds
});
457 return claims
.map((r
) => r
.id
);
459 this.logger
.error(_scope
, 'failed', { error: e
, claimant
, wanted
, claimTimeoutSeconds
});
465 async
subscriptionDeliveryClaimById(dbCtx
, subscriptionId
, claimTimeoutSeconds
, claimant
) {
466 const _scope
= _fileScope('subscriptionDeliveryClaimById');
467 this.logger
.debug(_scope
, 'called', { subscriptionId
, claimTimeoutSeconds
, claimant
});
471 result
= await dbCtx
.txIf(async (txCtx
) => {
472 result
= await txCtx
.result(this.statement
.subscriptionDeliveryClaimById
, { claimant
, subscriptionId
, claimTimeoutSeconds
});
473 if (result
.rowCount
!= 1) {
474 throw new DBErrors
.UnexpectedResult('did not claim subscription delivery');
478 return this._engineInfo(result
);
480 this.logger
.error(_scope
, 'failed', { error: e
, claimant
, subscriptionId
, claimTimeoutSeconds
});
486 async
subscriptionDeliveryComplete(dbCtx
, callback
, topicId
, topicContentUpdated
) {
487 const _scope
= _fileScope('subscriptionDeliveryComplete');
488 this.logger
.debug(_scope
, 'called', { callback
, topicId
, topicContentUpdated
});
492 await dbCtx
.txIf(async (txCtx
) => {
493 result
= await txCtx
.result(this.statement
.subscriptionDeliverySuccess
, { callback
, topicId
, topicContentUpdated
});
494 if (result
.rowCount
!= 1) {
495 throw new DBErrors
.UnexpectedResult('did not set subscription delivery success');
497 result
= await txCtx
.result(this.statement
.subscriptionDeliveryDone
, { callback
, topicId
});
498 if (result
.rowCount
!= 1) {
499 throw new DBErrors
.UnexpectedResult('did not release subscription delivery');
503 this.logger
.error(_scope
, 'failed', { error: e
, callback
, topicId
, topicContentUpdated
});
509 async
subscriptionDeliveryGone(dbCtx
, callback
, topicId
) {
510 const _scope
= _fileScope('subscriptionDeliveryGone');
511 this.logger
.debug(_scope
, 'called', { callback
, topicId
});
515 await dbCtx
.txIf(async (txCtx
) => {
516 result
= await txCtx
.result(this.statement
.subscriptionDelete
, { callback
, topicId
});
517 if (result
.rowCount
!= 1) {
518 throw new DBErrors
.UnexpectedResult('did not delete subscription');
520 // Delete cascades to delivery
521 // result = await txCtx.result(this.statement.subscriptionDeliveryDone, { callback, topicId });
522 // if (result.rowCount != 1) {
523 // throw new DBErrors.UnexpectedResult('did not release subscription delivery');
527 this.logger
.error(_scope
, 'failed', { error: e
, callback
, topicId
});
533 async
subscriptionDeliveryIncomplete(dbCtx
, callback
, topicId
, retryDelays
= [60]) {
534 const _scope
= _fileScope('subscriptionDeliveryIncomplete');
535 this.logger
.debug(_scope
, 'called', { callback
, topicId
, retryDelays
});
539 await dbCtx
.txIf(async (txCtx
) => {
540 const { currentAttempt
} = await txCtx
.one(this.statement
.subscriptionDeliveryAttempts
, { callback
, topicId
});
541 const nextAttemptDelaySeconds
= common
.attemptRetrySeconds(currentAttempt
, retryDelays
);
542 result
= await txCtx
.result(this.statement
.subscriptionDeliveryFailure
, { nextAttemptDelaySeconds
, callback
, topicId
});
543 if (result
.rowCount
!= 1) {
544 throw new DBErrors
.UnexpectedResult('did not set subscription delivery failure');
546 result
= await txCtx
.result(this.statement
.subscriptionDeliveryDone
, { callback
, topicId
});
547 if (result
.rowCount
!= 1) {
548 throw new DBErrors
.UnexpectedResult('did not release subscription delivery');
552 this.logger
.error(_scope
, 'failed', { error: e
, callback
, topicId
});
558 async
subscriptionGet(dbCtx
, callback
, topicId
) {
559 const _scope
= _fileScope('subscriptionGet');
560 this.logger
.debug(_scope
, 'called', { callback
, topicId
});
564 subscription
= await dbCtx
.oneOrNone(this.statement
.subscriptionGet
, { callback
, topicId
});
567 this.logger
.error(_scope
, 'failed', { error: e
, callback
, topicId
});
573 async
subscriptionGetById(dbCtx
, subscriptionId
) {
574 const _scope
= _fileScope('subscriptionGetById');
575 this.logger
.debug(_scope
, 'called', { subscriptionId
});
579 subscription
= await dbCtx
.oneOrNone(this.statement
.subscriptionGetById
, { subscriptionId
});
582 this.logger
.error(_scope
, 'failed', { error: e
, subscriptionId
});
588 async
subscriptionUpdate(dbCtx
, data
) {
589 const _scope
= _fileScope('subscriptionUpdate');
590 this.logger
.debug(_scope
, 'called', { data
});
592 const subscriptionData
= {
596 this._subscriptionUpdateDataValidate(subscriptionData
);
600 result
= await dbCtx
.result(this.statement
.subscriptionUpdate
, subscriptionData
);
601 if (result
.rowCount
!= 1) {
602 throw new DBErrors
.UnexpectedResult('did not update subscription');
605 this.logger
.error(_scope
, 'failed', { error: e
, subscriptionData
});
611 async
subscriptionUpsert(dbCtx
, data
) {
612 const _scope
= _fileScope('subscriptionUpsert');
613 this.logger
.debug(_scope
, 'called', { ...data
});
615 const subscriptionData
= {
617 httpRemoteAddr: null,
621 this._subscriptionUpsertDataValidate(subscriptionData
);
625 result
= await dbCtx
.result(this.statement
.subscriptionUpsert
, subscriptionData
);
626 if (result
.rowCount
!= 1) {
627 throw new DBErrors
.UnexpectedResult('did not upsert subscription');
629 return this._engineInfo(result
);
631 this.logger
.error(_scope
, 'failed', { error: e
, subscriptionData
});
637 async
topicDeleted(dbCtx
, topicId
) {
638 const _scope
= _fileScope('topicDeleted');
639 this.logger
.debug(_scope
, 'called', { topicId
});
643 result
= await dbCtx
.result(this.statement
.topicDeleted
, { topicId
});
644 if (result
.rowCount
!= 1) {
645 throw new DBErrors
.UnexpectedResult('did not update topic as deleted');
648 this.logger
.error(_scope
, 'failed to update topic as deleted', { error: e
, topicId
});
654 async
topicFetchClaim(dbCtx
, wanted
, claimTimeoutSeconds
, claimant
) {
655 const _scope
= _fileScope('topicFetchClaim');
656 this.logger
.debug(_scope
, 'called', { wanted
, claimTimeoutSeconds
});
660 await dbCtx
.txIf(async (txCtx
) => {
661 claims
= await txCtx
.manyOrNone(this.statement
.topicContentFetchClaim
, { claimant
, wanted
, claimTimeoutSeconds
});
663 return claims
.map((r
) => r
.id
);
665 this.logger
.error(_scope
, 'failed to claim topics for fetch', { error: e
});
671 async
topicFetchClaimById(dbCtx
, topicId
, claimTimeoutSeconds
, claimant
) {
672 const _scope
= _fileScope('topicFetchClaimById');
673 this.logger
.debug(_scope
, 'called', { topicId
, claimTimeoutSeconds
, claimant
});
677 await dbCtx
.txIf(async (txCtx
) => {
678 result
= await txCtx
.result(this.statement
.topicContentFetchClaimById
, { topicId
, claimant
, claimTimeoutSeconds
});
680 return this._engineInfo(result
);
682 this.logger
.error(_scope
, 'failed', { error: e
, topicId
});
688 async
topicFetchComplete(dbCtx
, topicId
) {
689 const _scope
= _fileScope('topicFetchComplete');
690 this.logger
.debug(_scope
, 'called', { topicId
});
694 await dbCtx
.txIf(async (txCtx
) => {
695 result
= await txCtx
.result(this.statement
.topicAttemptsReset
, { topicId
});
696 if (result
.rowCount
!= 1) {
697 throw new DBErrors
.UnexpectedResult('did not reset topic attempts');
699 result
= await txCtx
.result(this.statement
.topicContentFetchDone
, { topicId
});
700 if (result
.rowCount
!= 1) {
701 throw new DBErrors
.UnexpectedResult('did not release topic fetch');
704 this.logger
.debug(_scope
, 'success', { topicId
, ...this._resultLog(result
) });
705 return this._engineInfo(result
);
707 this.logger
.error(_scope
, 'failed', { error: e
, result
, topicId
});
713 async
topicFetchIncomplete(dbCtx
, topicId
, retryDelays
= [60]) {
714 const _scope
= _fileScope('topicFetchIncomplete');
715 this.logger
.debug(_scope
, 'called', { topicId
});
719 result
= await dbCtx
.txIf(async (txCtx
) => {
720 const { contentFetchAttemptsSinceSuccess: currentAttempt
} = await txCtx
.one(this.statement
.topicAttempts
, { topicId
});
721 const nextAttemptDelaySeconds
= common
.attemptRetrySeconds(currentAttempt
, retryDelays
);
722 result
= await txCtx
.result(this.statement
.topicAttemptsIncrement
, { topicId
, nextAttemptDelaySeconds
});
723 if (result
.rowCount
!= 1) {
724 throw new DBErrors
.UnexpectedResult('did not set topic attempts');
726 result
= await txCtx
.result(this.statement
.topicContentFetchDone
, { topicId
});
727 if (result
.rowCount
!= 1) {
728 throw new DBErrors
.UnexpectedResult('did not release topic fetch');
732 this.logger
.debug(_scope
, 'success', { topicId
, ...this._resultLog(result
) });
733 return this._engineInfo(result
);
735 this.logger
.error(_scope
, 'failed', { error: e
, result
, topicId
});
741 async
topicFetchRequested(dbCtx
, topicId
) {
742 const _scope
= _fileScope('topicFetchRequested');
743 this.logger
.debug(_scope
, 'called', { topicId
});
747 result
= await dbCtx
.result(this.statement
.topicContentFetchRequested
, { topicId
});
748 if (result
.rowCount
!= 1) {
749 throw new DBErrors
.UnexpectedResult('did not set topic fetch requested');
751 this.logger
.debug(_scope
, 'success', { topicId
, ...this._resultLog(result
) });
752 return this._engineInfo(result
);
754 this.logger
.error(_scope
, 'failed', { error: e
, topicId
});
760 async
topicGetAll(dbCtx
) {
761 const _scope
= _fileScope('topicGetAll');
762 this.logger
.debug(_scope
, 'called');
766 topics
= await dbCtx
.manyOrNone(this.statement
.topicGetInfoAll
);
768 this.logger
.error(_scope
, 'failed', { error: e
, topics
});
772 topics
= topics
.map(this._topicDefaults
.bind(this));
778 async
topicGetById(dbCtx
, topicId
, applyDefaults
= true) {
779 const _scope
= _fileScope('topicGetById');
780 this.logger
.debug(_scope
, 'called', { topicId
});
784 topic
= await dbCtx
.oneOrNone(this.statement
.topicGetById
, { topicId
});
786 topic
= this._topicDefaults(topic
);
790 this.logger
.error(_scope
, 'failed', { error: e
, topic
, topicId
});
796 async
topicGetByUrl(dbCtx
, topicUrl
, applyDefaults
= true) {
797 const _scope
= _fileScope('topicGetByUrl');
798 this.logger
.debug(_scope
, 'called', { topicUrl
});
802 topic
= await dbCtx
.oneOrNone(this.statement
.topicGetByUrl
, { topicUrl
});
804 topic
= this._topicDefaults(topic
);
808 this.logger
.error(_scope
, 'failed', { error: e
, topic
, topicUrl
});
814 async
topicGetContentById(dbCtx
, topicId
) {
815 const _scope
= _fileScope('topicGetContentById');
816 this.logger
.debug(_scope
, 'called', { topicId
});
820 topic
= this._cacheGet(topicId
);
824 topic
= await dbCtx
.oneOrNone(this.statement
.topicGetContentById
, { topicId
});
825 const topicWithDefaults
= this._topicDefaults(topic
);
826 this._cacheSet(topicId
, topicWithDefaults
);
827 return topicWithDefaults
;
829 this.logger
.error(_scope
, 'failed', { error: e
, topic
, topicId
});
835 async
topicPendingDelete(dbCtx
, topicId
) {
836 const _scope
= _fileScope('topicPendingDelete');
837 this.logger
.debug(_scope
, 'called', { topicId
});
840 await dbCtx
.txIf(async (txCtx
) => {
841 const topic
= await txCtx
.one(this.statement
.topicGetById
, { topicId
});
842 if (!topic
.isDeleted
) {
843 this.logger
.debug(_scope
, 'topic not set deleted, not deleting', { topicId
});
847 const { count: subscriberCount
} = await txCtx
.one(this.statement
.subscriptionCountByTopicUrl
, { topicUrl: topic
.url
});
848 if (subscriberCount
) {
849 this.logger
.debug(_scope
, 'topic has subscribers, not deleting', { topicId
, subscriberCount
});
853 const result
= await txCtx
.result(this.statement
.topicDeleteById
, { topicId
});
854 if (result
.rowCount
!== 1) {
855 throw new DBErrors
.UnexpectedResult('did not delete topic');
858 this.logger
.debug(_scope
, 'success', { topicId
});
860 this.logger
.error(_scope
, 'failed', { error: e
, topicId
});
866 async
topicPublishHistory(dbCtx
, topicId
, days
) {
867 const _scope
= _fileScope('topicPublishHistory');
868 this.logger
.debug(_scope
, 'called', { topicId
, days
});
870 const events
= await dbCtx
.manyOrNone(this.statement
.topicPublishHistory
, { topicIds: [topicId
], daysAgo: days
});
871 const history
= Array
.from({ length: days
}, () => 0);
872 events
.forEach(({ daysAgo
, contentUpdates
}) => history
[daysAgo
] = Number(contentUpdates
));
878 async
topicSet(dbCtx
, data
) {
879 const _scope
= _fileScope('topicSet');
880 this.logger
.debug(_scope
, 'called', data
);
882 const topicSetData
= {
883 publisherValidationUrl: null,
884 leaseSecondsPreferred: null,
885 leaseSecondsMin: null,
886 leaseSecondsMax: null,
892 this._topicSetDataValidate(topicSetData
);
893 result
= await dbCtx
.result(this.statement
.topicUpsert
, topicSetData
);
894 if (result
.rowCount
!= 1) {
895 throw new DBErrors
.UnexpectedResult('did not set topic data');
897 this.logger
.debug(_scope
, 'success', { topicSetData
, ...this._resultLog(result
) });
898 return this._engineInfo(result
);
900 this.logger
.error(_scope
, 'failed', { error: e
, result
});
906 async
topicSetContent(dbCtx
, data
) {
907 const _scope
= _fileScope('topicSetContent');
908 const topicSetContentData
= {
911 httpLastModified: null,
915 ...topicSetContentData
,
916 content: common
.logTruncate(topicSetContentData
.content
, 100),
918 this.logger
.debug(_scope
, 'called', data
);
922 this._topicSetContentDataValidate(topicSetContentData
);
923 result
= await dbCtx
.result(this.statement
.topicSetContent
, topicSetContentData
);
924 logData
.result
= this._resultLog(result
);
925 if (result
.rowCount
!= 1) {
926 throw new DBErrors
.UnexpectedResult('did not set topic content');
928 result
= await dbCtx
.result(this.statement
.topicSetContentHistory
, {
929 topicId: data
.topicId
,
930 contentHash: data
.contentHash
,
931 contentSize: data
.content
.length
,
933 if (result
.rowCount
!= 1) {
934 throw new DBErrors
.UnexpectedResult('did not set topic content history');
936 this.logger
.debug(_scope
, 'success', { ...logData
});
937 return this._engineInfo(result
);
939 this.logger
.error(_scope
, 'failed', { error: e
, ...logData
});
945 async
topicUpdate(dbCtx
, data
) {
946 const _scope
= _fileScope('topicUpdate');
947 this.logger
.debug(_scope
, 'called', { data
});
950 leaseSecondsPreferred: null,
951 leaseSecondsMin: null,
952 leaseSecondsMax: null,
953 publisherValidationUrl: null,
957 this._topicUpdateDataValidate(topicData
);
961 result
= await dbCtx
.result(this.statement
.topicUpdate
, topicData
);
962 if (result
.rowCount
!= 1) {
963 throw new DBErrors
.UnexpectedResult('did not update topic');
966 this.logger
.error(_scope
, 'failed', { error: e
, topicData
});
972 async
verificationClaim(dbCtx
, wanted
, claimTimeoutSeconds
, claimant
) {
973 const _scope
= _fileScope('verificationClaim');
974 this.logger
.debug(_scope
, 'called', { wanted
, claimTimeoutSeconds
});
978 await dbCtx
.txIf(async (txCtx
) => {
979 result
= await txCtx
.manyOrNone(this.statement
.verificationClaim
, { claimant
, wanted
, claimTimeoutSeconds
});
981 return result
.map((r
) => r
.id
);
983 this.logger
.error(_scope
, 'failed', { wanted
, claimTimeoutSeconds
});
990 async
verificationClaimById(dbCtx
, verificationId
, claimTimeoutSeconds
, claimant
) {
991 const _scope
= _fileScope('verificationClaimById');
992 this.logger
.debug(_scope
, 'called', { verificationId
, claimant
, claimTimeoutSeconds
});
996 await dbCtx
.txIf(async (txCtx
) => {
997 result
= await txCtx
.result(this.statement
.verificationClaimById
, { verificationId
, claimant
, claimTimeoutSeconds
});
999 return this._engineInfo(result
);
1001 this.logger
.error(_scope
, 'failed', { verificationId
, claimant
, claimTimeoutSeconds
});
1007 async
verificationComplete(dbCtx
, verificationId
, callback
, topicId
) {
1008 const _scope
= _fileScope('verificationComplete');
1009 this.logger
.debug(_scope
, 'called', { verificationId
});
1013 await dbCtx
.txIf(async (txCtx
) => {
1014 result
= await txCtx
.result(this.statement
.verificationScrub
, { verificationId
, callback
, topicId
});
1015 if (result
.rowCount
< 1) {
1016 throw new DBErrors
.UnexpectedResult('did not remove verifications');
1020 this.logger
.error(_scope
, 'failed', { verificationId
});
1023 return this._engineInfo(result
);
1027 async
verificationGetById(dbCtx
, verificationId
) {
1028 const _scope
= _fileScope('verificationGetById');
1029 this.logger
.debug(_scope
, 'called', { verificationId
});
1033 verification
= await dbCtx
.oneOrNone(this.statement
.verificationGetById
, { verificationId
});
1034 return verification
;
1036 this.logger
.error(_scope
, 'failed', { error: e
, verificationId
});
1042 async
verificationIncomplete(dbCtx
, verificationId
, retryDelays
= [60]) {
1043 const _scope
= _fileScope('verificationIncomplete');
1044 this.logger
.debug(_scope
, 'called', { verificationId
});
1048 await dbCtx
.txIf(async (txCtx
) => {
1049 const { attempts
} = await txCtx
.one(this.statement
.verificationAttempts
, { verificationId
});
1050 const nextAttemptDelaySeconds
= common
.attemptRetrySeconds(attempts
, retryDelays
);
1051 result
= await txCtx
.result(this.statement
.verificationAttemptIncrement
, { verificationId
, nextAttemptDelaySeconds
});
1052 if (result
.rowCount
!= 1) {
1053 throw new DBErrors
.UnexpectedResult('did not update verification attempts');
1055 result
= await txCtx
.result(this.statement
.verificationDone
, { verificationId
});
1056 if (result
.rowCount
!= 1) {
1057 throw new DBErrors
.UnexpectedResult('did not release verification');
1061 this.logger
.error(_scope
, 'failed', { error: e
, verificationId
});
1067 async
verificationInsert(dbCtx
, verification
) {
1068 const _scope
= _fileScope('verificationInsert');
1069 this.logger
.debug(_scope
, 'called', { verification
});
1071 const verificationData
= {
1073 httpRemoteAddr: null,
1079 let result
, verificationId
;
1081 this._verificationDataValidate(verificationData
);
1082 result
= await dbCtx
.result(this.statement
.verificationInsert
, verificationData
);
1083 if (result
.rowCount
!= 1) {
1084 throw new DBErrors
.UnexpectedResult('did not insert verification');
1086 verificationId
= result
.rows
[0].id
;
1087 this.logger
.debug(_scope
, 'inserted verification', { verificationId
});
1089 return verificationId
;
1091 this.logger
.error(_scope
, 'failed', { error: e
, verificationData
});
1097 async
verificationRelease(dbCtx
, verificationId
) {
1098 const _scope
= _fileScope('verificationRelease');
1099 this.logger
.debug(_scope
, 'called', { verificationId
});
1103 result
= await dbCtx
.result(this.statement
.verificationDone
, { verificationId
});
1104 if (result
.rowCount
!= 1) {
1105 throw new DBErrors
.UnexpectedResult('did not release verification');
1107 return this._engineInfo(result
);
1109 this.logger
.error(_scope
, 'failed', { error: e
, verificationId
});
1115 async
verificationUpdate(dbCtx
, verificationId
, data
) {
1116 const _scope
= _fileScope('verificationUpdate');
1117 this.logger
.debug(_scope
, 'called', { verificationId
, data
});
1119 const verificationData
= {
1127 this._verificationUpdateDataValidate(verificationData
);
1128 result
= await dbCtx
.result(this.statement
.verificationUpdate
, verificationData
);
1129 if (result
.rowCount
!= 1) {
1130 throw new DBErrors
.UnexpectedResult('did not update verification');
1133 this.logger
.error(_scope
, 'failed', { error: e
, verificationData
});
1139 async
verificationValidated(dbCtx
, verificationId
) {
1140 const _scope
= _fileScope('verificationValidated');
1141 this.logger
.debug(_scope
, 'called', { verificationId
});
1145 result
= await dbCtx
.result(this.statement
.verificationValidate
, { verificationId
});
1146 if (result
.rowCount
!= 1) {
1147 throw new DBErrors
.UnexpectedResult('did not set verification validation');
1150 this.logger
.error(_scope
, 'failed', { error: e
, verificationId
});
1157 module
.exports
= DatabasePostgres
;