apiVersion: argoproj.io/v1alpha1
kind: WorkflowTemplate
metadata:
  name: rest-poll-until
  labels:
    dagweave.io/catalog-item: rest-poll-until
  annotations:
    # The catalog semver this manifest was authored at. The dagweave app records
    # (catalog-item-id, semver) -> content-hash -> base-vN when it mints the tenant
    # cluster name via ResolveOrMint. Keep in sync with metadata.yaml `version`.
    dagweave.io/catalog-version: "1.0.2"
    dagweave.io/catalog-category: "HTTP"
spec:
  entrypoint: poll
  templates:
    - name: poll
      inputs:
        parameters:
          # Absolute URL to poll (GET). Its JSON response is evaluated each attempt.
          - name: url
          # A jq boolean filter over the JSON response. When it evaluates truthy the
          # poll succeeds, e.g. '.status == "complete"'.
          - name: jq-condition
          # Seconds to wait between attempts.
          - name: interval-seconds
            default: "10"
          # Maximum number of attempts before failing.
          - name: max-attempts
            default: "30"
      container:
        # Pinned by digest per the catalog convention: an image rebuild can never
        # silently change the behaviour of an already-released item version.
        # badouralix/curl-jq:ubuntu — provides sh, curl and jq.
        image: badouralix/curl-jq@sha256:38362e9b8ef4bd09a88c0db07941e61e0bf0f7240e9f36a3ff2c31ad75546be2
        command: [sh, -c]
        # Values are passed as env vars (below), never interpolated into the shell.
        # JQ_CONDITION is used as a jq program (jq -e), not spliced into the shell, so
        # the response is polled until the condition is truthy, the attempts run out,
        # or a request fails transiently (retried on the next tick).
        args:
          - |
            set -eu
            i=0
            while [ "$i" -lt "${MAX_ATTEMPTS}" ]; do
              i=$((i + 1))
              if RESP=$(curl -sSf "${URL}"); then
                if printf '%s' "${RESP}" | jq -e "${JQ_CONDITION}" >/dev/null 2>&1; then
                  echo "condition met on attempt ${i}"
                  printf '%s\n' "${RESP}"
                  exit 0
                fi
                echo "attempt ${i}/${MAX_ATTEMPTS}: condition not yet met"
              else
                echo "attempt ${i}/${MAX_ATTEMPTS}: request failed, will retry"
              fi
              sleep "${INTERVAL}"
            done
            echo "timed out after ${MAX_ATTEMPTS} attempts" >&2
            exit 1
        env:
          - name: URL
            value: "{{inputs.parameters.url}}"
          - name: JQ_CONDITION
            value: "{{inputs.parameters.jq-condition}}"
          - name: INTERVAL
            value: "{{inputs.parameters.interval-seconds}}"
          - name: MAX_ATTEMPTS
            value: "{{inputs.parameters.max-attempts}}"
