Skip to content

Commit aceb26c

Browse files
authored
Merge pull request #125 from hack-a-chain-software/feat/check-backward-orphans-optimization
refactor: optimize block selection logic and improve locking mechanism
2 parents 5aee802 + 11d5bb1 commit aceb26c

File tree

2 files changed

+16
-12
lines changed

2 files changed

+16
-12
lines changed

indexer/src/config/database.ts

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -336,15 +336,17 @@ DECLARE
336336
depth CONSTANT INT := 10; -- Default the depth constant
337337
buffer CONSTANT INT := 5; -- Number of heights to buffer, because some blocks can arrive out of order
338338
BEGIN
339+
PERFORM pg_advisory_xact_lock(hashtext(NEW."chainId"::text || NEW."chainwebVersion"::text));
340+
339341
-- Check the last 'depth' blocks
340342
FOR recent_blocks IN
341343
SELECT * FROM public."Blocks"
342-
WHERE height >= ((NEW.height - buffer) - depth) AND height < (NEW.height - buffer)
343-
AND "chainId" = NEW."chainId"
344-
AND "chainwebVersion" = NEW."chainwebVersion"
345-
AND (canonical IS NULL OR canonical = TRUE)
346-
ORDER BY height DESC
347-
FOR UPDATE
344+
WHERE height BETWEEN (NEW.height - buffer - depth) AND (NEW.height - buffer - 1)
345+
AND "chainId" = NEW."chainId"
346+
AND "chainwebVersion" = NEW."chainwebVersion"
347+
AND COALESCE(canonical, TRUE)
348+
ORDER BY height ASC
349+
FOR NO KEY UPDATE
348350
LOOP
349351
-- Set the first block
350352
IF block_count = 0 THEN

indexer/tests/database/init.sql

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -473,15 +473,17 @@ DECLARE
473473
depth CONSTANT INT := 10; -- Default the depth constant
474474
buffer CONSTANT INT := 5; -- Number of heights to buffer, because some blocks can arrive out of order
475475
BEGIN
476+
PERFORM pg_advisory_xact_lock(hashtext(NEW."chainId"::text || NEW."chainwebVersion"::text));
477+
476478
-- Check the last 'depth' blocks
477479
FOR recent_blocks IN
478480
SELECT * FROM public."Blocks"
479-
WHERE height >= ((NEW.height - buffer) - depth) AND height < (NEW.height - buffer)
480-
AND "chainId" = NEW."chainId"
481-
AND "chainwebVersion" = NEW."chainwebVersion"
482-
AND (canonical IS NULL OR canonical = TRUE)
483-
ORDER BY height DESC
484-
FOR UPDATE
481+
WHERE height BETWEEN (NEW.height - buffer - depth) AND (NEW.height - buffer - 1)
482+
AND "chainId" = NEW."chainId"
483+
AND "chainwebVersion" = NEW."chainwebVersion"
484+
AND COALESCE(canonical, TRUE)
485+
ORDER BY height ASC
486+
FOR NO KEY UPDATE
485487
LOOP
486488
-- Set the first block
487489
IF block_count = 0 THEN

0 commit comments

Comments
 (0)