-
Notifications
You must be signed in to change notification settings - Fork 4
Migrate Spark API service to Fastify #549
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,9 @@ | ||
import '../lib/instrument.js' | ||
import assert from 'node:assert' | ||
import http from 'node:http' | ||
import { once } from 'node:events' | ||
import { createHandler } from '../index.js' | ||
import Fastify from 'fastify' | ||
import { createFastifyApp } from '../fastify-app.js' | ||
// import { createHandler } from '../index.js' | ||
import pg from 'pg' | ||
import { startRoundTracker } from '../lib/round-tracker.js' | ||
import { migrate } from '../../migrations/index.js' | ||
|
@@ -24,7 +25,7 @@ const { | |
// The same token is configured in Fly.io secrets for the deal-observer service too. | ||
assert(DEAL_INGESTER_TOKEN, 'DEAL_INGESTER_TOKEN is required') | ||
|
||
const client = new pg.Pool({ | ||
const pgPool = new pg.Pool({ | ||
connectionString: DATABASE_URL, | ||
// allow the pool to close all connections and become empty | ||
min: 0, | ||
|
@@ -38,20 +39,20 @@ const client = new pg.Pool({ | |
maxLifetimeSeconds: 60 | ||
}) | ||
|
||
client.on('error', err => { | ||
pgPool.on('error', err => { | ||
// Prevent crashing the process on idle client errors, the pool will recover | ||
// itself. If all connections are lost, the process will still crash. | ||
// https://github.com/brianc/node-postgres/issues/1324#issuecomment-308778405 | ||
console.error('An idle client has experienced an error', err.stack) | ||
}) | ||
await migrate(client) | ||
await migrate(pgPool) | ||
|
||
console.log('Initializing round tracker...') | ||
const start = new Date() | ||
|
||
try { | ||
const currentRound = await startRoundTracker({ | ||
pgPool: client, | ||
pgPool, | ||
recordTelemetry: recordNetworkInfoTelemetry | ||
}) | ||
console.log( | ||
|
@@ -73,16 +74,21 @@ const logger = { | |
request: ['1', 'true'].includes(REQUEST_LOGGING) ? console.info : () => { } | ||
} | ||
|
||
const handler = await createHandler({ | ||
client, | ||
// Initialize Fastify app | ||
const fastifyApp = await createFastifyApp({ | ||
pgPool, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. please update There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Noted. |
||
logger, | ||
dealIngestionAccessToken: DEAL_INGESTER_TOKEN, | ||
domain: DOMAIN | ||
}) | ||
|
||
const port = Number(PORT) | ||
const server = http.createServer(handler) | ||
console.log('Starting the http server on host %j port %s', HOST, port) | ||
server.listen(port, HOST) | ||
await once(server, 'listening') | ||
console.log(`http://${HOST}:${PORT}`) | ||
try { | ||
await fastifyApp.listen({ | ||
port: Number(PORT), | ||
host: HOST | ||
}) | ||
console.log(`Server is running on ${fastifyApp.server.address().address}:${fastifyApp.server.address().port}`) | ||
} catch (err) { | ||
console.error('Error starting server:', err) | ||
process.exit(1) | ||
} |
Original file line number | Diff line number | Diff line change | ||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
@@ -0,0 +1,70 @@ | ||||||||||||||||
import Fastify from 'fastify' | ||||||||||||||||
import * as Sentry from '@sentry/node' | ||||||||||||||||
import { createRoutes } from './routes/index.js' | ||||||||||||||||
|
||||||||||||||||
export async function createFastifyApp({ | ||||||||||||||||
pgPool, | ||||||||||||||||
logger, | ||||||||||||||||
dealIngestionAccessToken, | ||||||||||||||||
domain | ||||||||||||||||
}) { | ||||||||||||||||
const fastify = Fastify({ | ||||||||||||||||
logger: { | ||||||||||||||||
level: 'info', | ||||||||||||||||
transport: { | ||||||||||||||||
target: 'pino-pretty' | ||||||||||||||||
} | ||||||||||||||||
} | ||||||||||||||||
Comment on lines
+12
to
+17
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
To allow the caller of There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Alright, noted |
||||||||||||||||
}) | ||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||||||||||||||||
|
||||||||||||||||
// Add shared context to each request | ||||||||||||||||
fastify.decorateRequest('pgPool', null) | ||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can we switch to @fastify/postgres instead of manual handling instead please? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. +1 on using There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @pyropy I have have made some commits after your review last week on this PR stats-api-pr, can you kindly help review once again, so I can replicate same @fastify/postgres implementation to this API as well, thanks. |
||||||||||||||||
fastify.decorateRequest('dealIngestionAccessToken', null) | ||||||||||||||||
fastify.decorateRequest('domain', null) | ||||||||||||||||
Comment on lines
+22
to
+23
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. These are constant and don't change from request to request. Therefore, they shouldn't be exposed on the request object. |
||||||||||||||||
|
||||||||||||||||
// Add hooks to setup request context | ||||||||||||||||
fastify.addHook('onRequest', async (request, reply) => { | ||||||||||||||||
request.pgPool = pgPool | ||||||||||||||||
request.dealIngestionAccessToken = dealIngestionAccessToken | ||||||||||||||||
request.domain = domain | ||||||||||||||||
|
||||||||||||||||
// Domain redirect check | ||||||||||||||||
if (request.headers.host && request.headers.host.split(':')[0] !== domain) { | ||||||||||||||||
return reply.redirect(301, `https://${domain}${request.url}`) | ||||||||||||||||
} | ||||||||||||||||
}) | ||||||||||||||||
|
||||||||||||||||
// Error handler | ||||||||||||||||
fastify.setErrorHandler((error, request, reply) => { | ||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can we use fastify's default error handler instead? No need to keep the current implementation, which we only created, because we didn't have any default error handler |
||||||||||||||||
if (error instanceof SyntaxError) { | ||||||||||||||||
reply.code(400).send('Invalid JSON Body') | ||||||||||||||||
} else if (error.statusCode) { | ||||||||||||||||
reply.code(error.statusCode).send(error.message) | ||||||||||||||||
} else { | ||||||||||||||||
logger.error(error) | ||||||||||||||||
reply.code(500).send('Internal Server Error') | ||||||||||||||||
} | ||||||||||||||||
|
||||||||||||||||
if (reply.statusCode >= 500) { | ||||||||||||||||
Sentry.captureException(error) | ||||||||||||||||
} | ||||||||||||||||
}) | ||||||||||||||||
|
||||||||||||||||
// Request logging | ||||||||||||||||
fastify.addHook('onRequest', (request, reply, done) => { | ||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This can also be removed, as fastify is taking care of request logging now |
||||||||||||||||
const start = new Date() | ||||||||||||||||
logger.request(`${request.method} ${request.url} ...`) | ||||||||||||||||
|
||||||||||||||||
reply.addHook('onResponse', (request, reply, done) => { | ||||||||||||||||
logger.request(`${request.method} ${request.url} ${reply.statusCode} (${new Date().getTime() - start.getTime()}ms)`) | ||||||||||||||||
done() | ||||||||||||||||
}) | ||||||||||||||||
|
||||||||||||||||
done() | ||||||||||||||||
}) | ||||||||||||||||
|
||||||||||||||||
// Register routes | ||||||||||||||||
createRoutes(fastify) | ||||||||||||||||
|
||||||||||||||||
return fastify | ||||||||||||||||
} |
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -9,6 +9,7 @@ | |||||
"scripts": { | ||||||
"start": "node bin/spark.js", | ||||||
"lint": "standard", | ||||||
"start:fastify": "node bin/spark-fastify.js", | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
That file doesn't exist |
||||||
"test": "mocha" | ||||||
}, | ||||||
"devDependencies": { | ||||||
|
@@ -24,13 +25,14 @@ | |||||
"@sentry/node": "^9.5.0", | ||||||
"compare-versions": "^6.1.1", | ||||||
"ethers": "^6.13.5", | ||||||
"fastify": "^4.26.0", | ||||||
"http-assert": "^1.5.0", | ||||||
"http-responders": "^2.2.0", | ||||||
"multiformats": "^13.3.2", | ||||||
"multiformats": "^13.3.2", | ||||||
"pg": "^8.14.0", | ||||||
"postgrator": "^8.0.0", | ||||||
"raw-body": "^3.0.0" | ||||||
}, | ||||||
}, | ||||||
"standard": { | ||||||
"env": [ | ||||||
"mocha" | ||||||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What is this code comment for?