# Isolates the vector-delivery WORKER container's own fields from the ECS stopped-task event's `containers`
# array and exposes them as scalars @worker.exit_code / @worker.reason / @worker.name. This is what lets the
# "worker task killed unexpectedly" monitor (monitors.tf) fire on a real worker crash — including a worker
# exit 137 — without matching the datadog-agent/fluentbit sidecars, which are SIGKILLed to exit 137 on every
# normal teardown. A plain Datadog query can't do this: it matches `@containers.*` element-wise and cannot
# tie an exit code to a specific array element, so a benign sidecar 137 and a real worker OOM/SIGKILL 137 are
# indistinguishable. The array processor selects the worker element (its container `name` is the service,
# vector-delivery-*; the sidecars are named datadog-agent / fluentbit-datadog) and copies the field out.
#
# @worker.name is extracted purely as a presence marker: it is set iff the pipeline matched the worker
# element, so the monitor gates its array-only fallback on `-@worker.name:*` and the canary monitor
# (monitors.tf) alerts when @worker.name stops appearing (pipeline broken).
#
# POST-APPLY VALIDATION (required): confirm a real stopped-task event has @worker.* populated (Log Explorer:
# `<local.vector_stopped_task_scope> @worker.name:*`). If null, the select filter didn't match the worker
# element — until then the monitor's @containers.* fallback keeps it working (degrades to array-only, never
# blind) and the canary monitor fires.
resource "datadog_logs_custom_pipeline" "vector_delivery_worker_exit" {
  name       = "[PROD] VECTOR delivery — extract worker container exit"
  is_enabled = true

  # Must cover (at least) everything the monitor matches — shared with monitors.tf so they can't drift.
  filter {
    query = local.vector_stopped_task_scope
  }

  processor {
    array_processor {
      name       = "worker exitCode -> @worker.exit_code"
      is_enabled = true
      operation {
        select {
          source           = "containers"
          filter           = "name:vector-delivery-*"
          value_to_extract = "exitCode"
          target           = "worker.exit_code"
        }
      }
    }
  }

  processor {
    array_processor {
      name       = "worker OOM reason -> @worker.reason"
      is_enabled = true
      operation {
        select {
          source           = "containers"
          filter           = "name:vector-delivery-*"
          value_to_extract = "reason"
          target           = "worker.reason"
        }
      }
    }
  }

  processor {
    array_processor {
      name       = "worker name -> @worker.name (fallback gate + pipeline-health canary)"
      is_enabled = true
      operation {
        select {
          source           = "containers"
          filter           = "name:vector-delivery-*"
          value_to_extract = "name"
          target           = "worker.name"
        }
      }
    }
  }
}
