id: tile38-geofence-drift-and-stale-object-guard
namespace: company.team
concurrency:
limit: 1
behavior: CANCEL
description: |
Tile38 geofences define geographic boundaries for roaming objects such as delivery vehicles,
field sensors, or IoT assets. When a tracked object drifts outside its expected boundary or
stops reporting, the responsible team needs both an alert and a clear remediation path:
confirm the object is genuinely out of bounds, then either issue a recovery command or mark
it as evicted so downstream systems stop waiting for it. This flow polls a Tile38 instance
on a schedule, detects drifted objects and stale objects (evaluating each object's `updated`
timestamp field), alerts the team on Slack, and pauses for operator approval before writing a
`FSET ... drifted 1` tag or dropping the object from the collection with `DEL`.
## How it works
1. `scheduled_poll` (`io.kestra.plugin.core.trigger.Schedule`) fires every five minutes.
`concurrency.limit: 1` with `behavior: CANCEL` ensures that if a run pauses for human review,
subsequent scheduled runs cancel immediately instead of creating execution backlog.
2. `load_previous_roster` (`io.kestra.plugin.core.kv.Get`) reads the roster written by the
previous successful run. On the first run the key is absent and the task returns null.
3. `query_within_geofence` (`io.kestra.plugin.core.http.Request`) sends a `WITHIN` command
to the Tile38 HTTP API using a POST body and returns every object ID currently inside the boundary.
4. `query_nearby_geofence` (`io.kestra.plugin.core.http.Request`) sends a `NEARBY` command
to retrieve the full fleet roster including coordinates and custom `updated` timestamp fields.
5. `evaluate_drift_and_staleness` (`io.kestra.plugin.transform.jsonata.TransformValue`)
cross-references the two results: objects present in the NEARBY roster but absent from
the WITHIN result have drifted out; objects whose `($millis() / 1000 - fields.updated)` exceeds
`inputs.stale_after_seconds` are flagged stale.
6. `check_alerts` (`io.kestra.plugin.core.flow.If`) evaluates `outputs.evaluate_drift_and_staleness.value.has_alerts`
and skips everything below when the fleet is healthy, keeping the Slack channel quiet on normal runs.
7. `send_slack_alert` (`io.kestra.plugin.slack.notifications.SlackIncomingWebhook`) posts the
drifted and stale object lists with an execution link for one-click operator triage.
8. `await_operator_decision` (`io.kestra.plugin.core.flow.Pause`) halts execution with `pauseDuration: PT4H`
and `behavior: CANCEL`, waiting for an operator to resume from the Kestra UI, selecting `evict`, `tag`, or `skip`.
9. `remediate_drifted_objects` (`io.kestra.plugin.core.flow.Switch`) routes the operator's chosen
action: `evict` loops over affected IDs sending `DEL` commands, `tag` loops sending `FSET ... drifted 1`,
and `skip` logs the acknowledgment without modifying Tile38 state.
10. `save_roster` (`io.kestra.plugin.core.kv.Set`) persists the post-remediation within-roster
for drift diffing on the next run.
11. `alert_flow_failure` (`io.kestra.plugin.slack.notifications.SlackIncomingWebhook`) in the top-level
`errors:` block alerts on-call if Tile38 is unreachable or a network failure occurs.
## What you get
- A Slack alert within one poll cycle when any tracked object leaves the geofence or stops
reporting, with the execution link for one-click review.
- A human-gated remediation step: operators choose evict, tag, or skip before Tile38 state
changes. Nothing is deleted without approval.
- Concurrency safety: `concurrency.limit: 1` prevents overlapping runs from stacking while
awaiting operator review.
- Persistent roster in Kestra KV so each run diffs against real state, not just the boundary.
- A clean execution history: every drift event, every operator decision, and every Tile38
command is a named task in the execution timeline.
## Who it's for
- Platform and operations teams running Tile38 for fleet tracking, logistics, or IoT asset
management who need an auditable record of every geofence breach response.
- On-call engineers who need a structured remediation path, not just a raw alert.
## Why orchestrate this with Kestra
A cron script can query Tile38 and post to Slack, but it cannot pause mid-execution and
wait for a human decision before modifying data. Kestra's `Pause` task makes that pattern
declarative and auditable: the approval step lives in the same YAML as the query and the
remediation command, the operator acts from the Kestra UI with a single click, and the full
decision trail is in the execution log rather than a Slack thread.
## Prerequisites
- A running Tile38 instance with the HTTP API enabled (default port 9851, no configuration
needed beyond starting the server).
- A fleet collection populated with objects via `SET fleet <id> FIELD updated <epoch> POINT <lat> <lon>`.
- A Slack incoming webhook URL.
- Kestra workers able to reach the Tile38 HTTP API endpoint.
### Secrets
- `TILE38_HTTP_URL`: Base URL of the Tile38 HTTP API, e.g. `http://tile38-host:9851`. No
trailing slash.
- `SLACK_WEBHOOK_URL`: Slack incoming webhook URL for the alert channel.
## Quick start
1. Add `TILE38_HTTP_URL` and `SLACK_WEBHOOK_URL` as Kestra secrets.
2. Load objects with an epoch timestamp: `SET fleet truck-1 FIELD updated 1700000000 POINT 33.45 -112.07`.
3. Set `geofence_geojson` to a GeoJSON Polygon covering the expected operating area.
4. Run once manually to seed the KV roster (the Pause step is skipped on clean runs).
5. Enable the schedule trigger.
6. When an alert fires, open the execution in the Kestra UI, choose the remediation action
in the Resume form, and click Resume.
## How to extend
- Add a `io.kestra.plugin.core.flow.Loop` over multiple fleet collections, one Parallel
branch per collection, so a single scheduled run covers the whole deployment.
- Replace the Slack task with `io.kestra.plugin.core.http.Request` to PagerDuty for
high-severity drift on mission-critical assets.
- Write each evicted object ID and timestamp to a DuckDB table for compliance reporting.
## Links
- [Tile38 HTTP API reference](https://tile38.com/commands/)
- [Tile38 WITHIN](https://tile38.com/commands/within/) / [NEARBY](https://tile38.com/commands/nearby/) / [DEL](https://tile38.com/commands/del/) / [FSET](https://tile38.com/commands/fset/)
- [Kestra HTTP Request plugin](https://kestra.io/plugins/plugin-http/tasks/io.kestra.plugin.core.http.request)
- [Kestra Pause task](https://kestra.io/plugins/plugin-core/tasks/flow/io.kestra.plugin.core.flow.pause)
- [Kestra Switch task](https://kestra.io/plugins/plugin-core/tasks/flow/io.kestra.plugin.core.flow.switch)
- [Kestra KV Store](https://kestra.io/plugins/plugin-core/tasks/kv/io.kestra.plugin.core.kv.set)
inputs:
- id: geofence_geojson
type: STRING
description: GeoJSON Polygon passed to the Tile38 WITHIN OBJECT command defining
the expected operating boundary.
defaults: '{"type":"Polygon","coordinates":[[[-112.10,33.43],[-111.95,33.43],[-111.95,33.53],[-112.10,33.53],[-112.10,33.43]]]}'
- id: center_lat
type: FLOAT
description: Latitude of the center point for the NEARBY query.
defaults: 33.48
- id: center_lon
type: FLOAT
description: Longitude of the center point for the NEARBY query.
defaults: -112.02
- id: radius_meters
type: INT
description: Search radius in meters for the NEARBY query. Should cover the full
expected fleet range.
defaults: 20000
- id: stale_after_seconds
type: INT
description: Maximum allowed seconds since last update (evaluated against object
`updated` field) before flagging stale.
defaults: 300
- id: fleet_collection
type: STRING
description: Name of the Tile38 collection holding the tracked objects.
defaults: fleet
triggers:
- id: scheduled_poll
type: io.kestra.plugin.core.trigger.Schedule
description: Poll every five minutes. Disabled until secrets are configured.
cron: "*/5 * * * *"
disabled: true
tasks:
- id: load_previous_roster
type: io.kestra.plugin.core.kv.Get
key: "tile38_geofence_roster_{{ inputs.fleet_collection }}"
errorOnMissing: false
- id: query_within_geofence
type: io.kestra.plugin.core.http.Request
description: Send WITHIN command via Tile38 HTTP POST body to find objects
currently inside boundary.
uri: "{{ secret('TILE38_HTTP_URL') }}"
method: POST
contentType: text/plain
body: "WITHIN {{ inputs.fleet_collection }} OBJECT {{ inputs.geofence_geojson }}"
- id: query_nearby_geofence
type: io.kestra.plugin.core.http.Request
description: Send NEARBY command to retrieve full fleet roster with position and
custom metadata fields.
uri: "{{ secret('TILE38_HTTP_URL') }}"
method: POST
contentType: text/plain
body: "NEARBY {{ inputs.fleet_collection }} DISTANCE POINT {{ inputs.center_lat
}} {{ inputs.center_lon }} {{ inputs.radius_meters }}"
- id: evaluate_drift_and_staleness
type: io.kestra.plugin.transform.jsonata.TransformValue
description: Cross-reference WITHIN and NEARBY results to produce drifted and
stale object lists.
from: |
{
"within": {{ outputs.query_within_geofence.body ?? '{"ok":false,"objects":[]}' }},
"nearby": {{ outputs.query_nearby_geofence.body ?? '{"ok":false,"objects":[]}' }},
"stale_after": {{ inputs.stale_after_seconds }}
}
expression: |
(
$nowSec := $millis() / 1000;
$withinIds := [within.objects.(id)];
$nearbyObjects := nearby.objects;
$drifted := [$nearbyObjects[$not(id in $withinIds)].(id)];
$stale := [$nearbyObjects[fields.updated and ($nowSec - fields.updated) > $$.stale_after].(id)];
$affected := [$distinct($append($drifted, $stale))];
{
"drifted_ids": $drifted,
"stale_ids": $stale,
"affected_ids": $affected,
"drifted_count": $count($drifted),
"stale_count": $count($stale),
"has_alerts": $count($affected) > 0
}
)
- id: check_alerts
type: io.kestra.plugin.core.flow.If
description: Skip all further steps on a healthy run.
condition: "{{ outputs.evaluate_drift_and_staleness.value.has_alerts }}"
then:
- id: send_slack_alert
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: >-
{{ {"text": ":rotating_light: *Tile38 Geofence Alert* — `" ~
inputs.fleet_collection ~ "`\n• *Drifted* (" ~
outputs.evaluate_drift_and_staleness.value.drifted_count ~ "): " ~
(outputs.evaluate_drift_and_staleness.value.drifted_ids | join(', '))
~ "\n• *Stale >" ~ inputs.stale_after_seconds ~ "s* (" ~
outputs.evaluate_drift_and_staleness.value.stale_count ~ "): " ~
(outputs.evaluate_drift_and_staleness.value.stale_ids | join(', ')) ~
"\nReview and choose remediation action: " ~ (kestra.url ??
'http://localhost:8080') ~ "/ui/executions/" ~ execution.id} | toJson
}}
- id: await_operator_decision
type: io.kestra.plugin.core.flow.Pause
description: >
Halt and wait for an operator to resume from the Kestra UI. On the
Resume form, set remediation_action to evict (remove objects from
Tile38), tag (write drifted=1 via FSET without removing), or skip
(acknowledge and close without changing state).
pauseDuration: PT4H
behavior: CANCEL
onResume:
- id: remediation_action
type: SELECT
displayName: Remediation action
values:
- evict
- tag
- skip
defaults: skip
- id: remediate_drifted_objects
type: io.kestra.plugin.core.flow.Switch
description: Execute the remediation action selected by the operator on resume.
value: "{{ outputs.await_operator_decision.onResume.remediation_action ?? 'skip'
}}"
cases:
evict:
- id: evict_objects
type: io.kestra.plugin.core.flow.Loop
description: Send DEL command for each affected object to remove it from the
collection.
values: "{{ outputs.evaluate_drift_and_staleness.value.affected_ids | toJson }}"
tasks:
- id: del_object
type: io.kestra.plugin.core.http.Request
uri: "{{ secret('TILE38_HTTP_URL') }}"
method: POST
contentType: text/plain
body: "DEL {{ inputs.fleet_collection }} {{ item.value }}"
tag:
- id: tag_objects
type: io.kestra.plugin.core.flow.Loop
description: Send FSET command for each affected object to flag drifted=1
without removing.
values: "{{ outputs.evaluate_drift_and_staleness.value.affected_ids | toJson }}"
tasks:
- id: fset_object
type: io.kestra.plugin.core.http.Request
uri: "{{ secret('TILE38_HTTP_URL') }}"
method: POST
contentType: text/plain
body: "FSET {{ inputs.fleet_collection }} {{ item.value }} drifted 1"
defaults:
- id: log_skipped
type: io.kestra.plugin.core.log.Log
message: "Drift alerts acknowledged by operator without modifying Tile38 state."
- id: save_roster
type: io.kestra.plugin.core.kv.Set
description: Persist the post-remediation within-roster for diffing on the next run.
key: "tile38_geofence_roster_{{ inputs.fleet_collection }}"
value: "{{ outputs.query_within_geofence.body }}"
ttl: PT1H
errors:
- id: alert_flow_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Send incident alert if database connection, HTTP request, or parsing fails.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: >-
{{ {"text": ":x: *Tile38 Geofence Guard Execution Failed*\n• *Collection:*
`" ~ inputs.fleet_collection ~ "`\n• *Execution ID:* `" ~ execution.id ~
"`\n• *Logs:* " ~ (kestra.url ?? 'http://localhost:8080') ~
"/ui/executions/" ~ execution.id} | toJson }}