Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ Stock analysis, screening, and backtesting live in the shared Python CLIs under
3. **Work in verifiable units.** For multi-step work, set the dependency order and verification check for each unit before editing, and verify each unit before building on it. Follow [ponytail](https://github.com/DietrichGebert/ponytail) by reusing [scripts/tool-calls.mjs](scripts/tool-calls.mjs), [scripts/venv-python.mjs](scripts/venv-python.mjs), [tools/_subproc.py](tools/_subproc.py), and [tests/conftest.py](tests/conftest.py) instead of adding parallel helpers or dependencies.
4. **Prove the change.** Rerun the failing reproduction and exercise the real affected entry point. Report the exact commands, observed results, and the host, OS, install mode, or artifact checked. When a target such as Windows, macOS, or an installed host is unavailable, run the nearest local check and state what remains unverified.

When the external [Matt Pocock skills](https://github.com/mattpocock/skills) are installed locally, use `diagnosing-bugs` for regressions, `tdd` for Python behavior changes, and `to-spec` with `to-tickets` for breaking or multi-phase changes. Keep specs, review notes, and external skill files out of commits.
When the external [Matt Pocock skills](https://github.com/mattpocock/skills) are installed locally, use `diagnosing-bugs` for regressions, `tdd` for Python behavior changes, and `to-spec` with `to-tickets` for breaking or multi-phase changes. When the [pstack skills](https://github.com/cursor/plugins/tree/main/pstack/) are installed locally, use `benchmark-checklist` and `principle-explain-the-number` before trusting or reporting performance measurements (name the limiter from profiles or counters, verify outputs and error counts, and report run count, median, and range), and use `blast-radius` for cross-cutting changes alongside `principle-fix-root-causes`, `principle-subtract-before-you-add`, and `principle-prove-it-works`. Keep specs, review notes, and external skill files out of commits.

## Local setup and verification

Expand Down
150 changes: 132 additions & 18 deletions dsh/dashboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writ
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { randomUUID } from "node:crypto";
import { createHash, randomUUID } from "node:crypto";
import type { IncomingMessage, ServerResponse } from "node:http";
import type { Context } from "@deepseek-ai/cordis";

Expand Down Expand Up @@ -233,8 +233,10 @@ interface Job {
/** Small priority queue so a burst of trend/stat work never delays quotes. */
function createPriorityLimiter(limit: number) {
let active = 0;
let held = 0;
const waiting: Array<{ priority: number; start: () => void; cancel: () => void }> = [];
const next = () => {
if (held > 0) return;
while (active < limit && waiting.length) {
waiting.sort((a, b) => a.priority - b.priority);
active++;
Expand All @@ -252,6 +254,11 @@ function createPriorityLimiter(limit: number) {
next();
});
},
/** Defer dispatch while a scheduling turn enqueues batched and unbatched jobs together. */
hold<T>(fn: () => T): T {
held++;
try { return fn(); } finally { held--; next(); }
},
/** Settle queued jobs without starting them. */
clear() { for (const job of waiting.splice(0)) job.cancel(); },
get queued() { return waiting.length + active; },
Expand Down Expand Up @@ -342,7 +349,8 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand
});
}
function flushBatch(command: "quotes" | "klines", key: string) {
const batch = pendingBatches.get(key)!;
const batch = pendingBatches.get(key);
if (!batch) return;
pendingBatches.delete(key);
const args = [command, batch.map(item => item.symbol).join(","), ...(command === "klines" ? ["--count", "30"] : ["--watchlist"])];
// The CLI times out slow rows itself after 30 s, so one hung provider cannot fail the whole batch.
Expand All @@ -357,10 +365,12 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand
}

function quoteJob(symbol: string, priority: number): Job {
const region = watchRegion(symbol);
return {
key: `quote:${symbol}`, kind: "quote", region: watchRegion(symbol), priority, batched: true,
key: `quote:${symbol}`, kind: "quote", region, priority, batched: true,
// Per-region batches: slow overseas/fund/advisor quotes must not hold up A-share quotes.
run: async () => {
const value = await batched("quotes", "all", symbol, priority) as Record<string, unknown> | null;
const value = await batched("quotes", region, symbol, priority) as Record<string, unknown> | null;
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("报价数据格式不正确");
if (value.error) throw new Error(safeError(value.error, "报价暂不可用"));
return { ...value, symbol };
Expand All @@ -382,16 +392,71 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand
};
}

const pendingPhases: Array<{ market: string; resolve: (value: unknown) => void; reject: (error: unknown) => void }> = [];
let phasesScheduled = false;
function batchedPhase(region: Region): Promise<unknown> {
const market = region.toUpperCase();
return new Promise((resolve, reject) => {
pendingPhases.push({ market, resolve, reject });
if (!phasesScheduled) {
phasesScheduled = true;
queueMicrotask(flushPhases);
}
});
}
function runSinglePhase(item: { market: string; resolve: (value: unknown) => void; reject: (error: unknown) => void }) {
limiter.run(0, () => py("trading_calendar.py", ["phase", item.market], 10_000)).then(
value => {
if (!value || typeof value !== "object" || Array.isArray(value) || "error" in value) {
item.reject(new Error("交易阶段暂不可用"));
} else {
item.resolve(value);
}
},
error => item.reject(error),
);
}
function flushPhases() {
phasesScheduled = false;
const batch = pendingPhases.splice(0);
if (!batch.length) return;
if (disposed) {
batch.forEach(item => item.reject(new Error("仪表盘已停止")));
return;
}
if (batch.length === 1) {
runSinglePhase(batch[0]);
return;
}
const markets = batch.map(item => item.market).join(",");
limiter.run(0, () => py("trading_calendar.py", ["phases", markets], 10_000)).then(
Comment thread
Weaxs marked this conversation as resolved.
Resolved
map => {
if (!map || typeof map !== "object" || Array.isArray(map) || "error" in map) {
throw new Error("交易阶段暂不可用");
}
const record = map as Record<string, unknown>;
for (const item of batch) {
const value = record[item.market] as Record<string, unknown> | undefined;
if (!value || typeof value !== "object" || value.error) item.reject(new Error("交易阶段暂不可用"));
else item.resolve(value);
}
},
).catch(error => {
if (disposed) {
batch.forEach(item => item.reject(error));
return;
}
// Process-level failure (timeout/crash): isolate each market with its own phase lookup.
for (const item of batch) runSinglePhase(item);
});
}

function jobs(symbols: string[]): Job[] {
const list: Job[] = [];
for (const region of REGIONS) {
list.push({
key: `phase:${region}`, kind: "phase", region, priority: 0,
run: async () => {
const value = await py("trading_calendar.py", ["phase", region.toUpperCase()], 10_000) as Record<string, unknown>;
if (!value || typeof value !== "object" || value.error) throw new Error("交易阶段暂不可用");
return value;
},
key: `phase:${region}`, kind: "phase", region, priority: 0, batched: true,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
run: () => batchedPhase(region),
});
}
for (const symbol of symbols) list.push(quoteJob(symbol, 1));
Expand Down Expand Up @@ -482,8 +547,32 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand
return task;
}

const assetCache = new Map<string, { ino: bigint; mtimeNs: bigint; size: bigint; body: Buffer; etag: string }>();
let watchlistCache: { ino: bigint; mtimeNs: bigint; size: bigint; symbols: string[] } | null = null;
function cachedWatchlist(): string[] {
let st;
try {
st = statSync(watchlistFile, { bigint: true });
} catch (error) {
watchlistCache = null;
if ((error as { code?: string }).code === "ENOENT") return [];
throw new Error("无法读取自选股文件");
}
if (watchlistCache && watchlistCache.ino === st.ino && watchlistCache.mtimeNs === st.mtimeNs && watchlistCache.size === st.size) {
return watchlistCache.symbols;
}
try {
const symbols = readWatchlist(watchlistFile);
watchlistCache = { ino: st.ino, mtimeNs: st.mtimeNs, size: st.size, symbols };
return symbols;
} catch (error) {
watchlistCache = null;
throw error;
}
}

function currentSymbols(): string[] {
try { return readWatchlist(watchlistFile); } catch { return []; }
try { return cachedWatchlist(); } catch { return []; }
}

/** Start every due job; resolves when the jobs started by this tick finish. */
Expand All @@ -494,7 +583,17 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand
const keep = new Set(list.map(job => job.key));
for (const key of slots.keys()) if (!keep.has(key) && !slots.get(key)!.running) slots.delete(key);
const now = Date.now();
await Promise.all(list.filter(job => due(job, now)).sort((a, b) => a.priority - b.priority).map(start));
const started = limiter.hold(() => {
const tasks = list.filter(job => due(job, now)).sort((a, b) => a.priority - b.priority).map(start);
// Submit queued phase/quote/kline batches before releasing limiter dispatch so priority-0 phases
// and priority-1 quotes enter workers ahead of priority-2 overseas index jobs.
flushPhases();
for (const key of [...pendingBatches.keys()]) {
flushBatch(key.startsWith("quotes:") ? "quotes" : "klines", key);
}
return tasks;
});
await Promise.all(started);
}

async function settle() {
Expand Down Expand Up @@ -548,7 +647,7 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand
function snapshot(region: Region) {
lastSeen = Date.now();
viewedRegion = region;
const symbols = readWatchlist(watchlistFile);
const symbols = cachedWatchlist();
kick();
void checkLatest();
return {
Expand Down Expand Up @@ -616,11 +715,12 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand
return sendJson(res, 202, { ok: true, pending: limiter.queued });
}
if (rest === "/api/watchlist") {
if (req.method === "GET") return sendJson(res, 200, { symbols: readWatchlist(watchlistFile) });
if (req.method === "GET") return sendJson(res, 200, { symbols: cachedWatchlist() });
if (req.method === "POST") {
const body = await readJson(req);
if (!body?.op) throw new HttpError(400, "必须指定 add 或 remove 操作");
const saved = await updateWatchlist(watchlistFile, body.op, body.symbols);
watchlistCache = null;
kick();
return sendJson(res, 200, { symbols: saved });
}
Expand Down Expand Up @@ -653,19 +753,33 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand
const asset = STATIC_FILES.get(rest as "/" | "/app.js" | "/style.css");
if (!asset) return sendJson(res, 404, { error: "Not found" });
const [file, contentType] = asset;
let body: Buffer;
const assetPath = join(webDir, file);
let entry = assetCache.get(file);
try {
body = readFileSync(join(webDir, file));
const st = statSync(assetPath, { bigint: true });
if (!entry || entry.ino !== st.ino || entry.mtimeNs !== st.mtimeNs || entry.size !== st.size) {
const body = readFileSync(assetPath);
const etag = `"${createHash("sha256").update(body).digest("base64url").slice(0, 16)}"`;
entry = { ino: st.ino, mtimeNs: st.mtimeNs, size: st.size, body, etag };
assetCache.set(file, entry);
}
} catch {
assetCache.delete(file);
return sendJson(res, 404, { error: "Not found" });
}
if (req.headers["if-none-match"] === entry.etag) {
res.writeHead(304, { etag: entry.etag, "cache-control": "no-cache" });
res.end();
return;
}
res.writeHead(200, {
"content-type": contentType,
"content-length": body.length,
"content-length": entry.body.length,
etag: entry.etag,
"cache-control": "no-cache",
"x-content-type-options": "nosniff",
});
res.end(req.method === "HEAD" ? undefined : body);
res.end(req.method === "HEAD" ? undefined : entry.body);
} catch (error) {
if (error instanceof HttpError) return sendJson(res, error.status, { error: error.message });
const message = error instanceof Error && !/[/\\]/.test(error.message) ? error.message : "仪表盘服务暂时不可用";
Expand Down
3 changes: 3 additions & 0 deletions dsh/web/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -743,9 +743,12 @@ function renderRows(flash: Map<string, Direction>) {
return;
}
if (!state.snap.watchlist.length) {
for (const key of sparkCache.keys()) if (key.startsWith("watch:")) sparkCache.delete(key);
body.append(emptyRow());
return;
}
const activeWatchKeys = new Set(state.snap.watchlist.map(item => `watch:${item.symbol}`));
for (const key of sparkCache.keys()) if (key.startsWith("watch:") && !activeWatchKeys.has(key)) sparkCache.delete(key);
for (const item of items!) {
const quote = item.quote;
const price = watchPrice(item);
Expand Down
Loading
Loading