Skip to content

Commit

Permalink
fix(runtime): wait for db ready (labring#1774)
Browse files Browse the repository at this point in the history
  • Loading branch information
0fatal authored Jan 4, 2024
1 parent 0ed539e commit f1f0798
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
25 changes: 22 additions & 3 deletions runtimes/nodejs/src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import { MongoAccessor } from 'database-proxy'
import Config from './config'
import { MongoClient } from 'mongodb'
import { logger } from './support/logger'

/**
* Database Management
Expand All @@ -29,9 +30,27 @@ export class DatabaseAgent {
return this.client.db()
}

static initialize() {
this._client = new MongoClient(Config.DB_URI)
return this._client.connect()
static async initialize() {
const client = new MongoClient(Config.DB_URI)

let retryDelay = 1000 // 1s
const maxDelay = 30 * 1000 // 30s

while (true) {
try {
this._client = await client.connect()
logger.info('db connected')
return this._client
} catch (error) {
if (retryDelay > maxDelay) {
retryDelay = 1000
logger.warn('connect db failed, try again...')
}

await new Promise((resolve) => setTimeout(resolve, retryDelay))
retryDelay *= 2
}
}
}

/**
Expand Down
9 changes: 8 additions & 1 deletion runtimes/nodejs/src/handler/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { handleDatabaseProxy } from './db-proxy'
import { handlePackageTypings } from './typings'
import { generateUUID } from '../support/utils'
import { handleInvokeFunction } from './invoke'
import { DatabaseAgent } from '../db'

/**
* multer uploader config
Expand All @@ -36,7 +37,13 @@ export const router = Router()

router.post('/proxy/:policy', handleDatabaseProxy)
router.get('/_/typing/package', handlePackageTypings)
router.get('/_/healthz', (_req, res) => res.status(200).send('ok'))
router.get('/_/healthz', (_req, res) => {
if (DatabaseAgent.client) {
res.status(200).send('ok')
} else {
res.status(503).send('db is not ready')
}
})

/**
* Invoke cloud function through HTTP request.
Expand Down

0 comments on commit f1f0798

Please sign in to comment.