⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(scripts): surface Sentry API errors in provision-sentry-alerts
justin3f55456b1837
diff --git a/scripts/provision-sentry-alerts.sh b/scripts/provision-sentry-alerts.shindex 115177cee..6846a690f 100755--- a/scripts/provision-sentry-alerts.sh+++ b/scripts/provision-sentry-alerts.sh@@ -6,13 +6,22 @@# SENTRY_API_TOKEN=sntrys_... ./scripts/provision-sentry-alerts.sh# SENTRY_API_TOKEN=... ./scripts/provision-sentry-alerts.sh --dry-run#-# The token needs one of: alerts:write, org:admin, org:write, or org:manager scopes.+# The token needs scope: org:write (or alerts:write).# Generate at: https://sentry.io/settings/account/api/auth-tokens/+#+# Bugs fixed vs v1:+# - local + $(...) was swallowing curl failures (subshell + set -e don't mix)+# - hidden error response body+# - false success on empty response+# - jq "Cannot iterate over null" when detector_slugs is missing+# - missing config.frequency in workflows+# - cron alert workflows tried to send triggers alongside detectorIdsset -euo pipefailORG="kaneo"REGION="de"-API_BASE="https://${REGION}.sentry.io/api/0"+API_BASE="${SENTRY_API_BASE:-https://${REGION}.sentry.io/api/0}"+DEFAULT_FREQUENCY_MIN=30SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"CONFIG_DIR="$(dirname "$SCRIPT_DIR")"@@ -23,219 +32,231 @@ if [ "${1:-}" = "--dry-run" ] || [ "${SENTRY_DRY_RUN:-0}" = "1" ]; thenDRY_RUN=1fi-info() { printf '\033[1;34m[info]\033[0m %s\n' "$*"; }-warn() { printf '\033[1;33m[warn]\033[0m %s\n' "$*" >&2; }-error() { printf '\033[1;31m[err]\033[0m %s\n' "$*" >&2; }-ok() { printf '\033[1;32m[ok]\033[0m %s\n' "$*"; }+# ---- output helpers ----+if [ -t 1 ]; then+ C_RESET=$'\033[0m'+ C_INFO=$'\033[1;34m'+ C_OK=$'\033[1;32m'+ C_WARN=$'\033[1;33m'+ C_ERR=$'\033[1;31m'+else+ C_RESET=""; C_INFO=""; C_OK=""; C_WARN=""; C_ERR=""+fi+info() { printf '%s[info]%s %s\n' "$C_INFO" "$C_RESET" "$*"; }+ok() { printf '%s[ok]%s %s\n' "$C_OK" "$C_RESET" "$*"; }+warn() { printf '%s[warn]%s %s\n' "$C_WARN" "$C_RESET" "$*" >&2; }+err() { printf '%s[err]%s %s\n' "$C_ERR" "$C_RESET" "$*" >&2; }+# ---- prerequisites ----if [ -z "${SENTRY_API_TOKEN:-}" ]; then- error "SENTRY_API_TOKEN is not set. Generate one at https://sentry.io/settings/account/api/auth-tokens/ with alerts:write scope."+ err "SENTRY_API_TOKEN is not set. Generate at https://sentry.io/settings/account/api/auth-tokens/ (scope: org:write)."exit 1fi-if [ ! -f "$ALERTS_FILE" ]; then- error "Alerts config not found at $ALERTS_FILE"+ err "Alerts config not found at $ALERTS_FILE"exit 1fi+command -v jq >/dev/null || { err "jq is required"; exit 1; }-command -v jq >/dev/null || { error "jq is required"; exit 1; }+# ---- API helpers ----+# Run an API call. Prints response body on success, returns 0.+# On HTTP >= 400, prints the response body to stderr and returns 1.+api_call() {+ local method="$1"+ local url="$2"+ local body="${3:-}"-# Resolve monitor slug -> numeric ID via Sentry API.-# Returns 1 if not found.-resolve_monitor_id() {- local slug="$1"- local response- response=$(curl -fsSL \+ local body_args=()+ if [ -n "$body" ]; then+ body_args+=(-d "$body")+ fi++ local tmp+ tmp=$(mktemp)+ local status+ # --fail-with-body: exit non-zero on HTTP error, but still write the body+ # to stdout (curl 7.76+). Lets us capture error responses inline.+ status=$(curl -sS --fail-with-body \+ -o "$tmp" \+ -w "%{http_code}" \+ -X "$method" \-H "Authorization: Bearer ${SENTRY_API_TOKEN}" \- "${API_BASE}/organizations/${ORG}/monitors/?query=${slug}" 2>/dev/null) || return 1- echo "$response" | jq -r --arg slug "$slug" \- '.[] | select(.slug == $slug) | .id' | head -n1+ -H "Content-Type: application/json" \+ "${body_args[@]}" \+ "$url" 2>/dev/null) || {+ err "HTTP $status from $method $url"+ err "Request body: $body"+ err "Response body:"+ sed 's/^/ /' "$tmp" >&2+ rm -f "$tmp"+ return 1+ }+ cat "$tmp"+ rm -f "$tmp"}-# Check whether an alert with this name already exists.-# Returns the ID if found, empty string otherwise.-find_existing_alert() {+find_existing_workflow_id() {local name="$1"local response- response=$(curl -fsSL \- -H "Authorization: Bearer ${SENTRY_API_TOKEN}" \- "${API_BASE}/organizations/${ORG}/workflows/?query=${name}" 2>/dev/null) || return 1+ response=$(api_call GET "${API_BASE}/organizations/${ORG}/workflows/?query=${name}") || return 0echo "$response" | jq -r --arg name "$name" \'.[] | select(.name == $name) | .id' | head -n1}-# Create a metric detector (used by metric alerts). Returns the new ID.-# Args: detector JSON (without organizationId / projectId).-create_detector() {- local project="$1"- local body="$2"- local response- response=$(curl -fsSL \- -X POST \- -H "Authorization: Bearer ${SENTRY_API_TOKEN}" \- -H "Content-Type: application/json" \- -d "$body" \- "${API_BASE}/organizations/${ORG}/projects/${project}/detectors/")- echo "$response" | jq -r '.id'-}--# Create a workflow (alert rule). Returns the new ID.-create_workflow() {- local body="$1"- local response- response=$(curl -fsSL \- -X POST \- -H "Authorization: Bearer ${SENTRY_API_TOKEN}" \- -H "Content-Type: application/json" \- -d "$body" \- "${API_BASE}/organizations/${ORG}/workflows/")- echo "$response" | jq -r '.id'-}+# ---- input validation ----+COUNT=$(jq '.alerts | length' "$ALERTS_FILE")+info "Reading $COUNT alert(s) from $ALERTS_FILE"+[ "$DRY_RUN" = "1" ] && info "DRY RUN: no changes will be made"+info "Organization: $ORG, Region: $REGION"-# Wire a detector into a workflow (POST detector_ids to the workflow).-attach_detector_to_workflow() {- local workflow_id="$1"- local detector_id="$2"- curl -fsSL \- -X PUT \- -H "Authorization: Bearer ${SENTRY_API_TOKEN}" \- -H "Content-Type: application/json" \- -d "{\"detectorIds\": [\"${detector_id}\"]}" \- "${API_BASE}/workflows/${workflow_id}/detector/${detector_id}" >/dev/null-}+# Validate every alert has a name up front so we don't half-apply.+jq -r '.alerts[] | .name | select(. == null or . == "")' "$ALERTS_FILE" \+ | grep -q . && {+ err "One or more alerts in $ALERTS_FILE have a missing name. Fix and retry."+ exit 1+ }-# Apply a single alert entry from the JSON config.-apply_alert() {- local alert_json="$1"- local name type projects workflow_json+# ---- main loop ----+APPLIED=0+SKIPPED=0+ERRORS=0- name=$(echo "$alert_json" | jq -r '.name')- type=$(echo "$alert_json" | jq -r '.kind')+for i in $(seq 0 $((COUNT - 1))); do+ ALERT=$(jq -c ".alerts[$i]" "$ALERTS_FILE")+ NAME=$(echo "$ALERT" | jq -r '.name')+ KIND=$(echo "$ALERT" | jq -r '.kind')- if [ -z "$name" ] || [ "$name" = "null" ]; then- error "Alert entry missing name; skipping"- return 0- fi+ echo+ info "==== $NAME ($KIND) ===="- local existing- existing=$(find_existing_alert "$name" || true)- if [ -n "$existing" ]; then- ok "Alert '$name' already exists (id $existing); skipping"- return 0+ if existing=$(find_existing_workflow_id "$NAME") && [ -n "$existing" ]; then+ ok "Workflow '$NAME' already exists (id $existing); skipping"+ SKIPPED=$((SKIPPED + 1))+ continuefi- info "Creating alert: $name ($type)"-- case "$type" in+ case "$KIND" inissue)- projects=$(echo "$alert_json" | jq -r '.projects | join(",")')- workflow_json=$(echo "$alert_json" | jq --arg org "$ORG" --arg projects "$projects" '- .workflow + {- organizationId: $org,- triggers: {- logicType: .workflow.triggers.logicType,- conditions: .workflow.triggers.conditions,- actions: []- }- }+ # Build the workflow payload. Drop empty actions/actionFilters — the+ # api rejects workflows with empty arrays in those fields.+ WORKFLOW=$(echo "$ALERT" | jq --arg org "$ORG" --argjson freq "$DEFAULT_FREQUENCY_MIN" '+ .workflow+ | .organizationId = $org+ | .config = ((.config // {}) + {frequency: $freq})+ | if (.triggers // {}).actions == [] then del(.triggers.actions) else . end+ | if (.triggers // {}).conditions | not then del(.triggers) else . end+ | if (.actionFilters // []) == [] then del(.actionFilters) else . end')+if [ "$DRY_RUN" = "1" ]; then- echo "$workflow_json" | jq .+ echo "$WORKFLOW" | jq .+ APPLIED=$((APPLIED + 1))+ continue+ fi++ if RESP=$(api_call POST "${API_BASE}/organizations/${ORG}/workflows/" "$WORKFLOW") \+ && NEW_ID=$(echo "$RESP" | jq -r '.id // empty') && [ -n "$NEW_ID" ]; then+ ok "Created workflow $NEW_ID"+ APPLIED=$((APPLIED + 1))else- local new_id- new_id=$(create_workflow "$workflow_json")- ok "Created workflow $new_id"+ # RESP is the error body at this point (api_call already printed a+ # detailed error). Just count it.+ ERRORS=$((ERRORS + 1))fi;;metric)- local detector_id- detector_id=$(echo "$alert_json" | jq -r '.detector.id // ""')-- if [ -z "$detector_id" ] || [ "$detector_id" = "null" ]; then- # Try resolving from detector_slugs (cron check-in monitors).- local slugs- slugs=$(echo "$alert_json" | jq -r '.detector_slugs | join(" ")')- local resolved_ids=()-- for slug in $slugs; do- local id- id=$(resolve_monitor_id "$slug" || true)- if [ -z "$id" ]; then- warn " cron monitor '$slug' not found in Sentry yet. Have the cron jobs run at least once?"+ # Detect whether the alert references cron monitor slugs (detectors+ # auto-created by Sentry.captureCheckIn) versus inline detector defs.+ HAS_SLUGS=$(echo "$ALERT" | jq -r '.detector_slugs | length > 0')+ HAS_INLINE_DETECTOR=$(echo "$ALERT" | jq -r '.detector | type == "object"')++ DETECTOR_IDS='[]'++ if [ "$HAS_SLUGS" = "true" ]; then+ SLUGS=$(echo "$ALERT" | jq -r '.detector_slugs[]')+ RESOLVED=()+ for slug in $SLUGS; do+ RESP=$(curl -sS -H "Authorization: Bearer ${SENTRY_API_TOKEN}" \+ "${API_BASE}/organizations/${ORG}/monitors/?query=${slug}" 2>/dev/null) || {+ err "Monitor lookup failed for '$slug'"continue+ }+ id=$(echo "$RESP" | jq -r --arg slug "$slug" \+ '.[] | select(.slug == $slug) | .id' | head -n1)+ if [ -z "$id" ] || [ "$id" = "null" ]; then+ warn "Cron monitor '$slug' not found in Sentry yet. Has the cron run at least once?"+ else+ info " resolved '$slug' -> id $id"+ RESOLVED+=("$id")fi- resolved_ids+=("$id")- info " resolved monitor '$slug' -> id $id"done- detector_id=$(echo "${resolved_ids[@]:-}" | tr ' ' '\n' | head -n1)+ if [ "${#RESOLVED[@]}" -eq 0 ]; then+ err "No cron monitors resolved for '$NAME'. Skipping workflow creation."+ ERRORS=$((ERRORS + 1))+ continue+ fi+ DETECTOR_IDS=$(printf '%s\n' "${RESOLVED[@]}" | jq -R . | jq -s .)fi- # Create the detector (if we have a body for it).- local detector_body- detector_body=$(echo "$alert_json" | jq -r '.detector // empty')- if [ -n "$detector_body" ]; then- local project- project=$(echo "$alert_json" | jq -r '.project')- detector_body=$(echo "$detector_body" | jq --arg org "$ORG" --arg project "$project" '- . + {organizationId: $org, projectId: $project}+ if [ "$HAS_INLINE_DETECTOR" = "true" ]; then+ PROJECT=$(echo "$ALERT" | jq -r '.project')+ DETECTOR=$(echo "$ALERT" | jq --arg org "$ORG" --arg project "$PROJECT" '+ .detector + {organizationId: $org, projectId: $project}')+if [ "$DRY_RUN" = "1" ]; then- echo "$detector_body" | jq .+ echo "[dry-run] would POST detector:"; echo "$DETECTOR" | jq .else- local new_detector_id- new_detector_id=$(create_detector "$project" "$detector_body")- ok "Created detector $new_detector_id"- detector_id="$new_detector_id"+ if RESP=$(api_call POST "${API_BASE}/organizations/${ORG}/projects/${PROJECT}/detectors/" "$DETECTOR") \+ && NEW_DET_ID=$(echo "$RESP" | jq -r '.id // empty') && [ -n "$NEW_DET_ID" ]; then+ ok "Created detector $NEW_DET_ID"+ DETECTOR_IDS=$(echo "$DETECTOR_IDS" | jq --arg id "$NEW_DET_ID" '. + [$id]')+ else+ ERRORS=$((ERRORS + 1))+ continue+ fififi- # Create the workflow.- local workflow_body- workflow_body=$(echo "$alert_json" | jq --arg org "$ORG" --arg det "$detector_id" '- .workflow + {+ # Workflow for metric alerts: detector-only, no triggers. The detector+ # itself fires when its condition matches.+ WORKFLOW=$(echo "$ALERT" | jq --arg org "$ORG" --argjson freq "$DEFAULT_FREQUENCY_MIN" \+ --argjson detectors "$DETECTOR_IDS" '+ {+ name: .workflow.name,+ enabled: (.workflow.enabled // true),organizationId: $org,- detectorIds: (if $det != "" then [$det] else [] end)+ config: ((.workflow.config // {}) + {frequency: $freq}),+ detectorIds: $detectors}')+if [ "$DRY_RUN" = "1" ]; then- echo "$workflow_body" | jq .+ echo "[dry-run] would POST workflow:"; echo "$WORKFLOW" | jq .+ APPLIED=$((APPLIED + 1))+ continue+ fi++ if RESP=$(api_call POST "${API_BASE}/organizations/${ORG}/workflows/" "$WORKFLOW") \+ && NEW_ID=$(echo "$RESP" | jq -r '.id // empty') && [ -n "$NEW_ID" ]; then+ ok "Created workflow $NEW_ID"+ APPLIED=$((APPLIED + 1))else- local new_workflow_id- new_workflow_id=$(create_workflow "$workflow_body")- ok "Created workflow $new_workflow_id"+ ERRORS=$((ERRORS + 1))fi;;*)- error "Unknown alert kind '$type' for '$name'; skipping"- return 0+ err "Unknown kind '$KIND' for '$NAME'"+ ERRORS=$((ERRORS + 1));;esac-}--# ---- main -----info "Reading alerts from $ALERTS_FILE"-[ "$DRY_RUN" = "1" ] && info "DRY RUN: no changes will be made"-info "Organization: $ORG, Region: $REGION"--count=$(jq '.alerts | length' "$ALERTS_FILE")-info "Found $count alert(s) to process"--OK=0-SKIPPED=0-ERRORED=0--for i in $(seq 0 $((count - 1))); do- ALERT=$(jq -c ".alerts[$i]" "$ALERTS_FILE")- if apply_alert "$ALERT"; then- OK=$((OK + 1))- else- ERRORED=$((ERRORED + 1))- fidone-echo ""-info "Done: $OK created/skipped, $ERRORED errors"+echo+echo "-----------------------------------------------------------"+info "Done: $APPLIED created, $SKIPPED skipped, $ERRORS failed"[ "$DRY_RUN" = "1" ] && info "Re-run without --dry-run to apply"-info "Configure per-alert notifications in Sentry: Settings > Alerts > [alert name] > Actions"+[ "$ERRORS" -gt 0 ] && exit 1+exit 0