|
| 1 | +-- Chat notification emails are best-effort. A webhook failure should never |
| 2 | +-- abort the original chat message insert. |
| 3 | + |
| 4 | +create or replace function private.notify_new_chat_message() |
| 5 | +returns trigger |
| 6 | +language plpgsql |
| 7 | +security definer |
| 8 | +set search_path = '' |
| 9 | +as $$ |
| 10 | +declare |
| 11 | + webhook_secret text; |
| 12 | +begin |
| 13 | + if to_regprocedure('net.http_post(text,jsonb,jsonb,jsonb,integer)') is null then |
| 14 | + raise warning 'Skipping chat message email webhook because pg_net is unavailable.'; |
| 15 | + return new; |
| 16 | + end if; |
| 17 | + |
| 18 | + if to_regclass('vault.decrypted_secrets') is not null then |
| 19 | + execute |
| 20 | + 'select decrypted_secret from vault.decrypted_secrets where name = $1 limit 1' |
| 21 | + into webhook_secret |
| 22 | + using 'PEELS_CHAT_MESSAGE_WEBHOOK_SECRET'; |
| 23 | + end if; |
| 24 | + |
| 25 | + if webhook_secret is null or webhook_secret = '' then |
| 26 | + raise warning 'Skipping chat message email webhook because PEELS_CHAT_MESSAGE_WEBHOOK_SECRET is not set in Vault.'; |
| 27 | + return new; |
| 28 | + end if; |
| 29 | + |
| 30 | + begin |
| 31 | + perform net.http_post( |
| 32 | + url := 'http://kong:8000/functions/v1/send-email-for-new-chat-message', |
| 33 | + body := jsonb_build_object( |
| 34 | + 'type', tg_op, |
| 35 | + 'table', tg_table_name, |
| 36 | + 'schema', tg_table_schema, |
| 37 | + 'record', to_jsonb(new), |
| 38 | + 'old_record', null |
| 39 | + ), |
| 40 | + params := '{}'::jsonb, |
| 41 | + headers := jsonb_build_object( |
| 42 | + 'Content-Type', 'application/json', |
| 43 | + 'x-peels-webhook-secret', webhook_secret |
| 44 | + ), |
| 45 | + timeout_milliseconds := 5000 |
| 46 | + ); |
| 47 | + exception |
| 48 | + when others then |
| 49 | + raise warning 'Skipping chat message email webhook because the request failed: %', sqlerrm; |
| 50 | + end; |
| 51 | + |
| 52 | + return new; |
| 53 | +end; |
| 54 | +$$; |
| 55 | + |
| 56 | +alter function private.notify_new_chat_message() owner to postgres; |
| 57 | + |
| 58 | +revoke all privileges on function private.notify_new_chat_message() |
| 59 | + from anon, authenticated, public; |
0 commit comments