@d86e/hive-panel 1.0.23 → 1.0.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/SPEC.md +7 -1
- package/package.json +1 -1
- package/public/panel.css +42 -0
- package/public/panel.js +1056 -102
- package/src/cache.js +269 -0
- package/src/data.js +73 -0
- package/src/event-store.js +68 -0
- package/src/server.js +77 -6
package/src/cache.js
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { execFile } from "node:child_process";
|
|
4
|
+
import { isInitialised } from "./data.js";
|
|
5
|
+
|
|
6
|
+
export const SNAPSHOT_TTL_MS = 2_000;
|
|
7
|
+
export const EVENT_TAIL_MAX = 5_000;
|
|
8
|
+
export const LANE_PAGE_LIMIT = 200;
|
|
9
|
+
const TASK_STATES = ["pending", "claimed", "done", "failed"];
|
|
10
|
+
|
|
11
|
+
function runCommand(file, args, cwd) {
|
|
12
|
+
return new Promise((resolve) => {
|
|
13
|
+
execFile(file, args, { cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }, (error, stdout, stderr) => {
|
|
14
|
+
resolve({ code: error ? (error.code ?? 1) : 0, stdout: stdout || "", stderr: stderr || "" });
|
|
15
|
+
});
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function parseJson(text, fallback) {
|
|
20
|
+
try { return JSON.parse(text); } catch { return fallback; }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const sortTimeCache = new WeakMap();
|
|
24
|
+
function sortTime(task) {
|
|
25
|
+
if (task !== null && typeof task === "object" && sortTimeCache.has(task)) return sortTimeCache.get(task);
|
|
26
|
+
const time = Date.parse(task?.stateChangedAt || task?.updatedAt || task?.createdAt || "");
|
|
27
|
+
const value = Number.isFinite(time)
|
|
28
|
+
? time
|
|
29
|
+
: (String(task?.id || "").match(/(\d+)$/) ? Number(String(task.id).match(/(\d+)$/)[1]) : Number.NaN);
|
|
30
|
+
if (task !== null && typeof task === "object") sortTimeCache.set(task, value);
|
|
31
|
+
return value;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function compareTasks(left, right) {
|
|
35
|
+
const a = sortTime(left);
|
|
36
|
+
const b = sortTime(right);
|
|
37
|
+
if (Number.isFinite(a) && Number.isFinite(b) && a !== b) return b - a;
|
|
38
|
+
if (Number.isFinite(a) !== Number.isFinite(b)) return Number.isFinite(a) ? -1 : 1;
|
|
39
|
+
return String(right?.id || "").localeCompare(String(left?.id || ""));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function lanePage(rows, stats, state, cursor, limit, search) {
|
|
43
|
+
const query = String(search || "").trim().toLowerCase();
|
|
44
|
+
let lane = rows.filter((task) => (task.state || "pending") === state);
|
|
45
|
+
if (query) {
|
|
46
|
+
lane = lane.filter((task) => String(task.id || "").toLowerCase().includes(query)
|
|
47
|
+
|| String(task.title || "").toLowerCase().includes(query));
|
|
48
|
+
}
|
|
49
|
+
lane.sort(compareTasks);
|
|
50
|
+
const total = Number(stats?.byState?.[state]);
|
|
51
|
+
const offset = Math.max(0, Math.floor(Number(cursor) || 0));
|
|
52
|
+
const size = Math.max(1, Math.min(LANE_PAGE_LIMIT, Math.floor(Number(limit) || LANE_PAGE_LIMIT)));
|
|
53
|
+
const items = lane.slice(offset, offset + size);
|
|
54
|
+
const next = offset + items.length;
|
|
55
|
+
return {
|
|
56
|
+
items,
|
|
57
|
+
total: Number.isFinite(total) && total >= 0 ? total : lane.length,
|
|
58
|
+
cursor: next,
|
|
59
|
+
hasMore: next < (Number.isFinite(total) && total >= 0 ? total : lane.length),
|
|
60
|
+
state,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Version-keyed snapshot cache. The expensive task CLI/stats/board calls run in
|
|
66
|
+
* parallel only on a version change; while the tasks ref and events file
|
|
67
|
+
* version stay unchanged, repeated requests are served from memory.
|
|
68
|
+
*/
|
|
69
|
+
export class SnapshotCache {
|
|
70
|
+
constructor({ repo, env = process.env, run = runCommand, now = () => Date.now(), statSync = fs.statSync } = {}) {
|
|
71
|
+
this.repo = repo;
|
|
72
|
+
this.env = env;
|
|
73
|
+
this.run = run;
|
|
74
|
+
this.now = now;
|
|
75
|
+
this.statSync = statSync;
|
|
76
|
+
this.versionKey = null;
|
|
77
|
+
this.taskData = null;
|
|
78
|
+
this.cache = null;
|
|
79
|
+
this.building = null;
|
|
80
|
+
this.lastBuildAt = 0;
|
|
81
|
+
this.metrics = { builds: 0, versionChecks: 0, eventBytesRead: 0, eventLinesParsed: 0, cliCalls: 0 };
|
|
82
|
+
this.events = { offset: 0, size: 0, mtimeMs: null, tail: [], total: 0, kinds: new Map() };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
eventsPath() { return path.join(this.repo, ".hive", "events.jsonl"); }
|
|
86
|
+
|
|
87
|
+
async version() {
|
|
88
|
+
this.metrics.versionChecks += 1;
|
|
89
|
+
const [ref, stat] = await Promise.all([
|
|
90
|
+
this.run("git", ["rev-parse", "refs/hive/v1/tasks"], this.repo).catch(() => ({ code: 1, stdout: "" })),
|
|
91
|
+
Promise.resolve().then(() => {
|
|
92
|
+
try { return this.statSync(this.eventsPath()); } catch { return null; }
|
|
93
|
+
}),
|
|
94
|
+
]);
|
|
95
|
+
const taskVersion = ref.code === 0 ? String(ref.stdout).trim() : "";
|
|
96
|
+
const eventsVersion = stat ? String(stat.size) + ":" + String(stat.mtimeMs) : "0:0";
|
|
97
|
+
return { taskVersion, eventsVersion, key: taskVersion + "|" + eventsVersion };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async #readEvents() {
|
|
101
|
+
const file = this.eventsPath();
|
|
102
|
+
let stat = null;
|
|
103
|
+
try { stat = this.statSync(file); } catch { stat = null; }
|
|
104
|
+
if (stat === null) {
|
|
105
|
+
this.events = { offset: 0, size: 0, mtimeMs: null, tail: [], total: 0, kinds: new Map() };
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
const size = Number(stat.size) || 0;
|
|
109
|
+
if (size < this.events.offset || (this.events.mtimeMs !== null && stat.mtimeMs < this.events.mtimeMs)) {
|
|
110
|
+
// Truncated/rewritten log: restart the byte cursor.
|
|
111
|
+
this.events = { offset: 0, size: 0, mtimeMs: null, tail: [], total: 0, kinds: new Map() };
|
|
112
|
+
}
|
|
113
|
+
if (size === this.events.offset && stat.mtimeMs === this.events.mtimeMs) return;
|
|
114
|
+
let bytes = "";
|
|
115
|
+
if (size > this.events.offset) {
|
|
116
|
+
const handle = await fs.promises.open(file, "r");
|
|
117
|
+
try {
|
|
118
|
+
const length = size - this.events.offset;
|
|
119
|
+
const buffer = Buffer.alloc(length);
|
|
120
|
+
const read = await handle.read(buffer, 0, length, this.events.offset);
|
|
121
|
+
bytes = buffer.subarray(0, read.bytesRead).toString("utf8");
|
|
122
|
+
this.metrics.eventBytesRead += read.bytesRead;
|
|
123
|
+
} finally {
|
|
124
|
+
await handle.close();
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const lines = bytes.split("\n");
|
|
128
|
+
lines.pop(); // an incomplete trailing line is left for the next read
|
|
129
|
+
for (const line of lines) {
|
|
130
|
+
if (!line.trim()) continue;
|
|
131
|
+
this.metrics.eventLinesParsed += 1;
|
|
132
|
+
const event = parseJson(line, null);
|
|
133
|
+
if (event === null || typeof event !== "object") continue;
|
|
134
|
+
this.events.total += 1;
|
|
135
|
+
const kind = String(event.kind || "");
|
|
136
|
+
if (kind) this.events.kinds.set(kind, (this.events.kinds.get(kind) || 0) + 1);
|
|
137
|
+
this.events.tail.push(event);
|
|
138
|
+
if (this.events.tail.length > EVENT_TAIL_MAX) this.events.tail.splice(0, this.events.tail.length - EVENT_TAIL_MAX);
|
|
139
|
+
}
|
|
140
|
+
this.events.offset = size;
|
|
141
|
+
this.events.size = size;
|
|
142
|
+
this.events.mtimeMs = stat.mtimeMs;
|
|
143
|
+
}
|
|
144
|
+
async #build(versions) {
|
|
145
|
+
let taskData = this.taskData;
|
|
146
|
+
if (taskData === null || taskData.taskVersion !== versions.taskVersion) {
|
|
147
|
+
const tasksBin = this.env.HIVE_TASKS_BIN || "hive-tasks";
|
|
148
|
+
const hiveBin = this.env.HIVE_BIN || "hive";
|
|
149
|
+
this.metrics.cliCalls += 4;
|
|
150
|
+
const [tasksResult, statsResult, boardResult, modeResult] = await Promise.all([
|
|
151
|
+
this.run(tasksBin, ["list", "--json"], this.repo).catch(() => ({ code: 1, stdout: "" })),
|
|
152
|
+
this.run(tasksBin, ["stats", "--json"], this.repo).catch(() => ({ code: 1, stdout: "" })),
|
|
153
|
+
this.run(hiveBin, ["board", "--json"], this.repo).catch(() => ({ code: 1, stdout: "" })),
|
|
154
|
+
this.run("git", ["cat-file", "-p", "refs/hive/v1/mode"], this.repo).catch(() => ({ code: 1, stdout: "" })),
|
|
155
|
+
]);
|
|
156
|
+
const tasks = tasksResult.code === 0 ? parseJson(tasksResult.stdout, []) : [];
|
|
157
|
+
const rows = Array.isArray(tasks) ? tasks.filter((task) => task && typeof task === "object") : [];
|
|
158
|
+
const stats = statsResult.code === 0 ? parseJson(statsResult.stdout, null) : null;
|
|
159
|
+
const board = boardResult.code === 0 ? parseJson(boardResult.stdout, []) : [];
|
|
160
|
+
const mode = modeResult.code === 0 ? parseJson(modeResult.stdout, { mode: "free" }) : { mode: "free" };
|
|
161
|
+
const lanePages = {};
|
|
162
|
+
for (const state of TASK_STATES) lanePages[state] = lanePage(rows, stats, state, 0, LANE_PAGE_LIMIT, "");
|
|
163
|
+
taskData = {
|
|
164
|
+
taskVersion: versions.taskVersion,
|
|
165
|
+
allTasks: rows,
|
|
166
|
+
tasks: Object.values(lanePages).flatMap((page) => page.items),
|
|
167
|
+
stats,
|
|
168
|
+
board: Array.isArray(board) ? board : [],
|
|
169
|
+
mode,
|
|
170
|
+
lanePages,
|
|
171
|
+
};
|
|
172
|
+
this.taskData = taskData;
|
|
173
|
+
this.metrics.builds += 1;
|
|
174
|
+
}
|
|
175
|
+
await this.#readEvents();
|
|
176
|
+
const eventKinds = [...this.events.kinds.entries()]
|
|
177
|
+
.map(([kind, count]) => ({ kind, count }))
|
|
178
|
+
.sort((a, b) => b.count - a.count || a.kind.localeCompare(b.kind))
|
|
179
|
+
.slice(0, 30);
|
|
180
|
+
this.cache = {
|
|
181
|
+
initialised: true,
|
|
182
|
+
version: versions.key,
|
|
183
|
+
taskVersion: versions.taskVersion,
|
|
184
|
+
eventsVersion: versions.eventsVersion,
|
|
185
|
+
at: new Date(this.now()).toISOString(),
|
|
186
|
+
...taskData,
|
|
187
|
+
events: this.events.tail.slice().reverse(),
|
|
188
|
+
eventTotal: this.events.total,
|
|
189
|
+
eventKinds,
|
|
190
|
+
};
|
|
191
|
+
this.versionKey = versions.key;
|
|
192
|
+
this.lastBuildAt = this.now();
|
|
193
|
+
return this.cache;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async #load() {
|
|
197
|
+
if (!isInitialised(this.repo)) {
|
|
198
|
+
const emptyPages = {};
|
|
199
|
+
for (const state of TASK_STATES) emptyPages[state] = { items: [], total: 0, cursor: 0, hasMore: false };
|
|
200
|
+
this.cache = {
|
|
201
|
+
initialised: false,
|
|
202
|
+
repo: this.repo,
|
|
203
|
+
at: new Date(this.now()).toISOString(),
|
|
204
|
+
version: "uninitialised",
|
|
205
|
+
allTasks: [],
|
|
206
|
+
tasks: [],
|
|
207
|
+
stats: null,
|
|
208
|
+
board: [],
|
|
209
|
+
mode: { mode: "free" },
|
|
210
|
+
lanePages: emptyPages,
|
|
211
|
+
events: [],
|
|
212
|
+
eventTotal: 0,
|
|
213
|
+
eventKinds: [],
|
|
214
|
+
};
|
|
215
|
+
this.versionKey = "uninitialised";
|
|
216
|
+
return this.cache;
|
|
217
|
+
}
|
|
218
|
+
const versions = await this.version();
|
|
219
|
+
if (this.cache !== null && versions.key === this.versionKey) return this.cache;
|
|
220
|
+
return this.#build(versions);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async snapshot() {
|
|
224
|
+
if (this.building !== null) return this.building;
|
|
225
|
+
this.building = this.#load().finally(() => { this.building = null; });
|
|
226
|
+
return this.building;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async newEvents({ after = 0, limit = 50, kind = "" } = {}) {
|
|
230
|
+
const data = await this.snapshot();
|
|
231
|
+
const total = data.eventTotal;
|
|
232
|
+
const tailCount = Math.min(EVENT_TAIL_MAX, total);
|
|
233
|
+
const firstIndex = total - tailCount;
|
|
234
|
+
const start = Math.max(0, Math.min(total, Math.floor(Number(after) || 0)));
|
|
235
|
+
const wanted = String(kind || "");
|
|
236
|
+
const fresh = [];
|
|
237
|
+
for (let index = Math.max(start, firstIndex); index < total; index += 1) {
|
|
238
|
+
const event = data.events[total - 1 - index];
|
|
239
|
+
if (event && (!wanted || String(event.kind || "") === wanted)) fresh.push(event);
|
|
240
|
+
}
|
|
241
|
+
const size = Math.max(1, Math.min(200, Math.floor(Number(limit) || 50)));
|
|
242
|
+
const items = fresh.slice(Math.max(0, fresh.length - size)).reverse();
|
|
243
|
+
return { items, total, cursor: total, hasMore: fresh.length > size, kind: wanted, dropped: start < firstIndex };
|
|
244
|
+
}
|
|
245
|
+
async tasksPage({ state = "", cursor = 0, limit = LANE_PAGE_LIMIT, search = "" } = {}) {
|
|
246
|
+
const data = await this.snapshot();
|
|
247
|
+
const all = Array.isArray(data.allTasks) ? data.allTasks : data.tasks;
|
|
248
|
+
if (!state) {
|
|
249
|
+
const offset = Math.max(0, Number(cursor) || 0);
|
|
250
|
+
const size = Math.max(1, Math.min(LANE_PAGE_LIMIT, Number(limit) || LANE_PAGE_LIMIT));
|
|
251
|
+
const items = [...all].sort(compareTasks).slice(offset, offset + size);
|
|
252
|
+
return { items, total: all.length, cursor: offset + items.length, hasMore: offset + items.length < all.length, state: "", search: String(search || "") };
|
|
253
|
+
}
|
|
254
|
+
return lanePage(all, data.stats, String(state), cursor, limit, search);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
async eventsPage({ cursor = 0, limit = 80, kind = "" } = {}) {
|
|
258
|
+
const data = await this.snapshot();
|
|
259
|
+
const wanted = String(kind || "");
|
|
260
|
+
const rows = data.events.filter((event) => !wanted || String(event.kind || "") === wanted);
|
|
261
|
+
const offset = Math.max(0, Math.floor(Number(cursor) || 0));
|
|
262
|
+
const size = Math.max(1, Math.min(200, Math.floor(Number(limit) || 80)));
|
|
263
|
+
const items = rows.slice(offset, offset + size);
|
|
264
|
+
const next = offset + items.length;
|
|
265
|
+
return { items, total: rows.length, eventTotal: data.eventTotal, cursor: next, hasMore: next < rows.length, kind: wanted };
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
export function createSnapshotCache(options) { return new SnapshotCache(options); }
|
package/src/data.js
CHANGED
|
@@ -169,6 +169,79 @@ export function findTaskById(repo, id, env = process.env) {
|
|
|
169
169
|
return readTasks(repo, env).find((task) => String(task.id || "") === wanted) || null;
|
|
170
170
|
}
|
|
171
171
|
|
|
172
|
+
/**
|
|
173
|
+
* Lightweight panel status: counts/metadata only, no task or event pages.
|
|
174
|
+
* @param {string} repo
|
|
175
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
176
|
+
*/
|
|
177
|
+
export function status(repo, env = process.env) {
|
|
178
|
+
const initialised = isInitialised(repo);
|
|
179
|
+
const data = {
|
|
180
|
+
at: new Date().toISOString(),
|
|
181
|
+
repo,
|
|
182
|
+
initialised,
|
|
183
|
+
mode: readMode(repo),
|
|
184
|
+
partial: true,
|
|
185
|
+
board: [],
|
|
186
|
+
tasks: [],
|
|
187
|
+
stats: null,
|
|
188
|
+
events: [],
|
|
189
|
+
eventTotal: 0,
|
|
190
|
+
eventKinds: [],
|
|
191
|
+
lanePages: paginateTasks([], null),
|
|
192
|
+
};
|
|
193
|
+
if (!initialised) return data;
|
|
194
|
+
const hive = env.HIVE_BIN || "hive";
|
|
195
|
+
const stats = readStats(repo, env);
|
|
196
|
+
const lanePages = {};
|
|
197
|
+
for (const state of ["pending", "claimed", "done", "failed"]) {
|
|
198
|
+
const total = Number(stats && stats.byState && stats.byState[state]);
|
|
199
|
+
lanePages[state] = { items: [], total: Number.isFinite(total) ? total : 0, cursor: 0, hasMore: total > 0 };
|
|
200
|
+
}
|
|
201
|
+
const eventRows = readEventRows(repo);
|
|
202
|
+
return {
|
|
203
|
+
...data,
|
|
204
|
+
board: json(hive, ["board", "--json"], repo, []),
|
|
205
|
+
stats,
|
|
206
|
+
lanePages,
|
|
207
|
+
eventTotal: eventRows.length,
|
|
208
|
+
eventKinds: readEventKinds(repo),
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* New events appended after a raw event-log cursor (line count), newest first.
|
|
214
|
+
*/
|
|
215
|
+
export function readNewEvents(repo, { after = 0, limit = 50, kind = "" } = {}) {
|
|
216
|
+
const file = path.join(repo, ".hive", "events.jsonl");
|
|
217
|
+
let lines = [];
|
|
218
|
+
try {
|
|
219
|
+
lines = fs.readFileSync(file, "utf8").split("\n").filter(Boolean);
|
|
220
|
+
} catch {
|
|
221
|
+
lines = [];
|
|
222
|
+
}
|
|
223
|
+
const cursor = Math.max(0, Math.floor(Number(after) || 0));
|
|
224
|
+
const wanted = String(kind || "");
|
|
225
|
+
const size = Math.max(1, Math.min(200, Math.floor(Number(limit) || 50)));
|
|
226
|
+
const fresh = [];
|
|
227
|
+
for (let index = Math.max(cursor, 0); index < lines.length; index += 1) {
|
|
228
|
+
try {
|
|
229
|
+
const event = JSON.parse(lines[index]);
|
|
230
|
+
if (wanted && String(event.kind || "") !== wanted) continue;
|
|
231
|
+
fresh.push(event);
|
|
232
|
+
} catch {
|
|
233
|
+
// Invalid lines never block the cursor.
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return {
|
|
237
|
+
items: fresh.slice(-size).reverse(),
|
|
238
|
+
total: lines.length,
|
|
239
|
+
cursor: lines.length,
|
|
240
|
+
hasMore: fresh.length > size,
|
|
241
|
+
kind: wanted,
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
|
|
172
245
|
export function snapshot(repo, env = process.env) {
|
|
173
246
|
const initialised = isInitialised(repo);
|
|
174
247
|
const eventPage = readEventPage(repo, { limit: EVENT_PAGE_LIMIT });
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
function eventFile(repo) {
|
|
5
|
+
return path.join(String(repo), ".hive", "events.jsonl");
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
function readLines(file) {
|
|
9
|
+
try {
|
|
10
|
+
return fs.readFileSync(file, "utf8").split("\n").filter(Boolean);
|
|
11
|
+
} catch {
|
|
12
|
+
return [];
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function eventKey(event) {
|
|
17
|
+
const raw = event && typeof event === "object" ? event : {};
|
|
18
|
+
return JSON.stringify([String(raw.ts ?? ""), String(raw.kind ?? ""), String(raw.actor ?? ""), String(raw.task ?? "")]);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Delete exact event keys, returning one result per key. Best effort, never throws. */
|
|
22
|
+
export function deleteEvents(repo, keys) {
|
|
23
|
+
const wanted = new Set((Array.isArray(keys) ? keys : []).map(String));
|
|
24
|
+
const file = eventFile(repo);
|
|
25
|
+
const lines = readLines(file);
|
|
26
|
+
const kept = [];
|
|
27
|
+
const removed = new Set();
|
|
28
|
+
let parseErrors = 0;
|
|
29
|
+
for (const line of lines) {
|
|
30
|
+
try {
|
|
31
|
+
const event = JSON.parse(line);
|
|
32
|
+
const key = eventKey(event);
|
|
33
|
+
if (wanted.has(key)) removed.add(key);
|
|
34
|
+
else kept.push(line);
|
|
35
|
+
} catch {
|
|
36
|
+
parseErrors += 1;
|
|
37
|
+
kept.push(line);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
if (removed.size > 0) fs.writeFileSync(file, kept.length > 0 ? kept.join("\n") + "\n" : "");
|
|
41
|
+
return [...wanted].map((key) => ({
|
|
42
|
+
key,
|
|
43
|
+
ok: removed.has(key),
|
|
44
|
+
error: removed.has(key) ? "" : "event not found",
|
|
45
|
+
}));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Delete every event older than the ISO timestamp. */
|
|
49
|
+
export function pruneEventsBefore(repo, before) {
|
|
50
|
+
const cutoff = Date.parse(before);
|
|
51
|
+
if (!Number.isFinite(cutoff)) return [{ key: "before", ok: false, error: "invalid timestamp" }];
|
|
52
|
+
const file = eventFile(repo);
|
|
53
|
+
const lines = readLines(file);
|
|
54
|
+
const kept = [];
|
|
55
|
+
let deleted = 0;
|
|
56
|
+
for (const line of lines) {
|
|
57
|
+
try {
|
|
58
|
+
const event = JSON.parse(line);
|
|
59
|
+
const ts = Date.parse(event.ts);
|
|
60
|
+
if (Number.isFinite(ts) && ts < cutoff) deleted += 1;
|
|
61
|
+
else kept.push(line);
|
|
62
|
+
} catch {
|
|
63
|
+
kept.push(line);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
if (deleted > 0) fs.writeFileSync(file, kept.length > 0 ? kept.join("\n") + "\n" : "");
|
|
67
|
+
return [{ key: "before", ok: true, error: "", deleted }];
|
|
68
|
+
}
|
package/src/server.js
CHANGED
|
@@ -2,7 +2,8 @@ import fs from "node:fs";
|
|
|
2
2
|
import http from "node:http";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { execFile } from "node:child_process";
|
|
5
|
-
import {
|
|
5
|
+
import { isInitialised, status } from "./data.js";
|
|
6
|
+
import { createSnapshotCache } from "./cache.js";
|
|
6
7
|
import { listActions, runAction } from "./actions.js";
|
|
7
8
|
|
|
8
9
|
const MIME = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".svg": "image/svg+xml" };
|
|
@@ -28,6 +29,7 @@ function body(request) {
|
|
|
28
29
|
export function createServer({ repo, publicDir, env = process.env, writable = false }) {
|
|
29
30
|
const hive = env.HIVE_BIN || "hive";
|
|
30
31
|
const tasks = env.HIVE_TASKS_BIN || "hive-tasks";
|
|
32
|
+
const snapshotCache = createSnapshotCache({ repo, env });
|
|
31
33
|
const server = http.createServer(async (request, response) => {
|
|
32
34
|
const url = new URL(request.url, "http://localhost");
|
|
33
35
|
|
|
@@ -38,14 +40,55 @@ export function createServer({ repo, publicDir, env = process.env, writable = fa
|
|
|
38
40
|
return response.end(JSON.stringify(data));
|
|
39
41
|
}
|
|
40
42
|
|
|
43
|
+
if (url.pathname === "/api/status") {
|
|
44
|
+
if (!isInitialised(repo)) {
|
|
45
|
+
const data = { ...status(repo, env), writable };
|
|
46
|
+
response.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
47
|
+
return response.end(JSON.stringify(data));
|
|
48
|
+
}
|
|
49
|
+
const data = await snapshotCache.snapshot();
|
|
50
|
+
const lanePages = {};
|
|
51
|
+
for (const state of ["pending", "claimed", "done", "failed"]) {
|
|
52
|
+
const page = data.lanePages?.[state] ?? { total: 0 };
|
|
53
|
+
lanePages[state] = { items: [], total: page.total, cursor: 0, hasMore: page.total > 0 };
|
|
54
|
+
}
|
|
55
|
+
const payload = {
|
|
56
|
+
at: data.at,
|
|
57
|
+
repo,
|
|
58
|
+
initialised: true,
|
|
59
|
+
mode: data.mode,
|
|
60
|
+
partial: false,
|
|
61
|
+
board: data.board,
|
|
62
|
+
tasks: [],
|
|
63
|
+
stats: data.stats,
|
|
64
|
+
events: [],
|
|
65
|
+
eventTotal: data.eventTotal,
|
|
66
|
+
eventKinds: data.eventKinds,
|
|
67
|
+
lanePages,
|
|
68
|
+
writable,
|
|
69
|
+
};
|
|
70
|
+
response.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
71
|
+
return response.end(JSON.stringify(payload));
|
|
72
|
+
}
|
|
73
|
+
|
|
41
74
|
if (url.pathname === "/api/snapshot") {
|
|
42
|
-
const data = { ...snapshot(
|
|
75
|
+
const data = { ...(await snapshotCache.snapshot()), writable };
|
|
43
76
|
response.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
44
77
|
return response.end(JSON.stringify(data));
|
|
45
78
|
}
|
|
46
79
|
|
|
80
|
+
if (request.method === "GET" && url.pathname === "/api/events" && url.searchParams.get("after") !== null) {
|
|
81
|
+
const page = await snapshotCache.newEvents({
|
|
82
|
+
after: url.searchParams.get("after") || "0",
|
|
83
|
+
limit: url.searchParams.get("limit") || "50",
|
|
84
|
+
kind: url.searchParams.get("kind") || "",
|
|
85
|
+
});
|
|
86
|
+
response.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
87
|
+
return response.end(JSON.stringify(page));
|
|
88
|
+
}
|
|
89
|
+
|
|
47
90
|
if (request.method === "GET" && url.pathname === "/api/events") {
|
|
48
|
-
const page =
|
|
91
|
+
const page = await snapshotCache.eventsPage({
|
|
49
92
|
cursor: url.searchParams.get("cursor") || "0",
|
|
50
93
|
limit: url.searchParams.get("limit") || "80",
|
|
51
94
|
kind: url.searchParams.get("kind") || "",
|
|
@@ -55,19 +98,21 @@ export function createServer({ repo, publicDir, env = process.env, writable = fa
|
|
|
55
98
|
}
|
|
56
99
|
|
|
57
100
|
if (request.method === "GET" && url.pathname === "/api/tasks") {
|
|
58
|
-
const page =
|
|
101
|
+
const page = await snapshotCache.tasksPage({
|
|
59
102
|
state: url.searchParams.get("state") || "",
|
|
60
103
|
cursor: url.searchParams.get("cursor") || "0",
|
|
61
104
|
limit: url.searchParams.get("limit") || "200",
|
|
62
105
|
search: url.searchParams.get("search") || url.searchParams.get("q") || "",
|
|
63
|
-
}
|
|
106
|
+
});
|
|
64
107
|
response.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
65
108
|
return response.end(JSON.stringify(page));
|
|
66
109
|
}
|
|
67
110
|
|
|
68
111
|
if (request.method === "GET" && url.pathname.startsWith("/api/tasks/")) {
|
|
69
112
|
const id = decodeURIComponent(url.pathname.slice("/api/tasks/".length));
|
|
70
|
-
const
|
|
113
|
+
const cached = await snapshotCache.snapshot();
|
|
114
|
+
const allTasks = Array.isArray(cached.allTasks) ? cached.allTasks : cached.tasks;
|
|
115
|
+
const task = allTasks.find((entry) => String(entry.id) === String(id)) ?? null;
|
|
71
116
|
response.writeHead(task ? 200 : 404, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
72
117
|
return response.end(JSON.stringify(task ? { ok: true, task } : { ok: false, error: "task not found" }));
|
|
73
118
|
}
|
|
@@ -77,6 +122,32 @@ export function createServer({ repo, publicDir, env = process.env, writable = fa
|
|
|
77
122
|
return response.end(JSON.stringify({ writable, actions: listActions() }));
|
|
78
123
|
}
|
|
79
124
|
|
|
125
|
+
if (request.method === "POST" && url.pathname === "/api/action") {
|
|
126
|
+
if (!writable) {
|
|
127
|
+
response.writeHead(403, { "content-type": "application/json" });
|
|
128
|
+
return response.end(JSON.stringify({ error: "read-only: start with --write" }));
|
|
129
|
+
}
|
|
130
|
+
const payload = await body(request);
|
|
131
|
+
const op = String(payload.op || "");
|
|
132
|
+
let results = [];
|
|
133
|
+
if (op === "tasks-rm" || op === "task-delete") {
|
|
134
|
+
const ids = Array.isArray(payload.ids) ? payload.ids.map(String) : [];
|
|
135
|
+
for (const id of ids) {
|
|
136
|
+
const result = await runAction("remove", { id }, { cwd: repo, env });
|
|
137
|
+
results.push({ id, ok: result.ok === true, error: result.ok ? "" : String(result.stderr || result.stdout || "failed").trim() });
|
|
138
|
+
}
|
|
139
|
+
} else if (op === "events-delete" || op === "event-delete") {
|
|
140
|
+
results = deleteEvents(repo, payload.keys || payload.ids);
|
|
141
|
+
} else if (op === "events-prune" || op === "event-prune") {
|
|
142
|
+
results = pruneEventsBefore(repo, payload.before);
|
|
143
|
+
} else {
|
|
144
|
+
response.writeHead(400, { "content-type": "application/json" });
|
|
145
|
+
return response.end(JSON.stringify({ ok: false, error: "unknown batch op: " + op }));
|
|
146
|
+
}
|
|
147
|
+
response.writeHead(200, { "content-type": "application/json" });
|
|
148
|
+
return response.end(JSON.stringify({ ok: true, results }));
|
|
149
|
+
}
|
|
150
|
+
|
|
80
151
|
if (request.method === "POST" && url.pathname.startsWith("/api/")) {
|
|
81
152
|
if (!writable) {
|
|
82
153
|
response.writeHead(403, { "content-type": "application/json" });
|