Skip to content

Use @fastify/fastify-postgres. CheckerNetwork/roadmap#220 #341

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

Open
wants to merge 15 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
4 changes: 3 additions & 1 deletion db/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
"dependencies": {
"@filecoin-station/spark-evaluate": "^1.2.0",
"pg": "^8.13.3",
"postgrator": "^8.0.0"
"postgrator": "^8.0.0",
"@fastify/postgres": "^5.2.0",
"@fastify/url-data": "^6.0.3"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"@fastify/postgres": "^5.2.0",
"@fastify/url-data": "^6.0.3"

I think we should remove these packages from db workspace and install @fastify/postgres inside the stats workspace only. You can install workspace specific packages by running npm install @fastify/postgres -w stats

},
"standard": {
"env": [
Expand Down
37 changes: 33 additions & 4 deletions stats/bin/migrate.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,38 @@
import Fastify from 'fastify'
import fastifyPostgres from '@fastify/postgres'
import {
getPgPools,
migrateEvaluateDB,
migrateStatsDB
} from '@filecoin-station/spark-stats-db'

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please undo this change to keep the diff clean

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alright, noted

const pgPools = await getPgPools()
await migrateStatsDB(pgPools.stats)
await migrateEvaluateDB(pgPools.evaluate)
const {
DATABASE_URL,
EVALUATE_DB_URL
} = process.env
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
const {
DATABASE_URL,
EVALUATE_DB_URL
} = process.env

These constants seem not to be used anywhere. Let's delete them.


const app = Fastify({ logger: false })
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that we shouldn't really create a new Fastify instance in order to run migrations. This should be done without the @fastify/postgres package.


await app.register(fastifyPostgres, {
connectionString: DATABASE_URL,
name: 'stats'
})

await app.register(fastifyPostgres, {
connectionString: EVALUATE_DB_URL,
name: 'evaluate'
})

try {
console.log('Running migrations for stats database...')
await migrateStatsDB(app.pg.stats)

console.log('Running migrations for evaluate database...')
await migrateEvaluateDB(app.pg.evaluate)

console.log('All migrations completed successfully')
} catch (error) {
console.error('Migration failed:', error)
process.exit(1)
} finally {
await app.close()
}
38 changes: 36 additions & 2 deletions stats/bin/spark-stats.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,50 @@
import '../lib/instrument.js'
import Fastify from 'fastify'
import fastifyPostgres from '@fastify/postgres'
import { createApp } from '../lib/app.js'
import { getPgPools } from '@filecoin-station/spark-stats-db'

const {
PORT = '8080',
HOST = '127.0.0.1',
SPARK_API_BASE_URL = 'https://api.filspark.com/',
REQUEST_LOGGING = 'true'
REQUEST_LOGGING = 'true',
DATABASE_URL,

} = process.env

const pgPools = await getPgPools()

const dbFastify = Fastify({ logger: false })
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we shouldn't create another Fastify instance here as we already do it inside createApp function. Rather, we should move registering the @fastify/postgres plugin and databases to be executed within createApp funciton.


await dbFastify.register(fastifyPostgres, {
connectionString: DATABASE_URL,
name: 'stats',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is wrong because because we're instantiate only connection to stats database, but we do reference evaluate database bellow.

pool: {
min: 0,
max: 100,
idleTimeoutMillis: 1000,
maxLifetimeSeconds: 60
}
})

const pgPools = {
stats: dbFastify.pg.stats,
evaluate: dbFastify.pg.evaluate,
async end() {
await dbFastify.close()
}
}


export const withDb = async (poolName, queryFn) => {
const client = await dbFastify.pg[poolName].connect()
try {
return await queryFn(client)
} finally {
client.release()
}
}

const app = await createApp({
SPARK_API_BASE_URL,
pgPools,
Expand Down
113 changes: 113 additions & 0 deletions stats/lib/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
// stats/lib/db.js
import Fastify from 'fastify'
import fastifyPostgres from '@fastify/postgres'

let fastifyApp = null
let isInitialized = false
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
let fastifyApp = null
let isInitialized = false

I would avoid using globals in this case.


/**
* Initialize database connections
* @param {Object} options
* @param {string} options.statsConnectionString - Stats DB connection string
* @param {string} options.evaluateConnectionString - Evaluate DB connection string
* @returns {Promise<void>}
*/
export async function initializeDb({ statsConnectionString, evaluateConnectionString }) {
if (isInitialized) return

// Create a minimal Fastify instance for database connections
fastifyApp = Fastify({ logger: false })
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of creating a new Fastify instance I think it would be better to pass down existing instance as function argument.


// Register the Postgres plugin for stats DB
await fastifyApp.register(fastifyPostgres, {
connectionString: statsConnectionString,
name: 'stats',
pool: {
min: 0,
max: 100,
idleTimeoutMillis: 1000,
maxLifetimeSeconds: 60
}
})

// Register the Postgres plugin for evaluate DB
await fastifyApp.register(fastifyPostgres, {
connectionString: evaluateConnectionString,
name: 'evaluate',
pool: {
min: 0,
max: 100,
idleTimeoutMillis: 1000,
maxLifetimeSeconds: 60
}
})

isInitialized = true
console.log('Database connections initialized')
}

/**
* Execute a query on the stats database
* @param {Function} queryFn - Function that takes a client and executes a query
* @returns {Promise<*>} The result of the query function
*/
export async function withStatsDb(queryFn) {
if (!isInitialized) {
throw new Error('Database connections not initialized')
}

const client = await fastifyApp.pg.stats.connect()
try {
return await queryFn(client)
} finally {
client.release()
}
}

/**
* Execute a query on the evaluate database
* @param {Function} queryFn - Function that takes a client and executes a query
* @returns {Promise<*>} The result of the query function
*/
export async function withEvaluateDb(queryFn) {
if (!isInitialized) {
throw new Error('Database connections not initialized')
}

const client = await fastifyApp.pg.evaluate.connect()
try {
return await queryFn(client)
} finally {
client.release()
}
}

/**
* Get PgPools object compatible with the existing API
* @returns {Object} PgPools object
*/
export function getPgPools() {
if (!isInitialized) {
throw new Error('Database connections not initialized')
}

return {
stats: fastifyApp.pg.stats,
evaluate: fastifyApp.pg.evaluate,
async end() {
await closeDb()
}
}
}

/**
* Close all database connections
* @returns {Promise<void>}
*/
export async function closeDb() {
if (isInitialized && fastifyApp) {
await fastifyApp.close()
isInitialized = false
console.log('Database connections closed')
}
}