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
, Object
.assign({}, options
.db
.listener
, {
49 channel: 'topic_changed',
50 dataCallback: this._topicChanged
.bind(this),
51 connectionEstablishedCallback: this._listenerEstablished
.bind(this),
52 connectionLostCallback: this._listenerLost
.bind(this),
57 const queryLogLevel
= options
.db
.queryLogLevel
;
59 pgpInitOptions
.query
= (event
) => {
60 // Quell outgoing pings
61 if (event
&& event
.query
&& event
.query
.startsWith('NOTIFY')) {
64 this.logger
[queryLogLevel
](_fileScope('pgp:query'), '', { ...common
.pick(event
, ['query', 'params']) });
69 pgpInitOptions
.error
= (err
, event
) => {
70 this.logger
.error(_fileScope('pgp:error'), '', { err
, event
});
73 // Deophidiate column names in-place, log results
74 pgpInitOptions
.receive
= (data
, result
, event
) => {
75 const exemplaryRow
= data
[0];
76 for (const prop
in exemplaryRow
) {
77 const camel
= Database
._camelfy(prop
);
78 if (!(camel
in exemplaryRow
)) {
79 for (const d
of data
) {
86 // Quell outgoing pings
87 if (result
&& result
.command
=== 'NOTIFY') {
91 const resultLog
= common
.pick(result
, ['command', 'rowCount', 'duration']);
92 this.logger
[queryLogLevel
](_fileScope('pgp:result'), '', { query: event
.query
, ...resultLog
});
96 // Expose these for test coverage
97 this.pgpInitOptions
= pgpInitOptions
;
100 this._initStatements(_pgp
);
104 _queryFileHelper(_pgp
) {
106 const _scope
= _fileScope('_queryFile');
107 /* istanbul ignore next */
110 ...(this.noWarnings
&& { noWarnings: this.noWarnings
}),
112 const qf
= new _pgp
.QueryFile(file
, qfParams
);
114 this.logger
.error(_scope
, 'failed to create SQL statement', { error: qf
.error
, file
});
122 async
initialize(applyMigrations
= true) {
123 const _scope
= _fileScope('initialize');
124 this.logger
.debug(_scope
, 'called', { applyMigrations
});
125 if (applyMigrations
) {
126 await
this._initTables();
128 await
super.initialize();
130 await
this.listener
.start();
135 async
_initTables(_pgp
) {
136 const _scope
= _fileScope('_initTables');
137 this.logger
.debug(_scope
, 'called', {});
139 const _queryFile
= this._queryFileHelper(_pgp
|| this._pgp
);
141 // Migrations rely upon this table, ensure it exists.
142 const metaVersionTable
= '_meta_schema_version';
144 const tableExists
= async (name
) => this.db
.oneOrNone('SELECT table_name FROM information_schema.tables WHERE table_name=$(name)', { name
});
145 let metaExists
= await
tableExists(metaVersionTable
);
147 const fPath
= path
.join(__dirname
, 'sql', 'schema', 'init.sql');
148 const initSql
= _queryFile(fPath
);
149 const results
= await
this.db
.multiResult(initSql
);
150 this.logger
.debug(_scope
, 'executed init sql', { results
});
151 metaExists
= await
tableExists(metaVersionTable
);
152 /* istanbul ignore if */
154 throw new DBErrors
.UnexpectedResult(`did not create ${metaVersionTable} table`);
156 this.logger
.info(_scope
, 'created schema version table', { metaVersionTable
});
160 const currentSchema
= await
this._currentSchema();
161 const migrationsWanted
= svh
.unappliedSchemaVersions(__dirname
, currentSchema
, this.schemaVersionsSupported
);
162 this.logger
.debug(_scope
, 'schema migrations wanted', { migrationsWanted
});
163 for (const v
of migrationsWanted
) {
164 const fPath
= path
.join(__dirname
, 'sql', 'schema', v
, 'apply.sql');
165 const migrationSql
= _queryFile(fPath
);
166 const results
= await
this.db
.multiResult(migrationSql
);
167 this.logger
.debug(_scope
, 'executed migration sql', { version: v
, results
});
168 this.logger
.info(_scope
, 'applied migration', { version: v
});
173 _initStatements(_pgp
) {
174 const _scope
= _fileScope('_initStatements');
175 const _queryFile
= this._queryFileHelper(_pgp
);
176 this.statement
= _pgp
.utils
.enumSql(path
.join(__dirname
, 'sql'), {}, _queryFile
);
177 this.logger
.debug(_scope
, 'statements initialized', { statements: Object
.keys(this.statement
).length
});
181 async
healthCheck() {
182 const _scope
= _fileScope('healthCheck');
183 this.logger
.debug(_scope
, 'called', {});
184 const c
= await
this.db
.connect();
186 return { serverVersion: c
.client
.serverVersion
};
190 async
_currentSchema() {
191 return this.db
.one('SELECT major, minor, patch FROM _meta_schema_version ORDER BY major DESC, minor DESC, patch DESC LIMIT 1');
195 async
_closeConnection() {
196 const _scope
= _fileScope('_closeConnection');
199 await
this.listener
.stop();
201 await
this._pgp
.end();
203 this.logger
.error(_scope
, 'failed', { error: e
});
209 /* istanbul ignore next */
210 async
_purgeTables(really
= false) {
211 const _scope
= _fileScope('_purgeTables');
214 await
this.db
.tx(async (t
) => {
217 // 'topic_fetch_in_progress',
219 // 'verification_in_progress',
221 // 'subscription_delivery_in_progress',
222 ].map(async (table
) => t
.query('TRUNCATE TABLE $(table:name) CASCADE', { table
})));
226 this.logger
.error(_scope
, 'failed', { error: e
});
232 // eslint-disable-next-line class-methods-use-this
233 _engineInfo(result
) {
235 changes: result
.rowCount
,
236 lastInsertRowid: result
.rows
.length
? result
.rows
[0].id : undefined,
237 duration: result
.duration
,
242 // eslint-disable-next-line class-methods-use-this
244 return common
.pick(result
, ['command', 'rowCount', 'duration']);
249 * Receive notices when topic entry is updated.
250 * Clear relevant cache entry.
251 * @param {String} payload
253 _topicChanged(payload
) {
254 const _scope
= _fileScope('_topicChanged');
255 if (payload
!== 'ping') {
256 this.logger
.debug(_scope
, 'called', { payload
});
257 this.cache
.delete(payload
);
263 * Called when a listener connection is opened.
266 _listenerEstablished() {
267 const _scope
= _fileScope('_listenerEstablished');
268 this.logger
.debug(_scope
, 'called', {});
269 this.cache
= new Map();
274 * Called when a listener connection is closed.
278 const _scope
= _fileScope('_listenerLost');
279 this.logger
.debug(_scope
, 'called', {});
285 * Return a cached entry, if available.
289 const _scope
= _fileScope('_cacheGet');
290 if (this.cache
&& this.cache
.has(key
)) {
291 const cacheEntry
= this.cache
.get(key
);
292 this.logger
.debug(_scope
, 'found cache entry', { key
, ...common
.pick(cacheEntry
, ['added', 'hits', 'lastHit']) });
293 cacheEntry
.hits
+= 1;
294 cacheEntry
.lastHit
= new Date();
295 return cacheEntry
.data
;
301 * Store an entry in cache, if available.
305 _cacheSet(key
, data
) {
306 const _scope
= _fileScope('_cacheSet');
308 this.cache
.set(key
, {
314 this.logger
.debug(_scope
, 'added cache entry', { key
});
320 return this.db
.task(async (t
) => fn(t
));
324 // eslint-disable-next-line class-methods-use-this
325 async
transaction(dbCtx
, fn
) {
326 return dbCtx
.txIf(async (t
) => fn(t
));
330 async
authenticationSuccess(dbCtx
, identifier
) {
331 const _scope
= _fileScope('authenticationSuccess');
332 this.logger
.debug(_scope
, 'called', { identifier
});
336 result
= await dbCtx
.result(this.statement
.authenticationSuccess
, { identifier
});
337 if (result
.rowCount
!= 1) {
338 throw new DBErrors
.UnexpectedResult('did not update authentication success event');
341 this.logger
.error(_scope
, 'failed', { error: e
, identifier
});
347 async
authenticationGet(dbCtx
, identifier
) {
348 const _scope
= _fileScope('authenticationGet');
349 this.logger
.debug(_scope
, 'called', { identifier
});
353 auth
= await dbCtx
.oneOrNone(this.statement
.authenticationGet
, { identifier
});
356 this.logger
.error(_scope
, 'failed', { error: e
, identifier
});
362 async
authenticationUpsert(dbCtx
, identifier
, credential
) {
363 const _scope
= _fileScope('authenticationUpsert');
364 const scrubbedCredential
= '*'.repeat((credential
|| '').length
);
365 this.logger
.debug(_scope
, 'called', { identifier
, scrubbedCredential
});
369 result
= await dbCtx
.result(this.statement
.authenticationUpsert
, { identifier
, credential
});
370 if (result
.rowCount
!= 1) {
371 throw new DBErrors
.UnexpectedResult('did not upsert authentication');
374 this.logger
.error(_scope
, 'failed', { error: e
, identifier
, scrubbedCredential
})
380 async
subscriptionsByTopicId(dbCtx
, topicId
) {
381 const _scope
= _fileScope('subscriptionsByTopicId');
382 this.logger
.debug(_scope
, 'called', { topicId
});
386 count
= await dbCtx
.manyOrNone(this.statement
.subscriptionsByTopicId
, { topicId
});
389 this.logger
.error(_scope
, 'failed', { error: e
, topicId
});
395 async
subscriptionCountByTopicUrl(dbCtx
, topicUrl
) {
396 const _scope
= _fileScope('subscriptionCountByTopicUrl');
397 this.logger
.debug(_scope
, 'called', { topicUrl
});
401 count
= await dbCtx
.one(this.statement
.subscriptionCountByTopicUrl
, { topicUrl
});
404 this.logger
.error(_scope
, 'failed', { error: e
, topicUrl
});
410 async
subscriptionDelete(dbCtx
, callback
, topicId
) {
411 const _scope
= _fileScope('subscriptionDelete');
412 this.logger
.debug(_scope
, 'called', { callback
, topicId
});
415 const result
= await dbCtx
.result(this.statement
.subscriptionDelete
, { callback
, topicId
});
416 return this._engineInfo(result
);
418 this.logger
.error(_scope
, 'failed', { error: e
, callback
, topicId
});
424 async
subscriptionDeleteExpired(dbCtx
, topicId
) {
425 const _scope
= _fileScope('subscriptionDeleteExpired');
426 this.logger
.debug(_scope
, 'called', { topicId
});
429 const result
= await dbCtx
.result(this.statement
.subscriptionDeleteExpired
, { topicId
});
430 this.logger
.debug(_scope
, 'success', { topicId
, deleted: result
.rowCount
});
431 return this._engineInfo(result
);
433 this.logger
.error(_scope
, 'failed', { error: e
, topicId
});
439 async
subscriptionDeliveryClaim(dbCtx
, wanted
, claimTimeoutSeconds
, claimant
) {
440 const _scope
= _fileScope('subscriptionDeliveryClaim');
441 this.logger
.debug(_scope
, 'called', { wanted
, claimTimeoutSeconds
, claimant
});
444 const claims
= await dbCtx
.txIf(async (txCtx
) => {
445 return txCtx
.manyOrNone(this.statement
.subscriptionDeliveryClaim
, { claimant
, wanted
, claimTimeoutSeconds
});
447 return claims
.map((r
) => r
.id
);
449 this.logger
.error(_scope
, 'failed', { error: e
, claimant
, wanted
, claimTimeoutSeconds
});
455 async
subscriptionDeliveryClaimById(dbCtx
, subscriptionId
, claimTimeoutSeconds
, claimant
) {
456 const _scope
= _fileScope('subscriptionDeliveryClaimById');
457 this.logger
.debug(_scope
, 'called', { subscriptionId
, claimTimeoutSeconds
, claimant
});
461 result
= await dbCtx
.txIf(async (txCtx
) => {
462 result
= await txCtx
.result(this.statement
.subscriptionDeliveryClaimById
, { claimant
, subscriptionId
, claimTimeoutSeconds
});
463 if (result
.rowCount
!= 1) {
464 throw new DBErrors
.UnexpectedResult('did not claim subscription delivery');
468 return this._engineInfo(result
);
470 this.logger
.error(_scope
, 'failed', { error: e
, claimant
, subscriptionId
, claimTimeoutSeconds
});
476 async
subscriptionDeliveryComplete(dbCtx
, callback
, topicId
) {
477 const _scope
= _fileScope('subscriptionDeliveryComplete');
478 this.logger
.debug(_scope
, 'called', { callback
, topicId
});
482 await dbCtx
.txIf(async (txCtx
) => {
483 result
= await txCtx
.result(this.statement
.subscriptionDeliverySuccess
, { callback
, topicId
});
484 if (result
.rowCount
!= 1) {
485 throw new DBErrors
.UnexpectedResult('did not set subscription delivery success');
487 result
= await txCtx
.result(this.statement
.subscriptionDeliveryDone
, { callback
, topicId
});
488 if (result
.rowCount
!= 1) {
489 throw new DBErrors
.UnexpectedResult('did not release subscription delivery');
493 this.logger
.error(_scope
, 'failed', { error: e
, callback
, topicId
});
499 async
subscriptionDeliveryGone(dbCtx
, callback
, topicId
) {
500 const _scope
= _fileScope('subscriptionDeliveryGone');
501 this.logger
.debug(_scope
, 'called', { callback
, topicId
});
505 await dbCtx
.txIf(async (txCtx
) => {
506 result
= await txCtx
.result(this.statement
.subscriptionDelete
, { callback
, topicId
});
507 if (result
.rowCount
!= 1) {
508 throw new DBErrors
.UnexpectedResult('did not delete subscription');
510 // Delete cascades to delivery
511 // result = await txCtx.result(this.statement.subscriptionDeliveryDone, { callback, topicId });
512 // if (result.rowCount != 1) {
513 // throw new DBErrors.UnexpectedResult('did not release subscription delivery');
517 this.logger
.error(_scope
, 'failed', { error: e
, callback
, topicId
});
523 async
subscriptionDeliveryIncomplete(dbCtx
, callback
, topicId
, retryDelays
= [60]) {
524 const _scope
= _fileScope('subscriptionDeliveryIncomplete');
525 this.logger
.debug(_scope
, 'called', { callback
, topicId
, retryDelays
});
529 await dbCtx
.txIf(async (txCtx
) => {
530 const { currentAttempt
} = await txCtx
.one(this.statement
.subscriptionDeliveryAttempts
, { callback
, topicId
});
531 const nextAttemptDelaySeconds
= common
.attemptRetrySeconds(currentAttempt
, retryDelays
);
532 result
= await txCtx
.result(this.statement
.subscriptionDeliveryFailure
, { nextAttemptDelaySeconds
, callback
, topicId
});
533 if (result
.rowCount
!= 1) {
534 throw new DBErrors
.UnexpectedResult('did not set subscription delivery failure');
536 result
= await txCtx
.result(this.statement
.subscriptionDeliveryDone
, { callback
, topicId
});
537 if (result
.rowCount
!= 1) {
538 throw new DBErrors
.UnexpectedResult('did not release subscription delivery');
542 this.logger
.error(_scope
, 'failed', { error: e
, callback
, topicId
});
548 async
subscriptionGet(dbCtx
, callback
, topicId
) {
549 const _scope
= _fileScope('subscriptionGet');
550 this.logger
.debug(_scope
, 'called', { callback
, topicId
});
554 subscription
= await dbCtx
.oneOrNone(this.statement
.subscriptionGet
, { callback
, topicId
});
557 this.logger
.error(_scope
, 'failed', { error: e
, callback
, topicId
});
563 async
subscriptionGetById(dbCtx
, subscriptionId
) {
564 const _scope
= _fileScope('subscriptionGetById');
565 this.logger
.debug(_scope
, 'called', { subscriptionId
});
569 subscription
= await dbCtx
.oneOrNone(this.statement
.subscriptionGetById
, { subscriptionId
});
572 this.logger
.error(_scope
, 'failed', { error: e
, subscriptionId
});
578 async
subscriptionUpdate(dbCtx
, data
) {
579 const _scope
= _fileScope('subscriptionUpdate');
580 this.logger
.debug(_scope
, 'called', { data
});
582 const subscriptionData
= {
586 this._subscriptionUpdateDataValidate(subscriptionData
);
590 result
= await dbCtx
.result(this.statement
.subscriptionUpdate
, subscriptionData
);
591 if (result
.rowCount
!= 1) {
592 throw new DBErrors
.UnexpectedResult('did not update subscription');
595 this.logger
.error(_scope
, 'failed', { error: e
, subscriptionData
});
601 async
subscriptionUpsert(dbCtx
, data
) {
602 const _scope
= _fileScope('subscriptionUpsert');
603 this.logger
.debug(_scope
, 'called', { ...data
});
605 const subscriptionData
= {
607 httpRemoteAddr: null,
611 this._subscriptionUpsertDataValidate(subscriptionData
);
615 result
= await dbCtx
.result(this.statement
.subscriptionUpsert
, subscriptionData
);
616 if (result
.rowCount
!= 1) {
617 throw new DBErrors
.UnexpectedResult('did not upsert subscription');
619 return this._engineInfo(result
);
621 this.logger
.error(_scope
, 'failed', { error: e
, subscriptionData
});
627 async
topicDeleted(dbCtx
, topicId
) {
628 const _scope
= _fileScope('topicDeleted');
629 this.logger
.debug(_scope
, 'called', { topicId
});
633 result
= await dbCtx
.result(this.statement
.topicDeleted
, { topicId
});
634 if (result
.rowCount
!= 1) {
635 throw new DBErrors
.UnexpectedResult('did not update topic as deleted');
638 this.logger
.error(_scope
, 'failed to update topic as deleted', { error: e
, topicId
});
644 async
topicFetchClaim(dbCtx
, wanted
, claimTimeoutSeconds
, claimant
) {
645 const _scope
= _fileScope('topicFetchClaim');
646 this.logger
.debug(_scope
, 'called', { wanted
, claimTimeoutSeconds
});
650 await dbCtx
.txIf(async (txCtx
) => {
651 claims
= await txCtx
.manyOrNone(this.statement
.topicContentFetchClaim
, { claimant
, wanted
, claimTimeoutSeconds
});
653 return claims
.map((r
) => r
.id
);
655 this.logger
.error(_scope
, 'failed to claim topics for fetch', { error: e
});
661 async
topicFetchClaimById(dbCtx
, topicId
, claimTimeoutSeconds
, claimant
) {
662 const _scope
= _fileScope('topicFetchClaimById');
663 this.logger
.debug(_scope
, 'called', { topicId
, claimTimeoutSeconds
, claimant
});
667 await dbCtx
.txIf(async (txCtx
) => {
668 result
= await txCtx
.result(this.statement
.topicContentFetchClaimById
, { topicId
, claimant
, claimTimeoutSeconds
});
670 return this._engineInfo(result
);
672 this.logger
.error(_scope
, 'failed', { error: e
, topicId
});
678 async
topicFetchComplete(dbCtx
, topicId
) {
679 const _scope
= _fileScope('topicFetchComplete');
680 this.logger
.debug(_scope
, 'called', { topicId
});
684 await dbCtx
.txIf(async (txCtx
) => {
685 result
= await txCtx
.result(this.statement
.topicAttemptsReset
, { topicId
});
686 if (result
.rowCount
!= 1) {
687 throw new DBErrors
.UnexpectedResult('did not reset topic attempts');
689 result
= await txCtx
.result(this.statement
.topicContentFetchDone
, { topicId
});
690 if (result
.rowCount
!= 1) {
691 throw new DBErrors
.UnexpectedResult('did not release topic fetch');
694 this.logger
.debug(_scope
, 'success', { topicId
, ...this._resultLog(result
) });
695 return this._engineInfo(result
);
697 this.logger
.error(_scope
, 'failed', { error: e
, result
, topicId
});
703 async
topicFetchIncomplete(dbCtx
, topicId
, retryDelays
= [60]) {
704 const _scope
= _fileScope('topicFetchIncomplete');
705 this.logger
.debug(_scope
, 'called', { topicId
});
709 result
= await dbCtx
.txIf(async (txCtx
) => {
710 const { contentFetchAttemptsSinceSuccess: currentAttempt
} = await txCtx
.one(this.statement
.topicAttempts
, { topicId
});
711 const nextAttemptDelaySeconds
= common
.attemptRetrySeconds(currentAttempt
, retryDelays
);
712 result
= await txCtx
.result(this.statement
.topicAttemptsIncrement
, { topicId
, nextAttemptDelaySeconds
});
713 if (result
.rowCount
!= 1) {
714 throw new DBErrors
.UnexpectedResult('did not set topic attempts');
716 result
= await txCtx
.result(this.statement
.topicContentFetchDone
, { topicId
});
717 if (result
.rowCount
!= 1) {
718 throw new DBErrors
.UnexpectedResult('did not release topic fetch');
722 this.logger
.debug(_scope
, 'success', { topicId
, ...this._resultLog(result
) });
723 return this._engineInfo(result
);
725 this.logger
.error(_scope
, 'failed', { error: e
, result
, topicId
});
731 async
topicFetchRequested(dbCtx
, topicId
) {
732 const _scope
= _fileScope('topicFetchRequested');
733 this.logger
.debug(_scope
, 'called', { topicId
});
737 result
= await dbCtx
.result(this.statement
.topicContentFetchRequested
, { topicId
});
738 if (result
.rowCount
!= 1) {
739 throw new DBErrors
.UnexpectedResult('did not set topic fetch requested');
741 this.logger
.debug(_scope
, 'success', { topicId
, ...this._resultLog(result
) });
742 return this._engineInfo(result
);
744 this.logger
.error(_scope
, 'failed', { error: e
, topicId
});
750 async
topicGetAll(dbCtx
) {
751 const _scope
= _fileScope('topicGetAll');
752 this.logger
.debug(_scope
, 'called');
756 topics
= await dbCtx
.manyOrNone(this.statement
.topicGetInfoAll
);
758 this.logger
.error(_scope
, 'failed', { error: e
, topics
});
762 topics
= topics
.map(this._topicDefaults
.bind(this));
768 async
topicGetById(dbCtx
, topicId
, applyDefaults
= true) {
769 const _scope
= _fileScope('topicGetById');
770 this.logger
.debug(_scope
, 'called', { topicId
});
774 topic
= await dbCtx
.oneOrNone(this.statement
.topicGetById
, { topicId
});
776 topic
= this._topicDefaults(topic
);
780 this.logger
.error(_scope
, 'failed', { error: e
, topic
, topicId
});
786 async
topicGetByUrl(dbCtx
, topicUrl
) {
787 const _scope
= _fileScope('topicGetByUrl');
788 this.logger
.debug(_scope
, 'called', { topicUrl
});
792 topic
= await dbCtx
.oneOrNone(this.statement
.topicGetByUrl
, { topicUrl
});
793 return this._topicDefaults(topic
);
795 this.logger
.error(_scope
, 'failed', { error: e
, topic
, topicUrl
});
801 async
topicGetContentById(dbCtx
, topicId
) {
802 const _scope
= _fileScope('topicGetContentById');
803 this.logger
.debug(_scope
, 'called', { topicId
});
807 topic
= this._cacheGet(topicId
);
811 topic
= await dbCtx
.oneOrNone(this.statement
.topicGetContentById
, { topicId
});
812 const topicWithDefaults
= this._topicDefaults(topic
);
813 this._cacheSet(topicId
, topicWithDefaults
);
814 return topicWithDefaults
;
816 this.logger
.error(_scope
, 'failed', { error: e
, topic
, topicId
});
822 async
topicPendingDelete(dbCtx
, topicId
) {
823 const _scope
= _fileScope('topicPendingDelete');
824 this.logger
.debug(_scope
, 'called', { topicId
});
827 await dbCtx
.txIf(async (txCtx
) => {
828 const topic
= await txCtx
.one(this.statement
.topicGetById
, { topicId
});
829 if (!topic
.isDeleted
) {
830 this.logger
.debug(_scope
, 'topic not set deleted, not deleting', { topicId
});
834 const { count: subscriberCount
} = await txCtx
.one(this.statement
.subscriptionCountByTopicUrl
, { topicUrl: topic
.url
});
835 if (subscriberCount
) {
836 this.logger
.debug(_scope
, 'topic has subscribers, not deleting', { topicId
, subscriberCount
});
840 const result
= await txCtx
.result(this.statement
.topicDeleteById
, { topicId
});
841 if (result
.rowCount
!== 1) {
842 throw new DBErrors
.UnexpectedResult('did not delete topic');
845 this.logger
.debug(_scope
, 'success', { topicId
});
847 this.logger
.error(_scope
, 'failed', { error: e
, topicId
});
853 async
topicSet(dbCtx
, data
) {
854 const _scope
= _fileScope('topicSet');
855 this.logger
.debug(_scope
, 'called', data
);
857 const topicSetData
= {
858 publisherValidationUrl: null,
859 leaseSecondsPreferred: null,
860 leaseSecondsMin: null,
861 leaseSecondsMax: null,
867 this._topicSetDataValidate(topicSetData
);
868 result
= await dbCtx
.result(this.statement
.topicUpsert
, topicSetData
);
869 if (result
.rowCount
!= 1) {
870 throw new DBErrors
.UnexpectedResult('did not set topic data');
872 this.logger
.debug(_scope
, 'success', { topicSetData
, ...this._resultLog(result
) });
873 return this._engineInfo(result
);
875 this.logger
.error(_scope
, 'failed', { error: e
, result
});
881 async
topicSetContent(dbCtx
, data
) {
882 const _scope
= _fileScope('topicSetContent');
883 const topicSetContentData
= {
888 ...topicSetContentData
,
889 content: common
.logTruncate(topicSetContentData
.content
, 100),
891 this.logger
.debug(_scope
, 'called', data
);
895 this._topicSetContentDataValidate(topicSetContentData
);
896 result
= await dbCtx
.result(this.statement
.topicSetContent
, topicSetContentData
);
897 logData
.result
= this._resultLog(result
);
898 if (result
.rowCount
!= 1) {
899 throw new DBErrors
.UnexpectedResult('did not set topic content');
901 this.logger
.debug(_scope
, 'success', { ...logData
});
902 return this._engineInfo(result
);
904 this.logger
.error(_scope
, 'failed', { error: e
, ...logData
});
910 async
topicUpdate(dbCtx
, data
) {
911 const _scope
= _fileScope('topicUpdate');
912 this.logger
.debug(_scope
, 'called', { data
});
915 leaseSecondsPreferred: null,
916 leaseSecondsMin: null,
917 leaseSecondsMax: null,
918 publisherValidationUrl: null,
922 this._topicUpdateDataValidate(topicData
);
926 result
= await dbCtx
.result(this.statement
.topicUpdate
, topicData
);
927 if (result
.rowCount
!= 1) {
928 throw new DBErrors
.UnexpectedResult('did not update topic');
931 this.logger
.error(_scope
, 'failed', { error: e
, topicData
});
937 async
verificationClaim(dbCtx
, wanted
, claimTimeoutSeconds
, claimant
) {
938 const _scope
= _fileScope('verificationClaim');
939 this.logger
.debug(_scope
, 'called', { wanted
, claimTimeoutSeconds
});
943 await dbCtx
.txIf(async (txCtx
) => {
944 result
= await txCtx
.manyOrNone(this.statement
.verificationClaim
, { claimant
, wanted
, claimTimeoutSeconds
});
946 return result
.map((r
) => r
.id
);
948 this.logger
.error(_scope
, 'failed', { wanted
, claimTimeoutSeconds
});
955 async
verificationClaimById(dbCtx
, verificationId
, claimTimeoutSeconds
, claimant
) {
956 const _scope
= _fileScope('verificationClaimById');
957 this.logger
.debug(_scope
, 'called', { verificationId
, claimant
, claimTimeoutSeconds
});
961 await dbCtx
.txIf(async (txCtx
) => {
962 result
= await txCtx
.result(this.statement
.verificationClaimById
, { verificationId
, claimant
, claimTimeoutSeconds
});
964 return this._engineInfo(result
);
966 this.logger
.error(_scope
, 'failed', { verificationId
, claimant
, claimTimeoutSeconds
});
972 async
verificationComplete(dbCtx
, verificationId
, callback
, topicId
) {
973 const _scope
= _fileScope('verificationComplete');
974 this.logger
.debug(_scope
, 'called', { verificationId
});
978 await dbCtx
.txIf(async (txCtx
) => {
979 result
= await txCtx
.result(this.statement
.verificationScrub
, { verificationId
, callback
, topicId
});
980 if (result
.rowCount
< 1) {
981 throw new DBErrors
.UnexpectedResult('did not remove verifications');
985 this.logger
.error(_scope
, 'failed', { verificationId
});
988 return this._engineInfo(result
);
992 async
verificationGetById(dbCtx
, verificationId
) {
993 const _scope
= _fileScope('verificationGetById');
994 this.logger
.debug(_scope
, 'called', { verificationId
});
998 verification
= await dbCtx
.oneOrNone(this.statement
.verificationGetById
, { verificationId
});
1001 this.logger
.error(_scope
, 'failed', { error: e
, verificationId
});
1007 async
verificationIncomplete(dbCtx
, verificationId
, retryDelays
= [60]) {
1008 const _scope
= _fileScope('verificationIncomplete');
1009 this.logger
.debug(_scope
, 'called', { verificationId
});
1013 await dbCtx
.txIf(async (txCtx
) => {
1014 const { attempts
} = await txCtx
.one(this.statement
.verificationAttempts
, { verificationId
});
1015 const nextAttemptDelaySeconds
= common
.attemptRetrySeconds(attempts
, retryDelays
);
1016 result
= await txCtx
.result(this.statement
.verificationAttemptIncrement
, { verificationId
, nextAttemptDelaySeconds
});
1017 if (result
.rowCount
!= 1) {
1018 throw new DBErrors
.UnexpectedResult('did not update verification attempts');
1020 result
= await txCtx
.result(this.statement
.verificationDone
, { verificationId
});
1021 if (result
.rowCount
!= 1) {
1022 throw new DBErrors
.UnexpectedResult('did not release verification');
1026 this.logger
.error(_scope
, 'failed', { error: e
, verificationId
});
1032 async
verificationInsert(dbCtx
, verification
) {
1033 const _scope
= _fileScope('verificationInsert');
1034 this.logger
.debug(_scope
, 'called', { verification
});
1036 const verificationData
= {
1038 httpRemoteAddr: null,
1044 let result
, verificationId
;
1046 this._verificationDataValidate(verificationData
);
1047 result
= await dbCtx
.result(this.statement
.verificationInsert
, verificationData
);
1048 if (result
.rowCount
!= 1) {
1049 throw new DBErrors
.UnexpectedResult('did not insert verification');
1051 verificationId
= result
.rows
[0].id
;
1052 this.logger
.debug(_scope
, 'inserted verification', { verificationId
});
1054 return verificationId
;
1056 this.logger
.error(_scope
, 'failed', { error: e
, verificationData
});
1062 async
verificationRelease(dbCtx
, verificationId
) {
1063 const _scope
= _fileScope('verificationRelease');
1064 this.logger
.debug(_scope
, 'called', { verificationId
});
1068 result
= await dbCtx
.result(this.statement
.verificationDone
, { verificationId
});
1069 if (result
.rowCount
!= 1) {
1070 throw new DBErrors
.UnexpectedResult('did not release verification');
1072 return this._engineInfo(result
);
1074 this.logger
.error(_scope
, 'failed', { error: e
, verificationId
});
1080 async
verificationUpdate(dbCtx
, verificationId
, data
) {
1081 const _scope
= _fileScope('verificationUpdate');
1082 this.logger
.debug(_scope
, 'called', { verificationId
, data
});
1084 const verificationData
= {
1092 this._verificationUpdateDataValidate(verificationData
);
1093 result
= await dbCtx
.result(this.statement
.verificationUpdate
, verificationData
);
1094 if (result
.rowCount
!= 1) {
1095 throw new DBErrors
.UnexpectedResult('did not update verification');
1098 this.logger
.error(_scope
, 'failed', { error: e
, verificationData
});
1104 async
verificationValidated(dbCtx
, verificationId
) {
1105 const _scope
= _fileScope('verificationValidated');
1106 this.logger
.debug(_scope
, 'called', { verificationId
});
1110 result
= await dbCtx
.result(this.statement
.verificationValidate
, { verificationId
});
1111 if (result
.rowCount
!= 1) {
1112 throw new DBErrors
.UnexpectedResult('did not set verification validation');
1115 this.logger
.error(_scope
, 'failed', { error: e
, verificationId
});
1122 module
.exports
= DatabasePostgres
;