hotosm / fmtm

Field Mapping Tasking Manager - coordinated field mapping.
https://fmtm.hotosm.org/
GNU Affero General Public License v3.0
49 stars 46 forks source link

Create small Postgres NOTIFY/LISTEN webhook service for ODK Central #1841

Open spwoodcock opened 1 month ago

spwoodcock commented 1 month ago

Is your feature request related to a problem? Please describe.

To achieve notifications that the submission was made in ODK we have three options:

I will describe the middleware based approach below.

Describe the solution you'd like

Short term solution:

Long term solution:

Example:

CREATE OR REPLACE FUNCTION data_change() RETURNS trigger AS
$$
    DECLARE
        js jsonb;
    BEGIN
        SELECT to_jsonb(NEW.*) INTO js;
        js := jsonb_set(js, '{dml_action}', to_jsonb(TG_OP));
        PERFORM (
            SELECT pg_notify('people', js::text)
        );
        RETURN NEW;
    END;
$$ LANGUAGE 'plpgsql';

DROP TRIGGER IF EXISTS data_change_trigger
  ON people;
CREATE TRIGGER data_change_trigger
    BEFORE INSERT OR UPDATE ON people
    FOR EACH ROW
        EXECUTE FUNCTION data_change();

Blogs about simple LISTEN / NOTIFY service in Golang:

https://brojonat.com/posts/go-postgres-listen-notify/ https://ds0nt.com/postgres-streaming-listen-notify-go https://brandur.org/notifier

It's also useful to take notes from the psycopg implementation of this: https://www.psycopg.org/psycopg3/docs/advanced/async.html#detecting-disconnections

While it could be nice to implement a more generic pub/sub server like this https://blog.geomusings.com/2023/07/13/a-simple-webhook-interface-for-notify/, I think it's overkill.

We can deploy the very small single Go binary alongside the ODK Central deployment in the compose stack & it will trigger a webhook call whenever an Entity is updated / on submission.

Note we obviously need to make sure this is only triggered on UPDATE not CREATE, as we don't want 1000's of API calls when 1000's of Entities are generated.

Note 2, we probably need to handle auth somehow? Perhaps we generate API tokens in FMTM for this.

Alternatives

spwoodcock commented 3 days ago

Two key things of note: