window-warmup 0.1.6: a host swap no longer leaves 3492 dead (#1227)
shawn8888 found it (#1227): server() probed the port, saw this plugin's marker and returned {} for good. During a host swap the old host is still serving, so the new one never started, and once the old one exited nothing served 3492 and the scheduler stopped until the next swap. The old host also holds service.lock, so retrying the bind alone would have come up read-only (lockedBy) with no scheduler. Now server() returns {} at once and, once per port, checks every second in the background: while the marker answers it waits; when it stops it runs the whole start (migrate, lock, bind, scheduler), and an EADDRINUSE from a port not let go yet is tried again the next second. The data directory is the one the call resolved. A port held by something without the marker still throws, as before. Run (mote, HOME=$(mktemp -d)): - bun test in packages/window-warmup: 280 pass, 0 fail. - tsc --noEmit: ok. bun scripts/check.mjs window-warmup: ok. - dist rebuilt with bun scripts/build.ts; dist.test passes. Broken by hand: origin/main's src/plugin.ts with the new tests: both fail (marker stops, real old service holding port and lock stops). Not tried: a real magpie host swap.
This commit is contained in:
+51
-18
@@ -963,7 +963,7 @@ import { randomBytes, timingSafeEqual } from "crypto";
|
||||
import { mkdir as mkdir2, readFile as readFile3, writeFile as writeFile2 } from "fs/promises";
|
||||
import path2, { basename, extname, join as join4, resolve as resolve2 } from "path";
|
||||
// package.json
|
||||
var version = "0.1.5";
|
||||
var version = "0.1.6";
|
||||
|
||||
// src/diagnostics.ts
|
||||
var DIAGNOSTICS_SCHEMA = "window-warmup-diagnostics/1";
|
||||
@@ -2524,30 +2524,63 @@ function defaultDir(env = process.env) {
|
||||
return join5(xdgConfigHome(env), "magpie", "window-warmup");
|
||||
}
|
||||
var instances = new Map;
|
||||
var waiting = new Set;
|
||||
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
var inUse = (e) => e?.code === "EADDRINUSE";
|
||||
function start(listen, dir) {
|
||||
let instance = instances.get(listen);
|
||||
if (!instance) {
|
||||
instance = (async () => {
|
||||
await migrateLegacyState(dir);
|
||||
return startService({ port: listen, dir, base: gatewayBase() });
|
||||
})().catch((e) => {
|
||||
instances.delete(listen);
|
||||
throw e;
|
||||
});
|
||||
instances.set(listen, instance);
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
function startWhenFree(listen, dir) {
|
||||
if (waiting.has(listen))
|
||||
return;
|
||||
waiting.add(listen);
|
||||
(async () => {
|
||||
try {
|
||||
for (;; ) {
|
||||
await sleep(1000);
|
||||
if (instances.has(listen))
|
||||
return;
|
||||
if (await alreadyServing(listen))
|
||||
continue;
|
||||
try {
|
||||
await start(listen, dir);
|
||||
console.log(`[window-warmup] \u4E0A\u4E00\u4E2A\u5BBF\u4E3B\u5DF2\u677E\u624B\uFF0C${listen} \u63A5\u4E0A\u4E86`);
|
||||
return;
|
||||
} catch (e) {
|
||||
if (!inUse(e)) {
|
||||
console.error(`[window-warmup] ${listen} \u8D77\u4E0D\u6765\uFF1A${e instanceof Error ? e.message : String(e)}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
waiting.delete(listen);
|
||||
}
|
||||
})();
|
||||
}
|
||||
var plugin_default = {
|
||||
id: "magpie-window-warmup",
|
||||
server: async (_input, opts = {}) => {
|
||||
const port = Number(opts?.port);
|
||||
const listen = Number.isFinite(port) && port > 0 ? port : DEFAULT_PORT;
|
||||
if (await alreadyServing(listen))
|
||||
const dir = defaultDir();
|
||||
if (!instances.has(listen) && await alreadyServing(listen)) {
|
||||
console.log(`[window-warmup] ${listen} \u88AB\u4E0A\u4E00\u4E2A\u5BBF\u4E3B\u5360\u7740\uFF0C\u5B83\u4E00\u677E\u624B\u5C31\u63A5\u4E0A`);
|
||||
startWhenFree(listen, dir);
|
||||
return {};
|
||||
let instance = instances.get(listen);
|
||||
if (!instance) {
|
||||
instance = (async () => {
|
||||
const dir = defaultDir();
|
||||
await migrateLegacyState(dir);
|
||||
return startService({
|
||||
port: listen,
|
||||
dir,
|
||||
base: gatewayBase()
|
||||
});
|
||||
})().catch((e) => {
|
||||
instances.delete(listen);
|
||||
throw e;
|
||||
});
|
||||
instances.set(listen, instance);
|
||||
}
|
||||
await instance;
|
||||
await start(listen, dir);
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/page-window-warmup",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.6",
|
||||
"description": "窗口预热 Window Warmup:定时消息插件,定时给指定供应商/账号/模型发一条短消息,在额度窗口重置后、每天定时或每隔几小时自动预热保活,提前开启5小时/每周订阅额度(配额)窗口,适用 Codex、Claude、GLM 智谱、ZCode 等。Scheduled keep-alive message to warm up quota / usage / rate limit windows after reset (cron-like).",
|
||||
"author": "YangHonghang (https://github.com/YangHonghang)",
|
||||
"type": "module",
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// 宿主入口:magpie 加载本包并调用 server() 时启动本地服务(每个端口只起一次)。
|
||||
// 单纯 import 不占端口、不读写磁盘;启动失败清掉对应单例,宿主下次调用可重试。
|
||||
// 启动前先探测端口:响应带本插件的自标记头(server.ts 所有响应都带 x-window-warmup: 1)
|
||||
// → 已有本服务在跑,直接返回 {}(不重开数据目录、不迁移、不报错);没探测到才真正启动,
|
||||
// 端口被别的程序占用时 Bun.serve 仍抛原错误。
|
||||
// → 已有本服务在跑(多半是正在换下的上一个宿主),先返回 {},在后台等它松手再起来;
|
||||
// 没探测到才当场启动,端口被别的程序占用时 Bun.serve 仍抛原错误。
|
||||
import { join } from "node:path";
|
||||
import { gatewayBase } from "./gateway";
|
||||
import { xdgConfigHome } from "./magpie-files";
|
||||
@@ -22,6 +22,62 @@ function defaultDir(env: Record<string, string | undefined> = process.env): stri
|
||||
|
||||
/** 端口 → 启动中的服务;按端口分键,端口改了旧实例也不串 */
|
||||
const instances = new Map<number, Promise<ServiceHandle>>();
|
||||
/** 正在等上一个宿主松手的端口:每个端口只等一份 */
|
||||
const waiting = new Set<number>();
|
||||
|
||||
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
const inUse = (e: unknown) => (e as { code?: string } | null)?.code === "EADDRINUSE";
|
||||
|
||||
/** 起服务(迁移 + startService);失败清掉单例,下次可重试 */
|
||||
function start(listen: number, dir: string): Promise<ServiceHandle> {
|
||||
let instance = instances.get(listen);
|
||||
if (!instance) {
|
||||
instance = (async () => {
|
||||
// 首次启动(新目录还没有 state.json)时把旧包的数据接过来;迁移在打开 store 之前完成
|
||||
await migrateLegacyState(dir);
|
||||
return startService({ port: listen, dir, base: gatewayBase() });
|
||||
})().catch((e: unknown) => {
|
||||
instances.delete(listen);
|
||||
throw e;
|
||||
});
|
||||
instances.set(listen, instance);
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* 端口上是本插件的另一个服务:多半是 magpie 正在换下的上一个宿主,手上还有调用要跑完
|
||||
* (1 到 10 多秒,最长 10 分钟),端口和 service.lock 都在它手里。以前这里直接返回 {},
|
||||
* 旧宿主一退出 3492 上就谁也没有,调度也停了,直到下次换宿主(#1227)。现在在后台
|
||||
* 每秒探一次:它不再应答就整套起来(抢锁 + 绑端口 + 调度)。它还在应答就一直等,
|
||||
* 一直在跑的另一份服务也只是让这里多等,不会抢它的锁。
|
||||
*/
|
||||
function startWhenFree(listen: number, dir: string): void {
|
||||
if (waiting.has(listen)) return;
|
||||
waiting.add(listen);
|
||||
void (async () => {
|
||||
try {
|
||||
for (;;) {
|
||||
await sleep(1000);
|
||||
if (instances.has(listen)) return;
|
||||
if (await alreadyServing(listen)) continue;
|
||||
try {
|
||||
await start(listen, dir);
|
||||
console.log(`[window-warmup] 上一个宿主已松手,${listen} 接上了`);
|
||||
return;
|
||||
} catch (e) {
|
||||
// 刚不应答、端口还没放:下一秒再试;别的错误报出来,不再空转
|
||||
if (!inUse(e)) {
|
||||
console.error(`[window-warmup] ${listen} 起不来:${e instanceof Error ? e.message : String(e)}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
waiting.delete(listen);
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
export default {
|
||||
id: "magpie-window-warmup",
|
||||
@@ -29,25 +85,14 @@ export default {
|
||||
server: async (_input: unknown, opts: { port?: number } = {}) => {
|
||||
const port = Number(opts?.port);
|
||||
const listen = Number.isFinite(port) && port > 0 ? port : DEFAULT_PORT;
|
||||
if (await alreadyServing(listen)) return {};
|
||||
let instance = instances.get(listen);
|
||||
if (!instance) {
|
||||
instance = (async () => {
|
||||
const dir = defaultDir();
|
||||
// 首次启动(新目录还没有 state.json)时把旧包的数据接过来;迁移在打开 store 之前完成
|
||||
await migrateLegacyState(dir);
|
||||
return startService({
|
||||
port: listen,
|
||||
dir,
|
||||
base: gatewayBase(),
|
||||
});
|
||||
})().catch((e: unknown) => {
|
||||
instances.delete(listen);
|
||||
throw e;
|
||||
});
|
||||
instances.set(listen, instance);
|
||||
// 数据目录在这里定下:后台接手时用的也是这一份
|
||||
const dir = defaultDir();
|
||||
if (!instances.has(listen) && (await alreadyServing(listen))) {
|
||||
console.log(`[window-warmup] ${listen} 被上一个宿主占着,它一松手就接上`);
|
||||
startWhenFree(listen, dir);
|
||||
return {};
|
||||
}
|
||||
await instance;
|
||||
await start(listen, dir);
|
||||
return {};
|
||||
},
|
||||
};
|
||||
|
||||
@@ -538,23 +538,72 @@ function withDir(dir: string): () => void {
|
||||
};
|
||||
}
|
||||
|
||||
test("端口探测:已有本插件的服务(带标记头)→ 直接返回,不重开数据目录", async () => {
|
||||
/** 等到 cond 成立(最多 ms 毫秒),等的是状态不是时长 */
|
||||
async function until(cond: () => Promise<boolean>, ms = 10_000): Promise<boolean> {
|
||||
const end = Date.now() + ms;
|
||||
while (Date.now() < end) {
|
||||
if (await cond()) return true;
|
||||
await Bun.sleep(100);
|
||||
}
|
||||
return cond();
|
||||
}
|
||||
|
||||
/** 一个空闲端口:先占后放 */
|
||||
function freePort(): number {
|
||||
const probe = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => new Response("x") });
|
||||
const port = probe.port!;
|
||||
probe.stop(true);
|
||||
return port;
|
||||
}
|
||||
|
||||
test("端口探测:已有本插件的服务(带标记头)→ 先返回,不重开数据目录;它松手后接上", async () => {
|
||||
const marker = Bun.serve({
|
||||
port: 0,
|
||||
hostname: "127.0.0.1",
|
||||
fetch: () => new Response("{}", { headers: { "x-window-warmup": "1" } }),
|
||||
});
|
||||
const port = marker.port!;
|
||||
// 故意用不存在的目录:startService 一旦被调就会 mkdir 出来
|
||||
const dir = join(tmpdir(), `ww-plugin-absent-${Date.now()}-${Math.random().toString(36).slice(2)}`);
|
||||
dirs.push(dir);
|
||||
const restore = withDir(dir);
|
||||
try {
|
||||
expect(await plugin.server(null, { port: marker.port })).toEqual({});
|
||||
expect(await plugin.server(null, { port })).toEqual({});
|
||||
} finally {
|
||||
restore();
|
||||
marker.stop(true);
|
||||
}
|
||||
// 它还在应答:一直不起,数据目录也不碰
|
||||
await Bun.sleep(1500);
|
||||
expect(await stat(dir).then(() => true, () => false)).toBe(false);
|
||||
});
|
||||
marker.stop(true);
|
||||
// 它不应答了:本插件的服务在同一端口、同一目录接上(#1227)
|
||||
expect(await until(async () => (await alreadyServing(port)) && (await stat(dir).then(() => true, () => false)))).toBe(true);
|
||||
}, 20_000);
|
||||
|
||||
test("换宿主:上一个宿主还占着端口和锁,它停下后新宿主接上并持锁调度(#1227)", async () => {
|
||||
const gw = fakeGateway({ models: MODELS });
|
||||
gateways.push(gw);
|
||||
const dir = await mkdtemp(join(tmpdir(), "ww-plugin-handover-"));
|
||||
dirs.push(dir);
|
||||
const port = freePort();
|
||||
// 上一个宿主:同一端口、同一目录,手上有 service.lock
|
||||
const old = await startService({ port, dir, base: gw.base });
|
||||
const restore = withDir(dir);
|
||||
try {
|
||||
expect(await plugin.server(null, { port })).toEqual({});
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
await old.stop();
|
||||
expect(await until(() => alreadyServing(port))).toBe(true);
|
||||
const token = await loadOrCreateToken(dir);
|
||||
const state = (await (
|
||||
await fetch(`http://127.0.0.1:${port}/api/state`, { headers: { "x-window-warmup-token": token } })
|
||||
).json()) as { lockedBy?: number; fatal?: string };
|
||||
// 接上的不是只读:锁是它的,调度在跑
|
||||
expect(state.lockedBy ?? null).toBeNull();
|
||||
expect(state.fatal ?? null).toBeNull();
|
||||
}, 20_000);
|
||||
|
||||
test("端口探测:端口空闲 → 照常启动,响应带标记头", async () => {
|
||||
const probe = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => new Response("x") });
|
||||
|
||||
Reference in New Issue
Block a user