Skip to content
Source
Sign inSign up
samwillis/one-million-boxes
Open History to see the last commit

draw.sql

346 lines12.0 KB

1-- Packed owners: 0 is empty; 1-4 identify the team. bytea bit numbering matches
2-- the browser's least-significant-bit-first three-bit codec, even across bytes.
3CREATE OR REPLACE FUNCTION boxes_owner (p_bytes bytea, p_index integer)
4 RETURNS integer
5 LANGUAGE sql
6 IMMUTABLE STRICT
7 AS $$
8 SELECT
9 get_bit(p_bytes, p_index * 3) | (get_bit(p_bytes, p_index * 3 + 1) << 1) | (get_bit(p_bytes,
10 p_index * 3 + 2) << 2)
11$$;
12​
13CREATE OR REPLACE FUNCTION boxes_set_owner (p_bytes bytea, p_index integer, p_owner integer)
14 RETURNS bytea
15 LANGUAGE sql
16 IMMUTABLE STRICT
17 AS $$
18 SELECT
19 set_bit(set_bit(set_bit(p_bytes, p_index * 3, p_owner & 1), p_index * 3 + 1, (p_owner >> 1) &
20 1), p_index * 3 + 2, (p_owner >> 2) & 1)
21$$;
22​
23-- Each tile owns its boxes' top/left edges. Bottom/right boundary tiles also
24-- own the outer edges, so shared edges are stored exactly once on the board.
25CREATE OR REPLACE FUNCTION boxes_edge_location (p_edge integer, p_width integer, p_height integer,
26 p_tile_size integer)
27 RETURNS TABLE (
28 tile_id integer,
29 owner_index integer)
30 LANGUAGE sql
31 IMMUTABLE STRICT
32 AS $$
33 WITH coords AS (
34 SELECT
35 p_edge < p_width * (p_height + 1) AS horizontal,
36 CASE WHEN p_edge < p_width * (p_height + 1) THEN
37 p_edge % p_width
38 ELSE
39 (p_edge - p_width * (p_height + 1)) % (p_width + 1)
40 END AS x,
41 CASE WHEN p_edge < p_width * (p_height + 1) THEN
42 p_edge / p_width
43 ELSE
44 (p_edge - p_width * (p_height + 1)) / (p_width + 1)
45 END AS y
47 SELECT
48 (least (y, p_height - 1) / p_tile_size) * (p_width / p_tile_size) + least (x, p_width - 1) / p_tile_size,
49 CASE WHEN horizontal
50 AND y = p_height THEN
51 2 * p_tile_size * p_tile_size + x % p_tile_size
52 WHEN NOT horizontal
53 AND x = p_width THEN
54 2 * p_tile_size * p_tile_size + CASE WHEN y / p_tile_size = p_height / p_tile_size - 1 THEN
55 p_tile_size
56 ELSE
57 0
58 END + y % p_tile_size
59 ELSE
60 CASE WHEN horizontal THEN
61 0
62 ELSE
63 p_tile_size * p_tile_size
64 END + (y % p_tile_size) * p_tile_size + x % p_tile_size
65 END
66 FROM
67 coords
68$$;
69​
70-- Invoked once in autocommit mode. Rules come from shared/game-config.ts;
71-- callers supply only a verified player/team and the selected edge to the API.
72CREATE OR REPLACE FUNCTION boxes_draw (p_player uuid, p_team integer, p_edge integer, p_rules jsonb)
73 RETURNS jsonb
74 LANGUAGE plpgsql
75 AS $$
76DECLARE
77 v_width integer := (p_rules ->> 'width')::integer;
78 v_height integer := (p_rules ->> 'height')::integer;
79 v_tile_size integer := (p_rules ->> 'tileSize')::integer;
80 v_max_quota integer := (p_rules ->> 'maxQuota')::integer;
81 v_refill_interval integer := (p_rules ->> 'refillIntervalMs')::integer;
82 v_leeway integer := (p_rules ->> 'leewayMs')::integer;
83 v_horizontal_count integer := v_width * (v_height + 1);
84 v_horizontal boolean := p_edge < v_horizontal_count;
85 v_x integer;
86 v_y integer;
87 v_box_x integer[] := '{}';
88 v_box_y integer[] := '{}';
89 -- Entry 1 is the move; each following group of four is one adjacent box.
90 v_edge_ids integer[] := ARRAY[p_edge];
91 v_edge_tiles integer[];
92 v_edge_indices integer[];
93 v_tile_ids integer[];
94 v_edges bytea[] := '{}';
95 v_boxes bytea[] := '{}';
96 v_dirty boolean[];
97 v_tile record;
98 v_quota record;
99 v_complete boolean;
100 v_now bigint;
101 v_last_refill bigint;
102 v_refills bigint;
103 v_tokens integer;
104 v_initial_tokens integer;
105 v_initial_refill_in double precision;
106 v_claims integer := 0;
107 v_slot integer;
108 v_box_slot integer;
109 v_box_index integer;
110 v_all_owned boolean;
111 v_i integer;
112 v_j integer;
113 v_entry integer;
114 v_loaded integer := 0;
115 v_status integer;
116 v_code text;
117BEGIN
118 IF p_edge IS NULL OR p_edge < 0 OR p_edge >= v_horizontal_count + v_height * (v_width + 1) THEN
119 RETURN jsonb_build_object('ok', FALSE, 'status', 400, 'code', 'INVALID_EDGE');
120 END IF;
121 IF p_player IS NULL OR p_team IS NULL OR p_team < 0 OR p_team > 3 THEN
122 RETURN jsonb_build_object('ok', FALSE, 'status', 400, 'code', 'INVALID_IDENTITY');
123 END IF;
124 -- Find the one or two adjacent boxes before acquiring locks. Include every
125 -- edge needed to check those boxes, not only the edge being placed.
126 IF v_horizontal THEN
127 v_x := p_edge % v_width;
128 v_y := p_edge / v_width;
129 IF v_y > 0 THEN
130 v_box_x := array_append(v_box_x, v_x);
131 v_box_y := array_append(v_box_y, v_y - 1);
132 END IF;
133 IF v_y < v_height THEN
134 v_box_x := array_append(v_box_x, v_x);
135 v_box_y := array_append(v_box_y, v_y);
136 END IF;
137 ELSE
138 v_x := (p_edge - v_horizontal_count) % (v_width + 1);
139 v_y := (p_edge - v_horizontal_count) / (v_width + 1);
140 IF v_x > 0 THEN
141 v_box_x := array_append(v_box_x, v_x - 1);
142 v_box_y := array_append(v_box_y, v_y);
143 END IF;
144 IF v_x < v_width THEN
145 v_box_x := array_append(v_box_x, v_x);
146 v_box_y := array_append(v_box_y, v_y);
147 END IF;
148 END IF;
149 FOR v_i IN 1..cardinality(v_box_x)
150 LOOP
151 v_edge_ids := v_edge_ids || ARRAY[v_box_y[v_i] * v_width + v_box_x[v_i], (v_box_y[v_i] + 1) *
152 v_width + v_box_x[v_i], v_horizontal_count + v_box_y[v_i] * (v_width + 1) + v_box_x[v_i],
153 v_horizontal_count + v_box_y[v_i] * (v_width + 1) + v_box_x[v_i] + 1];
154 END LOOP;
155 -- Deduplicate and sort tile IDs for locking. The parallel edge arrays preserve
156 -- the target/box-edge order so each owner can be found in the loaded tile buffers.
157 SELECT
158 array_agg(DISTINCT location.tile_id ORDER BY location.tile_id),
159 array_agg(location.tile_id ORDER BY edge.ordinality),
160 array_agg(location.owner_index ORDER BY edge.ordinality) INTO v_tile_ids,
161 v_edge_tiles,
162 v_edge_indices
163 FROM
164 unnest(v_edge_ids)
165 WITH ORDINALITY AS edge (edge_id, ORDINALITY)
166 CROSS JOIN LATERAL boxes_edge_location (edge.edge_id, v_width, v_height, v_tile_size) AS location;
167 v_dirty := array_fill(FALSE, ARRAY[cardinality(v_tile_ids)]);
168 -- This exception block is a subtransaction: expected rejection rolls back
169 -- every write (including a new quota row) before returning a normal result.
170 BEGIN
171 -- KEY SHARE permits other moves/counter updates; reset's FOR UPDATE waits
172 -- for this move to finish before replacing the game's tiles and quotas.
173 SELECT
174 complete INTO STRICT v_complete
175 FROM
176 games
177 WHERE
178 game_id = 1
179 FOR KEY SHARE;
180 v_now := floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint;
181 -- Insert before locking: simultaneous first moves must share one token bucket.
182 INSERT INTO player_quotas (game_id, player_id, tokens, last_refill_at, last_seen_at)
183 VALUES (1, p_player, v_max_quota, v_now, v_now)
184 ON CONFLICT (game_id, player_id)
185 DO NOTHING;
186 SELECT
187 tokens,
188 last_refill_at INTO STRICT v_quota
189 FROM
190 player_quotas
191 WHERE
192 game_id = 1
193 AND player_id = p_player
194 FOR UPDATE;
195 -- All moves lock tiles in the same order to avoid cross-boundary deadlocks.
196 -- Buffer slots follow the sorted tile IDs; corner checks can require four tiles.
197 FOR v_tile IN
198 SELECT
199 tile_id,
200 edges,
201 boxes
202 FROM
203 board_tiles
204 WHERE
205 game_id = 1
206 AND tile_id = ANY (v_tile_ids)
207 ORDER BY
208 tile_id
209 FOR UPDATE LOOP
210 v_edges := array_append(v_edges, v_tile.edges);
211 v_boxes := array_append(v_boxes, v_tile.boxes);
212 v_loaded := v_loaded + 1;
213 END LOOP;
214 IF v_loaded <> cardinality(v_tile_ids) THEN
215 RAISE EXCEPTION 'Board tiles are missing';
216 END IF;
217 -- Refill after any lock wait, using the database clock. Preserve this
218 -- pre-move quota for rejection, even if a later completion check rolls back.
219 v_now := floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint;
220 v_refills := greatest (0, (v_now - v_quota.last_refill_at + v_leeway) / v_refill_interval);
221 v_tokens := least (v_max_quota, v_quota.tokens + v_refills);
222 v_last_refill := CASE WHEN v_tokens = v_max_quota THEN
223 v_now
224 ELSE
225 v_quota.last_refill_at + v_refills * v_refill_interval
226 END;
227 v_initial_tokens := v_tokens;
228 v_initial_refill_in := CASE WHEN v_tokens = v_max_quota THEN
229 0
230 ELSE
231 greatest (0, (v_refill_interval - (v_now - v_last_refill)) / 1000.0)
232 END;
233 v_slot := array_position(v_tile_ids, v_edge_tiles[1]);
234 IF v_complete THEN
235 v_status := 410;
236 v_code := 'GAME_COMPLETE';
237 ELSIF boxes_owner (v_edges[v_slot], v_edge_indices[1]) <> 0 THEN
238 v_status := 409;
239 v_code := 'EDGE_TAKEN';
240 ELSIF v_tokens = 0 THEN
241 v_status := 429;
242 v_code := 'QUOTA_EXHAUSTED';
243 END IF;
244 IF v_code IS NOT NULL THEN
245 RAISE SQLSTATE 'P2001';
246 END IF;
247 v_tokens := v_tokens - 1;
248 v_edges[v_slot] := boxes_set_owner (v_edges[v_slot], v_edge_indices[1], p_team + 1);
249 v_dirty[v_slot] := TRUE;
250 -- Check both adjacent boxes against the changed buffers. Persist explicit
251 -- owners so browsers never infer the winner from unordered tile arrival.
252 FOR v_i IN 1..cardinality(v_box_x)
253 LOOP
254 v_box_slot := array_position(v_tile_ids, (v_box_y[v_i] / v_tile_size) * (v_width /
255 v_tile_size) + v_box_x[v_i] / v_tile_size);
256 v_box_index := (v_box_y[v_i] % v_tile_size) * v_tile_size + v_box_x[v_i] % v_tile_size;
257 IF boxes_owner (v_boxes[v_box_slot], v_box_index) <> 0 THEN
258 CONTINUE;
259 END IF;
260 v_all_owned := TRUE;
261 FOR v_j IN 1..4 LOOP
262 v_entry := 1 + (v_i - 1) * 4 + v_j;
263 v_slot := array_position(v_tile_ids, v_edge_tiles[v_entry]);
264 IF boxes_owner (v_edges[v_slot], v_edge_indices[v_entry]) = 0 THEN
265 v_all_owned := FALSE;
266 EXIT;
267 END IF;
268 END LOOP;
269 IF v_all_owned THEN
270 v_boxes[v_box_slot] := boxes_set_owner (v_boxes[v_box_slot], v_box_index, p_team + 1);
271 v_dirty[v_box_slot] := TRUE;
272 v_claims := v_claims + 1;
273 END IF;
274 END LOOP;
275 IF v_claims > 0 THEN
276 v_tokens := least (v_max_quota, v_tokens + CASE WHEN v_claims = 2 THEN
277 (p_rules ->> 'bonusDouble')::integer
278 ELSE
279 (p_rules ->> 'bonusSingle')::integer
280 END);
281 END IF;
282 -- Write each dirty tile once; locks already cover all tiles read for validation.
283 FOR v_i IN 1..cardinality(v_tile_ids)
284 LOOP
285 IF v_dirty[v_i] THEN
286 UPDATE
287 board_tiles
288 SET
289 edges = v_edges[v_i],
290 boxes = v_boxes[v_i],
291 revision = revision + 1
292 WHERE
293 game_id = 1
294 AND tile_id = v_tile_ids[v_i];
295 END IF;
296 END LOOP;
297 UPDATE
298 player_quotas
299 SET
300 tokens = v_tokens,
301 last_refill_at = v_last_refill,
302 last_seen_at = v_now
303 WHERE
304 game_id = 1
305 AND player_id = p_player;
306 -- Last write: increment current counters and recheck completion atomically.
307 UPDATE
308 games
309 SET
310 scores[p_team + 1] = scores[p_team + 1] + v_claims,
311 edges_placed = edges_placed + 1,
312 complete = CASE WHEN p_rules ->> 'endMode' = 'board_complete' THEN
313 scores[1] + scores[2] + scores[3] + scores[4] + v_claims >= v_width * v_height
314 ELSE
315 scores[p_team + 1] + v_claims >= (p_rules ->> 'scoreTarget')::integer
316 END
317 WHERE
318 game_id = 1
319 AND NOT complete;
320 IF NOT FOUND THEN
321 v_status := 410;
322 v_code := 'GAME_COMPLETE';
323 RAISE SQLSTATE 'P2001';
324 END IF;
325 -- The API awaits autocommit before responding with this transaction ID.
326 RETURN jsonb_build_object('ok', TRUE, 'status', 200, 'boxesClaimed',
327 v_claims, 'txid', pg_current_xact_id ()::text, 'quotaRemaining', v_tokens,
328 'refillIn', CASE WHEN v_tokens = v_max_quota THEN
329 0
330 ELSE
331 greatest (0, (v_refill_interval - (v_now - v_last_refill)) / 1000.0)
332 END);
333 EXCEPTION
334 WHEN SQLSTATE 'P2001' THEN
335 -- Handle only our expected rejection signal. Other SQL errors propagate
336 -- and abort the statement; this block has already undone every move write.
337 IF v_code IS NULL THEN
338 RAISE;
339 END IF;
340 RETURN jsonb_build_object(
341 'ok', FALSE, 'status', v_status, 'code', v_code,
342 'quotaRemaining', v_initial_tokens, 'refillIn', v_initial_refill_in
343 );
344 END;
345END
346$$;