id: nasa-eonet-asset-proximity-alert
namespace: company.team
description: |
Every hour, pull the open natural events (wildfires, severe storms, volcanoes, floods) from
NASA EONET v3 in one request, measure the great-circle distance from each of your sites to the
latest position of every event (inside-polygon counts as 0 km), and post one Slack alert per
site for the events inside its radius, with distance, compass direction, whether a storm is
approaching or receding, magnitude and source links. A KV state keyed on (event id, asset)
keeps the same fire or storm from being re-posted every hour unless it has moved closer by a
configurable number of kilometres; closed events drop out of the state. No API key.
inputs:
- id: assets
type: JSON
displayName: Assets to watch
description: JSON array of sites with `name`, `lat`, `lon` (decimal degrees,
WGS84) and `radius_km`, the distance at which an event becomes an alert
for that site. Names must be unique; they are half of the dedupe key.
defaults: |
[
{"name": "Reno distribution centre", "lat": 39.5296, "lon": -119.8138, "radius_km": 40},
{"name": "Los Angeles cold-storage warehouse", "lat": 34.0522, "lon": -118.2437, "radius_km": 75},
{"name": "Phoenix PHX-1 data centre", "lat": 33.4484, "lon": -112.0740, "radius_km": 150},
{"name": "Manzanillo port fuel terminal", "lat": 19.0522, "lon": -104.3158, "radius_km": 400},
{"name": "Guam cable landing station", "lat": 13.4443, "lon": 144.7937, "radius_km": 800},
{"name": "Houston ship channel terminal", "lat": 29.7355, "lon": -95.2000, "radius_km": 150}
]
- id: categories
type: MULTISELECT
displayName: EONET categories
description: EONET category ids sent in the single `category` parameter.
values:
- wildfires
- severeStorms
- volcanoes
- floods
- earthquakes
- landslides
- dustHaze
- seaLakeIce
- snow
- tempExtremes
- drought
- manmade
- waterColor
defaults:
- wildfires
- severeStorms
- volcanoes
- floods
- id: days
type: INT
defaults: 30
description: EONET returns only events with a geometry dated in the last N days.
- id: event_status
type: SELECT
values:
- open
- closed
- all
defaults: open
description: Keep `open` for alerting. `closed` or `all` replays recent history
against your sites, for example to tune radii; use a separate `state_key`
when you do.
- id: include_prescribed_fires
type: BOOL
defaults: false
description: EONET wildfires include planned prescribed burns reported to IRWIN
(titles starting with "Prescribed Fire"). They are skipped by default.
- id: closer_threshold_km
type: FLOAT
defaults: 10.0
description: An event already alerted for an asset is posted again only when its
latest position is at least this many kilometres closer than at the last
alert.
- id: state_key
type: STRING
defaults: eonet_asset_proximity_state
description: KV key holding the alert state. Use a different key per asset list.
triggers:
- id: hourly
type: io.kestra.plugin.core.trigger.Schedule
description: Checks EONET at minute 7 of every hour; EONET refreshes its sources
(IRWIN, JTWC, NHC, GDACS and others) several times an hour.
cron: "7 * * * *"
tasks:
- id: previous_state
type: io.kestra.plugin.core.kv.Get
description: JSON array of the (event id, asset) pairs already alerted, with the
distance at the time of the alert. Missing on the first run, so every
in-radius pair alerts once.
key: "{{ inputs.state_key }}"
errorOnMissing: false
- id: fetch_events
type: io.kestra.plugin.core.http.Download
description: |
One request for every category: `category` takes a comma-separated list, `status=open` drops closed events
and `days` limits the payload to events updated recently (about 50 KB for the defaults). Public endpoint, no key;
the retry covers the occasional EONET 5xx or timeout.
uri: https://eonet.gsfc.nasa.gov/api/v3/events
params:
status: "{{ inputs.event_status }}"
days: "{{ inputs.days }}"
category: "{{ inputs.categories | join(',') }}"
headers:
Accept: application/json
User-Agent: kestra-nasa-eonet-asset-proximity-alert/1.0 (https://kestra.io)
options:
timeout:
readIdleTimeout: PT2M
retry:
type: exponential
interval: PT30S
maxInterval: PT5M
maxAttempts: 4
- id: proximity
type: io.kestra.plugin.jdbc.duckdb.Queries
description: |
Validates the asset list, flattens every event geometry (Point, and the outer ring of a Polygon), keeps the latest
position of each event, computes the haversine distance and bearing from every asset to it (0 km when the asset is
inside a polygon), the trend against the previous position, compares the pairs inside the radius with the KV state
and writes the proximity CSV, the new state and one alert object per affected asset.
url: "jdbc:duckdb:"
timeZoneId: UTC
fetchType: FETCH_ONE
inputFiles:
events.json: "{{ outputs.fetch_events.uri }}"
assets.json: "{{ inputs.assets | toJson }}"
state.json: "{{ (outputs.previous_state.value ?? []) | toJson }}"
outputFiles:
- proximity_csv
- state_json
parameters:
include_prescribed: "{{ inputs.include_prescribed_fires }}"
closer_threshold_km: "{{ inputs.closer_threshold_km }}"
run_started: "{{ execution.startDate }}"
sql: |
-- EONET dates are UTC; keep the session in UTC so timestamps are not shifted to the worker's zone.
SET TimeZone = 'UTC';
CREATE MACRO hav_km(lat1, lon1, lat2, lon2) AS
2 * 6371.0088 * asin(least(1, sqrt(
pow(sin(radians(lat2 - lat1) / 2), 2)
+ cos(radians(lat1)) * cos(radians(lat2)) * pow(sin(radians(lon2 - lon1) / 2), 2))));
CREATE MACRO bearing_deg(lat1, lon1, lat2, lon2) AS
(degrees(atan2(
sin(radians(lon2 - lon1)) * cos(radians(lat2)),
cos(radians(lat1)) * sin(radians(lat2)) - sin(radians(lat1)) * cos(radians(lat2)) * cos(radians(lon2 - lon1)))) + 360) % 360;
-- Assets: keep the valid ones, report the rest instead of silently dropping them.
CREATE TABLE asset_input AS
SELECT trim(a ->> 'name') AS asset,
TRY_CAST(a ->> 'lat' AS DOUBLE) AS a_lat,
TRY_CAST(a ->> 'lon' AS DOUBLE) AS a_lon,
TRY_CAST(a ->> 'radius_km' AS DOUBLE) AS radius_km,
row_number() OVER () AS input_order
FROM (SELECT unnest(from_json(content, '["JSON"]')) AS a FROM read_text('assets.json'));
CREATE TABLE asset_check AS
SELECT *,
CASE WHEN asset IS NULL OR asset = '' THEN 'missing name'
WHEN a_lat IS NULL OR a_lat NOT BETWEEN -90 AND 90 THEN 'lat must be between -90 and 90'
WHEN a_lon IS NULL OR a_lon NOT BETWEEN -180 AND 180 THEN 'lon must be between -180 and 180'
WHEN radius_km IS NULL OR radius_km <= 0 THEN 'radius_km must be a positive number'
WHEN row_number() OVER (PARTITION BY asset ORDER BY input_order) > 1 THEN 'duplicate name, first entry kept'
END AS problem
FROM asset_input;
CREATE TABLE assets AS SELECT asset, a_lat, a_lon, radius_km FROM asset_check WHERE problem IS NULL;
CREATE TABLE raw_events AS
SELECT unnest(from_json(json_extract(content, '$.events'), '["JSON"]')) AS e
FROM read_text('events.json');
CREATE TABLE events AS
SELECT e ->> 'id' AS event_id,
e ->> 'title' AS title,
json_extract_string(e, '$.categories[0].title') AS category,
e ->> 'link' AS eonet_link,
coalesce((SELECT string_agg(json_extract_string(s, '$.id') || ' ' || json_extract_string(s, '$.url'), ' | ')
FROM unnest(from_json(e -> 'sources', '["JSON"]')) AS t(s)), '') AS sources,
coalesce((SELECT string_agg('<' || json_extract_string(s, '$.url') || '|' || json_extract_string(s, '$.id') || '>', ' ')
FROM unnest(from_json(e -> 'sources', '["JSON"]')) AS t(s)), '') AS source_links,
e -> 'geometry' AS geometry
FROM raw_events
WHERE :include_prescribed OR NOT starts_with(e ->> 'title', 'Prescribed Fire');
-- One row per geometry; rank 1 is the latest fix of the event, rank 2 the one before (storm tracks).
CREATE TABLE geoms AS
SELECT *, dense_rank() OVER (PARTITION BY event_id ORDER BY gdate DESC) AS fix_rank
FROM (
SELECT event_id, i AS geom_idx,
json_extract_string(geometry, '$[' || i || '].type') AS gtype,
CAST(json_extract_string(geometry, '$[' || i || '].date') AS TIMESTAMPTZ) AS gdate,
TRY_CAST(json_extract_string(geometry, '$[' || i || '].magnitudeValue') AS DOUBLE) AS magnitude,
json_extract_string(geometry, '$[' || i || '].magnitudeUnit') AS magnitude_unit,
json_extract(geometry, '$[' || i || '].coordinates') AS coords
FROM events, range(CAST(json_array_length(geometry) AS BIGINT)) AS r(i)
);
-- Point coordinates are [lon, lat]; polygons use the outer ring [[[lon, lat], ...]]. Some GDACS flood polygons
-- arrive as [lat, lon]: when a geometry has a latitude beyond +/-90 that fits as a longitude, it is swapped back.
CREATE TABLE raw_vertices AS
SELECT event_id, geom_idx, gtype, fix_rank, 0 AS vidx,
CAST(json_extract(coords, '$[0]') AS DOUBLE) AS x,
CAST(json_extract(coords, '$[1]') AS DOUBLE) AS y
FROM geoms WHERE gtype = 'Point'
UNION ALL
SELECT event_id, geom_idx, gtype, fix_rank, v AS vidx, ring[v + 1][1] AS x, ring[v + 1][2] AS y
FROM (SELECT *, from_json(json_extract(coords, '$[0]'), '[["DOUBLE"]]') AS ring FROM geoms WHERE gtype = 'Polygon'),
range(CAST(len(ring) AS BIGINT)) AS r(v);
CREATE TABLE vertices AS
SELECT event_id, geom_idx, gtype, fix_rank, vidx, swapped,
CASE WHEN swapped THEN y ELSE x END AS lon,
CASE WHEN swapped THEN x ELSE y END AS lat
FROM (
SELECT *, bool_or(abs(y) > 90) OVER (PARTITION BY event_id, geom_idx)
AND bool_and(abs(x) <= 90) OVER (PARTITION BY event_id, geom_idx) AS swapped
FROM raw_vertices WHERE x IS NOT NULL AND y IS NOT NULL
)
WHERE abs(CASE WHEN swapped THEN x ELSE y END) <= 90 AND abs(CASE WHEN swapped THEN y ELSE x END) <= 180;
-- Ray casting on the edges of the latest polygon: an odd number of crossings means the asset is inside.
CREATE TABLE inside AS
WITH edges AS (
SELECT event_id, geom_idx, lon AS x1, lat AS y1,
lead(lon) OVER w AS x2, lead(lat) OVER w AS y2
FROM vertices WHERE gtype = 'Polygon' AND fix_rank = 1
WINDOW w AS (PARTITION BY event_id, geom_idx ORDER BY vidx)
)
SELECT DISTINCT asset, event_id FROM (
SELECT a.asset, e.event_id, e.geom_idx
FROM assets a JOIN edges e ON e.x2 IS NOT NULL
WHERE (e.y1 > a.a_lat) <> (e.y2 > a.a_lat)
AND a.a_lon < (e.x2 - e.x1) * (a.a_lat - e.y1) / (e.y2 - e.y1) + e.x1
GROUP BY a.asset, e.event_id, e.geom_idx
HAVING count(*) % 2 = 1
);
CREATE TABLE pairs AS
WITH d AS (
SELECT a.asset, a.radius_km, v.event_id, v.fix_rank,
hav_km(a.a_lat, a.a_lon, v.lat, v.lon) AS km,
bearing_deg(a.a_lat, a.a_lon, v.lat, v.lon) AS bearing
FROM assets a CROSS JOIN vertices v
),
agg AS (
SELECT asset, event_id, any_value(radius_km) AS radius_km,
min(km) FILTER (WHERE fix_rank = 1) AS latest_km,
arg_min(bearing, km) FILTER (WHERE fix_rank = 1) AS bearing,
min(km) FILTER (WHERE fix_rank = 2) AS previous_fix_km,
min(km) AS closest_in_window_km
FROM d GROUP BY asset, event_id
),
meta AS (
SELECT event_id, max(gdate) AS last_update,
arg_max(magnitude, gdate) AS magnitude, arg_max(magnitude_unit, gdate) AS magnitude_unit,
arg_max(gtype, gdate) AS geometry_type, count(DISTINCT gdate) AS fixes
FROM geoms GROUP BY event_id
)
SELECT g.asset, g.radius_km, e.event_id, e.title, e.category, m.geometry_type, m.fixes,
round(CASE WHEN i.event_id IS NOT NULL THEN 0 ELSE g.latest_km END, 1) AS distance_km,
CASE WHEN i.event_id IS NOT NULL THEN 'INSIDE'
ELSE ['N','NE','E','SE','S','SW','W','NW'][CAST(floor(((g.bearing + 22.5) % 360) / 45) AS INTEGER) + 1] END AS direction,
CASE WHEN g.previous_fix_km IS NULL THEN 'SINGLE_FIX'
WHEN g.latest_km < g.previous_fix_km - 1 THEN 'APPROACHING'
WHEN g.latest_km > g.previous_fix_km + 1 THEN 'RECEDING'
ELSE 'STATIONARY' END AS trend,
round(g.previous_fix_km, 1) AS previous_fix_km,
round(g.closest_in_window_km, 1) AS closest_in_window_km,
m.magnitude, m.magnitude_unit, m.last_update, e.eonet_link, e.sources, e.source_links
FROM agg g
JOIN events e USING (event_id)
JOIN meta m USING (event_id)
LEFT JOIN inside i ON i.asset = g.asset AND i.event_id = g.event_id;
CREATE TABLE state AS
SELECT s ->> 'pair_key' AS pair_key, s ->> 'event_id' AS event_id, s ->> 'asset' AS asset,
CAST(s ->> 'alerted_km' AS DOUBLE) AS alerted_km, s ->> 'alerted_at' AS alerted_at
FROM (SELECT unnest(from_json(content, '["JSON"]')) AS s FROM read_text('state.json'));
CREATE TABLE in_radius AS
SELECT p.*, s.alerted_km AS previous_alert_km, s.alerted_at AS previous_alert_at,
CASE
WHEN s.pair_key IS NULL THEN 'NEW'
WHEN p.distance_km <= s.alerted_km - :closer_threshold_km THEN 'CLOSER'
ELSE 'ALREADY_ALERTED'
END AS alert_status
FROM pairs p
LEFT JOIN state s ON s.pair_key = p.event_id || '|' || p.asset
WHERE p.distance_km <= p.radius_km;
COPY (
SELECT asset, radius_km, event_id, title, category, distance_km, direction, trend, previous_fix_km,
closest_in_window_km, alert_status, previous_alert_km, previous_alert_at, geometry_type, fixes,
magnitude, magnitude_unit, strftime(last_update, '%Y-%m-%dT%H:%M:%SZ') AS last_update_utc, eonet_link, sources
FROM in_radius ORDER BY asset, distance_km
) TO '{{ outputFiles.proximity_csv }}' (HEADER true, DELIMITER ',');
-- New state: refresh the pairs alerted now, keep the others while their event is still in the feed, drop the rest.
COPY (
SELECT event_id || '|' || asset AS pair_key, event_id, asset, distance_km AS alerted_km, CAST(:run_started AS VARCHAR) AS alerted_at
FROM in_radius WHERE alert_status IN ('NEW', 'CLOSER')
UNION ALL
SELECT s.* FROM state s
WHERE s.event_id IN (SELECT event_id FROM events)
AND s.pair_key NOT IN (SELECT event_id || '|' || asset FROM in_radius WHERE alert_status IN ('NEW', 'CLOSER'))
ORDER BY pair_key
) TO '{{ outputFiles.state_json }}' (FORMAT JSON, ARRAY true);
WITH alert_lines AS (
SELECT asset, radius_km, distance_km / radius_km AS closeness,
'- <' || eonet_link || '|' || title || '> (' || category || '): *' || distance_km || ' km'
|| CASE WHEN direction = 'INSIDE' THEN ', inside the event area' ELSE ' ' || direction END || '*'
|| CASE WHEN trend IN ('APPROACHING', 'RECEDING') THEN ', ' || lower(trend) || ' (was ' || previous_fix_km || ' km at the previous fix)' ELSE '' END
|| CASE WHEN alert_status = 'CLOSER' THEN ', moved closer since the last alert at ' || previous_alert_km || ' km' ELSE '' END
|| CASE WHEN magnitude IS NOT NULL THEN ', ' || magnitude || ' ' || coalesce(magnitude_unit, '') ELSE '' END
|| ', updated ' || strftime(last_update, '%Y-%m-%d %H:%M UTC')
|| CASE WHEN source_links <> '' THEN ', ' || source_links ELSE '' END AS line,
alert_status
FROM in_radius WHERE alert_status IN ('NEW', 'CLOSER')
),
per_asset AS (
SELECT asset, any_value(radius_km) AS radius_km, count(*) AS events,
count(*) FILTER (WHERE alert_status = 'NEW') AS new_events,
count(*) FILTER (WHERE alert_status = 'CLOSER') AS closer_events,
string_agg(line, chr(10) ORDER BY closeness) AS lines
FROM alert_lines GROUP BY asset
),
nearest AS (
SELECT asset, arg_min(title, distance_km) AS title, min(distance_km) AS km FROM pairs GROUP BY asset
)
SELECT
(SELECT count(*) FROM raw_events) AS events_returned,
(SELECT count(*) FROM events) AS events_considered,
(SELECT count(*) FROM geoms) AS geometries,
(SELECT count(*) FROM geoms WHERE gtype = 'Polygon') AS polygon_geometries,
(SELECT count(DISTINCT (event_id, geom_idx)) FROM vertices WHERE swapped) AS swapped_geometries,
(SELECT count(*) FROM assets) AS assets,
(SELECT count(*) FROM asset_check WHERE problem IS NOT NULL) AS invalid_assets,
(SELECT coalesce(string_agg('#' || input_order || ' ' || coalesce(asset, '(no name)') || ': ' || problem, '; ' ORDER BY input_order), '') FROM asset_check WHERE problem IS NOT NULL) AS invalid_asset_list,
(SELECT count(*) FROM state) = 0 AS is_first_run,
(SELECT count(*) FROM in_radius) AS pairs_in_radius,
(SELECT count(*) FROM in_radius WHERE alert_status = 'NEW') AS new_alerts,
(SELECT count(*) FROM in_radius WHERE alert_status = 'CLOSER') AS closer_alerts,
(SELECT count(*) FROM in_radius WHERE alert_status = 'ALREADY_ALERTED') AS suppressed,
(SELECT count(*) FROM state) AS state_pairs_before,
(SELECT count(*) FROM state WHERE event_id NOT IN (SELECT event_id FROM events)) AS state_pairs_pruned,
(SELECT coalesce(string_agg(asset || ': ' || title || ' at ' || km || ' km', '; ' ORDER BY km), 'none') FROM nearest) AS nearest_by_asset,
(SELECT coalesce(string_agg(asset || ' (' || new_events || ' new, ' || closer_events || ' closer, radius ' || radius_km || ' km):' || chr(10) || lines, chr(10) ORDER BY asset), '') FROM per_asset) AS alert_text,
(SELECT coalesce(CAST(json_group_array(json_object('asset', asset, 'radius_km', radius_km, 'events', events, 'new_events', new_events, 'closer_events', closer_events,
'message', left('*' || asset || '*: ' || new_events || ' new, ' || closer_events || ' moved closer (radius ' || radius_km || ' km)' || chr(10) || lines, 2900))) AS VARCHAR), '[]')
FROM per_asset) AS alert_assets;
- id: save_state
type: io.kestra.plugin.core.kv.Set
description: Stores the alerted pairs with their distance. Pairs whose event has
closed or left the `days` window are dropped, so the state stays small.
key: "{{ inputs.state_key }}"
kvType: JSON
value: "{{ read(outputs.proximity.outputFiles.state_json) }}"
- id: warn_invalid_assets
type: io.kestra.plugin.core.log.Log
runIf: "{{ outputs.proximity.outputs[0].row.invalid_assets > 0 }}"
level: WARN
message: "Skipped {{ outputs.proximity.outputs[0].row.invalid_assets }} invalid
asset(s): {{ outputs.proximity.outputs[0].row.invalid_asset_list }}"
- id: alert_by_asset
type: io.kestra.plugin.core.flow.If
description: Posts only when at least one pair is new or has moved closer by the
threshold.
condition: "{{ (outputs.proximity.outputs[0].row.new_alerts +
outputs.proximity.outputs[0].row.closer_alerts) > 0 }}"
then:
- id: log_alerts
type: io.kestra.plugin.core.log.Log
level: WARN
message: "{{ outputs.proximity.outputs[0].row.alert_text }}"
- id: each_asset
type: io.kestra.plugin.core.flow.Loop
description: One Slack message per affected asset, so each site owner sees only
their events.
values: "{{ outputs.proximity.outputs[0].row.alert_assets }}"
concurrencyLimit: 1
tasks:
- id: slack_alert
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: allowFailure keeps the check running when `SLACK_WEBHOOK_URL` is
not configured or Slack is down; the same text is in the
`log_alerts` WARN line and the CSV.
allowFailure: true
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"text": {{ (':warning: ' ~ fromJson(item.value).events ~ ' natural event(s) within ' ~ fromJson(item.value).radius_km ~ ' km of ' ~ fromJson(item.value).asset) | toJson }},
"blocks": [
{"type": "section", "text": {"type": "mrkdwn", "text": {{ fromJson(item.value).message | toJson }}}},
{"type": "context", "elements": [{"type": "mrkdwn", "text": {{ ('NASA EONET via Kestra ' ~ flow.namespace ~ '.' ~ flow.id ~ ', execution ' ~ execution.id) | toJson }}}]}
]
}
else:
- id: nothing_new
type: io.kestra.plugin.core.log.Log
message: "No new or closer events: {{
outputs.proximity.outputs[0].row.pairs_in_radius }} pair(s) in radius,
all already alerted."
- id: summary
type: io.kestra.plugin.core.log.Log
message: |
EONET returned {{ outputs.proximity.outputs[0].row.events_returned }} {{ inputs.event_status }} events ({{ outputs.proximity.outputs[0].row.events_considered }} after the prescribed-fire filter, {{ outputs.proximity.outputs[0].row.geometries }} geometries, {{ outputs.proximity.outputs[0].row.polygon_geometries }} polygons, {{ outputs.proximity.outputs[0].row.swapped_geometries }} with lat/lon swapped back) for {{ inputs.categories | join(', ') }} in the last {{ inputs.days }} days.
{{ outputs.proximity.outputs[0].row.assets }} valid assets{{ outputs.proximity.outputs[0].row.is_first_run ? ' (first run: every in-radius pair alerts once)' : '' }}: {{ outputs.proximity.outputs[0].row.pairs_in_radius }} asset/event pairs in radius, {{ outputs.proximity.outputs[0].row.new_alerts }} new, {{ outputs.proximity.outputs[0].row.closer_alerts }} moved closer, {{ outputs.proximity.outputs[0].row.suppressed }} suppressed as already alerted.
State: {{ outputs.proximity.outputs[0].row.state_pairs_before }} pairs before this run, {{ outputs.proximity.outputs[0].row.state_pairs_pruned }} pruned (event closed or out of window).
Nearest event per asset: {{ outputs.proximity.outputs[0].row.nearest_by_asset }}
Proximity CSV: {{ outputs.proximity.outputFiles.proximity_csv }}
outputs:
- id: proximity_csv
type: FILE
value: "{{ outputs.proximity.outputFiles.proximity_csv }}"
- id: run_summary
type: JSON
value: "{{ outputs.proximity.outputs[0].row }}"