Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support running the app in API/background mode only #112

Draft
wants to merge 2 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 30 additions & 22 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,36 +26,44 @@ import cron from './plugins/cron';

async function routes(fastify: FastifyInstance) {
fastify.log.info(`Process env: ${JSON.stringify(getSafeEnvs(), null, 2)}`);
const env = container.resolve('env');

await fastify.register(cors);
await fastify.register(sentry);
fastify.register(sensible);
fastify.register(compress);
fastify.register(swagger);
fastify.register(jwt);
fastify.register(ipBlock);
fastify.register(cache);
fastify.register(rateLimit);
fastify.register(healthcheck);

const env = container.resolve('env');
await container.resolve('bitcoin').checkNetwork(env.NETWORK as NetworkType);

fastify.register(internalRoutes, { prefix: '/internal' });
fastify.register(tokenRoutes, { prefix: '/token' });
fastify.register(bitcoinRoutes, { prefix: '/bitcoin/v1' });
fastify.register(rgbppRoutes, { prefix: '/rgbpp/v1' });
fastify.log.info(`Application mode: ${env.APP_MODE}`);
if (['full', 'api'].includes(env.APP_MODE)) {
await fastify.register(cors);
fastify.register(swagger);
fastify.register(jwt);
fastify.register(ipBlock);
fastify.register(cache);
fastify.register(rateLimit);
fastify.register(healthcheck);

fastify.register(internalRoutes, { prefix: '/internal' });
fastify.register(tokenRoutes, { prefix: '/token' });
fastify.register(bitcoinRoutes, { prefix: '/bitcoin/v1' });
fastify.register(rgbppRoutes, { prefix: '/rgbpp/v1' });

fastify.log.info('Routes are registered');
}

// register cron routes only on Vercel
if (provider === 'vercel' || env.NODE_ENV === 'test') {
fastify.log.info('Cron routes is registered');
fastify.register(cronRoutes, { prefix: '/cron' });
} else {
fastify.log.info('Cron plugin is registered');
await fastify.register(cron);
fastify.addHook('onReady', () => {
fastify.cron.startAllJobs();
});
if (['full', 'background'].includes(env.APP_MODE)) {
// register cron routes only on Vercel
if (provider === 'vercel' || env.NODE_ENV === 'test') {
fastify.register(cronRoutes, { prefix: '/cron' });
fastify.log.info('Cron routes is registered');
} else {
await fastify.register(cron);
fastify.addHook('onReady', () => {
fastify.cron.startAllJobs();
});
fastify.log.info('Cron plugin is registered');
}
}
}

Expand Down
16 changes: 16 additions & 0 deletions src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,14 @@ const envSchema = z
.transform((value) => value.split(','))
.pipe(z.string().array()),

/**
* Application Mode
* - full: Full application mode, includes API and background tasks.
* - api_only: API only mode, excludes background tasks.
* - background_only: Background tasks only mode, excludes API.
*/
APP_MODE: z.enum(['full', 'api', 'background']).default('full'),

/**
* Bitcoin SPV service URL
* https://github.com/ckb-cell/ckb-bitcoin-spv-service
Expand Down Expand Up @@ -113,6 +121,14 @@ const envSchema = z
*/
PAYMASTER_BTC_CONTAINER_FEE_SATS: z.coerce.number().default(7000),

/**
* Enable BTCTimeLock cell unlock cron task
* set to false to disable the BTCTimeLock cell unlock cron task
*/
UNLOCKER_CRON_TASK_ENABLE: z
.enum(['true', 'false'])
.default('true')
.transform((value) => value === 'true'),
/**
* BTCTimeLock cell unlock batch size
*/
Expand Down
2 changes: 1 addition & 1 deletion src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const envToLogger = {
},
}
: {}),
level: env.LOGGER_LEVEL ?? 'debug',
level: 'debug',
},
production: {
level: env.LOGGER_LEVEL ?? 'info',
Expand Down
49 changes: 27 additions & 22 deletions src/plugins/cron.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import fp from 'fastify-plugin';
import TransactionProcessor from '../services/transaction';
import cron from 'fastify-cron';
import cron, { Params as CronJobParams } from 'fastify-cron';
import { Env } from '../env';
import Unlocker from '../services/unlocker';

export default fp(async (fastify) => {
try {
const cronJobs: CronJobParams[] = [];
const env: Env = fastify.container.resolve('env');

const getSentryCheckIn = (monitorSlug: string, crontab: string) => {
Expand Down Expand Up @@ -77,31 +78,35 @@ export default fp(async (fastify) => {
});
},
};
cronJobs.push(retryMissingTransactionsJob);

// processing unlock BTC_TIME_LOCK cells
const unlocker: Unlocker = fastify.container.resolve('unlocker');
const monitorSlug = env.UNLOCKER_MONITOR_SLUG;
const unlockBTCTimeLockCellsJob = {
name: monitorSlug,
cronTime: env.UNLOCKER_CRON_SCHEDULE,
onTick: async () => {
fastify.Sentry.startSpan({ op: 'cron', name: monitorSlug }, async () => {
const { name, cronTime } = unlockBTCTimeLockCellsJob;
const checkIn = getSentryCheckIn(name, cronTime);
try {
await unlocker.unlockCells();
checkIn.ok();
} catch (err) {
checkIn.error();
fastify.log.error(err);
fastify.Sentry.captureException(err);
}
});
},
};
if (env.UNLOCKER_CRON_TASK_ENABLE) {
const unlocker: Unlocker = fastify.container.resolve('unlocker');
const monitorSlug = env.UNLOCKER_MONITOR_SLUG;
const unlockBTCTimeLockCellsJob = {
name: monitorSlug,
cronTime: env.UNLOCKER_CRON_SCHEDULE,
onTick: async () => {
fastify.Sentry.startSpan({ op: 'cron', name: monitorSlug }, async () => {
const { name, cronTime } = unlockBTCTimeLockCellsJob;
const checkIn = getSentryCheckIn(name, cronTime);
try {
await unlocker.unlockCells();
checkIn.ok();
} catch (err) {
checkIn.error();
fastify.log.error(err);
fastify.Sentry.captureException(err);
}
});
},
};
cronJobs.push(unlockBTCTimeLockCellsJob);
}

fastify.register(cron, {
jobs: [retryMissingTransactionsJob, unlockBTCTimeLockCellsJob],
jobs: cronJobs,
});
} catch (err) {
fastify.log.error(err);
Expand Down
Loading