Skip to content
Source
Sign inSign up
samwillis/hackernews-realtime
Open History to see the last commit

seed.ts

51 lines1.5 KB

1import { Pool } from "pg";
2import { Leases } from "../ingest/lease";
3import { mapLimit, readHn, type HnItem } from "../ingest/source";
4import { publish } from "../ingest/store";
5import { FEED_SIZE } from "../lib/types";
6const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 2 });
7const owner = `seed-${Date.now()}`;
8const leases = new Leases(pool, owner, Date.now() + 120000, 90000, 30000);
9let timer: ReturnType<typeof setInterval> | undefined;
10try {
11 const acquired = await leases.acquire();
12 if (acquired.role !== "active")
13 throw new Error(
14 "An ingester already owns this branch. Stop it before seeding.",
15 );
16 timer = setInterval(
17 () => void leases.renew("active", acquired.fencing, false),
18 5000,
19 );
20 const [top, fresh] = await Promise.all([
21 readHn<number[]>("topstories"),
22 readHn<number[]>("newstories"),
23 ]);
24 const feeds = {
25 top: top.slice(0, FEED_SIZE),
26 new: fresh.slice(0, FEED_SIZE),
27 };
28 const items = new Map(
29 await mapLimit(
30 [...new Set([...feeds.top, ...feeds.new])],
31 20,
32 async (id) =>
33 [
34 id,
35 (await readHn<HnItem | null>(`item/${id}`)) ?? { id, deleted: true },
36 ] as const,
37 ),
38 );
39 const changed = await publish(pool, leases, acquired.fencing, {
40 feeds,
41 items,
42 receivedAt: Date.now(),
43 reconciledAt: Date.now(),
44 revision: 1,
45 });
46 console.log(`Seeded ${items.size} real HN items (${changed} changed rows).`);
47} finally {
48 clearInterval(timer);
49 await leases.release();
50 await pool.end();