feat(boot-notification): 添加超时处理和日志记录以增强引导通知的持久性

This commit is contained in:
2026-03-15 04:23:13 +08:00
parent 216a8e118d
commit 8a537e80e3
2 changed files with 73 additions and 43 deletions

View File

@@ -9,6 +9,8 @@ export const useDrizzle = () => {
if (!pgPoolInstance || !drizzleInstance) { if (!pgPoolInstance || !drizzleInstance) {
pgPoolInstance = new Pool({ pgPoolInstance = new Pool({
connectionString: process.env.DATABASE_CONNECTION_STRING, connectionString: process.env.DATABASE_CONNECTION_STRING,
connectionTimeoutMillis: 3000,
idleTimeoutMillis: 10000,
}) })
drizzleInstance = drizzle({ client: pgPoolInstance, schema }) drizzleInstance = drizzle({ client: pgPoolInstance, schema })
} }

View File

@@ -8,14 +8,29 @@ import type {
} from '../types.ts' } from '../types.ts'
const DEFAULT_HEARTBEAT_INTERVAL = 60 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( export async function handleBootNotification(
payload: BootNotificationRequest, payload: BootNotificationRequest,
ctx: OcppConnectionContext, ctx: OcppConnectionContext,
): Promise<BootNotificationResponse> { ): Promise<BootNotificationResponse> {
const db = useDrizzle() 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) .insert(chargePoint)
.values({ .values({
id: crypto.randomUUID(), id: crypto.randomUUID(),
@@ -50,7 +65,10 @@ export async function handleBootNotification(
updatedAt: dayjs().toDate(), updatedAt: dayjs().toDate(),
}, },
}) })
.returning() .returning(),
BOOT_NOTIFICATION_DB_TIMEOUT_MS,
`BootNotification persistence for ${ctx.chargePointIdentifier}`,
)
const status = cp.registrationStatus const status = cp.registrationStatus
ctx.isRegistered = status === 'Accepted' ctx.isRegistered = status === 'Accepted'
@@ -58,8 +76,18 @@ export async function handleBootNotification(
console.log(`[OCPP] BootNotification ${ctx.chargePointIdentifier} status=${status}`) console.log(`[OCPP] BootNotification ${ctx.chargePointIdentifier} status=${status}`)
return { return {
currentTime: dayjs().toISOString(), currentTime,
interval: DEFAULT_HEARTBEAT_INTERVAL, interval: DEFAULT_HEARTBEAT_INTERVAL,
status, status,
} }
} catch (error) {
ctx.isRegistered = false
console.error(`[OCPP] BootNotification ${ctx.chargePointIdentifier} persistence failed:`, error)
return {
currentTime,
interval: DEFAULT_HEARTBEAT_INTERVAL,
status: 'Pending',
}
}
} }