diff --git a/src/index.ts b/src/index.ts index 1944ab2..8769efa 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,7 +6,7 @@ import { initLogger, fallbackLogger } from '@snapshot-labs/snapshot-sentry'; import initMetrics from './helpers/metrics'; import api from './api'; import pkg from '../package.json'; -import { last_mci, run } from './replay'; +import { last_mci, lastActivityTime, run } from './replay'; import { closeDatabase } from './helpers/mysql'; const app = express(); @@ -22,6 +22,15 @@ app.use(bodyParser.urlencoded({ limit: '8mb', extended: false })); app.use(cors({ maxAge: 86400 })); app.get('/', async (req, res) => { + const timeSinceLastActivity = (Date.now() - lastActivityTime) / 1000; + const isStale = timeSinceLastActivity > 10 * 60; // 10 minutes + + // Restart if stale + if (isStale) { + console.log(`[index] Restarting run loop`); + run(); + } + return res.json({ name: pkg.name, version: pkg.version, diff --git a/src/replay.ts b/src/replay.ts index 08d9be6..e836333 100644 --- a/src/replay.ts +++ b/src/replay.ts @@ -7,8 +7,10 @@ import { handleCreatedEvent, handleDeletedEvent } from './events'; const hubURL = process.env.HUB_URL || 'https://hub.snapshot.org'; export let last_mci = 0; +export let lastActivityTime = Date.now(); async function getLastMci() { + lastActivityTime = Date.now(); // Update activity time const query = 'SELECT value FROM _metadatas WHERE id = ? LIMIT 1'; const results = await db.queryAsync(query, ['last_mci']); last_mci = parseInt(results[0].value);