#!/usr/bin/env bash
# Copyright 2026 ddbsh reimplementation contributors.
# SPDX-License-Identifier: Apache-2.0
#
# ddbsh-wait -- bounded control-plane poll helper for the CTest golden suite.
#
# Several test suites mutate a table's control plane (billing mode / on-demand
# throughput, GSI throughput, PITR) and then assert on a subsequent `describe`.
# DynamoDB applies these changes asynchronously, so the original suite inserted
# fixed `sleep`s between the mutation and the assertion. Fixed sleeps are racy
# against real DynamoDB (the settle time is not bounded by a constant), which
# produced the non-deterministic Bucket A `icd-create-table` / `ipt-pitr`
# failures. This helper replaces those sleeps with a deterministic bounded poll:
# it waits until the asserted control-plane state is actually reached, then
# exits 0; on timeout it exits non-zero so CTest marks the step (and thus the
# suite) failed instead of silently proceeding to a flaky assertion.
#
# It uses the AWS CLI against real DynamoDB via the same standard ~/.aws
# credential/region resolution as devtools/run-tests (no endpoint override).
#
# Usage:
#   ddbsh-wait table-settled <table> [region]
#       Wait until TableStatus == ACTIVE and every GSI IndexStatus == ACTIVE
#       (i.e. no table-level or index-level update is still in progress). The
#       optional third argument polls a specific region (default: the resolved
#       AWS_REGION); the global-tables family uses it to settle the primary
#       region (us-east-2) independent of the suite's default region.
#
#   ddbsh-wait table-settled-or-gone <table>
#       Wait until the table is gone, or settled as for table-settled. Gone
#       means DescribeTable answered ResourceNotFoundException; any other
#       DescribeTable error (credentials, throttling, network) counts as
#       neither, so the wait times out instead of passing on an error. The
#       test-cleanup-last family uses it before it drops a table whose GSI may
#       still be building: DynamoDB refuses DeleteTable while an index is
#       being created (DEV-P11-17).
#
#   ddbsh-wait pitr <table> <ENABLED|DISABLED>
#       Wait until the table's PointInTimeRecoveryStatus equals the target.
#
#   ddbsh-wait warm-throughput-active <table>
#       Wait until TableStatus == ACTIVE and the table's WarmThroughput.Status
#       == ACTIVE, i.e. an ALTER ... SET WARM THROUGHPUT has finished.
#       table-settled does not cover this: during the update the table can
#       stay ACTIVE while its warm throughput is UPDATING (D-P10-19).
#
#   ddbsh-wait replica-active <table> <primary-region> <replica-region>
#       Global-tables settling: poll DescribeTable in <primary-region> until the
#       replica in <replica-region> reports ReplicaStatus == ACTIVE (i.e. the
#       ADD REPLICA has finished provisioning). Replica creation is eventually
#       consistent (minutes), so this replaces a fixed sleep with a bounded poll.
#
#   ddbsh-wait replica-gone <table> <primary-region> <replica-region>
#       Global-tables teardown: poll DescribeTable in <primary-region> until the
#       replica in <replica-region> is no longer in the Replicas list. A DROP
#       REPLICA is asynchronous -- the table returns to ACTIVE while the replica
#       is still DELETING -- so the table must be awaited back to single-region
#       before DROP TABLE, or DynamoDB rejects the delete with the global-tables
#       source-region guard.
#
#   ddbsh-wait scan-count <table> <region> <count>
#       Global-tables settling: poll a COUNT scan of <table> in <region> until it
#       returns exactly <count> items. Used to wait out cross-region replication
#       lag before reading a replica (it also implies the replica table is ACTIVE
#       and readable, since a scan against a not-yet-ready replica yields 0).
#
#   ddbsh-wait retry-cmd -- <command> [args...]
#       Run <command>, retrying while it exits non-zero, until it succeeds or
#       the ceiling is reached. Used for control-plane operations that DynamoDB
#       answers with a transient "retry later" error (e.g. enabling PITR during
#       the post-create window when continuous backups are still being enabled
#       -- a condition that is NOT observable via any describe call). The
#       command under test still runs (and must eventually succeed), so its
#       coverage is preserved; only the transient race is absorbed.
#
# Tunables (env): DDBSH_WAIT_CEILING (seconds, default 900 = 15m),
#                 DDBSH_WAIT_CADENCE (seconds, default 5).
#
# TODO(portability): POSIX bash + AWS CLI; a Windows test-runner equivalent is
# Step-2 infra (the golden suite is not run on Windows yet).

