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

lease.ts

182 lines6.5 KB

1import type { Pool, PoolClient } from "pg";
2export interface Lease {
3 active_owner: string | null;
4 active_until: Date | null;
5 active_session_end: Date | null;
6 active_deadline: Date | null;
7 fencing: string;
8 standby_owner: string | null;
9 standby_until: Date | null;
10 standby_deadline: Date | null;
11 standby_ready: boolean;
13export class LostLease extends Error {
14 constructor() {
15 super("Ingestion ownership lost");
16 }
18export class Leases {
19 constructor(
20 private pool: Pool,
21 readonly owner: string,
22 readonly deadline: number,
23 private tenureMs: number,
24 private overlapMs: number,
25 ) {}
26 async transaction<T>(
27 fn: (client: PoolClient, lease: Lease, now: number) => Promise<T>,
28 ): Promise<T> {
29 const client = await this.pool.connect();
30 try {
31 await client.query("BEGIN");
32 const { rows } = await client.query(
33 "SELECT *, clock_timestamp() AS db_now FROM ingest_leases WHERE id=1 FOR UPDATE",
34 );
35 const result = await fn(
36 client,
37 rows[0],
38 new Date(rows[0].db_now).getTime(),
39 );
40 await client.query("COMMIT");
41 return result;
42 } catch (error) {
43 await client.query("ROLLBACK");
44 throw error;
45 } finally {
46 client.release();
47 }
48 }
49 private sessionEnd(now: number) {
50 return new Date(Math.min(now + this.tenureMs, this.deadline - 10000));
51 }
52 async acquire(): Promise<{
53 role: "active" | "standby" | "skip";
54 fencing: string;
55 }> {
56 return this.transaction(async (client, lease, now) => {
57 const activeValid =
58 lease.active_owner && lease.active_until && +lease.active_until > now;
59 const standbyValid =
60 lease.standby_owner &&
61 lease.standby_until &&
62 +lease.standby_until > now;
63 if (
64 !activeValid &&
65 (!standbyValid ||
66 !lease.standby_ready ||
67 lease.standby_owner === this.owner)
68 ) {
69 const { rows } = await client.query(
70 `UPDATE ingest_leases SET active_owner=$1, active_until=clock_timestamp()+interval '20 seconds',
71 active_session_end=$2, active_deadline=$3, fencing=fencing+1, standby_owner=NULL, standby_until=NULL,
72 standby_deadline=NULL, standby_ready=false WHERE id=1 RETURNING fencing`,
73 [this.owner, this.sessionEnd(now), new Date(this.deadline)],
74 );
75 return { role: "active", fencing: String(rows[0].fencing) };
76 }
77 if (
78 activeValid &&
79 lease.active_session_end &&
80 +lease.active_session_end - now <= this.overlapMs &&
81 !standbyValid
82 ) {
83 await client.query(
84 `UPDATE ingest_leases SET standby_owner=$1, standby_until=clock_timestamp()+interval '20 seconds', standby_deadline=$2, standby_ready=false WHERE id=1`,
85 [this.owner, new Date(this.deadline)],
86 );
87 return { role: "standby", fencing: lease.fencing };
88 }
89 return { role: "skip", fencing: lease.fencing };
90 });
91 }
92 async renew(
93 role: "active" | "standby",
94 fencing: string,
95 ready: boolean,
96 ): Promise<boolean> {
97 const { rowCount } =
98 role === "active"
99 ? await this.pool.query(
100 `UPDATE ingest_leases SET active_until=clock_timestamp()+interval '20 seconds', heartbeat_at=clock_timestamp()
101 WHERE id=1 AND active_owner=$1 AND fencing=$2 AND active_until>clock_timestamp() AND active_deadline>clock_timestamp()`,
102 [this.owner, fencing],
103 )
104 : await this.pool.query(
105 `UPDATE ingest_leases SET standby_until=clock_timestamp()+interval '20 seconds', standby_ready=$2
106 WHERE id=1 AND standby_owner=$1 AND standby_until>clock_timestamp() AND standby_deadline>clock_timestamp()`,
107 [this.owner, ready],
108 );
109 return rowCount === 1;
110 }
111 async assert(client: PoolClient, fencing: string) {
112 const { rowCount } = await client.query(
113 `SELECT id FROM ingest_leases WHERE id=1 AND active_owner=$1 AND fencing=$2
114 AND active_until>clock_timestamp() AND active_deadline>clock_timestamp() FOR UPDATE`,
115 [this.owner, fencing],
116 );
117 if (!rowCount) throw new LostLease();
118 }
119 async promoteIfNeeded(): Promise<{ fencing: string; end: number } | null> {
120 return this.transaction(async (client, lease, now) => {
121 if (
122 lease.active_owner === this.owner &&
123 lease.active_until &&
124 +lease.active_until > now
125 )
126 return { fencing: lease.fencing, end: +lease.active_session_end! };
127 if (
128 lease.standby_owner !== this.owner ||
129 !lease.standby_ready ||
130 !lease.standby_until ||
131 +lease.standby_until <= now ||
132 (lease.active_until && +lease.active_until > now)
133 )
134 return null;
135 const { rows } = await client.query(
136 `UPDATE ingest_leases SET active_owner=$1, active_until=clock_timestamp()+interval '20 seconds',
137 active_session_end=$2, active_deadline=$3, fencing=fencing+1, standby_owner=NULL, standby_until=NULL, standby_ready=false WHERE id=1 RETURNING fencing`,
138 [this.owner, this.sessionEnd(now), new Date(this.deadline)],
139 );
140 return { fencing: String(rows[0].fencing), end: +this.sessionEnd(now) };
141 });
142 }
143 async handoff(fencing: string): Promise<string | null> {
144 return this.transaction(async (client, lease, now) => {
145 await this.assert(client, fencing);
146 if (
147 !lease.standby_owner ||
148 !lease.standby_ready ||
149 !lease.standby_until ||
150 +lease.standby_until <= now ||
151 !lease.standby_deadline ||
152 +lease.standby_deadline - now < 15000
153 )
154 return null;
155 const next = lease.standby_owner;
156 const end = new Date(
157 Math.min(now + this.tenureMs, +lease.standby_deadline - 10000),
158 );
159 await client.query(
160 `UPDATE ingest_leases SET active_owner=standby_owner, active_until=clock_timestamp()+interval '20 seconds',
161 active_session_end=$1, active_deadline=standby_deadline, fencing=fencing+1, standby_owner=NULL,
162 standby_until=NULL, standby_deadline=NULL, standby_ready=false WHERE id=1`,
163 [end],
164 );
165 await client.query(
166 `UPDATE ingest_status SET handoff_at=clock_timestamp(), handoff_from=$1 WHERE id=1`,
167 [this.owner],
168 );
169 return next;
170 });
171 }
172 async release() {
173 await this.pool.query(
174 `UPDATE ingest_leases SET active_until=clock_timestamp() WHERE id=1 AND active_owner=$1`,
175 [this.owner],
176 );
177 await this.pool.query(
178 `UPDATE ingest_leases SET standby_until=clock_timestamp(), standby_ready=false WHERE id=1 AND standby_owner=$1`,
179 [this.owner],
180 );
181 }