Skip to content

Commit

Permalink
Use SYNCER_CURRENT_HEIGHT to trigger Forwarder
Browse files Browse the repository at this point in the history
  • Loading branch information
janekolszak committed Jun 5, 2023
1 parent 951dc95 commit 41df3b3
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
-- +migrate Down

-- +migrate Up

-- +migrate StatementBegin
CREATE OR REPLACE FUNCTION notify_sync_state() RETURNS trigger AS $$
DECLARE
is_queue_full boolean;
is_forwarder_listening boolean;
payload jsonb;
BEGIN
-- Notify only upon Sequencer's changes
IF NEW.name != 'Syncer' THEN
RETURN NEW;
END IF;

-- Skip if there's a risk pg_notify would fail
SELECT pg_notification_queue_usage() > 0.999 INTO is_queue_full;
IF is_queue_full THEN
-- pg_notify would fail upon full queue, so let's avoid this situation
-- This sync state won't get lost, it will be picked up by the polling mechanism
RETURN NEW;
END IF;

-- Skip if there's no forwarder listening
SELECT EXISTS(SELECT pid FROM pg_stat_activity WHERE query='listen "sync_state_sequencer"') INTO is_forwarder_listening;
IF NOT is_forwarder_listening THEN
-- Forwarder is down, it will get this sync_state update when it comes back up
RETURN NEW;
END IF;

PERFORM pg_notify('sync_state_sequencer', jsonb_build_object(
'finished_block_height', NEW.finished_block_height,
'finished_block_hash', NEW.finished_block_hash
)::TEXT);

RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- +migrate StatementEnd
20 changes: 20 additions & 0 deletions src/utils/model/sql_migrations/000500_sync_state_trigger.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
-- +migrate Down
DROP TRIGGER IF EXISTS sync_state_notify ON bundle_items;

-- +migrate Up

-- +migrate StatementBegin
DO $$ BEGIN IF NOT EXISTS (
SELECT
1
FROM
pg_trigger
WHERE
tgname = 'sync_state_notify'
) THEN CREATE TRIGGER sync_state_notify
AFTER
INSERT
ON interactions FOR EACH ROW EXECUTE PROCEDURE notify_sync_state();
END IF;
END $$;
-- +migrate StatementEnd

0 comments on commit 41df3b3

Please sign in to comment.