Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

3.0 KB
Raw Blame
import { aiDevtools, aiObservability, evlogSetup } from '@activepieces/server-utils'
import { ApEnvironment } from '@activepieces/shared'
import dayjs from 'dayjs'
import { FastifyInstance } from 'fastify'
import { appPostBoot } from './app/app'
import { initializeDatabase } from './app/database'
import { distributedLock } from './app/database/redis-connections'
import { system } from './app/helper/system/system'
import { AppSystemProp } from './app/helper/system/system-props'
import { setupServer } from './app/server'

const start = async (app: FastifyInstance): Promise<void> => {
    try {
        const port = Number(system.get(AppSystemProp.PORT))
        await app.listen({
            host: '::',
            port,
        })
        if (system.isApp()) {
            await appPostBoot(app)
        }
    }
    catch (err) {
        app.log.error({ err }, 'Failed to start server')
        process.exit(1)
    }
}

// This might be needed as it can be called twice
let shuttingDown = false


const stop = async ({ app, signal }: { app: FastifyInstance, signal: NodeJS.Signals }): Promise<void> => {
    if (shuttingDown) return
    shuttingDown = true

    try {
        app.log.info({ signal }, '[main#stop] Received shutdown signal, stopping server gracefully')
        await app.close()
        await Promise.all([evlogSetup.flush(), aiObservability.flush()])
        process.exit(0)
    }
    catch (err) {
        app.log.error({ err }, 'Error stopping server')
        process.exit(1)
    }
}

function setupTimeZone(): void {
    // It's important to set the time zone to UTC when working with dates in PostgreSQL.
    // If the time zone is not set to UTC, there can be problems when storing dates in UTC but not considering the UTC offset when converting them back to local time. This can lead to incorrect fields being displayed for the created
    // https://stackoverflow.com/questions/68240368/typeorm-find-methods-returns-wrong-timestamp-time
    process.env.TZ = 'UTC'
}


const main = async (): Promise<void> => {
    setupTimeZone()
    await aiDevtools.register({ enabled: system.get(AppSystemProp.ENVIRONMENT) === ApEnvironment.DEVELOPMENT })
    if (system.isApp()) {
        await distributedLock(system.globalLogger()).runExclusive({
            key: 'database-migration-lock',
            timeoutInSeconds: dayjs.duration(10, 'minutes').asSeconds(),
            fn: async () => initializeDatabase({ runMigrations: true }),
        })
    }
    const app = await setupServer()

    process.on('SIGINT', async () => {
        await stop({ app, signal: 'SIGINT' }).catch((e) => system.globalLogger().error({ err: e }, '[main#stop] Failed to stop server'))
    })

    process.on('SIGTERM', async () => {
        await stop({ app, signal: 'SIGTERM' }).catch((e) => system.globalLogger().error({ err: e }, '[main#stop] Failed to stop server'))
    })

    await start(app)
}

main().catch((e) => {
    system.globalLogger().error({ err: e }, '[main#start] Failed to start server')
    process.exit(1)
})