set -uo pipefail

CEILING="${DDBSH_WAIT_CEILING:-900}"
CADENCE="${DDBSH_WAIT_CADENCE:-5}"
REGION="${AWS_REGION:-${AWS_DEFAULT_REGION:-us-east-1}}"

die() {
    echo "ddbsh-wait: $*" >&2
    exit 1
}

MODE="${1:-}"
[ -n "$MODE" ] || die "usage: ddbsh-wait <table-settled|table-settled-or-gone|pitr|warm-throughput-active|replica-active|replica-gone|scan-count|retry-cmd> ..."

# retry-cmd is handled separately: it takes a command, not a table, and does
# not itself query the control plane.
if [ "$MODE" = "retry-cmd" ]; then
    shift
    [ "${1:-}" = "--" ] && shift
    [ $# -gt 0 ] || die "usage: ddbsh-wait retry-cmd -- <command> [args...]"
    echo "ddbsh-wait: retrying [$*] until success (ceiling ${CEILING}s, cadence ${CADENCE}s)"
    start=$SECONDS
    while :; do
        if "$@"; then
            echo "ddbsh-wait: command succeeded after $((SECONDS - start))s"
            exit 0
        fi
        if [ $((SECONDS - start)) -ge "$CEILING" ]; then
            die "timed out after ${CEILING}s; command [$*] never succeeded"
        fi
        sleep "$CADENCE"
    done
fi

command -v aws >/dev/null 2>&1 || die "AWS CLI not found on PATH (required to poll control-plane state)"

TABLE="${2:-}"
[ -n "$TABLE" ] || die "usage: ddbsh-wait $MODE <table> [args]"

describe_table_query() {
    # $1 = JMESPath query; prints text result (empty on failure).
    aws dynamodb describe-table --table-name "$TABLE" --region "$REGION" \
        --query "$1" --output text 2>/dev/null
}

table_settled() {
    local status gsi_statuses
    status="$(describe_table_query 'Table.TableStatus')"
    [ "$status" = "ACTIVE" ] || return 1

    # Every GSI (if any) must be ACTIVE. With `--output text`, a table without
    # GSIs yields "None" (JMESPath null) or an empty string; either means "no
    # GSIs to wait on". Otherwise the statuses are whitespace-separated.
    gsi_statuses="$(describe_table_query 'Table.GlobalSecondaryIndexes[].IndexStatus')"
    if [ -z "$gsi_statuses" ] || [ "$gsi_statuses" = "None" ]; then
        return 0
    fi
    # settled iff no status is anything other than ACTIVE.
    ! printf '%s\n' $gsi_statuses | grep -qvE '^ACTIVE$'
}

table_gone() {
    # Gone only when DynamoDB itself answers ResourceNotFoundException; the AWS
    # CLI prints the error code in parentheses. A describe that succeeds means
    # the table exists, and any other error does not show that it is gone.
    local err
    if err="$(aws dynamodb describe-table --table-name "$TABLE" --region "$REGION" \
        --query 'Table.TableStatus' --output text 2>&1 >/dev/null)"; then
        return 1
    fi
    [[ "$err" == *"(ResourceNotFoundException)"* ]]
}

table_settled_or_gone() {
    if table_gone; then
        echo "ddbsh-wait: table $TABLE does not exist"
        return 0
    fi
    table_settled
}

pitr_matches() {
    local want="$1" status
    status="$(aws dynamodb describe-continuous-backups --table-name "$TABLE" --region "$REGION" \
        --query 'ContinuousBackupsDescription.PointInTimeRecoveryDescription.PointInTimeRecoveryStatus' \
        --output text 2>/dev/null)"
    [ "$status" = "$want" ]
}

warm_throughput_active() {
    # Both statuses in one DescribeTable call ("ACTIVE<TAB>ACTIVE" when done). A
    # table without warm throughput prints "None" for it, so this never
    # succeeds on such a table and times out instead of passing by accident.
    local statuses
    statuses="$(describe_table_query '[Table.TableStatus, Table.WarmThroughput.Status]')"
    [ "$statuses" = "$(printf 'ACTIVE\tACTIVE')" ]
}

replica_active() {
    # $1 = replica region name. Poll DescribeTable in $REGION (the primary) and
    # read the ReplicaStatus for the requested replica region. A table with no
    # replica yet (or still CREATING) yields an empty/non-ACTIVE result.
    local want_region="$1" status
    status="$(describe_table_query "Table.Replicas[?RegionName=='${want_region}'].ReplicaStatus | [0]")"
    [ "$status" = "ACTIVE" ]
}

replica_gone() {
    # $1 = replica region name. Poll DescribeTable in $REGION (the primary) until
    # the requested replica region is no longer present in the Replicas list
    # (a DROP REPLICA is asynchronous: the table returns to ACTIVE while the
    # replica is still DELETING, so table-settled is too weak -- the table must
    # be fully single-region before DROP TABLE, or DynamoDB rejects the delete
    # with the global-tables source-region guard).
    local want_region="$1" status
    status="$(describe_table_query "Table.Replicas[?RegionName=='${want_region}'].ReplicaStatus | [0]")"
    [ -z "$status" ] || [ "$status" = "None" ]
}

scan_count_matches() {
    # $1 = expected item count. A COUNT scan against a not-yet-ready replica
    # (table missing/CREATING, or replication still in flight) returns 0 or
    # fails, so this waits out both replica activation and replication lag.
    local want="$1" count
    count="$(aws dynamodb scan --table-name "$TABLE" --region "$REGION" \
        --select COUNT --query 'Count' --output text 2>/dev/null)"
    [ "$count" = "$want" ]
}

case "$MODE" in
    table-settled)
        # Optional third arg overrides the polled region (global tables).
        [ -n "${3:-}" ] && REGION="$3"
        check() { table_settled; }
        desc="table $TABLE to settle (TableStatus + all GSIs ACTIVE) in $REGION"
        ;;
    table-settled-or-gone)
        check() { table_settled_or_gone; }
        desc="table $TABLE to be gone, or to settle (TableStatus + all GSIs ACTIVE), in $REGION"
        ;;
    pitr)
        WANT="${3:-}"
        [ -n "$WANT" ] || die "usage: ddbsh-wait pitr <table> <ENABLED|DISABLED>"
        check() { pitr_matches "$WANT"; }
        desc="table $TABLE PITR to reach $WANT"
        ;;
    warm-throughput-active)
        check() { warm_throughput_active; }
        desc="table $TABLE and its warm throughput to be ACTIVE in $REGION"
        ;;
    replica-active)
        PRIMARY="${3:-}"
        REPLICA="${4:-}"
        { [ -n "$PRIMARY" ] && [ -n "$REPLICA" ]; } || \
            die "usage: ddbsh-wait replica-active <table> <primary-region> <replica-region>"
        REGION="$PRIMARY"
        check() { replica_active "$REPLICA"; }
        desc="replica $REPLICA of $TABLE to become ACTIVE (polling $PRIMARY)"
        ;;
    replica-gone)
        PRIMARY="${3:-}"
        REPLICA="${4:-}"
        { [ -n "$PRIMARY" ] && [ -n "$REPLICA" ]; } || \
            die "usage: ddbsh-wait replica-gone <table> <primary-region> <replica-region>"
        REGION="$PRIMARY"
        check() { replica_gone "$REPLICA"; }
        desc="replica $REPLICA of $TABLE to be fully removed (polling $PRIMARY)"
        ;;
    scan-count)
        REGION="${3:-}"
        WANT_COUNT="${4:-}"
        { [ -n "$REGION" ] && [ -n "$WANT_COUNT" ]; } || \
            die "usage: ddbsh-wait scan-count <table> <region> <count>"
        check() { scan_count_matches "$WANT_COUNT"; }
        desc="table $TABLE in $REGION to hold $WANT_COUNT items"
        ;;
    *)
        die "unknown mode: $MODE (expected table-settled|table-settled-or-gone|pitr|warm-throughput-active|replica-active|replica-gone|scan-count|retry-cmd)"
        ;;
esac

echo "ddbsh-wait: waiting for $desc (ceiling ${CEILING}s, cadence ${CADENCE}s)"
start=$SECONDS
while :; do
    if check; then
        echo "ddbsh-wait: reached after $((SECONDS - start))s"
        exit 0
    fi
    if [ $((SECONDS - start)) -ge "$CEILING" ]; then
        die "timed out after ${CEILING}s waiting for $desc"
    fi
    sleep "$CADENCE"
done
