同步完整源码 - 2026-05-25
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# Function to check if a command exists
|
||||
check_command() {
|
||||
if ! command -v $1 &> /dev/null; then
|
||||
echo "❌ Error: $1 is not installed or not in PATH"
|
||||
echo "💡 Please run the following command from the repository root:"
|
||||
if [ "$1" = "ruff" ]; then
|
||||
echo " uv pip install -r requirements-dev.txt"
|
||||
elif [ "$1" = "eslint" ] || [ "$1" = "prettier" ]; then
|
||||
echo " npm install"
|
||||
fi
|
||||
return 1
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
# Check for required commands
|
||||
echo "🔍 Checking required dependencies..."
|
||||
check_command "ruff" && check_command "eslint" && check_command "prettier"
|
||||
DEPS_STATUS=$?
|
||||
|
||||
if [ $DEPS_STATUS -eq 0 ]; then
|
||||
DEPS_MESSAGE="All required dependencies are installed"
|
||||
echo "✅ $DEPS_MESSAGE"
|
||||
else
|
||||
DEPS_MESSAGE="Missing required dependencies"
|
||||
echo "❌ $DEPS_MESSAGE"
|
||||
fi
|
||||
|
||||
return 0 # Always return success
|
||||
@@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# $1 = Temporary directory path
|
||||
|
||||
if [ -z "$1" ]; then
|
||||
echo "Error: Temporary directory argument missing." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
TEMP_DIR="$1"
|
||||
STATUS_FILE="$TEMP_DIR/js_deps_status.txt"
|
||||
MESSAGE_FILE="$TEMP_DIR/js_deps_message.txt"
|
||||
|
||||
JS_DEPS_STATUS=0 # Assume success
|
||||
FINAL_MESSAGE=""
|
||||
MISSING_TOOLS=""
|
||||
|
||||
# Check dependencies
|
||||
if ! npx prettier --version &> /dev/null; then
|
||||
MISSING_TOOLS="Prettier"
|
||||
JS_DEPS_STATUS=2 # Warning
|
||||
fi
|
||||
if ! npx eslint --version &> /dev/null; then
|
||||
[ -n "$MISSING_TOOLS" ] && MISSING_TOOLS+=" and "
|
||||
MISSING_TOOLS+="ESLint"
|
||||
JS_DEPS_STATUS=2 # Warning
|
||||
fi
|
||||
|
||||
if [ $JS_DEPS_STATUS -eq 0 ]; then
|
||||
FINAL_MESSAGE="JS/TS dependencies (prettier, eslint) found."
|
||||
else
|
||||
FINAL_MESSAGE="$MISSING_TOOLS not installed. Run 'npm install'"
|
||||
fi
|
||||
|
||||
# Write results to temporary files
|
||||
echo "$JS_DEPS_STATUS" > "$STATUS_FILE"
|
||||
echo "$FINAL_MESSAGE" > "$MESSAGE_FILE"
|
||||
|
||||
# Always exit 0
|
||||
exit 0
|
||||
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# $1 = Temporary directory path
|
||||
|
||||
if [ -z "$1" ]; then
|
||||
echo "Error: Temporary directory argument missing." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
TEMP_DIR="$1"
|
||||
STATUS_FILE="$TEMP_DIR/python_deps_status.txt"
|
||||
MESSAGE_FILE="$TEMP_DIR/python_deps_message.txt"
|
||||
|
||||
PYTHON_DEPS_STATUS=0 # Assume success
|
||||
FINAL_MESSAGE=""
|
||||
|
||||
# Check for ruff
|
||||
if ! command -v ruff &> /dev/null; then
|
||||
PYTHON_DEPS_STATUS=2 # Warning
|
||||
FINAL_MESSAGE="Ruff not installed. Install with: uv pip install -r requirements-dev.txt"
|
||||
else
|
||||
FINAL_MESSAGE="Python dependencies (ruff) found."
|
||||
fi
|
||||
|
||||
# Write results to temporary files
|
||||
echo "$PYTHON_DEPS_STATUS" > "$STATUS_FILE"
|
||||
echo "$FINAL_MESSAGE" > "$MESSAGE_FILE"
|
||||
|
||||
# Always exit 0
|
||||
exit 0
|
||||
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# $1 = Temporary directory path
|
||||
|
||||
if [ -z "$1" ]; then
|
||||
echo "Error: Temporary directory argument missing." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
TEMP_DIR="$1"
|
||||
STATUS_FILE="$TEMP_DIR/unstaged_status.txt"
|
||||
MESSAGE_FILE="$TEMP_DIR/unstaged_message.txt"
|
||||
|
||||
# Initialize status
|
||||
UNSTAGED_STATUS=0 # Default to success
|
||||
FINAL_MESSAGE="No unstaged changes detected"
|
||||
|
||||
# Check if formatting/fixing introduced unstaged changes to *staged* files
|
||||
if ! git diff --cached --quiet --exit-code; then
|
||||
# echo "⚠️ Warning: Staged files were modified by formatters/linters." # Silenced
|
||||
# echo " Please review the changes before committing."
|
||||
UNSTAGED_STATUS=2 # Warning
|
||||
FINAL_MESSAGE="Staged files were modified by hooks"
|
||||
fi
|
||||
|
||||
# Check for *any* new unstaged changes (including untracked maybe? No, git diff doesn't show untracked)
|
||||
if ! git diff --quiet --exit-code; then
|
||||
# Only update message if we didn't already detect modified staged files
|
||||
if [ $UNSTAGED_STATUS -ne 2 ]; then
|
||||
# echo "⚠️ Warning: Unstaged changes detected after running hooks." # Silenced
|
||||
# echo " This might indicate issues during formatting or linting."
|
||||
UNSTAGED_STATUS=2 # Warning
|
||||
FINAL_MESSAGE="Other unstaged changes detected after hooks"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Write results to temporary files
|
||||
echo "$UNSTAGED_STATUS" > "$STATUS_FILE"
|
||||
echo "$FINAL_MESSAGE" > "$MESSAGE_FILE"
|
||||
|
||||
# Always exit 0 from this script
|
||||
exit 0
|
||||
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# Function to get staged JS/TS files anywhere in the repo
|
||||
get_staged_js_ts_files() {
|
||||
# Ensure grep returns 0 exit code even if no match found, and echo "" for empty result
|
||||
git diff --cached --name-only --diff-filter=ACMR | grep -E '\.(js|jsx|ts|tsx)$' || echo ""
|
||||
}
|
||||
|
||||
# Function to run JS/TS checks (using npx for repo-wide application)
|
||||
run_js_ts_checks() {
|
||||
local STAGED_JS_TS_FILES=$(get_staged_js_ts_files)
|
||||
local JS_STATUS=3 # Default to skipped
|
||||
|
||||
if [ ! -z "$STAGED_JS_TS_FILES" ]; then
|
||||
echo "🔍 Running JS/TS checks on staged files:"
|
||||
echo "$STAGED_JS_TS_FILES"
|
||||
|
||||
# Check if prettier is available via npx
|
||||
if ! npx prettier --version &> /dev/null; then
|
||||
echo "❌ Error: prettier is not installed"
|
||||
echo "💡 Please run the following command from the repository root:"
|
||||
echo " npm install"
|
||||
JS_STATUS=1
|
||||
JS_MESSAGE="Prettier is not installed"
|
||||
else
|
||||
# Run prettier on staged JS/TS files (paths relative to repo root)
|
||||
echo "🔍 Formatting staged JS/TS files with prettier..."
|
||||
# Assumes prettier config is discoverable (e.g., .prettierrc at root)
|
||||
echo "$STAGED_JS_TS_FILES" | xargs npx prettier --write --ignore-unknown || true
|
||||
|
||||
# Check if eslint is available via npx
|
||||
if ! npx eslint --version &> /dev/null; then
|
||||
echo "❌ Error: eslint is not installed"
|
||||
echo "💡 Please run the following command from the repository root:"
|
||||
echo " npm install"
|
||||
JS_STATUS=1
|
||||
JS_MESSAGE="ESLint is not installed"
|
||||
else
|
||||
# Run eslint with auto-fix on staged JS/TS files
|
||||
echo "🔍 Linting and fixing staged JS/TS files with eslint..."
|
||||
# Assumes eslint config is discoverable (e.g., .eslintrc.js at root)
|
||||
echo "$STAGED_JS_TS_FILES" | xargs npx eslint --fix || true
|
||||
|
||||
# Add back the fixed/formatted files (paths relative to repo root)
|
||||
echo "✅ Adding fixed/formatted JS/TS files back to staging..."
|
||||
echo "$STAGED_JS_TS_FILES" | xargs git add
|
||||
JS_STATUS=0
|
||||
JS_MESSAGE="JS/TS files formatted and linted"
|
||||
fi
|
||||
fi
|
||||
else
|
||||
JS_MESSAGE="No staged JS/TS files found"
|
||||
echo "✅ $JS_MESSAGE"
|
||||
fi
|
||||
|
||||
return 0 # Always return success
|
||||
}
|
||||
|
||||
# Run the checks
|
||||
run_js_ts_checks
|
||||
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# Function to get staged Python files anywhere in the repo
|
||||
get_python_files() {
|
||||
# Ensure grep returns 0 exit code even if no match found, and echo "" for empty result
|
||||
git diff --cached --name-only --diff-filter=ACMR | grep '\.py$' || echo ""
|
||||
}
|
||||
|
||||
# Function to run Python checks (using ruff - assumes ruff is installed and configured)
|
||||
run_python_checks() {
|
||||
local STAGED_PYTHON_FILES=$(get_python_files)
|
||||
local PYTHON_STATUS=3 # Default to skipped
|
||||
|
||||
if [ ! -z "$STAGED_PYTHON_FILES" ]; then
|
||||
echo "🔍 Running Python checks on staged files:"
|
||||
echo "$STAGED_PYTHON_FILES"
|
||||
|
||||
# Check if uvx is available, fallback to ruff
|
||||
if command -v uvx &> /dev/null; then
|
||||
RUFF_CMD="uvx ruff"
|
||||
echo "🔍 Using uvx ruff (no local Python env required)"
|
||||
elif command -v ruff &> /dev/null; then
|
||||
RUFF_CMD="ruff"
|
||||
echo "🔍 Using local ruff installation"
|
||||
else
|
||||
echo "❌ Error: Neither uvx nor ruff is installed"
|
||||
echo "💡 Please install uv (recommended) or run:"
|
||||
echo " uv pip install -r requirements-dev.txt"
|
||||
PYTHON_STATUS=1
|
||||
PYTHON_MESSAGE="Ruff is not installed (install uv or ruff)"
|
||||
fi
|
||||
|
||||
if [ "$PYTHON_STATUS" != "1" ]; then
|
||||
# Run ruff format on staged Python files (paths relative to repo root)
|
||||
echo "🔍 Formatting staged Python files with $RUFF_CMD..."
|
||||
# Pass files directly to ruff; use --force-exclude if necessary based on ruff config
|
||||
echo "$STAGED_PYTHON_FILES" | xargs $RUFF_CMD format --force-exclude || true
|
||||
|
||||
# Run ruff check with auto-fix on staged Python files
|
||||
echo "🔍 Linting and fixing staged Python files with $RUFF_CMD..."
|
||||
# Pass files directly to ruff; use --force-exclude if necessary
|
||||
echo "$STAGED_PYTHON_FILES" | xargs $RUFF_CMD check --fix --force-exclude || true
|
||||
|
||||
# Add back the fixed/formatted files (paths relative to repo root)
|
||||
echo "✅ Adding fixed/formatted Python files back to staging..."
|
||||
echo "$STAGED_PYTHON_FILES" | xargs git add
|
||||
PYTHON_STATUS=0
|
||||
PYTHON_MESSAGE="Python files formatted and linted successfully"
|
||||
fi
|
||||
else
|
||||
PYTHON_MESSAGE="No staged Python files found"
|
||||
echo "✅ $PYTHON_MESSAGE"
|
||||
fi
|
||||
|
||||
return 0 # Always return success
|
||||
}
|
||||
|
||||
# Run the checks
|
||||
run_python_checks
|
||||
@@ -0,0 +1,33 @@
|
||||
#!/bin/bash
|
||||
# Script to handle 'just api-build' logic, including optional Stripe/jq checks.
|
||||
|
||||
set -e # Exit immediately if a command exits with a non-zero status.
|
||||
|
||||
STRIPE_FLAG="${1:-}" # First argument is the stripe flag, default to empty
|
||||
|
||||
if [ "$STRIPE_FLAG" = "-s" ] || [ "$STRIPE_FLAG" = "--with-stripe" ]; then
|
||||
echo "Performing pre-build checks for Stripe integration tools..."
|
||||
echo "Checking for Stripe CLI..."
|
||||
if ! command -v stripe > /dev/null; then
|
||||
echo "Warning: Stripe CLI not found or not in PATH."
|
||||
echo " 'just api-run -s' (or running with Stripe) might fail to set up Stripe webhooks automatically."
|
||||
echo " Please install Stripe CLI from https://stripe.com/docs/stripe-cli and add it to your PATH."
|
||||
else
|
||||
echo "Stripe CLI found."
|
||||
fi
|
||||
echo "Checking for jq..."
|
||||
if ! command -v jq > /dev/null; then
|
||||
echo "Warning: jq (JSON processor) not found or not in PATH."
|
||||
echo " 'just api-run -s' (or running with Stripe) might fail to set up Stripe webhooks automatically."
|
||||
echo " Please install jq (e.g., 'pacman -S jq' in MINGW64/Git Bash, or download from https://stedolan.github.io/jq/download/)."
|
||||
else
|
||||
echo "jq found."
|
||||
fi
|
||||
else
|
||||
echo "Skipping Stripe/jq checks for this build (pass '-s' or '--with-stripe' to include them via 'just api-build -s')."
|
||||
fi
|
||||
|
||||
echo "Building Docker image for the backend API..."
|
||||
|
||||
docker build -f api/Dockerfile -t agentops-api .
|
||||
echo "Docker image build complete."
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/bin/bash
|
||||
# Script to handle 'just api-run' logic, including optional Stripe integration.
|
||||
|
||||
set -e # Exit immediately if a command exits with a non-zero status.
|
||||
|
||||
STRIPE_FLAG="${1:-}" # First argument is the stripe flag, default to empty
|
||||
API_PORT="8000" # Default API port
|
||||
ENV_FILE="${API_ENV_FILE:-api/.env.dev}" # Use .env.dev by default, allow override with API_ENV_FILE
|
||||
|
||||
API_DOCKER_COMMAND=("docker" "run" "-p" "${API_PORT}:${API_PORT}" "--env-file" "$ENV_FILE" "--rm" "--name" "agentops-api-container" "agentops-api")
|
||||
|
||||
if [ "$STRIPE_FLAG" = "-s" ] || [ "$STRIPE_FLAG" = "--with-stripe" ]; then
|
||||
echo "Attempting to run API on port $API_PORT with Stripe integration (using scripts/run-api-with-stripe.sh)..."
|
||||
|
||||
"$(dirname "$0")/run-api-with-stripe.sh" "$API_PORT" "${API_DOCKER_COMMAND[@]}"
|
||||
else
|
||||
echo "Running API on port $API_PORT without Stripe integration (direct Docker run)..."
|
||||
"${API_DOCKER_COMMAND[@]}"
|
||||
fi
|
||||
|
||||
echo "API execution finished (or was launched in background by run-api-with-stripe.sh)."
|
||||
@@ -0,0 +1,210 @@
|
||||
#!/bin/bash
|
||||
# This script automates running the API with Stripe webhook listening.
|
||||
# It fetches the webhook secret, starts 'stripe listen' in the background,
|
||||
# and then runs the provided API command with the secret injected.
|
||||
|
||||
set -e # Exit immediately if a command exits with a non-zero status.
|
||||
|
||||
# --- Configuration ---
|
||||
DEFAULT_API_PORT="8000" # Default API port if not provided as first argument
|
||||
# Events Stripe CLI should listen for.
|
||||
STRIPE_EVENTS="checkout.session.completed,subscription_schedule.canceled,subscription_schedule.completed,subscription_schedule.created,subscription_schedule.expiring,subscription_schedule.released"
|
||||
# Command to run the API will be passed as arguments to this script after the optional port.
|
||||
|
||||
# --- Helper Functions ---
|
||||
function check_command() {
|
||||
if ! command -v "$1" &> /dev/null; then
|
||||
echo "Error: Required command '$1' not found in PATH."
|
||||
echo "Please install '$1' and ensure it's in your PATH."
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
STRIPE_LISTEN_PID=""
|
||||
SECRET_OUTPUT_FILE=""
|
||||
|
||||
function cleanup() {
|
||||
echo "Cleaning up... (called from LNO: ${BASH_LINENO[0]})"
|
||||
set +x # Turn off command printing during cleanup to reduce noise
|
||||
if [ -n "$STRIPE_LISTEN_PID" ] && ps -p "$STRIPE_LISTEN_PID" > /dev/null; then
|
||||
echo "Stopping background Stripe listen process (PID: $STRIPE_LISTEN_PID)..."
|
||||
kill "$STRIPE_LISTEN_PID"
|
||||
wait "$STRIPE_LISTEN_PID" 2>/dev/null || true # Allow wait to not cause script exit
|
||||
echo "Stripe listen process stopped."
|
||||
elif [ -n "$STRIPE_LISTEN_PID" ]; then # If PID was set but process not found
|
||||
echo "Background Stripe listen process (PID: $STRIPE_LISTEN_PID) was expected but not found or already stopped."
|
||||
else # If PID was never set for persistent listener
|
||||
echo "Background Stripe listen process was not started or its PID was not captured."
|
||||
fi
|
||||
if [ -n "$SECRET_OUTPUT_FILE" ] && [ -f "$SECRET_OUTPUT_FILE" ]; then
|
||||
echo "Removing temporary secret file (if not preserved for error): $SECRET_OUTPUT_FILE"
|
||||
# Check if we are exiting due to an error before removing, to preserve for inspection
|
||||
# This is a simple check; a more robust way would be to pass exit code to cleanup.
|
||||
# For now, if an error occurred in secret retrieval, it would have exited before successful rm.
|
||||
rm -f "$SECRET_OUTPUT_FILE"
|
||||
fi
|
||||
}
|
||||
|
||||
# --- Main Script ---
|
||||
|
||||
# Trap exit signals to ensure cleanup
|
||||
trap cleanup EXIT SIGINT SIGTERM
|
||||
|
||||
# Check for required tools
|
||||
check_command "stripe"
|
||||
check_command "mktemp"
|
||||
check_command "grep"
|
||||
check_command "sed"
|
||||
|
||||
# Determine API Port and API command
|
||||
API_PORT="${1:-$DEFAULT_API_PORT}"
|
||||
if [[ "$1" =~ ^[0-9]+$ ]]; then # if first arg is a port number
|
||||
shift # remove port from arguments, rest are the API command
|
||||
fi
|
||||
|
||||
if [ $# -eq 0 ]; then
|
||||
echo "Error: No API command provided."
|
||||
echo "Usage: $0 [API_PORT] <command_to_run_api...>"
|
||||
echo "Example: $0 8000 docker compose up my-api-service"
|
||||
exit 1
|
||||
fi
|
||||
API_RUN_COMMAND=("$@")
|
||||
|
||||
echo "Attempting to obtain Stripe webhook secret..."
|
||||
echo "You may be prompted to authenticate with Stripe in your browser."
|
||||
|
||||
SECRET_OUTPUT_FILE=$(mktemp)
|
||||
if [ -z "$SECRET_OUTPUT_FILE" ]; then
|
||||
echo "Error: Could not create temporary file."
|
||||
exit 1
|
||||
fi
|
||||
echo "Stripe CLI output for secret retrieval will be logged to: $SECRET_OUTPUT_FILE"
|
||||
|
||||
stripe listen --format JSON --forward-to "http://localhost:${API_PORT}/v4/stripe-webhook" --events "${STRIPE_EVENTS}" --skip-update > "${SECRET_OUTPUT_FILE}" 2>&1 &
|
||||
STRIPE_SECRET_PID_TEMP=$!
|
||||
echo "Started temporary Stripe listen for secret (PID: $STRIPE_SECRET_PID_TEMP). Waiting for secret..."
|
||||
|
||||
sleep 1
|
||||
|
||||
if ! ps -p "$STRIPE_SECRET_PID_TEMP" > /dev/null; then
|
||||
echo "Error: Stripe listen process for secret retrieval (PID: $STRIPE_SECRET_PID_TEMP) seems to have died immediately after start."
|
||||
echo "--- Output from Stripe CLI (from $SECRET_OUTPUT_FILE) --- BEGIN --- "
|
||||
cat "${SECRET_OUTPUT_FILE}"
|
||||
echo "--- Output from Stripe CLI (from $SECRET_OUTPUT_FILE) --- END --- "
|
||||
exit 1
|
||||
fi
|
||||
|
||||
timeout=300 # 5 minutes
|
||||
elapsed=0
|
||||
secret_found=false
|
||||
WEBHOOK_SECRET=""
|
||||
|
||||
while [ $elapsed -lt $timeout ]; do
|
||||
if ! ps -p "$STRIPE_SECRET_PID_TEMP" > /dev/null; then
|
||||
echo "Error: Stripe listen process for secret retrieval (PID: $STRIPE_SECRET_PID_TEMP) died prematurely during wait loop."
|
||||
echo "--- Output from Stripe CLI (from $SECRET_OUTPUT_FILE) --- BEGIN --- "
|
||||
cat "${SECRET_OUTPUT_FILE}"
|
||||
echo "--- Output from Stripe CLI (from $SECRET_OUTPUT_FILE) --- END --- "
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if grep -q "Your webhook signing secret is" "${SECRET_OUTPUT_FILE}"; then
|
||||
WEBHOOK_SECRET=$(grep "Your webhook signing secret is" "${SECRET_OUTPUT_FILE}" | sed -n 's/.*Your webhook signing secret is \(whsec_[^[:space:]]*\).*/\1/p' | tr -d '[:space:]')
|
||||
if [ -n "$WEBHOOK_SECRET" ]; then
|
||||
secret_found=true
|
||||
echo "Stripe webhook secret identified from text output."
|
||||
break
|
||||
fi
|
||||
fi
|
||||
|
||||
JQ_SECRET=$(jq -r '.secret' "${SECRET_OUTPUT_FILE}" 2>/dev/null)
|
||||
if [ $? -eq 0 ] && [ -n "$JQ_SECRET" ] && [ "$JQ_SECRET" != "null" ]; then
|
||||
WEBHOOK_SECRET=$JQ_SECRET
|
||||
secret_found=true
|
||||
echo "Stripe webhook secret identified from JSON output."
|
||||
break
|
||||
fi
|
||||
|
||||
sleep 1
|
||||
elapsed=$((elapsed + 1))
|
||||
if [ $((elapsed % 10)) -eq 0 ]; then
|
||||
echo "Still waiting for Stripe secret... ($elapsed/$timeout seconds) (Temp PID: $STRIPE_SECRET_PID_TEMP is alive)"
|
||||
fi
|
||||
done
|
||||
|
||||
if ps -p "$STRIPE_SECRET_PID_TEMP" > /dev/null; then
|
||||
echo "Stopping temporary Stripe listen for secret (PID: $STRIPE_SECRET_PID_TEMP)..."
|
||||
kill "$STRIPE_SECRET_PID_TEMP"
|
||||
wait "$STRIPE_SECRET_PID_TEMP" 2>/dev/null || true
|
||||
echo "Temporary Stripe listen stopped."
|
||||
fi
|
||||
|
||||
if [ "$secret_found" = false ]; then
|
||||
echo "Error: Timed out waiting for Stripe webhook secret after $timeout seconds."
|
||||
echo "--- Final output from Stripe CLI (from $SECRET_OUTPUT_FILE) --- BEGIN --- "
|
||||
cat "${SECRET_OUTPUT_FILE}"
|
||||
echo "--- Final output from Stripe CLI (from $SECRET_OUTPUT_FILE) --- END --- "
|
||||
echo "!!! Preserving temporary secret file for inspection due to timeout: $SECRET_OUTPUT_FILE !!!"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$WEBHOOK_SECRET" ]; then
|
||||
echo "Error: Logic failure - secret_found is true but WEBHOOK_SECRET is empty."
|
||||
echo "!!! Preserving temporary secret file for inspection due to empty secret: $SECRET_OUTPUT_FILE !!!"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -f "$SECRET_OUTPUT_FILE" ]; then
|
||||
echo "Secret obtained, removing temporary file: $SECRET_OUTPUT_FILE"
|
||||
rm -f "$SECRET_OUTPUT_FILE"
|
||||
SECRET_OUTPUT_FILE=""
|
||||
fi
|
||||
echo "Stripe Webhook Secret obtained successfully: whsec_... (masked)"
|
||||
|
||||
# Now, start the actual 'stripe listen' in the background that will stay running
|
||||
echo "Starting persistent background Stripe listen process..."
|
||||
# Using --skip-update to prevent auto-updates.
|
||||
stripe listen --forward-to "http://localhost:${API_PORT}/v4/stripe-webhook" --events "${STRIPE_EVENTS}" --skip-update &
|
||||
STRIPE_LISTEN_PID=$!
|
||||
echo "Persistent Stripe listen command launched. Captured PID: [$STRIPE_LISTEN_PID]"
|
||||
|
||||
if [ -z "$STRIPE_LISTEN_PID" ]; then
|
||||
echo "Critical Error: Failed to capture PID of persistent Stripe listen process immediately after launch (PID was empty)."
|
||||
exit 1 # Should not happen if stripe listen & itself doesn't error out before $! is assigned
|
||||
fi
|
||||
|
||||
echo "Waiting a moment for persistent Stripe listen (PID: $STRIPE_LISTEN_PID) to initialize..."
|
||||
sleep 3 # Increased sleep slightly
|
||||
|
||||
if ! ps -p "$STRIPE_LISTEN_PID" > /dev/null; then
|
||||
echo "Error: Persistent background Stripe listen process (PID: $STRIPE_LISTEN_PID) failed to start or died shortly after starting."
|
||||
echo "Check for errors in the terminal output above from Stripe CLI (it logs directly when run with '&')."
|
||||
# STRIPE_LISTEN_PID is kept so cleanup knows which PID it was attempting to manage
|
||||
exit 1 # This will trigger cleanup
|
||||
fi
|
||||
echo "Persistent background Stripe listen started (PID: $STRIPE_LISTEN_PID). Forwarding events."
|
||||
echo "API logs will follow. Stripe listen logs will be mixed with API logs."
|
||||
echo "---"
|
||||
|
||||
# Run the API command with the webhook secret
|
||||
echo "Executing API command with injected -e STRIPE_WEBHOOK_SECRET=whsec_... (masked)"
|
||||
|
||||
# API_RUN_COMMAND is ("docker" "run" "-p" "8000:8000" ...)
|
||||
# We want ("docker" "run" "-e" "STRIPE_WEBHOOK_SECRET=value" "-p" "8000:8000" ...)
|
||||
CMD_ARRAY=()
|
||||
CMD_ARRAY+=("${API_RUN_COMMAND[0]}") # docker
|
||||
CMD_ARRAY+=("${API_RUN_COMMAND[1]}") # run
|
||||
CMD_ARRAY+=("-e")
|
||||
CMD_ARRAY+=("STRIPE_WEBHOOK_SECRET=${WEBHOOK_SECRET}")
|
||||
# Add the rest of the original command, skipping the first two elements ("docker" "run")
|
||||
# This assumes that API_RUN_COMMAND always starts with "docker run"
|
||||
# Ensure elements from index 2 onwards are correctly appended.
|
||||
if [ ${#API_RUN_COMMAND[@]} -gt 2 ]; then
|
||||
CMD_ARRAY+=("${API_RUN_COMMAND[@]:2}")
|
||||
fi
|
||||
|
||||
"${CMD_ARRAY[@]}"
|
||||
|
||||
API_EXIT_CODE=$?
|
||||
echo "API command exited with code $API_EXIT_CODE."
|
||||
exit $API_EXIT_CODE
|
||||
@@ -0,0 +1,151 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Script to sunset all legacy subscriptions by setting them to cancel at period end.
|
||||
This should be run after updating the STRIPE_SUBSCRIPTION_PRICE_ID environment variable.
|
||||
|
||||
Usage:
|
||||
python scripts/sunset_legacy_subscriptions.py [--dry-run]
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import stripe
|
||||
import time
|
||||
import argparse
|
||||
from datetime import datetime
|
||||
import logging
|
||||
|
||||
# Setup logging
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Sunset all legacy subscriptions')
|
||||
parser.add_argument(
|
||||
'--dry-run', action='store_true', help='Show what would be done without making changes'
|
||||
)
|
||||
parser.add_argument('--limit', type=int, default=100, help='Number of subscriptions to process per page')
|
||||
args = parser.parse_args()
|
||||
|
||||
# Get environment variables
|
||||
stripe_secret_key = os.getenv('STRIPE_SECRET_KEY')
|
||||
current_price_id = os.getenv('STRIPE_SUBSCRIPTION_PRICE_ID')
|
||||
|
||||
if not stripe_secret_key:
|
||||
logger.error("STRIPE_SECRET_KEY environment variable not set")
|
||||
sys.exit(1)
|
||||
|
||||
if not current_price_id:
|
||||
logger.error("STRIPE_SUBSCRIPTION_PRICE_ID environment variable not set")
|
||||
sys.exit(1)
|
||||
|
||||
stripe.api_key = stripe_secret_key
|
||||
|
||||
logger.info(f"Current price ID: {current_price_id}")
|
||||
logger.info(f"Dry run: {args.dry_run}")
|
||||
|
||||
sunset_count = 0
|
||||
already_cancelled_count = 0
|
||||
current_pricing_count = 0
|
||||
error_count = 0
|
||||
|
||||
try:
|
||||
# Get all active subscriptions
|
||||
has_more = True
|
||||
starting_after = None
|
||||
|
||||
while has_more:
|
||||
params = {
|
||||
'status': 'active',
|
||||
'limit': args.limit,
|
||||
}
|
||||
if starting_after:
|
||||
params['starting_after'] = starting_after
|
||||
|
||||
subscriptions = stripe.Subscription.list(**params)
|
||||
|
||||
for sub in subscriptions.data:
|
||||
try:
|
||||
# Check if it's using the old price
|
||||
is_legacy = True
|
||||
legacy_price_id = None
|
||||
|
||||
for item in sub.get('items', {}).get('data', []):
|
||||
price_id = item.get('price', {}).get('id')
|
||||
if price_id == current_price_id:
|
||||
is_legacy = False
|
||||
break
|
||||
else:
|
||||
legacy_price_id = price_id
|
||||
|
||||
if not is_legacy:
|
||||
current_pricing_count += 1
|
||||
continue
|
||||
|
||||
if sub.get('cancel_at_period_end'):
|
||||
already_cancelled_count += 1
|
||||
logger.debug(f"Subscription {sub.id} already set to cancel")
|
||||
continue
|
||||
|
||||
# Get customer info for logging
|
||||
customer_email = 'unknown'
|
||||
try:
|
||||
customer = stripe.Customer.retrieve(sub.customer)
|
||||
customer_email = customer.get('email', 'unknown')
|
||||
except:
|
||||
pass
|
||||
|
||||
if args.dry_run:
|
||||
logger.info(
|
||||
f"[DRY RUN] Would sunset subscription {sub.id} for customer {customer_email} (price: {legacy_price_id})"
|
||||
)
|
||||
sunset_count += 1 # Count what would be done in dry run
|
||||
else:
|
||||
# Cancel at period end
|
||||
stripe.Subscription.modify(
|
||||
sub.id,
|
||||
cancel_at_period_end=True,
|
||||
metadata={
|
||||
'cancellation_reason': 'billing_model_change',
|
||||
'notification_email_sent': 'pending',
|
||||
'original_price_id': legacy_price_id or 'unknown',
|
||||
'sunset_script_run': datetime.utcnow().isoformat(),
|
||||
},
|
||||
)
|
||||
logger.info(f"✓ Sunset subscription {sub.id} for customer {customer_email}")
|
||||
sunset_count += 1
|
||||
|
||||
# Rate limit to avoid hitting Stripe's API limits
|
||||
time.sleep(0.1)
|
||||
|
||||
except Exception as e:
|
||||
error_count += 1
|
||||
logger.error(f"✗ Error with subscription {sub.id}: {e}")
|
||||
|
||||
# Check if there are more pages
|
||||
has_more = subscriptions.has_more
|
||||
if has_more and subscriptions.data:
|
||||
starting_after = subscriptions.data[-1].id
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Fatal error: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
# Summary
|
||||
logger.info("\n=== SUMMARY ===")
|
||||
if args.dry_run:
|
||||
logger.info(f"Would sunset: {sunset_count} subscriptions")
|
||||
else:
|
||||
logger.info(f"Total subscriptions sunset: {sunset_count}")
|
||||
logger.info(f"Already cancelled: {already_cancelled_count}")
|
||||
logger.info(f"Using current pricing: {current_pricing_count}")
|
||||
logger.info(f"Errors: {error_count}")
|
||||
|
||||
if args.dry_run:
|
||||
logger.info("\nThis was a dry run. No changes were made.")
|
||||
logger.info(f"Run without --dry-run to sunset {sunset_count} legacy subscriptions.")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,121 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Simple script to verify which subscriptions will be caught by the invoice webhook check.
|
||||
This shows which subscriptions have both cancel_at_period_end=True and cancellation_reason='billing_model_change'.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import stripe
|
||||
from datetime import datetime
|
||||
import logging
|
||||
|
||||
# Setup logging
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def main():
|
||||
# Get environment variables
|
||||
stripe_secret_key = os.getenv('STRIPE_SECRET_KEY')
|
||||
if not stripe_secret_key:
|
||||
logger.error("STRIPE_SECRET_KEY environment variable not set")
|
||||
sys.exit(1)
|
||||
|
||||
stripe.api_key = stripe_secret_key
|
||||
|
||||
logger.info("Checking for sunset legacy subscriptions...")
|
||||
|
||||
# Counters
|
||||
total_active = 0
|
||||
sunset_legacy = 0
|
||||
cancelling_other_reason = 0
|
||||
not_cancelling = 0
|
||||
|
||||
sunset_subscriptions = []
|
||||
|
||||
try:
|
||||
# Get all active subscriptions
|
||||
has_more = True
|
||||
starting_after = None
|
||||
|
||||
while has_more:
|
||||
params = {
|
||||
'status': 'active',
|
||||
'limit': 100,
|
||||
}
|
||||
if starting_after:
|
||||
params['starting_after'] = starting_after
|
||||
|
||||
subscriptions = stripe.Subscription.list(**params)
|
||||
|
||||
for sub in subscriptions.data:
|
||||
total_active += 1
|
||||
|
||||
cancel_at_period_end = sub.get('cancel_at_period_end', False)
|
||||
cancellation_reason = sub.get('metadata', {}).get('cancellation_reason')
|
||||
|
||||
# This is the exact check from the webhook handler
|
||||
if cancel_at_period_end and cancellation_reason == 'billing_model_change':
|
||||
sunset_legacy += 1
|
||||
|
||||
# Get customer email for display
|
||||
customer_email = 'unknown'
|
||||
try:
|
||||
customer = stripe.Customer.retrieve(sub.get('customer'))
|
||||
customer_email = customer.get('email', 'unknown')
|
||||
except:
|
||||
pass
|
||||
|
||||
# Calculate days until cancellation
|
||||
current_period_end_ts = sub.get('current_period_end')
|
||||
if current_period_end_ts:
|
||||
current_period_end = datetime.fromtimestamp(current_period_end_ts)
|
||||
days_until_cancel = (current_period_end - datetime.now()).days
|
||||
cancel_date = current_period_end.strftime('%Y-%m-%d')
|
||||
else:
|
||||
days_until_cancel = -1
|
||||
cancel_date = 'Unknown'
|
||||
|
||||
sunset_subscriptions.append(
|
||||
{
|
||||
'id': sub.get('id'),
|
||||
'customer': customer_email,
|
||||
'days_until_cancel': days_until_cancel,
|
||||
'cancel_date': cancel_date,
|
||||
}
|
||||
)
|
||||
|
||||
elif cancel_at_period_end:
|
||||
cancelling_other_reason += 1
|
||||
else:
|
||||
not_cancelling += 1
|
||||
|
||||
# Check if there are more pages
|
||||
has_more = subscriptions.has_more
|
||||
if has_more and subscriptions.data:
|
||||
starting_after = subscriptions.data[-1].get('id')
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error fetching subscriptions: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
# Display results
|
||||
logger.info("\n=== VERIFICATION RESULTS ===")
|
||||
logger.info(f"Total active subscriptions: {total_active}")
|
||||
logger.info(f"Sunset legacy (will skip usage charges): {sunset_legacy}")
|
||||
logger.info(f"Cancelling for other reasons: {cancelling_other_reason}")
|
||||
logger.info(f"Not cancelling: {not_cancelling}")
|
||||
|
||||
if sunset_subscriptions:
|
||||
logger.info("\n=== SUNSET SUBSCRIPTIONS (Usage charges will be skipped) ===")
|
||||
for sub in sorted(sunset_subscriptions, key=lambda x: x['days_until_cancel']):
|
||||
logger.info(
|
||||
f"- {sub['id']} | {sub['customer']} | Cancels in {sub['days_until_cancel']} days ({sub['cancel_date']})"
|
||||
)
|
||||
|
||||
logger.info("\n✅ These subscriptions will NOT receive usage charges on their final invoice.")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user