@omercnet/paseo-pr-radar 3.0.1-next.298.1 → 3.0.1-next.299.1
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/client/use-radar.ts +4 -2
- package/index.server.ts +8 -2
- package/package.json +1 -1
- package/server/viewer-scope.ts +214 -67
package/client/use-radar.ts
CHANGED
|
@@ -44,8 +44,10 @@ export function useRadar(hostId: string, windowDays = 30, live = true) {
|
|
|
44
44
|
queryKey: ["pr-radar-viewer-scope", hostId, scopeUrls, windowDays],
|
|
45
45
|
queryFn: () => resolveViewerScope({ urls: scopeUrls, windowDays }),
|
|
46
46
|
enabled: Boolean(directory.data),
|
|
47
|
-
|
|
48
|
-
|
|
47
|
+
// The server answers from its background cache, so polling is cheap; this only picks up
|
|
48
|
+
// what the server's own refresh loop (every 2 min) has already fetched.
|
|
49
|
+
staleTime: 30_000,
|
|
50
|
+
refetchInterval: live ? 60_000 : false,
|
|
49
51
|
});
|
|
50
52
|
useEffect(() => {
|
|
51
53
|
if (!live) return;
|
package/index.server.ts
CHANGED
|
@@ -1,9 +1,15 @@
|
|
|
1
1
|
import type { PluginServerContext } from "@getpaseo/plugin/server";
|
|
2
|
-
import {
|
|
2
|
+
import {
|
|
3
|
+
acknowledgeViewerUpdates,
|
|
4
|
+
resolveViewerScope,
|
|
5
|
+
startBackgroundRefresh,
|
|
6
|
+
} from "./server/viewer-scope";
|
|
3
7
|
import { acknowledgeViewerScope, viewerScope } from "./shared/viewer-scope";
|
|
4
8
|
|
|
5
9
|
export default function contribute(server: PluginServerContext) {
|
|
6
10
|
server.handle(viewerScope, resolveViewerScope);
|
|
7
11
|
server.handle(acknowledgeViewerScope, acknowledgeViewerUpdates);
|
|
8
|
-
|
|
12
|
+
// Keep GitHub data warm so opening the radar never waits on gh.
|
|
13
|
+
const stop = startBackgroundRefresh();
|
|
14
|
+
return () => stop();
|
|
9
15
|
}
|
package/package.json
CHANGED
package/server/viewer-scope.ts
CHANGED
|
@@ -292,14 +292,35 @@ async function readState(): Promise<StoredState> {
|
|
|
292
292
|
return { version: 2, windows: {} };
|
|
293
293
|
}
|
|
294
294
|
|
|
295
|
+
let writeSequence = 0;
|
|
296
|
+
|
|
295
297
|
async function writeState(state: StoredState): Promise<void> {
|
|
296
298
|
const path = statePath();
|
|
297
299
|
await mkdir(dirname(path), { recursive: true });
|
|
298
|
-
|
|
300
|
+
// Unique per write: overlapping writes must not rename each other's temp file away.
|
|
301
|
+
const temporaryPath = `${path}.${process.pid}.${++writeSequence}.tmp`;
|
|
299
302
|
await writeFile(temporaryPath, `${JSON.stringify(state)}\n`, { mode: 0o600 });
|
|
300
303
|
await rename(temporaryPath, path);
|
|
301
304
|
}
|
|
302
305
|
|
|
306
|
+
let stateQueue: Promise<unknown> = Promise.resolve();
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Serialises read-modify-write cycles on the state file. The change callback runs inside the
|
|
310
|
+
* queue after a fresh read, so a slow GitHub refresh cannot overwrite an acknowledgement made
|
|
311
|
+
* while it was in flight.
|
|
312
|
+
*/
|
|
313
|
+
function updateState<T>(change: (state: StoredState) => T): Promise<T> {
|
|
314
|
+
const run = stateQueue.then(async () => {
|
|
315
|
+
const state = await readState();
|
|
316
|
+
const result = change(state);
|
|
317
|
+
await writeState(state);
|
|
318
|
+
return result;
|
|
319
|
+
});
|
|
320
|
+
stateQueue = run.catch(() => undefined);
|
|
321
|
+
return run;
|
|
322
|
+
}
|
|
323
|
+
|
|
303
324
|
function storedItem(item: GitHubInboxItem): StoredItem {
|
|
304
325
|
return {
|
|
305
326
|
updatedAt: item.updatedAt,
|
|
@@ -331,32 +352,41 @@ function detectChanges(previous: StoredItem | undefined, item: GitHubInboxItem):
|
|
|
331
352
|
return [...changes];
|
|
332
353
|
}
|
|
333
354
|
|
|
334
|
-
|
|
335
|
-
urls,
|
|
336
|
-
windowDays,
|
|
337
|
-
}: z.output<typeof viewerScope.input>): Promise<z.input<typeof viewerScope.output>> {
|
|
338
|
-
try {
|
|
339
|
-
const viewer = await viewerLogin();
|
|
340
|
-
const since = new Date(Date.now() - windowDays * 24 * 60 * 60 * 1_000)
|
|
341
|
-
.toISOString()
|
|
342
|
-
.slice(0, 10);
|
|
343
|
-
const [authored, reviewRequested, authoredScope, reviewRequestedScope, stored] =
|
|
344
|
-
await Promise.all([
|
|
345
|
-
searchPullRequests("author", viewer, since),
|
|
346
|
-
searchPullRequests("review-requested", viewer, since),
|
|
347
|
-
searchScopeUrls("author"),
|
|
348
|
-
searchScopeUrls("review-requested"),
|
|
349
|
-
readState(),
|
|
350
|
-
]);
|
|
351
|
-
const records = new Map<string, { record: SearchRecord; role: GitHubInboxItem["role"] }>();
|
|
352
|
-
for (const record of reviewRequested) records.set(record.id, { record, role: "reviewer" });
|
|
353
|
-
for (const record of authored) records.set(record.id, { record, role: "author" });
|
|
354
|
-
const enrichment = await enrich([...records.keys()]);
|
|
355
|
-
const inboxItems = [...records.values()].map(({ record, role }) =>
|
|
356
|
-
toInboxItem(record, role, enrichment.states.get(record.id)),
|
|
357
|
-
);
|
|
355
|
+
type ViewerScopeOutput = z.input<typeof viewerScope.output>;
|
|
358
356
|
|
|
359
|
-
|
|
357
|
+
/** Everything one GitHub refresh learns for a window; independent of the URLs a client asks about. */
|
|
358
|
+
interface Snapshot {
|
|
359
|
+
viewer: string;
|
|
360
|
+
authored: SearchRecord[];
|
|
361
|
+
reviewRequested: SearchRecord[];
|
|
362
|
+
authoredScope: string[];
|
|
363
|
+
reviewRequestedScope: string[];
|
|
364
|
+
inboxItems: GitHubInboxItem[];
|
|
365
|
+
enrichmentFailures: number;
|
|
366
|
+
acknowledgedAt: string | null;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** The expensive part: ~5 s of gh searches and GraphQL enrichment. */
|
|
370
|
+
async function fetchSnapshot(windowDays: number): Promise<Snapshot> {
|
|
371
|
+
const viewer = await viewerLogin();
|
|
372
|
+
const since = new Date(Date.now() - windowDays * 24 * 60 * 60 * 1_000).toISOString().slice(0, 10);
|
|
373
|
+
const [authored, reviewRequested, authoredScope, reviewRequestedScope] = await Promise.all([
|
|
374
|
+
searchPullRequests("author", viewer, since),
|
|
375
|
+
searchPullRequests("review-requested", viewer, since),
|
|
376
|
+
searchScopeUrls("author"),
|
|
377
|
+
searchScopeUrls("review-requested"),
|
|
378
|
+
]);
|
|
379
|
+
const records = new Map<string, { record: SearchRecord; role: GitHubInboxItem["role"] }>();
|
|
380
|
+
for (const record of reviewRequested) records.set(record.id, { record, role: "reviewer" });
|
|
381
|
+
for (const record of authored) records.set(record.id, { record, role: "author" });
|
|
382
|
+
const enrichment = await enrich([...records.keys()]);
|
|
383
|
+
const inboxItems = [...records.values()].map(({ record, role }) =>
|
|
384
|
+
toInboxItem(record, role, enrichment.states.get(record.id)),
|
|
385
|
+
);
|
|
386
|
+
|
|
387
|
+
// Change tracking reads the state only now, after the slow GitHub work, inside the queue.
|
|
388
|
+
const key = String(windowDays);
|
|
389
|
+
const acknowledgedAt = await updateState((stored) => {
|
|
360
390
|
const previous = stored.windows[key] ?? { items: {}, pendingChanges: {}, acknowledgedAt: null };
|
|
361
391
|
const initialized = Object.keys(previous.items).length > 0;
|
|
362
392
|
const nextItems: Record<string, StoredItem> = {};
|
|
@@ -392,58 +422,175 @@ export async function resolveViewerScope({
|
|
|
392
422
|
pendingChanges: nextPending,
|
|
393
423
|
acknowledgedAt: previous.acknowledgedAt,
|
|
394
424
|
};
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
425
|
+
return previous.acknowledgedAt;
|
|
426
|
+
});
|
|
427
|
+
|
|
428
|
+
return {
|
|
429
|
+
viewer,
|
|
430
|
+
authored,
|
|
431
|
+
reviewRequested,
|
|
432
|
+
authoredScope,
|
|
433
|
+
reviewRequestedScope,
|
|
434
|
+
inboxItems,
|
|
435
|
+
enrichmentFailures: enrichment.failures,
|
|
436
|
+
acknowledgedAt,
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** The cheap part: shape a snapshot for the URLs this client knows about. */
|
|
441
|
+
export function projectSnapshot(snapshot: Snapshot, urls: string[]): ViewerScopeOutput {
|
|
442
|
+
const requestedUrls = new Set(urls.map((url) => url.toLowerCase()));
|
|
443
|
+
const withScope = (direct: SearchRecord[], scope: string[]) => [
|
|
444
|
+
...new Set([
|
|
445
|
+
...direct.map(({ url }) => url),
|
|
446
|
+
...scope.filter((url) => requestedUrls.has(url.toLowerCase())),
|
|
447
|
+
]),
|
|
448
|
+
];
|
|
449
|
+
const coverageNote =
|
|
450
|
+
snapshot.enrichmentFailures > 0
|
|
451
|
+
? `${snapshot.enrichmentFailures} GitHub detail request${snapshot.enrichmentFailures === 1 ? "" : "s"} failed; affected PRs use conservative states.`
|
|
452
|
+
: `Open PRs visible to the GitHub CLI. Organization SSO restrictions may omit results.`;
|
|
453
|
+
return {
|
|
454
|
+
viewer: snapshot.viewer,
|
|
455
|
+
authoredUrls: withScope(snapshot.authored, snapshot.authoredScope),
|
|
456
|
+
reviewRequestedUrls: withScope(snapshot.reviewRequested, snapshot.reviewRequestedScope),
|
|
457
|
+
inboxItems: snapshot.inboxItems,
|
|
458
|
+
truncated:
|
|
459
|
+
snapshot.authored.length === SEARCH_LIMIT || snapshot.reviewRequested.length === SEARCH_LIMIT,
|
|
460
|
+
coverageNote,
|
|
461
|
+
updates: snapshot.inboxItems.filter(({ changes }) => changes.length > 0).length,
|
|
462
|
+
acknowledgedAt: snapshot.acknowledgedAt,
|
|
463
|
+
error: null,
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
function errorOutput(error: unknown): ViewerScopeOutput {
|
|
468
|
+
return {
|
|
469
|
+
viewer: null,
|
|
470
|
+
authoredUrls: [],
|
|
471
|
+
reviewRequestedUrls: [],
|
|
472
|
+
inboxItems: [],
|
|
473
|
+
truncated: false,
|
|
474
|
+
coverageNote: "GitHub inbox data is unavailable.",
|
|
475
|
+
updates: 0,
|
|
476
|
+
acknowledgedAt: null,
|
|
477
|
+
error: error instanceof Error ? error.message : "GitHub viewer scope is unavailable.",
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// ---------------------------------------------------------------------------
|
|
482
|
+
// Background cache. The plugin's server process is long-lived, so it keeps the last snapshot per
|
|
483
|
+
// window and refreshes it on a timer; client requests are answered from memory.
|
|
484
|
+
// ---------------------------------------------------------------------------
|
|
485
|
+
|
|
486
|
+
export const BACKGROUND_INTERVAL_MS = 2 * 60_000;
|
|
487
|
+
/** A request older than this triggers a refresh in the background (still answered from cache). */
|
|
488
|
+
export const STALE_AFTER_MS = 60_000;
|
|
489
|
+
/**
|
|
490
|
+
* A snapshot older than this is not served: a refresh that keeps failing (auth lost, rate limited)
|
|
491
|
+
* is reported instead of hiding behind old data. Entries are bounded by the 365 possible windows.
|
|
492
|
+
*/
|
|
493
|
+
export const MAX_STALE_MS = 3 * BACKGROUND_INTERVAL_MS;
|
|
494
|
+
/** Windows nobody has asked about for this long stop being refreshed, so an unused radar costs no GitHub calls. */
|
|
495
|
+
const WINDOW_IDLE_MS = 30 * 60_000;
|
|
496
|
+
/** Warmed at startup so the first open of the radar does not wait on GitHub. */
|
|
497
|
+
const DEFAULT_WINDOW_DAYS = 30;
|
|
498
|
+
|
|
499
|
+
const snapshots = new Map<number, { snapshot: Snapshot; at: number }>();
|
|
500
|
+
const inflight = new Map<number, Promise<Snapshot>>();
|
|
501
|
+
const lastRequested = new Map<number, number>([[DEFAULT_WINDOW_DAYS, Date.now()]]);
|
|
502
|
+
|
|
503
|
+
/** Single-flight refresh: concurrent callers share one GitHub sweep. */
|
|
504
|
+
function refreshWindow(windowDays: number): Promise<Snapshot> {
|
|
505
|
+
const running = inflight.get(windowDays);
|
|
506
|
+
if (running) return running;
|
|
507
|
+
const started = Date.now();
|
|
508
|
+
const promise = fetchSnapshot(windowDays)
|
|
509
|
+
.then((snapshot) => {
|
|
510
|
+
snapshots.set(windowDays, { snapshot, at: Date.now() });
|
|
511
|
+
console.log(
|
|
512
|
+
`PR Radar: refreshed ${windowDays}d window in ${((Date.now() - started) / 1000).toFixed(1)}s (${snapshot.inboxItems.length} PRs)`,
|
|
513
|
+
);
|
|
514
|
+
return snapshot;
|
|
515
|
+
})
|
|
516
|
+
.finally(() => inflight.delete(windowDays));
|
|
517
|
+
inflight.set(windowDays, promise);
|
|
518
|
+
return promise;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
function refreshInBackground(windowDays: number): void {
|
|
522
|
+
refreshWindow(windowDays).catch((error) => {
|
|
523
|
+
// Keep serving the last good snapshot until it passes MAX_STALE_MS.
|
|
524
|
+
console.error(`PR Radar: background refresh of ${windowDays}d window failed`, error);
|
|
525
|
+
});
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/** Starts the refresh timer; returns a stop function for the plugin's cleanup. */
|
|
529
|
+
export function startBackgroundRefresh(intervalMs = BACKGROUND_INTERVAL_MS): () => void {
|
|
530
|
+
const tick = () => {
|
|
531
|
+
const now = Date.now();
|
|
532
|
+
for (const [windowDays, requestedAt] of lastRequested) {
|
|
533
|
+
if (now - requestedAt > WINDOW_IDLE_MS) {
|
|
534
|
+
lastRequested.delete(windowDays);
|
|
535
|
+
continue;
|
|
536
|
+
}
|
|
537
|
+
refreshInBackground(windowDays);
|
|
538
|
+
}
|
|
539
|
+
};
|
|
540
|
+
tick();
|
|
541
|
+
const timer = setInterval(tick, intervalMs);
|
|
542
|
+
timer.unref?.();
|
|
543
|
+
return () => clearInterval(timer);
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
export async function resolveViewerScope({
|
|
547
|
+
urls,
|
|
548
|
+
windowDays,
|
|
549
|
+
}: z.output<typeof viewerScope.input>): Promise<ViewerScopeOutput> {
|
|
550
|
+
lastRequested.set(windowDays, Date.now());
|
|
551
|
+
const cached = snapshots.get(windowDays);
|
|
552
|
+
if (cached && Date.now() - cached.at <= MAX_STALE_MS) {
|
|
553
|
+
if (Date.now() - cached.at > STALE_AFTER_MS) refreshInBackground(windowDays);
|
|
554
|
+
return projectSnapshot(cached.snapshot, urls);
|
|
555
|
+
}
|
|
556
|
+
// First request for this window, or its snapshot expired: wait once.
|
|
557
|
+
try {
|
|
558
|
+
return projectSnapshot(await refreshWindow(windowDays), urls);
|
|
421
559
|
} catch (error) {
|
|
422
560
|
console.error("PR Radar GitHub inbox refresh failed", error);
|
|
423
|
-
return
|
|
424
|
-
viewer: null,
|
|
425
|
-
authoredUrls: [],
|
|
426
|
-
reviewRequestedUrls: [],
|
|
427
|
-
inboxItems: [],
|
|
428
|
-
truncated: false,
|
|
429
|
-
coverageNote: "GitHub inbox data is unavailable.",
|
|
430
|
-
updates: 0,
|
|
431
|
-
acknowledgedAt: null,
|
|
432
|
-
error: error instanceof Error ? error.message : "GitHub viewer scope is unavailable.",
|
|
433
|
-
};
|
|
561
|
+
return errorOutput(error);
|
|
434
562
|
}
|
|
435
563
|
}
|
|
436
564
|
|
|
565
|
+
/** Test seam: waits for running refreshes so tests do not bleed into each other. */
|
|
566
|
+
export async function resetViewerScopeCache(): Promise<void> {
|
|
567
|
+
await Promise.allSettled([...inflight.values()]);
|
|
568
|
+
await stateQueue;
|
|
569
|
+
snapshots.clear();
|
|
570
|
+
inflight.clear();
|
|
571
|
+
lastRequested.clear();
|
|
572
|
+
lastRequested.set(DEFAULT_WINDOW_DAYS, Date.now());
|
|
573
|
+
}
|
|
574
|
+
|
|
437
575
|
export async function acknowledgeViewerUpdates({
|
|
438
576
|
windowDays,
|
|
439
577
|
}: z.output<typeof acknowledgeViewerScope.input>): Promise<
|
|
440
578
|
z.input<typeof acknowledgeViewerScope.output>
|
|
441
579
|
> {
|
|
442
|
-
const state = await readState();
|
|
443
580
|
const key = String(windowDays);
|
|
444
581
|
const acknowledgedAt = new Date().toISOString();
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
582
|
+
await updateState((state) => {
|
|
583
|
+
const current = state.windows[key] ?? { items: {}, pendingChanges: {}, acknowledgedAt: null };
|
|
584
|
+
state.windows[key] = { ...current, pendingChanges: {}, acknowledgedAt };
|
|
585
|
+
});
|
|
586
|
+
// Keep the cached snapshot in step so the badge clears without waiting for a refresh.
|
|
587
|
+
const cached = snapshots.get(windowDays);
|
|
588
|
+
if (cached) {
|
|
589
|
+
cached.snapshot = {
|
|
590
|
+
...cached.snapshot,
|
|
591
|
+
acknowledgedAt,
|
|
592
|
+
inboxItems: cached.snapshot.inboxItems.map((item) => ({ ...item, changes: [] })),
|
|
593
|
+
};
|
|
594
|
+
}
|
|
448
595
|
return { acknowledgedAt };
|
|
449
596
|
}
|