feat(boot-notification): 添加超时处理和日志记录以增强引导通知的持久性
This commit is contained in:
@@ -9,6 +9,8 @@ export const useDrizzle = () => {
|
||||
if (!pgPoolInstance || !drizzleInstance) {
|
||||
pgPoolInstance = new Pool({
|
||||
connectionString: process.env.DATABASE_CONNECTION_STRING,
|
||||
connectionTimeoutMillis: 3000,
|
||||
idleTimeoutMillis: 10000,
|
||||
})
|
||||
drizzleInstance = drizzle({ client: pgPoolInstance, schema })
|
||||
}
|
||||
|
||||
@@ -8,14 +8,29 @@ import type {
|
||||
} from '../types.ts'
|
||||
|
||||
const DEFAULT_HEARTBEAT_INTERVAL = 60
|
||||
const BOOT_NOTIFICATION_DB_TIMEOUT_MS = 3000
|
||||
|
||||
function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string) {
|
||||
return Promise.race<T>([
|
||||
promise,
|
||||
new Promise<T>((_, reject) => {
|
||||
setTimeout(() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)), timeoutMs)
|
||||
}),
|
||||
])
|
||||
}
|
||||
|
||||
export async function handleBootNotification(
|
||||
payload: BootNotificationRequest,
|
||||
ctx: OcppConnectionContext,
|
||||
): Promise<BootNotificationResponse> {
|
||||
const db = useDrizzle()
|
||||
const currentTime = dayjs().toISOString()
|
||||
|
||||
const [cp] = await db
|
||||
console.log(`[OCPP] BootNotification ${ctx.chargePointIdentifier} received`)
|
||||
|
||||
try {
|
||||
const [cp] = await withTimeout(
|
||||
db
|
||||
.insert(chargePoint)
|
||||
.values({
|
||||
id: crypto.randomUUID(),
|
||||
@@ -50,7 +65,10 @@ export async function handleBootNotification(
|
||||
updatedAt: dayjs().toDate(),
|
||||
},
|
||||
})
|
||||
.returning()
|
||||
.returning(),
|
||||
BOOT_NOTIFICATION_DB_TIMEOUT_MS,
|
||||
`BootNotification persistence for ${ctx.chargePointIdentifier}`,
|
||||
)
|
||||
|
||||
const status = cp.registrationStatus
|
||||
ctx.isRegistered = status === 'Accepted'
|
||||
@@ -58,8 +76,18 @@ export async function handleBootNotification(
|
||||
console.log(`[OCPP] BootNotification ${ctx.chargePointIdentifier} status=${status}`)
|
||||
|
||||
return {
|
||||
currentTime: dayjs().toISOString(),
|
||||
currentTime,
|
||||
interval: DEFAULT_HEARTBEAT_INTERVAL,
|
||||
status,
|
||||
}
|
||||
} catch (error) {
|
||||
ctx.isRegistered = false
|
||||
console.error(`[OCPP] BootNotification ${ctx.chargePointIdentifier} persistence failed:`, error)
|
||||
|
||||
return {
|
||||
currentTime,
|
||||
interval: DEFAULT_HEARTBEAT_INTERVAL,
|
||||
status: 'Pending',
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user