Bladeren bron

fix: 修复一些已知问题

iaun 7 maanden geleden
bovenliggende
commit
330cac19f1
2 gewijzigde bestanden met toevoegingen van 57 en 5 verwijderingen
  1. 20 5
      server/src/services/instance-manager.ts
  2. 37 0
      server/src/services/lifetime-timer.ts

+ 20 - 5
server/src/services/instance-manager.ts

@@ -123,11 +123,26 @@ async function waitForState(
 ): Promise<void> {
   const deadline = Date.now() + timeoutMs;
   while (Date.now() < deadline) {
-    const desc = await ec2.send(
-      new DescribeInstancesCommand({ InstanceIds: [ec2InstanceId] }),
-    );
-    const state = desc.Reservations?.[0]?.Instances?.[0]?.State?.Name;
-    if (state === desiredState) return;
+    try {
+      const desc = await ec2.send(
+        new DescribeInstancesCommand({ InstanceIds: [ec2InstanceId] }),
+      );
+      const state = desc.Reservations?.[0]?.Instances?.[0]?.State?.Name;
+      if (state === desiredState) return;
+    } catch (err: any) {
+      // AWS eventual consistency: instance ID may not be visible yet
+      const code = err.Code ?? err.name ?? '';
+      if (
+        code === 'InvalidInstanceID.NotFound' ||
+        err.message?.includes('does not exist')
+      ) {
+        console.warn(
+          `[waitForState] 实例 ${ec2InstanceId} 尚未可见,等待重试...`,
+        );
+      } else {
+        throw err;
+      }
+    }
     await new Promise((r) => setTimeout(r, intervalMs));
   }
   throw new Error(`实例 ${ec2InstanceId} 未在超时时间内进入 ${desiredState} 状态`);

+ 37 - 0
server/src/services/lifetime-timer.ts

@@ -40,6 +40,39 @@ export async function checkExpiredInstances(
   }
 }
 
+/**
+ * Delete instance records that have been in 'terminated' status for over 24 hours.
+ * Also cleans up associated rdp_sessions to avoid FK constraint issues.
+ */
+export async function cleanupTerminatedInstances(): Promise<void> {
+  const db = getDb();
+  const cutoff = Math.floor(Date.now() / 1000) - 24 * 3600;
+
+  const rows = db
+    .prepare(
+      `SELECT id, ec2_instance_id FROM instances
+       WHERE status = 'terminated' AND created_at < ?`,
+    )
+    .all(cutoff) as { id: number; ec2_instance_id: string }[];
+
+  if (rows.length === 0) return;
+
+  const deleteRdp = db.prepare('DELETE FROM rdp_sessions WHERE instance_id = ?');
+  const deleteInstance = db.prepare('DELETE FROM instances WHERE id = ?');
+
+  const tx = db.transaction(() => {
+    for (const row of rows) {
+      deleteRdp.run(row.id);
+      deleteInstance.run(row.id);
+    }
+  });
+  tx();
+
+  console.log(
+    `[Lifetime_Timer] 已清理 ${rows.length} 条已销毁实例记录`,
+  );
+}
+
 /**
  * Start the cron job that checks for expired instances every minute.
  */
@@ -49,6 +82,10 @@ export function startLifetimeTimer(): void {
     checkExpiredInstances().catch((err) => {
       console.error('[Lifetime_Timer] 检查过期实例时出错:', err.message);
     });
+    // Clean up terminated instance records older than 24 hours
+    cleanupTerminatedInstances().catch((err) => {
+      console.error('[Lifetime_Timer] 清理已销毁实例记录时出错:', err.message);
+    });
     // Clean up logs older than 30 days
     try {
       const db = getDb();