Skip to content

Commit

Permalink
chore: add retries for caching
Browse files Browse the repository at this point in the history
  • Loading branch information
tsmbl committed Jul 24, 2024
1 parent 5bb7f26 commit 39d0647
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 6 deletions.
31 changes: 25 additions & 6 deletions src/realms-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
} from './realms-sdk';
import { groupBy, keyBy } from 'lodash';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { retry } from './retry';

export interface CachingEvent {
type: CachingEventType;
Expand Down Expand Up @@ -99,7 +100,7 @@ export class RealmsCache implements OnModuleInit {
);
}

@Cron(CronExpression.EVERY_30_MINUTES, {
@Cron(CronExpression.EVERY_HOUR, {
name: 'cacheStaticAccounts',
})
async periodicCacheStaticAccounts() {
Expand All @@ -118,10 +119,19 @@ export class RealmsCache implements OnModuleInit {
}
this.staticAccountCachingInProgress = true;
try {
await this.cacheGovernancePrograms();
await this.cacheRealms();
await this.cacheGovernances();
await this.cacheTokenOwnerRecords();
await retry({
func: async () => {
await this.cacheGovernancePrograms();
await this.cacheRealms();
await this.cacheGovernances();
await this.cacheTokenOwnerRecords();
},
maxRetries: 3,
onError: (e) => {
this.logger.error('Error during caching of static accounts');
this.logger.error(e);
},
});
this.lastStaticAccountCachingSuccessFinishedAt = new Date();
} finally {
this.staticAccountCachingInProgress = false;
Expand All @@ -148,7 +158,16 @@ export class RealmsCache implements OnModuleInit {
}
this.dynamicAccountCachingInProgress = true;
try {
await this.cacheProposals();
await retry({
func: async () => {
await this.cacheProposals();
},
maxRetries: 3,
onError: (e) => {
this.logger.error('Error during caching of dynamic accounts');
this.logger.error(e);
},
});
this.lastDynamicAccountCachingSuccessFinishedAt = new Date();
} finally {
this.dynamicAccountCachingInProgress = false;
Expand Down
23 changes: 23 additions & 0 deletions src/retry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { noop } from 'lodash';

export interface RetryParameters<T> {
func: () => Promise<T>;
maxRetries?: number;
onError?: (e: Error) => void;
}
export async function retry<T>({
func,
maxRetries = 2,
onError = noop,
}: RetryParameters<T>): Promise<T> {
for (let count = 0; count < maxRetries; count++) {
try {
return await func();
} catch (e) {
if (e instanceof Error) {
onError(e);
}
}
}
throw new Error('Retries exceeded: try again later');
}

0 comments on commit 39d0647

Please sign in to comment.