Restore

O Operator
Restore

Restore file to captured state

Every captured change carries its SHA-256-addressed content in BLOB_STORE. Restoring writes that content back to the original path — current file gets backed up to <path>.drift_restore_backup_<epoch> before overwrite.

What will change
Preview -- nothing has been written yet.
Target file/var/www/vhosts/3dshawn.com/site1/_alert_dispatch.pl
SiteDriftSense self-monitor on local
Kindlocal
Captured at2026-07-11 19:38:00
Captured SHAad10d46443a15412a8e99cf91ebfa462cce1de88674043364ed0dfb63797a664
Current state on disk
Live check just now. If SHAs match, the restore is a no-op.
File presentyes
Size22933 bytes
Current SHAa53566efc691
Same as captured?no -- restore will change it
What restore will change — live diff
Left column shows current on-disk content; right shows what restore will write. +2 additions, -268 deletions, 325 unchanged context lines.
11#!/usr/bin/perl
22#======================================================================
33# DriftSense -- alert dispatcher
44#
55# Cron entry point (NOT a CGI). Walks FILE_CHANGES + SCHEMA_CHANGE rows
66# inserted since the last cursor tick, evaluates every ACTIVE rule
77# against each new row, and POSTs matching payloads to the configured
88# webhook (Slack / Discord / generic HTTP). Every attempt is logged
99# to ALERT_DELIVERIES for the operator's audit trail.
1010#
1111# Config: /etc/drift_sense/drift_sense.conf (via MODS::Config).
1212# Log: /var/log/drift_sense/alert_dispatch.log (via cron redirect).
1313#======================================================================
1414use strict;
1515use warnings;
1616use lib '/var/www/vhosts/3dshawn.com/site1';
1717use POSIX ();
18use Symbol ();
1918use JSON::PP;
2019use MODS::Config;
2120use MODS::DBConnect;
2221use MODS::Webhook;
2322
2423$| = 1;
2524my $ts = POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime);
2625
2726my $cfg = MODS::Config->new;
2827my $db = MODS::DBConnect->new;
2928my $dbh = $db->db_connect or die "[$ts] cannot connect to DriftSense storage DB\n";
3029
3130my $public_url = $cfg->settings('public_url') || 'https://watchtower.3dshawn.com';
3231
3332# ---- Fetch active rules ---------------------------------------------
3433my @rules = $db->db_readwrite_multiple($dbh, q~
3534 SELECT alert_rule_id, rule_name, match_kind, match_path_glob,
3635 match_status_list, exclude_ts_only,
3736 delivery_kind, delivery_url, delivery_email,
38 rate_limit_per_min, coalesce_window_s,
39 frequency_threshold, frequency_window_min,
40 UNIX_TIMESTAMP(last_frequency_fire_at) AS last_freq_fire_epoch
37 rate_limit_per_min, coalesce_window_s
4138 FROM ALERT_RULES
4239 WHERE is_active = 1
4340~, __FILE__, __LINE__);
4441
4542unless (@rules) {
4643 print "[$ts] no active alert rules, exiting\n";
4744 $db->db_disconnect($dbh);
4845 exit 0;
4946}
5047
5148# ---- Fetch cursor ---------------------------------------------------
5249my %cursor;
5350foreach my $r ($db->db_readwrite_multiple($dbh, q~
5451 SELECT source_kind, last_seen_id FROM ALERT_CURSOR
5552~, __FILE__, __LINE__)) {
5653 $cursor{$r->{source_kind}} = $r->{last_seen_id};
5754}
5855$cursor{file} //= 0;
5956$cursor{schema} //= 0;
6057
6158# ---- Pull new FILE_CHANGES since cursor ------------------------------
6259my $file_max = $cursor{file};
6360my @file_new = $db->db_readwrite_multiple($dbh, qq~
6461 SELECT fc.file_changes_id AS id, fc.file_name, fc.status, fc.blob_sha,
6562 fc.is_ts_only, fc.date_time,
6663 UNIX_TIMESTAMP(fc.date_time) AS ts_epoch,
6764 s.server_name
6865 FROM FILE_CHANGES fc
6966 LEFT JOIN SERVERS s ON s.server_id = fc.server_id
7067 WHERE fc.file_changes_id > $cursor{file}
7168 ORDER BY fc.file_changes_id ASC
7269 LIMIT 500
7370~, __FILE__, __LINE__);
7471foreach my $r (@file_new) {
7572 $file_max = $r->{id} if $r->{id} > $file_max;
7673}
7774
7875# ---- Pull new SCHEMA_CHANGE since cursor -----------------------------
7976my $schema_max = $cursor{schema};
8077my @schema_new = $db->db_readwrite_multiple($dbh, qq~
8178 SELECT sc.schema_change_id AS id, sc.database_name, sc.table_name,
8279 sc.changes, sc.is_ts_only, sc.change_datetime,
8380 UNIX_TIMESTAMP(sc.change_datetime) AS ts_epoch,
8481 s.server_name
8582 FROM SCHEMA_CHANGE sc
8683 LEFT JOIN SERVERS s ON s.server_id = sc.server_id
8784 WHERE sc.schema_change_id > $cursor{schema}
8885 ORDER BY sc.schema_change_id ASC
8986 LIMIT 500
9087~, __FILE__, __LINE__);
9188foreach my $r (@schema_new) {
9289 $schema_max = $r->{id} if $r->{id} > $schema_max;
9390}
9491
9592my $total_new = scalar(@file_new) + scalar(@schema_new);
9693if ($total_new == 0) {
9794 print "[$ts] no new changes since cursor (file=$cursor{file} schema=$cursor{schema})\n";
9895 $db->db_disconnect($dbh);
9996 exit 0;
10097}
10198
10299# ---- Evaluate + deliver ---------------------------------------------
103100# HTTP transport is MODS::Webhook (shells out to /usr/bin/curl) so we
104101# don't need LWP::Protocol::https / IO::Socket::SSL as CPAN installs.
105102
106103my $delivered = 0;
107104my $skipped = 0;
108105my $failed = 0;
109106
110107foreach my $row (@file_new) { _process_row($row, 'file'); }
111108foreach my $row (@schema_new) { _process_row($row, 'schema'); }
112
113# ---- Frequency-mode rules ------------------------------------------
114# For any rule where frequency_threshold > 0, we ignore the per-row loop
115# above and instead: query how many file changes matching the rule's
116# path glob happened in the last window_min minutes. If it crosses the
117# threshold and we haven't fired within the same window, fire once with
118# the top offender.
119foreach my $rule (@rules) {
120 next unless ($rule->{frequency_threshold} || 0) > 0;
121 my $win = int($rule->{frequency_window_min} || 60);
122 my $thr = int($rule->{frequency_threshold});
123
124 # Re-fire cooldown: don't fire more than once per window
125 my $last = int($rule->{last_freq_fire_epoch} || 0);
126 if ($last && (time - $last) < $win * 60) {
127 next;
128 }
129
130 # Find files whose match_path_glob-hit change count > threshold
131 my $glob = $rule->{match_path_glob} // '';
132 my $glob_sql = '';
133 if (length $glob) {
134 # Approx: SQL LIKE. Convert glob wildcards to SQL % / _.
135 my $like = $glob;
136 $like =~ s/\*\*/%/g;
137 $like =~ s/\*/%/g;
138 $like =~ s/\?/_/g;
139 my $q_like = $dbh->quote($like);
140 $glob_sql = " AND fc.file_name LIKE $q_like";
141 }
142 my @hot = $db->db_readwrite_multiple($dbh, qq~
143 SELECT fc.file_name,
144 COUNT(*) AS ct,
145 MAX(fc.file_changes_id) AS latest_id,
146 s.server_name
147 FROM FILE_CHANGES fc
148 LEFT JOIN SERVERS s ON s.server_id = fc.server_id
149 WHERE fc.date_time >= DATE_SUB(NOW(), INTERVAL $win MINUTE)
150 $glob_sql
151 GROUP BY fc.file_name
152 HAVING ct >= $thr
153 ORDER BY ct DESC
154 LIMIT 5
155 ~, __FILE__, __LINE__);
156 next unless @hot;
157
158 # Fire once with the top offender's info
159 my $top = $hot[0];
160 my $fake_row = {
161 id => $top->{latest_id},
162 file_name => $top->{file_name},
163 server_name => $top->{server_name} // 'local',
164 date_time => POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime),
165 ts_epoch => time,
166 status => 'frequency_alert',
167 };
168 my $payload = _build_payload($rule, $fake_row, 'file');
169 # Enrich summary with count + threshold
170 my $extra = "frequency alert: $top->{file_name} changed $top->{ct} times in the last $win min (threshold: $thr)";
171 if (ref($payload->{generic_webhook}) eq 'HASH') {
172 $payload->{generic_webhook}{frequency_summary} = $extra;
173 $payload->{generic_webhook}{frequency_count} = $top->{ct};
174 $payload->{generic_webhook}{frequency_window} = $win;
175 $payload->{generic_webhook}{summary} = $extra;
176 }
177 my ($status, $http_code, $body, $err) = _deliver($rule, $payload);
178 _log_delivery($rule, $fake_row, 'file', $status, $http_code, $body, $err);
179 if ($status eq 'sent') {
180 $delivered++;
181 $db->db_readwrite($dbh, qq~
182 UPDATE ALERT_RULES
183 SET fire_count = fire_count + 1,
184 last_fired_at = NOW(),
185 last_frequency_fire_at = NOW()
186 WHERE alert_rule_id = $rule->{alert_rule_id}
187 ~, __FILE__, __LINE__);
188 } else {
189 $failed++;
190 }
191}
192109
193110# ---- Advance cursor atomically --------------------------------------
194111if ($file_max > $cursor{file}) {
195112 $db->db_readwrite($dbh,
196113 "UPDATE ALERT_CURSOR SET last_seen_id = $file_max WHERE source_kind = 'file'",
197114 __FILE__, __LINE__);
198115}
199116if ($schema_max > $cursor{schema}) {
200117 $db->db_readwrite($dbh,
201118 "UPDATE ALERT_CURSOR SET last_seen_id = $schema_max WHERE source_kind = 'schema'",
202119 __FILE__, __LINE__);
203}
204
205# ---- Pin-drift alerts (Feature 5 wave 4) ---------------------------
206# For each Named Release with alert_delivery_url set, check whether any
207# pin's current-latest SHA differs from the pinned SHA. Log the drift
208# to PIN_DRIFT_LOG (with notified=0) and, if not yet notified, POST an
209# alert to the release's delivery URL, then set notified=1.
210foreach my $rel ($db->db_readwrite_multiple($dbh, q~
211 SELECT named_release_id, name, alert_delivery_kind, alert_delivery_url
212 FROM NAMED_RELEASES
213 WHERE alert_delivery_kind IS NOT NULL
214 AND alert_delivery_kind != 'none'
215 AND alert_delivery_url IS NOT NULL
216 AND alert_delivery_url != ''
217~, __FILE__, __LINE__)) {
218
219 my $rid = $rel->{named_release_id};
220 my @drifts;
221 foreach my $pin ($db->db_readwrite_multiple($dbh, qq~
222 SELECT p.pin_id, p.file_name, p.blob_sha AS pinned_sha,
223 fc.server_id
224 FROM NAMED_RELEASE_PINS p
225 LEFT JOIN FILE_CHANGES fc ON fc.file_changes_id = p.file_changes_id
226 WHERE p.named_release_id = $rid
227 ~, __FILE__, __LINE__)) {
228 my $q_file = $dbh->quote($pin->{file_name});
229 my $sid = int($pin->{server_id} || 0);
230 my $cur = $db->db_readwrite($dbh, qq~
231 SELECT blob_sha, file_changes_id FROM FILE_CHANGES
232 WHERE server_id = $sid AND file_name = $q_file
233 ORDER BY file_changes_id DESC LIMIT 1
234 ~, __FILE__, __LINE__);
235 my $cur_sha = $cur ? $cur->{blob_sha} : '';
236 next unless $cur_sha && $cur_sha ne $pin->{pinned_sha};
237
238 # Have we already logged + notified this (pin, current_sha) tuple?
239 my $q_pinned = $dbh->quote($pin->{pinned_sha});
240 my $q_current = $dbh->quote($cur_sha);
241 my $seen = $db->db_readwrite($dbh, qq~
242 SELECT drift_id, notified FROM PIN_DRIFT_LOG
243 WHERE pin_id = $pin->{pin_id}
244 AND current_sha = $q_current
245 ORDER BY drift_id DESC LIMIT 1
246 ~, __FILE__, __LINE__);
247 if ($seen && $seen->{notified}) {
248 next; # already notified for this exact drift state
249 }
250
251 # Log the drift
252 my $q_fname = $dbh->quote($pin->{file_name});
253 my $cid = int($cur->{file_changes_id} || 0);
254 $db->db_readwrite($dbh, qq~
255 INSERT INTO PIN_DRIFT_LOG
256 (named_release_id, pin_id, file_name, pinned_sha, current_sha, file_changes_id, notified)
257 VALUES
258 ($rid, $pin->{pin_id}, $q_fname, $q_pinned, $q_current, $cid, 0)
259 ~, __FILE__, __LINE__);
260 push @drifts, {
261 file_name => $pin->{file_name},
262 pinned_sha => $pin->{pinned_sha},
263 current_sha => $cur_sha,
264 change_id => $cid,
265 };
266 }
267
268 next unless @drifts;
269
270 # Build a summary payload
271 my $summary = sprintf('Named release "%s" -- %d pinned file(s) have drifted', $rel->{name}, scalar @drifts);
272 my $public_url = $cfg->settings('public_url') || 'https://watchtower.3dshawn.com';
273 my $files_list = join("\n", map {
274 " * $_->{file_name} (pinned: " . substr($_->{pinned_sha}, 0, 12) .
275 " -> current: " . substr($_->{current_sha}, 0, 12) . ")"
276 } @drifts);
277 my $link = "$public_url/restore_release.cgi?release_id=$rid";
278
279 my $slack_body = {
280 text => "*DriftSense pin drift*: $summary",
281 attachments => [{
282 color => '#f43f5e',
283 fields => [
284 { title => 'Release', value => $rel->{name}, short => 1 },
285 { title => 'Drifted files', value => scalar(@drifts), short => 1 },
286 { title => 'Details', value => $files_list, short => 0 },
287 ],
288 actions => [{ type => 'button', text => 'Restore all pinned', url => $link }],
289 }],
290 };
291 my $discord_body = {
292 content => "**DriftSense pin drift**: $summary",
293 embeds => [{
294 title => $rel->{name},
295 url => $link,
296 color => 16005694,
297 description => $files_list,
298 }],
299 };
300 my $generic_body = {
301 source => 'drift_sense',
302 alert_type => 'pin_drift',
303 release_id => $rid,
304 release_name => $rel->{name},
305 drifted_count=> scalar @drifts,
306 summary => $summary,
307 files => \@drifts,
308 restore_url => $link,
309 };
310
311 my $body_ref = $rel->{alert_delivery_kind} eq 'slack' ? $slack_body
312 : $rel->{alert_delivery_kind} eq 'discord' ? $discord_body
313 : $generic_body;
314
315 my ($code, $rbody, $err) = MODS::Webhook::post_json(
316 $rel->{alert_delivery_url}, $body_ref,
317 timeout => 8,
318 user_agent => 'DriftSense/1.0 (pin-drift)',
319 );
320
321 if (!$err && $code >= 200 && $code < 400) {
322 # Mark all just-logged rows as notified
323 foreach my $d (@drifts) {
324 my $q_current = $dbh->quote($d->{current_sha});
325 $db->db_readwrite($dbh, qq~
326 UPDATE PIN_DRIFT_LOG SET notified = 1
327 WHERE named_release_id = $rid
328 AND file_name = @{[ $dbh->quote($d->{file_name}) ]}
329 AND current_sha = $q_current
330 AND notified = 0
331 ~, __FILE__, __LINE__);
332 }
333 $delivered++;
334 print "[$ts] pin-drift alert delivered for release '$rel->{name}' (" . scalar(@drifts) . " drifted)\n";
335 } else {
336 $failed++;
337 print "[$ts] pin-drift alert FAILED for release '$rel->{name}': " . ($err // "HTTP $code") . "\n";
338 }
339
340 # Bookkeep the check timestamp
341 $db->db_readwrite($dbh, qq~
342 UPDATE NAMED_RELEASES SET last_pin_drift_check_at = NOW()
343 WHERE named_release_id = $rid
344 ~, __FILE__, __LINE__);
345120}
346121
347122$db->db_disconnect($dbh);
348123print "[$ts] processed +$total_new new changes: $delivered delivered, $skipped skipped, $failed failed\n";
349124exit 0;
350125
351126#---------------------------------------------------------------------
352127sub _process_row {
353128 my ($row, $kind) = @_;
354129 foreach my $rule (@rules) {
355130 next unless _rule_matches($rule, $row, $kind);
356131
357132 # Rate limit check
358133 if ($rule->{rate_limit_per_min} > 0) {
359134 my $rlq = $db->db_readwrite($dbh, qq~
360135 SELECT COUNT(*) AS n FROM ALERT_DELIVERIES
361136 WHERE alert_rule_id = $rule->{alert_rule_id}
362137 AND fired_at >= DATE_SUB(NOW(), INTERVAL 1 MINUTE)
363138 AND delivery_status IN ('sent','pending')
364139 ~, __FILE__, __LINE__);
365140 if ($rlq && $rlq->{n} >= $rule->{rate_limit_per_min}) {
366141 _log_delivery($rule, $row, $kind, 'skipped', undef, undef,
367142 "rate limit ($rule->{rate_limit_per_min}/min) reached");
368143 $skipped++;
369144 next;
370145 }
371146 }
372147
373148 # Build payload + POST
374149 my $payload = _build_payload($rule, $row, $kind);
375150 my ($status, $http_code, $body, $err) = _deliver($rule, $payload);
376151 _log_delivery($rule, $row, $kind, $status, $http_code, $body, $err);
377152
378153 if ($status eq 'sent') { $delivered++; }
379154 elsif ($status eq 'skipped') { $skipped++; }
380155 else { $failed++; }
381156
382157 # Bump the rule's fire_count + last_fired_at
383158 if ($status eq 'sent') {
384159 $db->db_readwrite($dbh, qq~
385160 UPDATE ALERT_RULES
386161 SET fire_count = fire_count + 1,
387162 last_fired_at = NOW()
388163 WHERE alert_rule_id = $rule->{alert_rule_id}
389164 ~, __FILE__, __LINE__);
390165 }
391166 }
392167}
393168
394169#---------------------------------------------------------------------
395170sub _rule_matches {
396171 my ($rule, $row, $kind) = @_;
397172
398173 # Kind filter
399174 return 0 if $rule->{match_kind} ne 'either' && $rule->{match_kind} ne $kind;
400175
401176 # ts-only exclusion (files only)
402177 return 0 if $kind eq 'file' && $rule->{exclude_ts_only} && $row->{is_ts_only};
403178
404179 # Path glob
405180 my $glob = $rule->{match_path_glob} // '';
406181 if (length $glob) {
407182 my $target = $kind eq 'file'
408183 ? ($row->{file_name} // '')
409184 : (($row->{database_name} // '') . '.' . ($row->{table_name} // ''));
410185 my $re = _glob_to_regex($glob);
411186 return 0 unless $target =~ $re;
412187 }
413188
414189 # Status filter (files only)
415190 if ($kind eq 'file' && $rule->{match_status_list}) {
416191 my %allowed = map { s/^\s+|\s+$//g; $_ => 1 }
417192 split /,/, $rule->{match_status_list};
418193 return 0 unless $allowed{ $row->{status} // '' };
419194 }
420195
421196 return 1;
422197}
423198
424199sub _glob_to_regex {
425200 my $g = shift;
426201 my $re = quotemeta $g;
427202 # Handle glob patterns: escaped meta chars back to regex meaning
428203 $re =~ s{\\\*\\\*}{.*}g; # ** -> .*
429204 $re =~ s{\\\*}{[^/]*}g; # * -> [^/]*
430205 $re =~ s{\\\?}{.}g; # ? -> .
431206 return qr/^$re$/;
432207}
433208
434209#---------------------------------------------------------------------
435210sub _build_payload {
436211 my ($rule, $row, $kind) = @_;
437212
438213 my $where = $kind eq 'file'
439214 ? ($row->{file_name} // '(unknown file)')
440215 : (($row->{database_name} // '?') . '.' . ($row->{table_name} // '?'));
441216 my $when_utc = $row->{date_time} || $row->{change_datetime} || '';
442217 my $server = $row->{server_name} || 'local';
443218 my $status_h = $kind eq 'file' ? ($row->{status} // '') : 'DDL change';
444219 my $link_id = $row->{id};
445220 my $link = "$public_url/diff.cgi?kind=$kind&id=$link_id";
446221
447222 my $summary = $kind eq 'file'
448223 ? "$status_h: $where on $server"
449224 : "$where changed on $server";
450225
451226 my $slack = {
452227 text => "*DriftSense*: $summary",
453228 attachments => [{
454229 color => $kind eq 'schema' ? '#f59e0b' : '#14b8a6',
455230 fields => [
456231 { title => 'What', value => $where, short => 0 },
457232 { title => 'When', value => $when_utc, short => 1 },
458233 { title => 'Server', value => $server, short => 1 },
459234 ],
460235 actions => [{
461236 type => 'button', text => 'View diff', url => $link,
462237 }],
463238 }],
464239 };
465240 my $discord = {
466241 content => "**DriftSense**: $summary",
467242 embeds => [{
468243 title => $where,
469244 url => $link,
470245 color => $kind eq 'schema' ? 16101915 : 1349286, # amber, teal
471246 fields => [
472247 { name => 'When', value => $when_utc || '?', inline => \1 },
473248 { name => 'Server', value => $server, inline => \1 },
474249 ],
475250 }],
476251 };
477252 my $generic = {
478253 source => 'drift_sense',
479254 rule_id => $rule->{alert_rule_id},
480255 rule_name => $rule->{rule_name},
481256 kind => $kind,
482257 summary => $summary,
483258 target => $where,
484259 server => $server,
485260 when_utc => $when_utc,
486261 ts_epoch => $row->{ts_epoch},
487262 diff_url => $link,
488263 status => $status_h,
489264 };
490265
491266 return {
492267 slack => $slack,
493268 discord => $discord,
494269 generic_webhook => $generic,
495270 summary => $summary,
496271 };
497272}
498273
499274#---------------------------------------------------------------------
500275sub _deliver {
501276 my ($rule, $payload) = @_;
502277 my $kind = $rule->{delivery_kind};
503278 my $url = $rule->{delivery_url};
504279
505280 if ($kind eq 'email') {
506 my $to = $rule->{delivery_email} || '';
507 return ('failed', undef, undef, 'no delivery_email configured') unless length $to;
508 my $summary = $payload->{summary} // 'DriftSense alert';
509 my $target = ($payload->{generic_webhook} && $payload->{generic_webhook}{target}) // '(unknown)';
510 my $server = ($payload->{generic_webhook} && $payload->{generic_webhook}{server}) // 'local';
511 my $link = ($payload->{generic_webhook} && $payload->{generic_webhook}{diff_url}) // '';
512
513 my $mail_body = "DriftSense captured a change matching alert rule: $rule->{rule_name}\n\n"
514 . "Target : $target\n"
515 . "Server : $server\n"
516 . "Summary: $summary\n"
517 . ($link ? "Diff : $link\n" : '')
518 . "\n(Automated notification from DriftSense.)\n";
519
520 my $from = $cfg->settings('alert_from_email') || 'drift_sense@localhost';
521 my $subj = "[DriftSense] " . substr($summary, 0, 120);
522
523 my $sendmail = '/usr/sbin/sendmail';
524 $sendmail = '/usr/lib/sendmail' unless -x $sendmail;
525 return ('failed', undef, undef, "no sendmail binary") unless -x $sendmail;
526
527 require IPC::Open3;
528 my ($wtr, $rdr, $err_fh);
529 $err_fh = Symbol::gensym();
530 my $pid = eval { IPC::Open3::open3($wtr, $rdr, $err_fh, $sendmail, '-t', '-i') };
531 return ('failed', undef, undef, "spawn: $@") if $@ || !$pid;
532 binmode $wtr;
533 print {$wtr} "From: $from\r\n";
534 print {$wtr} "To: $to\r\n";
535 print {$wtr} "Subject: $subj\r\n";
536 print {$wtr} "Content-Type: text/plain; charset=utf-8\r\n";
537 print {$wtr} "\r\n";
538 print {$wtr} $mail_body;
539 close $wtr;
540 do { local $/; <$rdr> // ''; };
541 do { local $/; <$err_fh> // ''; };
542 close $rdr; close $err_fh;
543 waitpid $pid, 0;
544 my $rc = $? >> 8;
545 return $rc == 0
546 ? ('sent', 0, "delivered to $to", undef)
547 : ('failed', $rc, undef, "sendmail exit $rc");
281 return ('skipped', undef, undef, 'email delivery not yet implemented');
548282 }
549283 unless (length($url // '')) {
550284 return ('failed', undef, undef, "no delivery URL configured");
551285 }
552286
553287 my $body_ref = $kind eq 'slack' ? $payload->{slack}
554288 : $kind eq 'discord' ? $payload->{discord}
555289 : $payload->{generic_webhook};
556290
557291 # MODS::Webhook handles JSON encoding + curl transport; returns
558292 # (http_code, response_body, error_message).
559293 my ($code, $rbody, $err) = MODS::Webhook::post_json(
560294 $url, $body_ref,
561295 timeout => 8,
562296 user_agent => 'DriftSense/1.0 (alert-dispatch)',
563297 );
564298 $rbody //= '';
565299 $rbody = substr($rbody, 0, 500) if length($rbody) > 500;
566300
567301 if (!$err && $code >= 200 && $code < 400) {
568302 return ('sent', $code, $rbody, undef);
569303 }
570304 return ('failed', $code, $rbody, $err || "HTTP $code");
571305}
572306
573307#---------------------------------------------------------------------
574308sub _log_delivery {
575309 my ($rule, $row, $kind, $status, $http_code, $body, $err) = @_;
576310 my $summary = substr(($rule->{rule_name} // '') . ' :: ' . ($row->{file_name}
577311 || ($row->{database_name} . '.' . $row->{table_name})
578312 || '?'), 0, 490);
579313 my $q_summary = $dbh->quote($summary);
580314 my $q_status = $dbh->quote($status);
581315 my $q_body = $dbh->quote($body // '');
582316 my $q_err = $dbh->quote($err // '');
583317 my $q_code = defined($http_code) ? int($http_code) : 'NULL';
584318
585319 $db->db_readwrite($dbh, qq~
586320 INSERT INTO ALERT_DELIVERIES
587321 (alert_rule_id, source_kind, source_id, match_summary,
588322 delivery_status, http_status, http_response, error_message)
589323 VALUES
590324 ($rule->{alert_rule_id}, '$kind', $row->{id}, $q_summary,
591325 $q_status, $q_code, $q_body, $q_err)
592326 ~, __FILE__, __LINE__);
593327}
Confirm restore
Backs current content to <target>.drift_restore_backup_<epoch>, writes the captured content, verifies SHA post-write.
Cancel Logged to RESTORE_LOG regardless of outcome.