diff --git a/.env.example b/.env.example
new file mode 100644
index 0000000000000000000000000000000000000000..022ce6e381d1e4d72d5d0ef3f34048a0f49d22cc
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,21 @@
+# Server
+HOST_ADDRESS=0.0.0.0
+HOST_PORT=8080
+
+# Database (Supabase: use the Session pooler, port 5432)
+DB_HOST=
+DB_PORT=5432
+DB_USER=
+DB_PASSWORD=
+DB_NAME=postgres
+DB_SSLMODE=require
+DB_POOL_SIZE=20
+
+# Booking rules
+HOLD_TTL=10m
+SWEEP_INTERVAL=5s
+SWEEPER_ENABLED=true
+PAYMENT_TIMEOUT=2s
+MOCKPAY_LATENCY_MS=0
+IDEMPOTENCY_TTL=24h
+REQUEST_TIMEOUT=4s
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000000000000000000000000000000000000..dfdb8b771ce07609491fa2e83698969fd917a135
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1 @@
+*.sh text eol=lf
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 0000000000000000000000000000000000000000..d06f75ee23176d4a82d26200987264e3deddd617
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,11 @@
+version: 2
+updates:
+ - package-ecosystem: gomod
+ directory: /
+ schedule: { interval: weekly }
+ - package-ecosystem: github-actions
+ directory: /
+ schedule: { interval: weekly }
+ - package-ecosystem: docker
+ directory: /
+ schedule: { interval: weekly }
diff --git a/.github/workflows/ci-2.yml b/.github/workflows/ci-2.yml
new file mode 100644
index 0000000000000000000000000000000000000000..672b223885b0f33aaf64da916c2f3eda15fcf13e
--- /dev/null
+++ b/.github/workflows/ci-2.yml
@@ -0,0 +1,54 @@
+name: CI
+
+# Pull-request checks. Pushes to master run the full delivery pipeline
+# (pipeline.yml), which repeats these tests before deploying.
+on:
+ pull_request:
+
+concurrency:
+ group: ci-${{ github.ref }}
+ cancel-in-progress: true
+
+permissions:
+ contents: read
+
+jobs:
+ test:
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ services:
+ # Throwaway database for the integration tests; it exists only for this job.
+ postgres:
+ image: postgres:16
+ env:
+ POSTGRES_HOST_AUTH_METHOD: trust
+ POSTGRES_DB: booking_test
+ ports: ["5432:5432"]
+ options: >-
+ --health-cmd "pg_isready -U postgres" --health-interval 2s --health-retries 30
+ env:
+ # Integration tests skip when this is unset; it points them at the service above.
+ TEST_DATABASE_URL: host=localhost port=5432 user=postgres dbname=booking_test sslmode=disable
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-go@v5
+ with:
+ # Latest 1.26 patch release: an exact version from go.mod would miss
+ # standard-library security fixes and fail govulncheck.
+ go-version: "1.26"
+ check-latest: true
+
+ - name: Vet
+ run: go vet ./...
+
+ - name: Unit, seeder and integration tests
+ run: go test ./... -count=1
+
+ - name: Concurrency tests (20 repetitions)
+ run: go test ./tests/integration/... -run 'Concurrent|IdempotentConcurrent' -count=20
+
+ - name: Vulnerability check
+ run: go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 ./...
+
+ - name: Docker build
+ run: docker build -t event-booking-api:${{ github.sha }} .
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000000000000000000000000000000000000..d8aab87986e08b2c37e4796c30138aa64a134183
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,54 @@
+name: CI
+
+# Pull-request checks. Pushes to master run the full delivery pipeline
+# (pipeline.yml), which repeats these tests before deploying.
+on:
+ pull_request:
+
+concurrency:
+ group: ci-${{ github.ref }}
+ cancel-in-progress: true
+
+permissions:
+ contents: read
+
+jobs:
+ test:
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ services:
+ # Throwaway database for the integration tests; it exists only for this job.
+ postgres:
+ image: postgres:16
+ env:
+ POSTGRES_HOST_AUTH_METHOD: trust
+ POSTGRES_DB: booking_test
+ ports: ["5432:5432"]
+ options: >-
+ --health-cmd "pg_isready -U postgres" --health-interval 2s --health-retries 30
+ env:
+ # Integration tests skip when this is unset; it points them at the service above.
+ TEST_DATABASE_URL: host=localhost port=5432 user=postgres dbname=booking_test sslmode=disable
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-go@v5
+ with:
+ # Latest 1.26 patch release: an exact version from go.mod would miss
+ # standard-library security fixes and fail govulncheck.
+ go-version: "1.26"
+ check-latest: true
+
+ - name: Vet
+ run: go vet ./...
+
+ - name: Unit, seeder and integration tests
+ run: go test ./... -count=1
+
+ - name: Concurrency tests (20 repetitions)
+ run: go test ./tests/integration/... -run 'Concurrent|IdempotentConcurrent' -count=20
+
+ - name: Vulnerability check
+ run: go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 ./...
+
+ - name: Docker build
+ run: docker build -t event-booking-api:${{ github.sha }} .
diff --git a/.github/workflows/pipeline-2.yml b/.github/workflows/pipeline-2.yml
new file mode 100644
index 0000000000000000000000000000000000000000..b08f1328bf112a533895d2c9da621222e11c4999
--- /dev/null
+++ b/.github/workflows/pipeline-2.yml
@@ -0,0 +1,239 @@
+# Delivery pipeline (see the architecture diagram):
+# merge to master -> unit & integration tests -> dependency check
+# -> deploy to Hugging Face Space (QA) -> OpenAPI smoke test
+# -> BlazeMeter performance test -> report (BlazeMeter + Actions log)
+#
+# Required configuration, all on the "qa" environment:
+# secrets HF_TOKEN, QA_DB_HOST, QA_DB_PORT, QA_DB_USER, QA_DB_PASSWORD, QA_DB_NAME,
+# BLAZEMETER_API_KEY_ID, BLAZEMETER_API_KEY_SECRET
+# variables HF_SPACE (owner/space), QA_BASE_URL (https://owner-space.hf.space),
+# BLAZEMETER_TEST_ID, BLAZEMETER_SCENARIOS (optional, default "PT-01,PT-05")
+name: Pipeline
+
+on:
+ push:
+ branches: [master]
+ workflow_dispatch:
+ inputs:
+ scenarios:
+ description: Comma-separated performance scenarios (PT-01 ... PT-05)
+ default: PT-01,PT-05
+ required: true
+
+permissions:
+ contents: read
+
+# Explicit bash turns on -o pipefail, so "check | tee" still fails the step.
+defaults:
+ run:
+ shell: bash
+
+# One pipeline at a time: QA is a single shared environment. A newer push waits
+# instead of cancelling a deployment halfway.
+concurrency:
+ group: pipeline-qa
+ cancel-in-progress: false
+
+jobs:
+ unit-test:
+ name: Run Unit Test
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ services:
+ postgres:
+ image: postgres:16
+ env:
+ POSTGRES_HOST_AUTH_METHOD: trust
+ POSTGRES_DB: booking_test
+ ports: ["5432:5432"]
+ options: >-
+ --health-cmd "pg_isready -U postgres" --health-interval 2s --health-retries 30
+ env:
+ # Integration tests skip when this is unset; it points them at the service above.
+ TEST_DATABASE_URL: host=localhost port=5432 user=postgres dbname=booking_test sslmode=disable
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-go@v5
+ with:
+ go-version: "1.26"
+ check-latest: true
+ - run: go vet ./...
+ - name: Unit, seeder and integration tests
+ run: |
+ mkdir -p out
+ go run gotest.tools/gotestsum@v1.13.0 --junitfile out/integration.xml -- ./... -count=1
+ - name: Concurrency tests (20 repetitions)
+ run: go test ./tests/integration/... -run 'Concurrent|IdempotentConcurrent' -count=20
+ - if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: integration-report
+ path: out/integration.xml
+ if-no-files-found: ignore
+
+ dependency-check:
+ name: Run Dependabot
+ # Dependabot itself runs from .github/dependabot.yml and opens update PRs.
+ # This gate blocks a deploy when a dependency has a known, reachable vulnerability.
+ needs: unit-test
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-go@v5
+ with:
+ go-version: "1.26"
+ check-latest: true
+ - name: Verify module checksums
+ run: go mod verify
+ - name: Vulnerability scan
+ run: go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 ./...
+
+ deploy:
+ name: Deploy to HF
+ needs: dependency-check
+ runs-on: ubuntu-latest
+ timeout-minutes: 25
+ environment: qa
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.12"
+ - run: pip install --quiet "huggingface_hub>=0.25"
+ - name: Prepare Space contents
+ run: |
+ mkdir -p "$RUNNER_TEMP/space"
+ git archive HEAD | tar -x -C "$RUNNER_TEMP/space"
+ echo "$GITHUB_SHA" > "$RUNNER_TEMP/space/VERSION"
+ # Hugging Face reads the Space configuration from README front matter.
+ { printf -- '---\ntitle: Event Booking API\nsdk: docker\napp_port: 7860\npinned: false\n---\n\n'
+ cat README.md; } > "$RUNNER_TEMP/space/README.md"
+ - name: Configure secrets and push to Space
+ env:
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
+ HF_SPACE: ${{ vars.HF_SPACE }}
+ DB_HOST: ${{ secrets.QA_DB_HOST }}
+ DB_PORT: ${{ secrets.QA_DB_PORT }}
+ DB_USER: ${{ secrets.QA_DB_USER }}
+ DB_PASSWORD: ${{ secrets.QA_DB_PASSWORD }}
+ DB_NAME: ${{ secrets.QA_DB_NAME }}
+ run: python scripts/hf_deploy.py "$RUNNER_TEMP/space"
+ - name: Wait for the new version to go live
+ run: bash scripts/wait_for_version.sh "${{ vars.QA_BASE_URL }}" "$GITHUB_SHA" 900
+
+ smoke-test:
+ name: Run Smoke-test OpenAPI
+ needs: deploy
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ environment: qa
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-go@v5
+ with:
+ go-version: "1.26"
+ check-latest: true
+ # The container seeds the fixed dataset on startup (skipping if already
+ # seeded). Here we only derive its deterministic IDs; no database access.
+ - name: Export fixture IDs
+ run: go run ./cmd/seed -export out/smoke
+ - name: Smoke test against the OpenAPI document
+ run: bash scripts/smoke_test.sh "${{ vars.QA_BASE_URL }}" out/smoke
+ - if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: smoke-test
+ path: out/smoke/smoke-results.md
+ if-no-files-found: ignore
+
+ plan-performance:
+ name: Select performance scenarios
+ needs: smoke-test
+ runs-on: ubuntu-latest
+ outputs:
+ scenarios: ${{ steps.pick.outputs.scenarios }}
+ steps:
+ - id: pick
+ env:
+ REQUESTED: ${{ github.event.inputs.scenarios || vars.BLAZEMETER_SCENARIOS || 'PT-01,PT-05' }}
+ run: echo "scenarios=$(echo "$REQUESTED" | jq -Rc 'split(",") | map(gsub(" ";""))')" >> "$GITHUB_OUTPUT"
+
+ blazemeter:
+ name: Run Blazemeter Test (${{ matrix.scenario }})
+ needs: plan-performance
+ runs-on: ubuntu-latest
+ timeout-minutes: 60
+ environment: qa
+ strategy:
+ fail-fast: false
+ max-parallel: 1 # never load QA with two scenarios at once
+ matrix:
+ scenario: ${{ fromJson(needs.plan-performance.outputs.scenarios) }}
+ env:
+ SCENARIO: ${{ matrix.scenario }}
+ # Read-only use: the post-run correctness queries.
+ DB_HOST: ${{ secrets.QA_DB_HOST }}
+ DB_PORT: ${{ secrets.QA_DB_PORT }}
+ DB_USER: ${{ secrets.QA_DB_USER }}
+ DB_PASSWORD: ${{ secrets.QA_DB_PASSWORD }}
+ DB_NAME: ${{ secrets.QA_DB_NAME }}
+ DB_SSLMODE: require
+ OUT: out/perf/${{ matrix.scenario }}
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-go@v5
+ with:
+ go-version: "1.26"
+ check-latest: true
+ - name: Export fixture IDs
+ run: go run ./cmd/seed -export "$OUT/data"
+ - name: Wait for flash-sale stock to be released by the previous run
+ if: matrix.scenario == 'PT-05'
+ run: bash scripts/perf/wait_for_stock.sh "${{ vars.QA_BASE_URL }}" "$OUT/data/event.properties" flash 720
+ - name: Build BlazeMeter (Taurus) test files
+ run: bash scripts/perf/build_taurus.sh "$SCENARIO" "${{ vars.QA_BASE_URL }}" "$OUT/data" "$OUT/bzt"
+ - name: Run on BlazeMeter
+ id: bzm
+ env:
+ BLAZEMETER_API_KEY_ID: ${{ secrets.BLAZEMETER_API_KEY_ID }}
+ BLAZEMETER_API_KEY_SECRET: ${{ secrets.BLAZEMETER_API_KEY_SECRET }}
+ BLAZEMETER_TEST_ID: ${{ vars.BLAZEMETER_TEST_ID }}
+ run: bash scripts/perf/blazemeter_run.sh "$OUT/bzt" "$(jq -r --arg s "$SCENARIO" '.[$s].timeout_min' perf/scenarios.json)" "$OUT"
+ - name: Correctness checks on the QA database
+ if: always() && steps.bzm.outcome != 'skipped'
+ run: |
+ sleep 20 # let the sweeper release holds that expired at the end of the run
+ bash scripts/perf/correctness.sh "$SCENARIO" "$OUT/data/event.properties" | tee "$OUT/correctness.txt"
+ - name: Check thresholds
+ if: always() && steps.bzm.outcome == 'success'
+ run: python scripts/perf/check_thresholds.py "$SCENARIO" "$OUT/aggregate.json" perf/thresholds.json | tee -a "$GITHUB_STEP_SUMMARY"
+ - if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: blazemeter-${{ matrix.scenario }}
+ path: |
+ ${{ env.OUT }}/*.json
+ ${{ env.OUT }}/*.txt
+ if-no-files-found: ignore
+
+ report:
+ name: Report
+ needs: [unit-test, dependency-check, deploy, smoke-test, blazemeter]
+ if: always()
+ runs-on: ubuntu-latest
+ steps:
+ - name: Pipeline summary
+ env:
+ RESULTS: ${{ toJson(needs) }}
+ run: |
+ {
+ echo "## Pipeline result for \`${GITHUB_SHA::7}\`"
+ echo
+ echo "| Stage | Result |"
+ echo "| --- | --- |"
+ echo "$RESULTS" | jq -r 'to_entries[] | "| \(.key) | \(.value.result) |"'
+ echo
+ echo "BlazeMeter report links and threshold tables are in each **Run Blazemeter Test** job summary and artifact."
+ } >> "$GITHUB_STEP_SUMMARY"
+ echo "$RESULTS" | jq -e 'all(.[]; .result == "success")' > /dev/null
diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml
new file mode 100644
index 0000000000000000000000000000000000000000..b08f1328bf112a533895d2c9da621222e11c4999
--- /dev/null
+++ b/.github/workflows/pipeline.yml
@@ -0,0 +1,239 @@
+# Delivery pipeline (see the architecture diagram):
+# merge to master -> unit & integration tests -> dependency check
+# -> deploy to Hugging Face Space (QA) -> OpenAPI smoke test
+# -> BlazeMeter performance test -> report (BlazeMeter + Actions log)
+#
+# Required configuration, all on the "qa" environment:
+# secrets HF_TOKEN, QA_DB_HOST, QA_DB_PORT, QA_DB_USER, QA_DB_PASSWORD, QA_DB_NAME,
+# BLAZEMETER_API_KEY_ID, BLAZEMETER_API_KEY_SECRET
+# variables HF_SPACE (owner/space), QA_BASE_URL (https://owner-space.hf.space),
+# BLAZEMETER_TEST_ID, BLAZEMETER_SCENARIOS (optional, default "PT-01,PT-05")
+name: Pipeline
+
+on:
+ push:
+ branches: [master]
+ workflow_dispatch:
+ inputs:
+ scenarios:
+ description: Comma-separated performance scenarios (PT-01 ... PT-05)
+ default: PT-01,PT-05
+ required: true
+
+permissions:
+ contents: read
+
+# Explicit bash turns on -o pipefail, so "check | tee" still fails the step.
+defaults:
+ run:
+ shell: bash
+
+# One pipeline at a time: QA is a single shared environment. A newer push waits
+# instead of cancelling a deployment halfway.
+concurrency:
+ group: pipeline-qa
+ cancel-in-progress: false
+
+jobs:
+ unit-test:
+ name: Run Unit Test
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ services:
+ postgres:
+ image: postgres:16
+ env:
+ POSTGRES_HOST_AUTH_METHOD: trust
+ POSTGRES_DB: booking_test
+ ports: ["5432:5432"]
+ options: >-
+ --health-cmd "pg_isready -U postgres" --health-interval 2s --health-retries 30
+ env:
+ # Integration tests skip when this is unset; it points them at the service above.
+ TEST_DATABASE_URL: host=localhost port=5432 user=postgres dbname=booking_test sslmode=disable
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-go@v5
+ with:
+ go-version: "1.26"
+ check-latest: true
+ - run: go vet ./...
+ - name: Unit, seeder and integration tests
+ run: |
+ mkdir -p out
+ go run gotest.tools/gotestsum@v1.13.0 --junitfile out/integration.xml -- ./... -count=1
+ - name: Concurrency tests (20 repetitions)
+ run: go test ./tests/integration/... -run 'Concurrent|IdempotentConcurrent' -count=20
+ - if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: integration-report
+ path: out/integration.xml
+ if-no-files-found: ignore
+
+ dependency-check:
+ name: Run Dependabot
+ # Dependabot itself runs from .github/dependabot.yml and opens update PRs.
+ # This gate blocks a deploy when a dependency has a known, reachable vulnerability.
+ needs: unit-test
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-go@v5
+ with:
+ go-version: "1.26"
+ check-latest: true
+ - name: Verify module checksums
+ run: go mod verify
+ - name: Vulnerability scan
+ run: go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 ./...
+
+ deploy:
+ name: Deploy to HF
+ needs: dependency-check
+ runs-on: ubuntu-latest
+ timeout-minutes: 25
+ environment: qa
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.12"
+ - run: pip install --quiet "huggingface_hub>=0.25"
+ - name: Prepare Space contents
+ run: |
+ mkdir -p "$RUNNER_TEMP/space"
+ git archive HEAD | tar -x -C "$RUNNER_TEMP/space"
+ echo "$GITHUB_SHA" > "$RUNNER_TEMP/space/VERSION"
+ # Hugging Face reads the Space configuration from README front matter.
+ { printf -- '---\ntitle: Event Booking API\nsdk: docker\napp_port: 7860\npinned: false\n---\n\n'
+ cat README.md; } > "$RUNNER_TEMP/space/README.md"
+ - name: Configure secrets and push to Space
+ env:
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
+ HF_SPACE: ${{ vars.HF_SPACE }}
+ DB_HOST: ${{ secrets.QA_DB_HOST }}
+ DB_PORT: ${{ secrets.QA_DB_PORT }}
+ DB_USER: ${{ secrets.QA_DB_USER }}
+ DB_PASSWORD: ${{ secrets.QA_DB_PASSWORD }}
+ DB_NAME: ${{ secrets.QA_DB_NAME }}
+ run: python scripts/hf_deploy.py "$RUNNER_TEMP/space"
+ - name: Wait for the new version to go live
+ run: bash scripts/wait_for_version.sh "${{ vars.QA_BASE_URL }}" "$GITHUB_SHA" 900
+
+ smoke-test:
+ name: Run Smoke-test OpenAPI
+ needs: deploy
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ environment: qa
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-go@v5
+ with:
+ go-version: "1.26"
+ check-latest: true
+ # The container seeds the fixed dataset on startup (skipping if already
+ # seeded). Here we only derive its deterministic IDs; no database access.
+ - name: Export fixture IDs
+ run: go run ./cmd/seed -export out/smoke
+ - name: Smoke test against the OpenAPI document
+ run: bash scripts/smoke_test.sh "${{ vars.QA_BASE_URL }}" out/smoke
+ - if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: smoke-test
+ path: out/smoke/smoke-results.md
+ if-no-files-found: ignore
+
+ plan-performance:
+ name: Select performance scenarios
+ needs: smoke-test
+ runs-on: ubuntu-latest
+ outputs:
+ scenarios: ${{ steps.pick.outputs.scenarios }}
+ steps:
+ - id: pick
+ env:
+ REQUESTED: ${{ github.event.inputs.scenarios || vars.BLAZEMETER_SCENARIOS || 'PT-01,PT-05' }}
+ run: echo "scenarios=$(echo "$REQUESTED" | jq -Rc 'split(",") | map(gsub(" ";""))')" >> "$GITHUB_OUTPUT"
+
+ blazemeter:
+ name: Run Blazemeter Test (${{ matrix.scenario }})
+ needs: plan-performance
+ runs-on: ubuntu-latest
+ timeout-minutes: 60
+ environment: qa
+ strategy:
+ fail-fast: false
+ max-parallel: 1 # never load QA with two scenarios at once
+ matrix:
+ scenario: ${{ fromJson(needs.plan-performance.outputs.scenarios) }}
+ env:
+ SCENARIO: ${{ matrix.scenario }}
+ # Read-only use: the post-run correctness queries.
+ DB_HOST: ${{ secrets.QA_DB_HOST }}
+ DB_PORT: ${{ secrets.QA_DB_PORT }}
+ DB_USER: ${{ secrets.QA_DB_USER }}
+ DB_PASSWORD: ${{ secrets.QA_DB_PASSWORD }}
+ DB_NAME: ${{ secrets.QA_DB_NAME }}
+ DB_SSLMODE: require
+ OUT: out/perf/${{ matrix.scenario }}
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-go@v5
+ with:
+ go-version: "1.26"
+ check-latest: true
+ - name: Export fixture IDs
+ run: go run ./cmd/seed -export "$OUT/data"
+ - name: Wait for flash-sale stock to be released by the previous run
+ if: matrix.scenario == 'PT-05'
+ run: bash scripts/perf/wait_for_stock.sh "${{ vars.QA_BASE_URL }}" "$OUT/data/event.properties" flash 720
+ - name: Build BlazeMeter (Taurus) test files
+ run: bash scripts/perf/build_taurus.sh "$SCENARIO" "${{ vars.QA_BASE_URL }}" "$OUT/data" "$OUT/bzt"
+ - name: Run on BlazeMeter
+ id: bzm
+ env:
+ BLAZEMETER_API_KEY_ID: ${{ secrets.BLAZEMETER_API_KEY_ID }}
+ BLAZEMETER_API_KEY_SECRET: ${{ secrets.BLAZEMETER_API_KEY_SECRET }}
+ BLAZEMETER_TEST_ID: ${{ vars.BLAZEMETER_TEST_ID }}
+ run: bash scripts/perf/blazemeter_run.sh "$OUT/bzt" "$(jq -r --arg s "$SCENARIO" '.[$s].timeout_min' perf/scenarios.json)" "$OUT"
+ - name: Correctness checks on the QA database
+ if: always() && steps.bzm.outcome != 'skipped'
+ run: |
+ sleep 20 # let the sweeper release holds that expired at the end of the run
+ bash scripts/perf/correctness.sh "$SCENARIO" "$OUT/data/event.properties" | tee "$OUT/correctness.txt"
+ - name: Check thresholds
+ if: always() && steps.bzm.outcome == 'success'
+ run: python scripts/perf/check_thresholds.py "$SCENARIO" "$OUT/aggregate.json" perf/thresholds.json | tee -a "$GITHUB_STEP_SUMMARY"
+ - if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: blazemeter-${{ matrix.scenario }}
+ path: |
+ ${{ env.OUT }}/*.json
+ ${{ env.OUT }}/*.txt
+ if-no-files-found: ignore
+
+ report:
+ name: Report
+ needs: [unit-test, dependency-check, deploy, smoke-test, blazemeter]
+ if: always()
+ runs-on: ubuntu-latest
+ steps:
+ - name: Pipeline summary
+ env:
+ RESULTS: ${{ toJson(needs) }}
+ run: |
+ {
+ echo "## Pipeline result for \`${GITHUB_SHA::7}\`"
+ echo
+ echo "| Stage | Result |"
+ echo "| --- | --- |"
+ echo "$RESULTS" | jq -r 'to_entries[] | "| \(.key) | \(.value.result) |"'
+ echo
+ echo "BlazeMeter report links and threshold tables are in each **Run Blazemeter Test** job summary and artifact."
+ } >> "$GITHUB_STEP_SUMMARY"
+ echo "$RESULTS" | jq -e 'all(.[]; .result == "success")' > /dev/null
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..d11f1fad5717cbcd0221183a96e20c251e570c3e
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,8 @@
+*.env
+.env
+*.exe
+*.log
+vendor/
+out/
+perf/data/
+__pycache__/
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..c6535ccd7c8fa0196034d6734a62e13661b83edc
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,44 @@
+# =====================
+# BUILD STAGE
+# =====================
+FROM golang:1.26 AS builder
+
+WORKDIR /app
+
+COPY go.mod go.sum ./
+RUN go mod download
+
+COPY . .
+# VERSION is written by the deploy job (the commit SHA); /health reports it.
+RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \
+ -ldflags "-X abdanhafidz.com/event-booking-api/router.Version=$(cat VERSION 2>/dev/null || echo dev)" \
+ -o app . \
+ && CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o seed ./cmd/seed
+
+# =====================
+# RUNTIME STAGE
+# =====================
+# Alpine rather than distroless: the entrypoint is a shell script.
+FROM alpine:3.20
+
+RUN apk add --no-cache ca-certificates tzdata \
+ && adduser -D -u 1000 app
+
+WORKDIR /app
+
+COPY --from=builder /app/app /app/seed /app/
+COPY entrypoint.sh /app/entrypoint.sh
+RUN chmod +x /app/entrypoint.sh
+
+# Hugging Face Spaces routes traffic to 7860 by default.
+ENV HOST_ADDRESS=0.0.0.0 \
+ HOST_PORT=7860 \
+ GIN_MODE=release \
+ SEED_ON_STARTUP=true
+
+# Non-root user (uid 1000, as Hugging Face Spaces expects)
+USER app
+
+EXPOSE 7860
+
+ENTRYPOINT ["/app/entrypoint.sh"]
diff --git a/README.md b/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..8630a46a52adadf1995d0682e145e68588a60946
--- /dev/null
+++ b/README.md
@@ -0,0 +1,152 @@
+---
+title: Event Booking API
+sdk: docker
+app_port: 7860
+pinned: false
+---
+
+# Event Ticket Booking API
+
+A deliberately small REST API built to be tested: it must never oversell a
+limited stock of tickets, never take two payments for one booking, and release
+abandoned holds on time. Built on the
+[go-clean-layered-architecture](https://github.com/abdanhafidz/go-clean-layered-architecture)
+starter (Gin, GORM, PostgreSQL, provider-based DI).
+
+The PRD, test plan and RFC live in the project log:
+`logs.abdanhafidz.com/projects/event-booking-api`.
+
+## Endpoints
+
+| Method and path | Success | Notes |
+| --- | --- | --- |
+| `GET /health` | `200` | Database ping and build version |
+| `GET /v1/events/{id}` | `200` | Ticket types with live `available` |
+| `POST /v1/bookings` | `201` | Needs `X-User-Id` and `Idempotency-Key` |
+| `GET /v1/bookings/{id}` | `200` | Own bookings only |
+| `POST /v1/bookings/{id}/pay` | `200` | Needs `Idempotency-Key`; token `tok_success`, `tok_decline` or `tok_timeout` |
+| `POST /v1/bookings/{id}/cancel` | `200` | Pending or confirmed, before the event starts |
+| `GET /swagger/index.html` | `200` | OpenAPI UI; the document is at `/swagger/doc.json` |
+
+Responses use the starter's envelope:
+
+```json
+{ "status": "success", "data": { "id": "…", "status": "PENDING_PAYMENT" }, "message": "…", "meta_data": null }
+{ "status": "error", "code": "INSUFFICIENT_TICKETS", "errors": { "available": 3 }, "message": "…", "meta_data": null }
+```
+
+## Run locally
+
+```bash
+cp .env.example .env # fill in the database settings
+go run ./cmd/seed # load the fixed dataset; skips if already seeded
+go run .
+```
+
+## Test data
+
+The container runs `entrypoint.sh` on startup: `seed`, then the API. The
+seeder loads one fixed dataset (10,000 users and three fixture events) and
+records a version marker in `seed_markers`. If that version is already there,
+it logs "already seeded" and skips, so restarts and redeploys never reseed.
+Two containers starting together are serialised by an advisory lock. Set
+`SEED_ON_STARTUP=false` to skip seeding entirely.
+
+| Fixture | Stock | Why it never needs re-seeding |
+| --- | --- | --- |
+| `load` | 5 × 1,000,000 | PT-01 to PT-04 use a few thousand tickets per run |
+| `flash` | 500 | PT-05 never pays; the sweeper returns the stock when its holds expire, and the pipeline waits for that |
+| `smoke` | 5 | The smoke test cancels or fails everything it books |
+
+All IDs are deterministic (UUIDv5), so `go run ./cmd/seed -export DIR` writes
+`users.csv` and `event.properties` for JMeter and the smoke test without
+touching the database. Change `DatasetVersion` in `cmd/seed/fixtures.go` when
+the fixtures change.
+
+With Docker: `docker compose up --build` starts PostgreSQL and the API on
+`localhost:8080`.
+
+## Tests
+
+```bash
+go test ./config/... ./services/... # unit
+export TEST_DATABASE_URL="host=localhost port=5432 user=postgres password=postgres dbname=booking_test sslmode=disable"
+go test ./tests/integration/... -count=1 -v # integration (27 cases)
+go test ./tests/integration/... -run Concurrent -count=20
+```
+
+Integration tests run the API in-process against a real PostgreSQL. Each test
+creates its own event and users, and after every test the harness checks the
+inventory invariant `capacity = available + tickets held by active bookings`.
+Point `TEST_DATABASE_URL` at a dedicated test database, never at the QA or
+production database.
+
+## How correctness is enforced
+
+| Risk | Mechanism |
+| --- | --- |
+| Overselling | `UPDATE ticket_types SET available = available - q WHERE id = ? AND available >= q`, plus `CHECK (available BETWEEN 0 AND capacity)` |
+| Double payment | Booking row locked `FOR UPDATE` during payment; partial unique index on successful payments |
+| Duplicate requests | `idempotency_keys` row claimed as the first statement of the transaction; duplicates wait on it and replay the stored outcome |
+| Abandoned holds | Sweeper every 5 s with `FOR UPDATE SKIP LOCKED`; payment also checks the hold itself |
+
+## Configuration
+
+See `.env.example`. The values that tests change are `HOLD_TTL`,
+`SWEEP_INTERVAL`, `SWEEPER_ENABLED`, `PAYMENT_TIMEOUT`, `MOCKPAY_LATENCY_MS` and
+`IDEMPOTENCY_TTL`. For Supabase use the Session pooler (port 5432) with
+`DB_SSLMODE=require`.
+
+## Delivery pipeline
+
+`.github/workflows/pipeline.yml` runs on every push to `master`:
+
+```
+Run Unit Test -> Run Dependabot -> Deploy to HF -> Run Smoke-test OpenAPI -> Run Blazemeter Test -> Report
+```
+
+| Job | What it does | Fails when |
+| --- | --- | --- |
+| Run Unit Test | Unit tests, 27 integration tests on a PostgreSQL service container, concurrency tests ×20 | Any test fails |
+| Run Dependabot | `go mod verify` and `govulncheck`. Dependabot itself opens update PRs from `.github/dependabot.yml` | A reachable known vulnerability |
+| Deploy to HF | Copies the `QA_DB_*` secrets into the Space, uploads the repo, waits until `/health` reports this commit | Build or health check times out (15 min) |
+| Run Smoke-test OpenAPI | Every path in `/swagger/doc.json` is routed; book, replay, pay, decline, sold out, cancel | Any check fails |
+| Run Blazemeter Test | Exports fixture IDs, waits for flash stock (PT-05), uploads JMX, users and Taurus config, runs the scenario, then runs read-only correctness queries on the QA database | Correctness check, strict gate, or (after calibration) a target |
+| Report | Stage table in the run summary | Any stage did not succeed |
+
+Pull requests run `ci.yml` instead (tests only, no deploy).
+
+**One-time setup**, all on a GitHub environment named `qa`:
+
+| Name | Kind | Value |
+| --- | --- | --- |
+| `HF_TOKEN` | secret | Hugging Face token with write access to the Space |
+| `QA_DB_HOST`, `QA_DB_PORT`, `QA_DB_USER`, `QA_DB_PASSWORD`, `QA_DB_NAME` | secret | Supabase session pooler settings |
+| `BLAZEMETER_API_KEY_ID`, `BLAZEMETER_API_KEY_SECRET` | secret | BlazeMeter API key |
+| `HF_SPACE` | variable | `owner/space-name` (a Docker Space) |
+| `QA_BASE_URL` | variable | `https://owner-space-name.hf.space` |
+| `BLAZEMETER_TEST_ID` | variable | ID of the BlazeMeter test (below) |
+| `BLAZEMETER_SCENARIOS` | variable, optional | Scenarios on push; default `PT-01,PT-05` |
+
+In BlazeMeter, create one performance test of type **Taurus** with main file
+`bzt-test.yml`. Generate the three files once with
+`scripts/perf/build_taurus.sh` and upload them; every run then replaces them.
+Scenarios PT-02 to PT-04 are long and are meant for **Run workflow** with the
+`scenarios` input rather than every push.
+
+Run a scenario locally with JMeter:
+
+```bash
+go run ./cmd/seed && go run ./cmd/seed -export perf/data
+jmeter -n -t perf/jmeter/booking.jmx -q perf/data/event.properties -Jusers_csv=perf/data/users.csv \
+ -Jhost=localhost -Jport=8080 -Jbuyers=1 -Jbuyer_loops=50 -Jthink_min_ms=0 -Jthink_range_ms=0 \
+ -l out/results.jtl -e -o out/report
+python scripts/perf/check_thresholds.py PT-01 out/report/statistics.json perf/thresholds.json
+```
+
+## Deployment
+
+The image listens on `7860`, the Hugging Face Spaces default. Set the `DB_*`
+variables as Space secrets. A `VERSION` file in the build context (the commit
+SHA) is baked into `/health`, so a pipeline can wait for the new build to go
+live before smoke testing.
diff --git a/VERSION b/VERSION
new file mode 100644
index 0000000000000000000000000000000000000000..ae332994a4e327a512049e72b4f7c96db43f5736
--- /dev/null
+++ b/VERSION
@@ -0,0 +1 @@
+4b73e190ab6513c1f3f928a165cbc38343890994
diff --git a/cmd/compile_swagger.ps1 b/cmd/compile_swagger.ps1
new file mode 100644
index 0000000000000000000000000000000000000000..d7c4d137def8e8833fabfda7ea34a75e0d413ae8
--- /dev/null
+++ b/cmd/compile_swagger.ps1
@@ -0,0 +1 @@
+swag init -g swagger/swagger_info.go -o swagger/docs --parseDependency --parseInternal
\ No newline at end of file
diff --git a/cmd/do_inject_config.ps1 b/cmd/do_inject_config.ps1
new file mode 100644
index 0000000000000000000000000000000000000000..4d5b5e704da73e33f715f9168744c96109cbc50b
--- /dev/null
+++ b/cmd/do_inject_config.ps1
@@ -0,0 +1,435 @@
+#Requires -Version 5.1
+<#
+.SYNOPSIS
+ Automatic Dependency Injection Generator for Go Configuration
+
+.DESCRIPTION
+ Scans ./config/ directory, discovers all config constructors, infers their dependencies,
+ and generates provider/config_provider.go with full DI wiring. Special handling for
+ chained dependencies where configs depend on other configs (e.g., DatabaseConfig depends on EnvConfig).
+
+.EXAMPLE
+ .\config_injector.ps1
+
+.NOTES
+ - Works with PowerShell 5.1+ and PowerShell 7+
+ - No external dependencies required
+ - Supports multi-line constructor signatures
+ - Handles config-to-config dependencies with topological sorting
+ - Special handling for method calls like envConfig.GetDatabaseHost()
+#>
+
+[CmdletBinding()]
+param()
+
+# Configuration
+$ConfigDir = "./config"
+$OutputFile = "provider/config_provider.go"
+$ModulePath = "abdanhafidz.com/event-booking-api/config"
+
+# ANSI colors for better output
+$script:UseColors = $Host.UI.SupportsVirtualTerminal
+function Write-ColorOutput {
+ param([string]$Message, [string]$Color = "White")
+ if ($script:UseColors) {
+ $colors = @{
+ "Green" = "`e[32m"; "Yellow" = "`e[33m"; "Red" = "`e[31m"
+ "Cyan" = "`e[36m"; "Blue" = "`e[34m"; "Reset" = "`e[0m"
+ }
+ Write-Host "$($colors[$Color])$Message$($colors['Reset'])"
+ } else {
+ Write-Host $Message
+ }
+}
+
+# Data structures
+class ConfigInfo {
+ [string]$ConstructorName # NewDatabaseConfig
+ [string]$Domain # DatabaseConfig
+ [string]$VarName # databaseConfig
+ [System.Collections.Generic.List[Parameter]]$Parameters
+ [System.Collections.Generic.List[string]]$ConfigDependencies
+
+ ConfigInfo() {
+ $this.Parameters = [System.Collections.Generic.List[Parameter]]::new()
+ $this.ConfigDependencies = [System.Collections.Generic.List[string]]::new()
+ }
+}
+
+class Parameter {
+ [string]$Name
+ [string]$RawType
+ [string]$NormalizedType
+}
+
+function Get-LowerCamelCase {
+ param([string]$Text)
+ if ($Text.Length -eq 0) { return $Text }
+ return $Text.Substring(0, 1).ToLower() + $Text.Substring(1)
+}
+
+function Normalize-TypeName {
+ param([string]$TypeStr)
+
+ # Remove leading pointer
+ $cleaned = $TypeStr -replace '^\*+', ''
+
+ # Remove package prefix (everything before last dot)
+ if ($cleaned -match '\.([^.]+)$') {
+ $cleaned = $matches[1]
+ }
+
+ return $cleaned.Trim()
+}
+
+function Parse-GoFiles {
+ param([string]$Directory)
+
+ Write-ColorOutput "Scanning for config constructors in $Directory..." "Cyan"
+
+ if (-not (Test-Path $Directory)) {
+ Write-ColorOutput "ERROR: Directory '$Directory' not found!" "Red"
+ exit 1
+ }
+
+ $goFiles = Get-ChildItem -Path $Directory -Filter "*.go" -Recurse -File
+ $configs = [System.Collections.Generic.List[ConfigInfo]]::new()
+
+ foreach ($file in $goFiles) {
+ $content = Get-Content $file.FullName -Raw
+
+ # Match function signatures (support multi-line)
+ # Pattern: func NewXxxConfig(...) XxxConfig
+ $pattern = '(?ms)func\s+(New[a-zA-Z0-9]+Config)\s*\(([^)]*)\)\s+([a-zA-Z0-9*_.]+Config)'
+ $matches = [regex]::Matches($content, $pattern)
+
+ foreach ($match in $matches) {
+ $constructorName = $match.Groups[1].Value
+ $paramsStr = $match.Groups[2].Value
+ $returnType = $match.Groups[3].Value
+
+ # Extract domain name (XxxConfig)
+ $domain = Normalize-TypeName $returnType
+ $varName = Get-LowerCamelCase $domain
+
+ $config = [ConfigInfo]::new()
+ $config.ConstructorName = $constructorName
+ $config.Domain = $domain
+ $config.VarName = $varName
+
+ # Parse parameters
+ if ($paramsStr.Trim() -ne "") {
+ # Split by comma, but be careful with nested types
+ $paramList = $paramsStr -split ',\s*(?![^<>]*>)'
+
+ foreach ($param in $paramList) {
+ $param = $param.Trim()
+ if ($param -eq "") { continue }
+
+ # Split into name and type
+ $parts = $param -split '\s+', 2
+
+ $p = [Parameter]::new()
+ if ($parts.Count -eq 2) {
+ $p.Name = $parts[0]
+ $p.RawType = $parts[1]
+ } elseif ($parts.Count -eq 1) {
+ # Anonymous parameter - synthesize name
+ $p.Name = "param$($config.Parameters.Count)"
+ $p.RawType = $parts[0]
+ } else {
+ continue
+ }
+
+ $p.NormalizedType = Normalize-TypeName $p.RawType
+ $config.Parameters.Add($p)
+
+ # Track config dependencies (configs that depend on other configs)
+ if ($p.NormalizedType -match 'Config$') {
+ $config.ConfigDependencies.Add($p.NormalizedType)
+ }
+ }
+ }
+
+ $configs.Add($config)
+ Write-ColorOutput " Found: $constructorName" "Green"
+ }
+ }
+
+ if ($configs.Count -eq 0) {
+ Write-ColorOutput "No config constructors found matching pattern 'NewXxxConfig'!" "Red"
+ exit 1
+ }
+
+ Write-ColorOutput "`nTotal configs discovered: $($configs.Count)" "Blue"
+ return $configs
+}
+
+function Get-TopologicalOrder {
+ param([System.Collections.Generic.List[ConfigInfo]]$Configs)
+
+ Write-ColorOutput "`nBuilding dependency graph..." "Cyan"
+
+ # Build adjacency list
+ $graph = @{}
+ $inDegree = @{}
+ $domainToConfig = @{}
+
+ foreach ($cfg in $Configs) {
+ $graph[$cfg.Domain] = [System.Collections.Generic.List[string]]::new()
+ $inDegree[$cfg.Domain] = 0
+ $domainToConfig[$cfg.Domain] = $cfg
+ }
+
+ # Build edges (dependencies)
+ foreach ($cfg in $Configs) {
+ foreach ($dep in $cfg.ConfigDependencies) {
+ if ($graph.ContainsKey($dep)) {
+ $graph[$dep].Add($cfg.Domain)
+ $inDegree[$cfg.Domain]++
+ }
+ }
+ }
+
+ # Kahn's algorithm for topological sort
+ $queue = [System.Collections.Generic.Queue[string]]::new()
+ foreach ($domain in $inDegree.Keys) {
+ if ($inDegree[$domain] -eq 0) {
+ $queue.Enqueue($domain)
+ }
+ }
+
+ $sorted = [System.Collections.Generic.List[string]]::new()
+
+ while ($queue.Count -gt 0) {
+ $current = $queue.Dequeue()
+ $sorted.Add($current)
+
+ foreach ($neighbor in $graph[$current]) {
+ $inDegree[$neighbor]--
+ if ($inDegree[$neighbor] -eq 0) {
+ $queue.Enqueue($neighbor)
+ }
+ }
+ }
+
+ # Check for cycles
+ if ($sorted.Count -ne $Configs.Count) {
+ $remaining = $inDegree.Keys | Where-Object { $inDegree[$_] -gt 0 }
+ Write-ColorOutput "`nERROR: Circular dependency detected in configs!" "Red"
+ Write-ColorOutput "Configs involved in cycle: $($remaining -join ', ')" "Yellow"
+ exit 1
+ }
+
+ Write-ColorOutput " Dependency graph validated (no cycles)" "Green"
+ Write-ColorOutput " Topological order: $($sorted -join ' -> ')" "Blue"
+
+ # Return configs in topological order
+ return $sorted | ForEach-Object { $domainToConfig[$_] }
+}
+
+function Resolve-ConfigArgument {
+ param(
+ [Parameter]$Param,
+ [string]$DependentConfigVar
+ )
+
+ $type = $Param.NormalizedType
+ $paramName = $Param.Name
+
+ # SPECIAL CASE MAPPINGS FOR CONFIG
+ # ============================================
+
+ # 1. Config pattern: XxxConfig -> already instantiated config variable
+ if ($type -match '^(.+)Config$') {
+ $configVarName = Get-LowerCamelCase $type
+ return $configVarName
+ }
+
+ # 2. String parameters - try to infer from parameter name and match with config getter methods
+ if ($type -eq "string") {
+ # Common patterns for EnvConfig getters
+ $getterMappings = @{
+ "host" = "GetDatabaseHost()"
+ "databaseHost" = "GetDatabaseHost()"
+ "user" = "GetDatabaseUser()"
+ "databaseUser" = "GetDatabaseUser()"
+ "password" = "GetDatabasePassword()"
+ "databasePassword" = "GetDatabasePassword()"
+ "name" = "GetDatabaseName()"
+ "databaseName" = "GetDatabaseName()"
+ "dbName" = "GetDatabaseName()"
+ "port" = "GetDatabasePort()"
+ "databasePort" = "GetDatabasePort()"
+ "salt" = "GetSalt()"
+ "secret" = "GetSecretKey()"
+ "secretKey" = "GetSecretKey()"
+ "jwtSecret" = "GetSecretKey()"
+ "apiKey" = "GetAPIKey()"
+ "timezone" = "GetTimezone()"
+ }
+
+ # Try to find matching getter
+ foreach ($key in $getterMappings.Keys) {
+ if ($paramName -like "*$key*") {
+ return "envConfig.$($getterMappings[$key])"
+ }
+ }
+
+ # If dependent on a config, try to construct getter name from param name
+ if ($DependentConfigVar) {
+ # Convert paramName to PascalCase for getter
+ $getterName = (Get-Culture).TextInfo.ToTitleCase($paramName)
+ $getterName = $getterName -replace '\s', ''
+ return "${DependentConfigVar}.Get${getterName}()"
+ }
+ }
+
+ # 3. Int/port parameters
+ if ($type -eq "int" -or $type -eq "int32" -or $type -eq "int64") {
+ if ($paramName -match "port") {
+ return "envConfig.GetDatabasePort()"
+ }
+ }
+
+ # ADD MORE SPECIAL CASES HERE:
+ # --------------------------------------------
+ # Example: Redis config
+ # if ($paramName -match "redis") {
+ # return "envConfig.GetRedisURL()"
+ # }
+ #
+ # Example: Mail config
+ # if ($paramName -match "smtp") {
+ # return "envConfig.GetSMTPHost()"
+ # }
+ # --------------------------------------------
+
+ # 4. Hardcoded constants (timezone example)
+ if ($type -eq "string" -and $paramName -match "timezone|location") {
+ return "`"Asia/Jakarta`""
+ }
+
+ # 5. Fallback: unresolved type
+ return "/* TODO: provide $($Param.RawType) for $paramName */"
+}
+
+function Generate-ProviderCode {
+ param([System.Collections.Generic.List[ConfigInfo]]$ConfigsInOrder)
+
+ Write-ColorOutput "`nGenerating config provider code..." "Cyan"
+
+ $sb = [System.Text.StringBuilder]::new()
+ [void]$sb.AppendLine("package provider")
+ [void]$sb.AppendLine()
+ [void]$sb.AppendLine("import `"$ModulePath`"")
+ [void]$sb.AppendLine()
+
+ # Interface
+ [void]$sb.AppendLine("type ConfigProvider interface {")
+ foreach ($cfg in $ConfigsInOrder) {
+ $line = "`tProvide$($cfg.Domain)() config.$($cfg.Domain)"
+ [void]$sb.AppendLine($line)
+ }
+ [void]$sb.AppendLine("}")
+ [void]$sb.AppendLine()
+
+ # Struct
+ [void]$sb.AppendLine("type configProvider struct {")
+ foreach ($cfg in $ConfigsInOrder) {
+ $line = "`t$($cfg.VarName) config.$($cfg.Domain)"
+ [void]$sb.AppendLine($line)
+ }
+ [void]$sb.AppendLine("}")
+ [void]$sb.AppendLine()
+
+ # Constructor
+ [void]$sb.AppendLine("func NewConfigProvider() ConfigProvider {")
+
+ # Initialize configs in topological order
+ foreach ($cfg in $ConfigsInOrder) {
+ # Check if this config depends on another config
+ $dependentConfigVar = $null
+ if ($cfg.ConfigDependencies.Count -gt 0) {
+ $dependentConfigVar = Get-LowerCamelCase $cfg.ConfigDependencies[0]
+ }
+
+ $args = @()
+ foreach ($param in $cfg.Parameters) {
+ $args += Resolve-ConfigArgument -Param $param -DependentConfigVar $dependentConfigVar
+ }
+ $argsStr = $args -join ", "
+ $line = "`t$($cfg.VarName) := config.$($cfg.ConstructorName)($argsStr)"
+ [void]$sb.AppendLine($line)
+ }
+
+ [void]$sb.AppendLine("`treturn &configProvider{")
+ foreach ($cfg in $ConfigsInOrder) {
+ $line = "`t`t$($cfg.VarName): $($cfg.VarName),"
+ [void]$sb.AppendLine($line)
+ }
+ [void]$sb.AppendLine("`t}")
+ [void]$sb.AppendLine("}")
+ [void]$sb.AppendLine()
+
+ # Getter methods
+ foreach ($cfg in $ConfigsInOrder) {
+ [void]$sb.AppendLine("func (c *configProvider) Provide$($cfg.Domain)() config.$($cfg.Domain) {")
+ [void]$sb.AppendLine("`treturn c.$($cfg.VarName)")
+ [void]$sb.AppendLine("}")
+ [void]$sb.AppendLine()
+ }
+
+ return $sb.ToString()
+}
+
+function Write-ProviderFile {
+ param([string]$Code, [string]$OutputPath)
+
+ Write-ColorOutput "Writing to $OutputPath..." "Cyan"
+
+ # Ensure directory exists
+ $dir = Split-Path $OutputPath -Parent
+ if ($dir -and -not (Test-Path $dir)) {
+ New-Item -ItemType Directory -Path $dir -Force | Out-Null
+ }
+
+ # Write file as UTF-8 without BOM
+ $utf8NoBom = [System.Text.UTF8Encoding]::new($false)
+ [System.IO.File]::WriteAllText($OutputPath, $Code, $utf8NoBom)
+
+ Write-ColorOutput " Successfully generated $OutputPath" "Green"
+}
+
+# ============================================
+# MAIN EXECUTION
+# ============================================
+
+try {
+ Write-ColorOutput "`n=========================================" "Blue"
+ Write-ColorOutput " Go Config Provider Generator v1.0" "Blue"
+ Write-ColorOutput "=========================================`n" "Blue"
+
+ # Step 1: Parse all config constructors
+ $configs = Parse-GoFiles -Directory $ConfigDir
+
+ # Step 2: Perform topological sort (configs can depend on other configs)
+ $sortedConfigs = Get-TopologicalOrder -Configs $configs
+
+ # Step 3: Generate provider code
+ $code = Generate-ProviderCode -ConfigsInOrder $sortedConfigs
+
+ # Step 4: Write to file
+ Write-ProviderFile -Code $code -OutputPath $OutputFile
+
+ Write-ColorOutput "`nSUCCESS! Config provider generated successfully.`n" "Green"
+ Write-ColorOutput "Next steps:" "Cyan"
+ Write-ColorOutput " 1. Review $OutputFile" "White"
+ Write-ColorOutput " 2. Fill any /* TODO: provide ... */ placeholders" "White"
+ Write-ColorOutput " 3. Run: go build ./provider" "White"
+
+} catch {
+ Write-ColorOutput "`nERROR: $($_.Exception.Message)" "Red"
+ Write-ColorOutput "Stack trace: $($_.ScriptStackTrace)" "Yellow"
+ exit 1
+}
\ No newline at end of file
diff --git a/cmd/do_inject_controllers.ps1 b/cmd/do_inject_controllers.ps1
new file mode 100644
index 0000000000000000000000000000000000000000..782c798fcb0babef452a290c10468bfd6ca7c296
--- /dev/null
+++ b/cmd/do_inject_controllers.ps1
@@ -0,0 +1,310 @@
+#Requires -Version 5.1
+<#
+.SYNOPSIS
+ Automatic Dependency Injection Generator for Go Controllers
+
+.DESCRIPTION
+ Scans ./controllers/ directory, discovers all controller constructors, infers their dependencies,
+ and generates provider/controller_provider.go with full DI wiring.
+
+.EXAMPLE
+ .\controller_injector.ps1
+
+.NOTES
+ - Works with PowerShell 5.1+ and PowerShell 7+
+ - No external dependencies required
+ - Supports multi-line constructor signatures
+ - Controllers depend on services from ServicesProvider
+#>
+
+[CmdletBinding()]
+param()
+
+# Configuration
+$ControllersDir = "./controllers"
+$OutputFile = "provider/controller_provider.go"
+$ModulePath = "abdanhafidz.com/event-booking-api/controllers"
+
+# ANSI colors for better output
+$script:UseColors = $Host.UI.SupportsVirtualTerminal
+function Write-ColorOutput {
+ param([string]$Message, [string]$Color = "White")
+ if ($script:UseColors) {
+ $colors = @{
+ "Green" = "`e[32m"; "Yellow" = "`e[33m"; "Red" = "`e[31m"
+ "Cyan" = "`e[36m"; "Blue" = "`e[34m"; "Reset" = "`e[0m"
+ }
+ Write-Host "$($colors[$Color])$Message$($colors['Reset'])"
+ } else {
+ Write-Host $Message
+ }
+}
+
+# Data structures
+class ControllerInfo {
+ [string]$ConstructorName # NewAccountController
+ [string]$Domain # AccountController
+ [string]$VarName # accountController
+ [System.Collections.Generic.List[Parameter]]$Parameters
+
+ ControllerInfo() {
+ $this.Parameters = [System.Collections.Generic.List[Parameter]]::new()
+ }
+}
+
+class Parameter {
+ [string]$Name
+ [string]$RawType
+ [string]$NormalizedType
+}
+
+function Get-LowerCamelCase {
+ param([string]$Text)
+ if ($Text.Length -eq 0) { return $Text }
+ return $Text.Substring(0, 1).ToLower() + $Text.Substring(1)
+}
+
+function Normalize-TypeName {
+ param([string]$TypeStr)
+
+ # Remove leading pointer
+ $cleaned = $TypeStr -replace '^\*+', ''
+
+ # Remove package prefix (everything before last dot)
+ if ($cleaned -match '\.([^.]+)$') {
+ $cleaned = $matches[1]
+ }
+
+ return $cleaned.Trim()
+}
+
+function Parse-GoFiles {
+ param([string]$Directory)
+
+ Write-ColorOutput "Scanning for controller constructors in $Directory..." "Cyan"
+
+ if (-not (Test-Path $Directory)) {
+ Write-ColorOutput "ERROR: Directory '$Directory' not found!" "Red"
+ exit 1
+ }
+
+ $goFiles = Get-ChildItem -Path $Directory -Filter "*.go" -Recurse -File
+ $controllers = [System.Collections.Generic.List[ControllerInfo]]::new()
+
+ foreach ($file in $goFiles) {
+ $content = Get-Content $file.FullName -Raw
+
+ # Match function signatures (support multi-line)
+ # Pattern: func NewXxxController(...) XxxController
+ $pattern = '(?ms)func\s+(New[a-zA-Z0-9]+Controller)\s*\(([^)]*)\)\s+([a-zA-Z0-9*_.]+Controller)'
+ $matches = [regex]::Matches($content, $pattern)
+
+ foreach ($match in $matches) {
+ $constructorName = $match.Groups[1].Value
+ $paramsStr = $match.Groups[2].Value
+ $returnType = $match.Groups[3].Value
+
+ # Extract domain name (XxxController)
+ $domain = Normalize-TypeName $returnType
+ $varName = Get-LowerCamelCase $domain
+
+ $controller = [ControllerInfo]::new()
+ $controller.ConstructorName = $constructorName
+ $controller.Domain = $domain
+ $controller.VarName = $varName
+
+ # Parse parameters
+ if ($paramsStr.Trim() -ne "") {
+ # Split by comma, but be careful with nested types
+ $paramList = $paramsStr -split ',\s*(?![^<>]*>)'
+
+ foreach ($param in $paramList) {
+ $param = $param.Trim()
+ if ($param -eq "") { continue }
+
+ # Split into name and type
+ $parts = $param -split '\s+', 2
+
+ $p = [Parameter]::new()
+ if ($parts.Count -eq 2) {
+ $p.Name = $parts[0]
+ $p.RawType = $parts[1]
+ } elseif ($parts.Count -eq 1) {
+ # Anonymous parameter - synthesize name
+ $p.Name = "param$($controller.Parameters.Count)"
+ $p.RawType = $parts[0]
+ } else {
+ continue
+ }
+
+ $p.NormalizedType = Normalize-TypeName $p.RawType
+ $controller.Parameters.Add($p)
+ }
+ }
+
+ $controllers.Add($controller)
+ Write-ColorOutput " Found: $constructorName" "Green"
+ }
+ }
+
+ if ($controllers.Count -eq 0) {
+ Write-ColorOutput "No controller constructors found matching pattern 'NewXxxController'!" "Red"
+ exit 1
+ }
+
+ Write-ColorOutput "`nTotal controllers discovered: $($controllers.Count)" "Blue"
+ return $controllers
+}
+
+function Resolve-ControllerArgument {
+ param([Parameter]$Param)
+
+ $type = $Param.NormalizedType
+
+ # DEPENDENCY RESOLUTION RULES
+ # ============================================
+
+ # 1. Service pattern: XxxxService -> servicesProvider.ProvideXxxxService()
+ if ($type -match '^(.+)Service$') {
+ $serviceName = $type
+ return "servicesProvider.Provide${serviceName}()"
+ }
+
+ # ADD MORE SPECIAL CASES HERE:
+ # --------------------------------------------
+ # Example: Config dependency
+ # if ($type -eq "Config") {
+ # return "configProvider.ProvideConfig()"
+ # }
+ #
+ # Example: Logger
+ # if ($type -eq "Logger") {
+ # return "loggerProvider.ProvideLogger()"
+ # }
+ #
+ # Example: Validator
+ # if ($type -eq "Validator") {
+ # return "validatorProvider.ProvideValidator()"
+ # }
+ # --------------------------------------------
+
+ # 2. Fallback: unresolved type
+ return "/* TODO: provide $($Param.RawType) */"
+}
+
+function Generate-ProviderCode {
+ param([System.Collections.Generic.List[ControllerInfo]]$Controllers)
+
+ Write-ColorOutput "`nGenerating controller provider code..." "Cyan"
+
+ # Sort controllers alphabetically for consistent output
+ $sortedControllers = $Controllers | Sort-Object -Property Domain
+
+ $sb = [System.Text.StringBuilder]::new()
+ [void]$sb.AppendLine("package provider")
+ [void]$sb.AppendLine()
+ [void]$sb.AppendLine("import `"$ModulePath`"")
+ [void]$sb.AppendLine()
+
+ # Interface
+ [void]$sb.AppendLine("type ControllerProvider interface {")
+ foreach ($ctrl in $sortedControllers) {
+ $line = "`tProvide$($ctrl.Domain)() controllers.$($ctrl.Domain)"
+ [void]$sb.AppendLine($line)
+ }
+ [void]$sb.AppendLine("}")
+ [void]$sb.AppendLine()
+
+ # Struct
+ [void]$sb.AppendLine("type controllerProvider struct {")
+ foreach ($ctrl in $sortedControllers) {
+ $line = "`t$($ctrl.VarName) controllers.$($ctrl.Domain)"
+ [void]$sb.AppendLine($line)
+ }
+ [void]$sb.AppendLine("}")
+ [void]$sb.AppendLine()
+
+ # Constructor
+ [void]$sb.AppendLine("func NewControllerProvider(servicesProvider ServicesProvider) ControllerProvider {")
+ [void]$sb.AppendLine()
+
+ # Initialize controllers
+ foreach ($ctrl in $sortedControllers) {
+ $args = @()
+ foreach ($param in $ctrl.Parameters) {
+ $args += Resolve-ControllerArgument $param
+ }
+ $argsStr = $args -join ", "
+ $line = "`t$($ctrl.VarName) := controllers.$($ctrl.ConstructorName)($argsStr)"
+ [void]$sb.AppendLine($line)
+ }
+
+ [void]$sb.AppendLine("`treturn &controllerProvider{")
+ foreach ($ctrl in $sortedControllers) {
+ $line = "`t`t$($ctrl.VarName): $($ctrl.VarName),"
+ [void]$sb.AppendLine($line)
+ }
+ [void]$sb.AppendLine("`t}")
+ [void]$sb.AppendLine("}")
+ [void]$sb.AppendLine()
+
+ # Getter methods
+ [void]$sb.AppendLine("// --- Getter Methods ---")
+ [void]$sb.AppendLine()
+ foreach ($ctrl in $sortedControllers) {
+ [void]$sb.AppendLine("func (c *controllerProvider) Provide$($ctrl.Domain)() controllers.$($ctrl.Domain) {")
+ [void]$sb.AppendLine("`treturn c.$($ctrl.VarName)")
+ [void]$sb.AppendLine("}")
+ [void]$sb.AppendLine()
+ }
+
+ return $sb.ToString()
+}
+
+function Write-ProviderFile {
+ param([string]$Code, [string]$OutputPath)
+
+ Write-ColorOutput "Writing to $OutputPath..." "Cyan"
+
+ # Ensure directory exists
+ $dir = Split-Path $OutputPath -Parent
+ if ($dir -and -not (Test-Path $dir)) {
+ New-Item -ItemType Directory -Path $dir -Force | Out-Null
+ }
+
+ # Write file as UTF-8 without BOM
+ $utf8NoBom = [System.Text.UTF8Encoding]::new($false)
+ [System.IO.File]::WriteAllText($OutputPath, $Code, $utf8NoBom)
+
+ Write-ColorOutput " Successfully generated $OutputPath" "Green"
+}
+
+# ============================================
+# MAIN EXECUTION
+# ============================================
+
+try {
+ Write-ColorOutput "`n=========================================" "Blue"
+ Write-ColorOutput " Go Controller Provider Generator v1.0" "Blue"
+ Write-ColorOutput "=========================================`n" "Blue"
+
+ # Step 1: Parse all controller constructors
+ $controllers = Parse-GoFiles -Directory $ControllersDir
+
+ # Step 2: Generate provider code
+ $code = Generate-ProviderCode -Controllers $controllers
+
+ # Step 3: Write to file
+ Write-ProviderFile -Code $code -OutputPath $OutputFile
+
+ Write-ColorOutput "`nSUCCESS! Controller provider generated successfully.`n" "Green"
+ Write-ColorOutput "Next steps:" "Cyan"
+ Write-ColorOutput " 1. Review $OutputFile" "White"
+ Write-ColorOutput " 2. Fill any /* TODO: provide ... */ placeholders" "White"
+ Write-ColorOutput " 3. Run: go build ./provider" "White"
+
+} catch {
+ Write-ColorOutput "`nERROR: $($_.Exception.Message)" "Red"
+ Write-ColorOutput "Stack trace: $($_.ScriptStackTrace)" "Yellow"
+ exit 1
+}
\ No newline at end of file
diff --git a/cmd/do_inject_middleware.ps1 b/cmd/do_inject_middleware.ps1
new file mode 100644
index 0000000000000000000000000000000000000000..f9ea2a6a6eac0a065389e11fc5894b3b2ccd111a
--- /dev/null
+++ b/cmd/do_inject_middleware.ps1
@@ -0,0 +1,312 @@
+#Requires -Version 5.1
+<#
+.SYNOPSIS
+ Automatic Dependency Injection Generator for Go Middleware
+
+.DESCRIPTION
+ Scans ./middleware/ directory, discovers all middleware constructors, infers their dependencies,
+ and generates provider/middleware_provider.go with full DI wiring.
+
+.EXAMPLE
+ .\middleware_injector.ps1
+
+.NOTES
+ - Works with PowerShell 5.1+ and PowerShell 7+
+ - No external dependencies required
+ - Supports multi-line constructor signatures
+ - Middleware depend on services from ServicesProvider
+#>
+
+[CmdletBinding()]
+param()
+
+# Configuration
+$MiddlewareDir = "./middleware"
+$OutputFile = "provider/middleware_provider.go"
+$ModulePath = "abdanhafidz.com/event-booking-api/middleware"
+
+# ANSI colors for better output
+$script:UseColors = $Host.UI.SupportsVirtualTerminal
+function Write-ColorOutput {
+ param([string]$Message, [string]$Color = "White")
+ if ($script:UseColors) {
+ $colors = @{
+ "Green" = "`e[32m"; "Yellow" = "`e[33m"; "Red" = "`e[31m"
+ "Cyan" = "`e[36m"; "Blue" = "`e[34m"; "Reset" = "`e[0m"
+ }
+ Write-Host "$($colors[$Color])$Message$($colors['Reset'])"
+ } else {
+ Write-Host $Message
+ }
+}
+
+# Data structures
+class MiddlewareInfo {
+ [string]$ConstructorName # NewAuthenticationMiddleware
+ [string]$Domain # AuthenticationMiddleware
+ [string]$VarName # authenticationMiddleware
+ [System.Collections.Generic.List[Parameter]]$Parameters
+
+ MiddlewareInfo() {
+ $this.Parameters = [System.Collections.Generic.List[Parameter]]::new()
+ }
+}
+
+class Parameter {
+ [string]$Name
+ [string]$RawType
+ [string]$NormalizedType
+}
+
+function Get-LowerCamelCase {
+ param([string]$Text)
+ if ($Text.Length -eq 0) { return $Text }
+ return $Text.Substring(0, 1).ToLower() + $Text.Substring(1)
+}
+
+function Normalize-TypeName {
+ param([string]$TypeStr)
+
+ # Remove leading pointer
+ $cleaned = $TypeStr -replace '^\*+', ''
+
+ # Remove package prefix (everything before last dot)
+ if ($cleaned -match '\.([^.]+)$') {
+ $cleaned = $matches[1]
+ }
+
+ return $cleaned.Trim()
+}
+
+function Parse-GoFiles {
+ param([string]$Directory)
+
+ Write-ColorOutput "Scanning for middleware constructors in $Directory..." "Cyan"
+
+ if (-not (Test-Path $Directory)) {
+ Write-ColorOutput "ERROR: Directory '$Directory' not found!" "Red"
+ exit 1
+ }
+
+ $goFiles = Get-ChildItem -Path $Directory -Filter "*.go" -Recurse -File
+ $middlewares = [System.Collections.Generic.List[MiddlewareInfo]]::new()
+
+ foreach ($file in $goFiles) {
+ $content = Get-Content $file.FullName -Raw
+
+ # Match function signatures (support multi-line)
+ # Pattern: func NewXxxMiddleware(...) XxxMiddleware
+ $pattern = '(?ms)func\s+(New[a-zA-Z0-9]+Middleware)\s*\(([^)]*)\)\s+([a-zA-Z0-9*_.]+Middleware)'
+ $matches = [regex]::Matches($content, $pattern)
+
+ foreach ($match in $matches) {
+ $constructorName = $match.Groups[1].Value
+ $paramsStr = $match.Groups[2].Value
+ $returnType = $match.Groups[3].Value
+
+ # Extract domain name (XxxMiddleware)
+ $domain = Normalize-TypeName $returnType
+ $varName = Get-LowerCamelCase $domain
+
+ $middleware = [MiddlewareInfo]::new()
+ $middleware.ConstructorName = $constructorName
+ $middleware.Domain = $domain
+ $middleware.VarName = $varName
+
+ # Parse parameters
+ if ($paramsStr.Trim() -ne "") {
+ # Split by comma, but be careful with nested types
+ $paramList = $paramsStr -split ',\s*(?![^<>]*>)'
+
+ foreach ($param in $paramList) {
+ $param = $param.Trim()
+ if ($param -eq "") { continue }
+
+ # Split into name and type
+ $parts = $param -split '\s+', 2
+
+ $p = [Parameter]::new()
+ if ($parts.Count -eq 2) {
+ $p.Name = $parts[0]
+ $p.RawType = $parts[1]
+ } elseif ($parts.Count -eq 1) {
+ # Anonymous parameter - synthesize name
+ $p.Name = "param$($middleware.Parameters.Count)"
+ $p.RawType = $parts[0]
+ } else {
+ continue
+ }
+
+ $p.NormalizedType = Normalize-TypeName $p.RawType
+ $middleware.Parameters.Add($p)
+ }
+ }
+
+ $middlewares.Add($middleware)
+ Write-ColorOutput " Found: $constructorName" "Green"
+ }
+ }
+
+ if ($middlewares.Count -eq 0) {
+ Write-ColorOutput "No middleware constructors found matching pattern 'NewXxxMiddleware'!" "Red"
+ exit 1
+ }
+
+ Write-ColorOutput "`nTotal middleware discovered: $($middlewares.Count)" "Blue"
+ return $middlewares
+}
+
+function Resolve-MiddlewareArgument {
+ param([Parameter]$Param)
+
+ $type = $Param.NormalizedType
+
+ # DEPENDENCY RESOLUTION RULES
+ # ============================================
+
+ # 1. Service pattern: XxxxService -> servicesProvider.ProvideXxxxService()
+ if ($type -match '^(.+)Service$') {
+ $serviceName = $type
+ return "servicesProvider.Provide${serviceName}()"
+ }
+
+ # ADD MORE SPECIAL CASES HERE:
+ # --------------------------------------------
+ # Example: Config dependency
+ # if ($type -eq "Config") {
+ # return "configProvider.ProvideConfig()"
+ # }
+ #
+ # Example: Logger
+ # if ($type -eq "Logger") {
+ # return "loggerProvider.ProvideLogger()"
+ # }
+ #
+ # Example: JWT Config
+ # if ($type -eq "JWTConfig") {
+ # return "configProvider.ProvideJWTConfig()"
+ # }
+ #
+ # Example: Database
+ # if ($type -eq "DB" -or $type -eq "Database") {
+ # return "dbProvider.ProvideDatabase()"
+ # }
+ # --------------------------------------------
+
+ # 2. Fallback: unresolved type
+ return "/* TODO: provide $($Param.RawType) */"
+}
+
+function Generate-ProviderCode {
+ param([System.Collections.Generic.List[MiddlewareInfo]]$Middlewares)
+
+ Write-ColorOutput "`nGenerating middleware provider code..." "Cyan"
+
+ # Sort middleware alphabetically for consistent output
+ $sortedMiddlewares = $Middlewares | Sort-Object -Property Domain
+
+ $sb = [System.Text.StringBuilder]::new()
+ [void]$sb.AppendLine("package provider")
+ [void]$sb.AppendLine()
+ [void]$sb.AppendLine("import `"$ModulePath`"")
+ [void]$sb.AppendLine()
+
+ # Interface
+ [void]$sb.AppendLine("type MiddlewareProvider interface {")
+ foreach ($mw in $sortedMiddlewares) {
+ $line = "`tProvide$($mw.Domain)() middleware.$($mw.Domain)"
+ [void]$sb.AppendLine($line)
+ }
+ [void]$sb.AppendLine("}")
+ [void]$sb.AppendLine()
+
+ # Struct
+ [void]$sb.AppendLine("type middlewareProvider struct {")
+ foreach ($mw in $sortedMiddlewares) {
+ $line = "`t$($mw.VarName) middleware.$($mw.Domain)"
+ [void]$sb.AppendLine($line)
+ }
+ [void]$sb.AppendLine("}")
+ [void]$sb.AppendLine()
+
+ # Constructor
+ [void]$sb.AppendLine("func NewMiddlewareProvider(servicesProvider ServicesProvider) MiddlewareProvider {")
+
+ # Initialize middleware
+ foreach ($mw in $sortedMiddlewares) {
+ $args = @()
+ foreach ($param in $mw.Parameters) {
+ $args += Resolve-MiddlewareArgument $param
+ }
+ $argsStr = $args -join ", "
+ $line = "`t$($mw.VarName) := middleware.$($mw.ConstructorName)($argsStr)"
+ [void]$sb.AppendLine($line)
+ }
+
+ [void]$sb.AppendLine("`treturn &middlewareProvider{")
+ foreach ($mw in $sortedMiddlewares) {
+ $line = "`t`t$($mw.VarName): $($mw.VarName),"
+ [void]$sb.AppendLine($line)
+ }
+ [void]$sb.AppendLine("`t}")
+ [void]$sb.AppendLine("}")
+ [void]$sb.AppendLine()
+
+ # Getter methods
+ foreach ($mw in $sortedMiddlewares) {
+ [void]$sb.AppendLine("func (p *middlewareProvider) Provide$($mw.Domain)() middleware.$($mw.Domain) {")
+ [void]$sb.AppendLine("`treturn p.$($mw.VarName)")
+ [void]$sb.AppendLine("}")
+ [void]$sb.AppendLine()
+ }
+
+ return $sb.ToString()
+}
+
+function Write-ProviderFile {
+ param([string]$Code, [string]$OutputPath)
+
+ Write-ColorOutput "Writing to $OutputPath..." "Cyan"
+
+ # Ensure directory exists
+ $dir = Split-Path $OutputPath -Parent
+ if ($dir -and -not (Test-Path $dir)) {
+ New-Item -ItemType Directory -Path $dir -Force | Out-Null
+ }
+
+ # Write file as UTF-8 without BOM
+ $utf8NoBom = [System.Text.UTF8Encoding]::new($false)
+ [System.IO.File]::WriteAllText($OutputPath, $Code, $utf8NoBom)
+
+ Write-ColorOutput " Successfully generated $OutputPath" "Green"
+}
+
+# ============================================
+# MAIN EXECUTION
+# ============================================
+
+try {
+ Write-ColorOutput "`n=========================================" "Blue"
+ Write-ColorOutput " Go Middleware Provider Generator v1.0" "Blue"
+ Write-ColorOutput "=========================================`n" "Blue"
+
+ # Step 1: Parse all middleware constructors
+ $middlewares = Parse-GoFiles -Directory $MiddlewareDir
+
+ # Step 2: Generate provider code
+ $code = Generate-ProviderCode -Middlewares $middlewares
+
+ # Step 3: Write to file
+ Write-ProviderFile -Code $code -OutputPath $OutputFile
+
+ Write-ColorOutput "`nSUCCESS! Middleware provider generated successfully.`n" "Green"
+ Write-ColorOutput "Next steps:" "Cyan"
+ Write-ColorOutput " 1. Review $OutputFile" "White"
+ Write-ColorOutput " 2. Fill any /* TODO: provide ... */ placeholders" "White"
+ Write-ColorOutput " 3. Run: go build ./provider" "White"
+
+} catch {
+ Write-ColorOutput "`nERROR: $($_.Exception.Message)" "Red"
+ Write-ColorOutput "Stack trace: $($_.ScriptStackTrace)" "Yellow"
+ exit 1
+}
\ No newline at end of file
diff --git a/cmd/do_inject_repository.ps1 b/cmd/do_inject_repository.ps1
new file mode 100644
index 0000000000000000000000000000000000000000..47b84c024e3657513fba48ec72c8c2e0cf445ffa
--- /dev/null
+++ b/cmd/do_inject_repository.ps1
@@ -0,0 +1,327 @@
+#Requires -Version 5.1
+<#
+.SYNOPSIS
+ Automatic Dependency Injection Generator for Go Repositories
+
+.DESCRIPTION
+ Scans ./repositories/ directory, discovers all repository constructors,
+ and generates provider/repositories_provider.go with full DI wiring.
+ Repositories typically depend on database connection from ConfigProvider.
+
+.EXAMPLE
+ .\repository_injector.ps1
+
+.NOTES
+ - Works with PowerShell 5.1+ and PowerShell 7+
+ - No external dependencies required
+ - Supports multi-line constructor signatures
+ - Repositories depend on database instance from ConfigProvider
+#>
+
+[CmdletBinding()]
+param()
+
+# Configuration
+$RepositoriesDir = "./repositories"
+$OutputFile = "provider/repositories_provider.go"
+$ModulePath = "abdanhafidz.com/event-booking-api/repositories"
+
+# ANSI colors for better output
+$script:UseColors = $Host.UI.SupportsVirtualTerminal
+function Write-ColorOutput {
+ param([string]$Message, [string]$Color = "White")
+ if ($script:UseColors) {
+ $colors = @{
+ "Green" = "`e[32m"; "Yellow" = "`e[33m"; "Red" = "`e[31m"
+ "Cyan" = "`e[36m"; "Blue" = "`e[34m"; "Reset" = "`e[0m"
+ }
+ Write-Host "$($colors[$Color])$Message$($colors['Reset'])"
+ } else {
+ Write-Host $Message
+ }
+}
+
+# Data structures
+class RepositoryInfo {
+ [string]$ConstructorName # NewAccountRepository
+ [string]$Domain # AccountRepository
+ [string]$VarName # accountRepository
+ [System.Collections.Generic.List[Parameter]]$Parameters
+
+ RepositoryInfo() {
+ $this.Parameters = [System.Collections.Generic.List[Parameter]]::new()
+ }
+}
+
+class Parameter {
+ [string]$Name
+ [string]$RawType
+ [string]$NormalizedType
+}
+
+function Get-LowerCamelCase {
+ param([string]$Text)
+ if ($Text.Length -eq 0) { return $Text }
+ return $Text.Substring(0, 1).ToLower() + $Text.Substring(1)
+}
+
+function Normalize-TypeName {
+ param([string]$TypeStr)
+
+ # Remove leading pointer
+ $cleaned = $TypeStr -replace '^\*+', ''
+
+ # Remove package prefix (everything before last dot)
+ if ($cleaned -match '\.([^.]+)$') {
+ $cleaned = $matches[1]
+ }
+
+ return $cleaned.Trim()
+}
+
+function Parse-GoFiles {
+ param([string]$Directory)
+
+ Write-ColorOutput "Scanning for repository constructors in $Directory..." "Cyan"
+
+ if (-not (Test-Path $Directory)) {
+ Write-ColorOutput "ERROR: Directory '$Directory' not found!" "Red"
+ exit 1
+ }
+
+ $goFiles = Get-ChildItem -Path $Directory -Filter "*.go" -Recurse -File
+ $repositories = [System.Collections.Generic.List[RepositoryInfo]]::new()
+
+ foreach ($file in $goFiles) {
+ $content = Get-Content $file.FullName -Raw
+
+ # Match function signatures (support multi-line)
+ # Pattern: func NewXxxRepository(...) XxxRepository
+ $pattern = '(?ms)func\s+(New[a-zA-Z0-9]+Repository)\s*\(([^)]*)\)\s+([a-zA-Z0-9*_.]+Repository)'
+ $matches = [regex]::Matches($content, $pattern)
+
+ foreach ($match in $matches) {
+ $constructorName = $match.Groups[1].Value
+ $paramsStr = $match.Groups[2].Value
+ $returnType = $match.Groups[3].Value
+
+ # Extract domain name (XxxRepository)
+ $domain = Normalize-TypeName $returnType
+ $varName = Get-LowerCamelCase $domain
+
+ $repo = [RepositoryInfo]::new()
+ $repo.ConstructorName = $constructorName
+ $repo.Domain = $domain
+ $repo.VarName = $varName
+
+ # Parse parameters
+ if ($paramsStr.Trim() -ne "") {
+ # Split by comma, but be careful with nested types
+ $paramList = $paramsStr -split ',\s*(?![^<>]*>)'
+
+ foreach ($param in $paramList) {
+ $param = $param.Trim()
+ if ($param -eq "") { continue }
+
+ # Split into name and type
+ $parts = $param -split '\s+', 2
+
+ $p = [Parameter]::new()
+ if ($parts.Count -eq 2) {
+ $p.Name = $parts[0]
+ $p.RawType = $parts[1]
+ } elseif ($parts.Count -eq 1) {
+ # Anonymous parameter - synthesize name
+ $p.Name = "param$($repo.Parameters.Count)"
+ $p.RawType = $parts[0]
+ } else {
+ continue
+ }
+
+ $p.NormalizedType = Normalize-TypeName $p.RawType
+ $repo.Parameters.Add($p)
+ }
+ }
+
+ $repositories.Add($repo)
+ Write-ColorOutput " Found: $constructorName" "Green"
+ }
+ }
+
+ if ($repositories.Count -eq 0) {
+ Write-ColorOutput "No repository constructors found matching pattern 'NewXxxRepository'!" "Red"
+ exit 1
+ }
+
+ Write-ColorOutput "`nTotal repositories discovered: $($repositories.Count)" "Blue"
+ return $repositories
+}
+
+function Resolve-RepositoryArgument {
+ param([Parameter]$Param)
+
+ $type = $Param.NormalizedType
+ $paramName = $Param.Name
+
+ # DEPENDENCY RESOLUTION RULES FOR REPOSITORIES
+ # ============================================
+
+ # 1. Database connection patterns
+ if ($type -match '^(DB|Database|Gorm|SqlDB|Connection)$' -or $paramName -match '^(db|database|conn|connection)$') {
+ return "db"
+ }
+
+ # 2. *gorm.DB (most common in Go GORM projects)
+ if ($Param.RawType -match 'gorm\.DB' -or $type -eq "DB") {
+ return "db"
+ }
+
+ # 3. *sql.DB (standard library)
+ if ($Param.RawType -match 'sql\.DB') {
+ return "db"
+ }
+
+ # ADD MORE SPECIAL CASES HERE:
+ # --------------------------------------------
+ # Example: Redis connection
+ # if ($type -eq "RedisClient" -or $paramName -match "redis") {
+ # return "redisClient"
+ # }
+ #
+ # Example: MongoDB connection
+ # if ($type -eq "MongoClient" -or $paramName -match "mongo") {
+ # return "mongoClient"
+ # }
+ #
+ # Example: Cache
+ # if ($type -eq "Cache" -or $paramName -match "cache") {
+ # return "cache"
+ # }
+ #
+ # Example: Logger
+ # if ($type -eq "Logger" -or $paramName -match "logger") {
+ # return "logger"
+ # }
+ # --------------------------------------------
+
+ # 4. Fallback: unresolved type
+ return "/* TODO: provide $($Param.RawType) */"
+}
+
+function Generate-ProviderCode {
+ param([System.Collections.Generic.List[RepositoryInfo]]$Repositories)
+
+ Write-ColorOutput "`nGenerating repositories provider code..." "Cyan"
+
+ # Sort repositories alphabetically for consistent output
+ $sortedRepos = $Repositories | Sort-Object -Property Domain
+
+ $sb = [System.Text.StringBuilder]::new()
+ [void]$sb.AppendLine("package provider")
+ [void]$sb.AppendLine()
+ [void]$sb.AppendLine("import `"$ModulePath`"")
+ [void]$sb.AppendLine()
+
+ # Interface
+ [void]$sb.AppendLine("type RepositoriesProvider interface {")
+ foreach ($repo in $sortedRepos) {
+ $line = "`tProvide$($repo.Domain)() repositories.$($repo.Domain)"
+ [void]$sb.AppendLine($line)
+ }
+ [void]$sb.AppendLine("}")
+ [void]$sb.AppendLine()
+
+ # Struct
+ [void]$sb.AppendLine("type repositoriesProvider struct {")
+ foreach ($repo in $sortedRepos) {
+ $line = "`t$($repo.VarName) repositories.$($repo.Domain)"
+ [void]$sb.AppendLine($line)
+ }
+ [void]$sb.AppendLine("}")
+ [void]$sb.AppendLine()
+
+ # Constructor
+ [void]$sb.AppendLine("func NewRepositoriesProvider(cfg ConfigProvider) RepositoriesProvider {")
+ [void]$sb.AppendLine("`tdbConfig := cfg.ProvideDatabaseConfig()")
+ [void]$sb.AppendLine("`tdb := dbConfig.GetInstance()")
+ [void]$sb.AppendLine()
+
+ # Initialize repositories
+ foreach ($repo in $sortedRepos) {
+ $args = @()
+ foreach ($param in $repo.Parameters) {
+ $args += Resolve-RepositoryArgument $param
+ }
+ $argsStr = $args -join ", "
+ $line = "`t$($repo.VarName) := repositories.$($repo.ConstructorName)($argsStr)"
+ [void]$sb.AppendLine($line)
+ }
+
+ [void]$sb.AppendLine()
+ [void]$sb.AppendLine("`treturn &repositoriesProvider{")
+ foreach ($repo in $sortedRepos) {
+ $line = "`t`t$($repo.VarName): $($repo.VarName),"
+ [void]$sb.AppendLine($line)
+ }
+ [void]$sb.AppendLine("`t}")
+ [void]$sb.AppendLine("}")
+ [void]$sb.AppendLine()
+
+ # Getter methods
+ foreach ($repo in $sortedRepos) {
+ [void]$sb.AppendLine("func (r *repositoriesProvider) Provide$($repo.Domain)() repositories.$($repo.Domain) {")
+ [void]$sb.AppendLine("`treturn r.$($repo.VarName)")
+ [void]$sb.AppendLine("}")
+ [void]$sb.AppendLine()
+ }
+
+ return $sb.ToString()
+}
+
+function Write-ProviderFile {
+ param([string]$Code, [string]$OutputPath)
+
+ Write-ColorOutput "Writing to $OutputPath..." "Cyan"
+
+ # Ensure directory exists
+ $dir = Split-Path $OutputPath -Parent
+ if ($dir -and -not (Test-Path $dir)) {
+ New-Item -ItemType Directory -Path $dir -Force | Out-Null
+ }
+
+ # Write file as UTF-8 without BOM
+ $utf8NoBom = [System.Text.UTF8Encoding]::new($false)
+ [System.IO.File]::WriteAllText($OutputPath, $Code, $utf8NoBom)
+
+ Write-ColorOutput " Successfully generated $OutputPath" "Green"
+}
+
+# ============================================
+# MAIN EXECUTION
+# ============================================
+
+try {
+ Write-ColorOutput "`n=========================================" "Blue"
+ Write-ColorOutput " Go Repository Provider Generator v1.0" "Blue"
+ Write-ColorOutput "=========================================`n" "Blue"
+
+ # Step 1: Parse all repository constructors
+ $repositories = Parse-GoFiles -Directory $RepositoriesDir
+
+ # Step 2: Generate provider code
+ $code = Generate-ProviderCode -Repositories $repositories
+
+ # Step 3: Write to file
+ Write-ProviderFile -Code $code -OutputPath $OutputFile
+
+ Write-ColorOutput "`nSUCCESS! Repositories provider generated successfully.`n" "Green"
+ Write-ColorOutput "Next steps:" "Cyan"
+ Write-ColorOutput " 1. Review $OutputFile" "White"
+ Write-ColorOutput " 2. Fill any /* TODO: provide ... */ placeholders" "White"
+ Write-ColorOutput " 3. Run: go build ./provider" "White"
+
+} catch {
+ Write-ColorOutput "`nERROR: $($_.Exception.Message)" "Red"
+ Write-ColorOutput "Stack trace: $($_.ScriptStackTrace)" "Yellow"
+ exit 1
+}
\ No newline at end of file
diff --git a/cmd/do_inject_services.ps1 b/cmd/do_inject_services.ps1
new file mode 100644
index 0000000000000000000000000000000000000000..af6f40682d98b7720b9e3897a1266f78afea887a
--- /dev/null
+++ b/cmd/do_inject_services.ps1
@@ -0,0 +1,383 @@
+#Requires -Version 5.1
+<#
+.SYNOPSIS
+ Automatic Dependency Injection Generator for Go Services
+
+.DESCRIPTION
+ Scans ./services/ directory, discovers service constructors, resolves dependencies,
+ performs topological sorting, and generates provider/services_provider.go with full DI wiring.
+
+.EXAMPLE
+ .\service_injector.ps1
+
+.NOTES
+ - Works with PowerShell 5.1+ and PowerShell 7+
+ - No external dependencies required
+ - Supports multi-line constructor signatures
+ - Handles dependency cycles with clear error messages
+#>
+
+[CmdletBinding()]
+param()
+
+# Configuration
+$ServicesDir = "./services"
+$OutputFile = "provider/services_provider.go"
+$ModulePath = "abdanhafidz.com/event-booking-api/services"
+
+# ANSI colors for better output (fallback to plain text if not supported)
+$script:UseColors = $Host.UI.SupportsVirtualTerminal
+function Write-ColorOutput {
+ param([string]$Message, [string]$Color = "White")
+ if ($script:UseColors) {
+ $colors = @{
+ "Green" = "`e[32m"; "Yellow" = "`e[33m"; "Red" = "`e[31m"
+ "Cyan" = "`e[36m"; "Blue" = "`e[34m"; "Reset" = "`e[0m"
+ }
+ Write-Host "$($colors[$Color])$Message$($colors['Reset'])"
+ } else {
+ Write-Host $Message
+ }
+}
+
+# Data structures
+class ServiceInfo {
+ [string]$ConstructorName # NewAccountService
+ [string]$Domain # AccountService
+ [string]$VarName # accountService
+ [System.Collections.Generic.List[Parameter]]$Parameters
+ [System.Collections.Generic.List[string]]$ServiceDependencies
+
+ ServiceInfo() {
+ $this.Parameters = [System.Collections.Generic.List[Parameter]]::new()
+ $this.ServiceDependencies = [System.Collections.Generic.List[string]]::new()
+ }
+}
+
+class Parameter {
+ [string]$Name
+ [string]$RawType
+ [string]$NormalizedType
+}
+
+function Get-LowerCamelCase {
+ param([string]$Text)
+ if ($Text.Length -eq 0) { return $Text }
+ return $Text.Substring(0, 1).ToLower() + $Text.Substring(1)
+}
+
+function Normalize-TypeName {
+ param([string]$TypeStr)
+
+ # Remove leading pointer
+ $cleaned = $TypeStr -replace '^\*+', ''
+
+ # Remove package prefix (everything before last dot)
+ if ($cleaned -match '\.([^.]+)$') {
+ $cleaned = $matches[1]
+ }
+
+ return $cleaned.Trim()
+}
+
+function Parse-GoFiles {
+ param([string]$Directory)
+
+ Write-ColorOutput "Scanning for service constructors in $Directory..." "Cyan"
+
+ if (-not (Test-Path $Directory)) {
+ Write-ColorOutput "ERROR: Directory '$Directory' not found!" "Red"
+ exit 1
+ }
+
+ $goFiles = Get-ChildItem -Path $Directory -Filter "*.go" -Recurse -File
+ $services = [System.Collections.Generic.List[ServiceInfo]]::new()
+
+ foreach ($file in $goFiles) {
+ $content = Get-Content $file.FullName -Raw
+
+ # Match function signatures (support multi-line)
+ # Pattern: func NewXxxService(...) XxxService
+ $pattern = '(?ms)func\s+(New[a-zA-Z0-9]+Service)\s*\(([^)]*)\)\s+([a-zA-Z0-9*_.]+Service)'
+ $matches = [regex]::Matches($content, $pattern)
+
+ foreach ($match in $matches) {
+ $constructorName = $match.Groups[1].Value
+ $paramsStr = $match.Groups[2].Value
+ $returnType = $match.Groups[3].Value
+
+ # Extract domain name (XxxService)
+ $domain = Normalize-TypeName $returnType
+ $varName = Get-LowerCamelCase $domain
+
+ $service = [ServiceInfo]::new()
+ $service.ConstructorName = $constructorName
+ $service.Domain = $domain
+ $service.VarName = $varName
+
+ # Parse parameters
+ if ($paramsStr.Trim() -ne "") {
+ # Split by comma, but be careful with nested types
+ $paramList = $paramsStr -split ',\s*(?![^<>]*>)'
+
+ foreach ($param in $paramList) {
+ $param = $param.Trim()
+ if ($param -eq "") { continue }
+
+ # Split into name and type
+ $parts = $param -split '\s+', 2
+
+ $p = [Parameter]::new()
+ if ($parts.Count -eq 2) {
+ $p.Name = $parts[0]
+ $p.RawType = $parts[1]
+ } elseif ($parts.Count -eq 1) {
+ # Anonymous parameter - synthesize name
+ $p.Name = "param$($service.Parameters.Count)"
+ $p.RawType = $parts[0]
+ } else {
+ continue
+ }
+
+ $p.NormalizedType = Normalize-TypeName $p.RawType
+ $service.Parameters.Add($p)
+
+ # Track service dependencies
+ if ($p.NormalizedType -match 'Service$') {
+ $service.ServiceDependencies.Add($p.NormalizedType)
+ }
+ }
+ }
+
+ $services.Add($service)
+ Write-ColorOutput " Found: $constructorName" "Green"
+ }
+ }
+
+ if ($services.Count -eq 0) {
+ Write-ColorOutput "No service constructors found matching pattern 'NewXxxService'!" "Red"
+ exit 1
+ }
+
+ Write-ColorOutput "`nTotal services discovered: $($services.Count)" "Blue"
+ return $services
+}
+
+function Get-TopologicalOrder {
+ param([System.Collections.Generic.List[ServiceInfo]]$Services)
+
+ Write-ColorOutput "`nBuilding dependency graph..." "Cyan"
+
+ # Build adjacency list
+ $graph = @{}
+ $inDegree = @{}
+ $domainToService = @{}
+
+ foreach ($svc in $Services) {
+ $graph[$svc.Domain] = [System.Collections.Generic.List[string]]::new()
+ $inDegree[$svc.Domain] = 0
+ $domainToService[$svc.Domain] = $svc
+ }
+
+ # Build edges
+ foreach ($svc in $Services) {
+ foreach ($dep in $svc.ServiceDependencies) {
+ if ($graph.ContainsKey($dep)) {
+ $graph[$dep].Add($svc.Domain)
+ $inDegree[$svc.Domain]++
+ }
+ }
+ }
+
+ # Kahn's algorithm for topological sort
+ $queue = [System.Collections.Generic.Queue[string]]::new()
+ foreach ($domain in $inDegree.Keys) {
+ if ($inDegree[$domain] -eq 0) {
+ $queue.Enqueue($domain)
+ }
+ }
+
+ $sorted = [System.Collections.Generic.List[string]]::new()
+
+ while ($queue.Count -gt 0) {
+ $current = $queue.Dequeue()
+ $sorted.Add($current)
+
+ foreach ($neighbor in $graph[$current]) {
+ $inDegree[$neighbor]--
+ if ($inDegree[$neighbor] -eq 0) {
+ $queue.Enqueue($neighbor)
+ }
+ }
+ }
+
+ # Check for cycles
+ if ($sorted.Count -ne $Services.Count) {
+ $remaining = $inDegree.Keys | Where-Object { $inDegree[$_] -gt 0 }
+ Write-ColorOutput "`nERROR: Circular dependency detected!" "Red"
+ Write-ColorOutput "Services involved in cycle: $($remaining -join ', ')" "Yellow"
+ exit 1
+ }
+
+ Write-ColorOutput " Dependency graph validated (no cycles)" "Green"
+ Write-ColorOutput " Topological order: $($sorted -join ' -> ')" "Blue"
+
+ # Return services in topological order
+ return $sorted | ForEach-Object { $domainToService[$_] }
+}
+
+function Resolve-ConstructorArgument {
+ param([Parameter]$Param)
+
+ $type = $Param.NormalizedType
+
+ # SPECIAL CASE MAPPINGS - Add more here as needed
+ # ============================================
+
+ # 1. JWT secret string
+ if ($Param.RawType -eq "string" -and $Param.Name -match "secret|key") {
+ return "configProvider.ProvideJWTConfig().GetSecretKey()"
+ }
+
+ # 2. Repository pattern: XxxxRepository -> repoProvider.ProvideXxxxRepository()
+ if ($type -match '^(.+)Repository$') {
+ $repoName = $matches[1]
+ return "repoProvider.Provide${repoName}Repository()"
+ }
+
+ # 3. Service pattern: XxxxService -> use variable (will be constructed before this)
+ if ($type -match 'Service$') {
+ return (Get-LowerCamelCase $type)
+ }
+
+ # ADD MORE SPECIAL CASES HERE:
+ # --------------------------------------------
+ # Example: Mail config
+ # if ($type -eq "MailConfig") {
+ # return "configProvider.ProvideMailConfig()"
+ # }
+ #
+ # Example: Redis client
+ # if ($type -eq "RedisClient") {
+ # return "configProvider.ProvideRedisClient()"
+ # }
+ # --------------------------------------------
+
+ # 4. Fallback: unresolved type
+ return "/* TODO: provide $($Param.RawType) */"
+}
+
+function Generate-ProviderCode {
+ param([System.Collections.Generic.List[ServiceInfo]]$ServicesInOrder)
+
+ Write-ColorOutput "`nGenerating provider code..." "Cyan"
+
+ $sb = [System.Text.StringBuilder]::new()
+ [void]$sb.AppendLine("package provider")
+ [void]$sb.AppendLine()
+ [void]$sb.AppendLine("import `"$ModulePath`"")
+ [void]$sb.AppendLine()
+
+ # Interface
+ [void]$sb.AppendLine("type ServicesProvider interface {")
+ foreach ($svc in $ServicesInOrder) {
+ $line = "`tProvide$($svc.Domain)() services.$($svc.Domain)"
+ [void]$sb.AppendLine($line)
+ }
+ [void]$sb.AppendLine("}")
+ [void]$sb.AppendLine()
+
+ # Struct
+ [void]$sb.AppendLine("type servicesProvider struct {")
+ foreach ($svc in $ServicesInOrder) {
+ $line = "`t$($svc.VarName) services.$($svc.Domain)"
+ [void]$sb.AppendLine($line)
+ }
+ [void]$sb.AppendLine("}")
+ [void]$sb.AppendLine()
+
+ # Constructor
+ [void]$sb.AppendLine("func NewServicesProvider(repoProvider RepositoriesProvider, configProvider ConfigProvider) ServicesProvider {")
+
+ # Initialize services in topological order
+ foreach ($svc in $ServicesInOrder) {
+ $args = @()
+ foreach ($param in $svc.Parameters) {
+ $args += Resolve-ConstructorArgument $param
+ }
+ $argsStr = $args -join ", "
+ $line = "`t$($svc.VarName) := services.$($svc.ConstructorName)($argsStr)"
+ [void]$sb.AppendLine($line)
+ }
+
+ [void]$sb.AppendLine()
+ [void]$sb.AppendLine("`treturn &servicesProvider{")
+ foreach ($svc in $ServicesInOrder) {
+ $line = "`t`t$($svc.VarName): $($svc.VarName),"
+ [void]$sb.AppendLine($line)
+ }
+ [void]$sb.AppendLine("`t}")
+ [void]$sb.AppendLine("}")
+ [void]$sb.AppendLine()
+
+ # Getter methods
+ foreach ($svc in $ServicesInOrder) {
+ [void]$sb.AppendLine("func (s *servicesProvider) Provide$($svc.Domain)() services.$($svc.Domain) {")
+ [void]$sb.AppendLine("`treturn s.$($svc.VarName)")
+ [void]$sb.AppendLine("}")
+ [void]$sb.AppendLine()
+ }
+
+ return $sb.ToString()
+}
+
+function Write-ProviderFile {
+ param([string]$Code, [string]$OutputPath)
+
+ Write-ColorOutput "Writing to $OutputPath..." "Cyan"
+
+ # Ensure directory exists
+ $dir = Split-Path $OutputPath -Parent
+ if ($dir -and -not (Test-Path $dir)) {
+ New-Item -ItemType Directory -Path $dir -Force | Out-Null
+ }
+
+ # Write file as UTF-8 without BOM
+ $utf8NoBom = [System.Text.UTF8Encoding]::new($false)
+ [System.IO.File]::WriteAllText($OutputPath, $Code, $utf8NoBom)
+
+ Write-ColorOutput " Successfully generated $OutputPath" "Green"
+}
+
+# ============================================
+# MAIN EXECUTION
+# ============================================
+
+try {
+ Write-ColorOutput "`n=========================================" "Blue"
+ Write-ColorOutput " Go Service Dependency Injector v1.0" "Blue"
+ Write-ColorOutput "=========================================`n" "Blue"
+
+ # Step 1: Parse all service constructors
+ $services = Parse-GoFiles -Directory $ServicesDir
+
+ # Step 2: Perform topological sort
+ $sortedServices = Get-TopologicalOrder -Services $services
+
+ # Step 3: Generate provider code
+ $code = Generate-ProviderCode -ServicesInOrder $sortedServices
+
+ # Step 4: Write to file
+ Write-ProviderFile -Code $code -OutputPath $OutputFile
+
+ Write-ColorOutput "`nSUCCESS! Provider generated successfully.`n" "Green"
+ Write-ColorOutput "Next steps:" "Cyan"
+ Write-ColorOutput " 1. Review $OutputFile" "White"
+ Write-ColorOutput " 2. Fill any /* TODO: provide ... */ placeholders" "White"
+ Write-ColorOutput " 3. Run: go build ./provider" "White"
+
+} catch {
+ Write-ColorOutput "`nERROR: $($_.Exception.Message)" "Red"
+ Write-ColorOutput "Stack trace: $($_.ScriptStackTrace)" "Yellow"
+ exit 1
+}
\ No newline at end of file
diff --git a/cmd/seed/fixtures.go b/cmd/seed/fixtures.go
new file mode 100644
index 0000000000000000000000000000000000000000..0561003f5cb68a1ed39a2bb18e4d88eab5228e07
--- /dev/null
+++ b/cmd/seed/fixtures.go
@@ -0,0 +1,53 @@
+package main
+
+import (
+ "fmt"
+ "strconv"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+// DatasetVersion identifies the fixture set. Change it when the fixtures below
+// change; the startup seeder loads a version only once.
+const DatasetVersion = "2026-10-11.v1"
+
+// UserCount covers the largest scenario: PT-05 needs 2,000 distinct users.
+const UserCount = 10000
+
+// Every fixture has a deterministic ID (UUIDv5), so the pipeline can derive the
+// IDs it needs (seed -export) without connecting to the database.
+var namespace = uuid.MustParse("6f0c1b8e-3d2a-4c55-9b7e-1a2b3c4d5e6f")
+
+func fixtureId(name string) uuid.UUID { return uuid.NewSHA1(namespace, []byte(name)) }
+
+func UserId(n int) uuid.UUID { return fixtureId("user/" + strconv.Itoa(n)) }
+
+func EventId(key string) uuid.UUID { return fixtureId("event/" + key) }
+
+func TicketTypeId(key string, i int) uuid.UUID {
+ return fixtureId(fmt.Sprintf("event/%s/ticket-type/%d", key, i))
+}
+
+type fixtureEvent struct {
+ Key string
+ Name string
+ TicketTypes int
+ Capacity int
+}
+
+// Fixture events. Stock is reused across runs:
+// - load: 5 × 1,000,000 tickets, enough for many runs of PT-01 to PT-04.
+// - flash: 500 tickets. PT-05 never pays, so its holds expire and the sweeper
+// returns the stock 10 minutes after each run.
+// - smoke: 5 tickets. The smoke test releases everything it books.
+var fixtureEvents = []fixtureEvent{
+ {Key: "load", Name: "Perf load event", TicketTypes: 5, Capacity: 1_000_000},
+ {Key: "flash", Name: "Perf flash sale", TicketTypes: 1, Capacity: 500},
+ {Key: "smoke", Name: "Smoke test event", TicketTypes: 1, Capacity: 5},
+}
+
+// Far enough ahead that fixture events never stop selling.
+var fixtureStartsAt = time.Date(2099, 12, 31, 0, 0, 0, 0, time.UTC)
+
+const fixturePrice = 150000
diff --git a/cmd/seed/main.go b/cmd/seed/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..2361e8aaffa93cfa1eb5424bfe21ce2d015e8bc7
--- /dev/null
+++ b/cmd/seed/main.go
@@ -0,0 +1,150 @@
+// Command seed loads the fixed QA dataset (users and fixture events).
+//
+// seed ensure the dataset is in the database; skip if this
+// version was already seeded (runs at container startup)
+// seed -export DIR write users.csv and event.properties for JMeter and the
+// smoke test, from the deterministic IDs; no database needed
+package main
+
+import (
+ "context"
+ "encoding/csv"
+ "flag"
+ "fmt"
+ "log"
+ "os"
+ "path/filepath"
+ "time"
+
+ entity "abdanhafidz.com/event-booking-api/models/entity"
+ "abdanhafidz.com/event-booking-api/provider"
+ "gorm.io/gorm"
+ "gorm.io/gorm/clause"
+)
+
+// seedLockKey serialises seeders that start at the same time (two replicas).
+const seedLockKey = 7420001
+
+func main() {
+ export := flag.String("export", "", "write users.csv and event.properties to this directory and exit")
+ flag.Parse()
+
+ if *export != "" {
+ if err := Export(*export); err != nil {
+ log.Fatalf("[SEED] export failed: %v", err)
+ }
+ log.Printf("[SEED] exported dataset %s to %s", DatasetVersion, *export)
+ return
+ }
+
+ cfg := provider.NewConfigProvider()
+ if err := provider.Migrate(cfg); err != nil {
+ log.Fatalf("[SEED] migrate failed: %v", err)
+ }
+ seeded, err := Ensure(context.Background(), cfg.ProvideDatabaseConfig().GetInstance())
+ if err != nil {
+ log.Fatalf("[SEED] seeding failed: %v", err)
+ }
+ if seeded {
+ log.Printf("[SEED] dataset %s seeded: %d users, %d events", DatasetVersion, UserCount, len(fixtureEvents))
+ } else {
+ log.Printf("[SEED] dataset %s already seeded, skipping", DatasetVersion)
+ }
+}
+
+// Ensure loads the dataset unless its version marker exists. It reports
+// whether it seeded. The marker is written in the same transaction as the
+// data, so a failed seed leaves no marker and is retried on the next start.
+func Ensure(ctx context.Context, db *gorm.DB) (bool, error) {
+ seeded := false
+ err := db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if err := tx.Exec("SELECT pg_advisory_xact_lock(?)", seedLockKey).Error; err != nil {
+ return err
+ }
+ var markers int64
+ if err := tx.Model(&entity.SeedMarker{}).Where("version = ?", DatasetVersion).Count(&markers).Error; err != nil {
+ return err
+ }
+ if markers > 0 {
+ return nil
+ }
+
+ // ON CONFLICT DO NOTHING keeps rows from an older dataset version intact.
+ // A fresh chain per insert: a reused *gorm.DB would carry Omit/Clauses over.
+ insert := func() *gorm.DB { return tx.Clauses(clause.OnConflict{DoNothing: true}) }
+ users := make([]entity.User, 0, UserCount)
+ for i := 1; i <= UserCount; i++ {
+ users = append(users, entity.User{Id: UserId(i), Name: fmt.Sprintf("user-%d", i)})
+ }
+ if err := insert().CreateInBatches(&users, 1000).Error; err != nil {
+ return err
+ }
+
+ for _, f := range fixtureEvents {
+ event := entity.Event{Id: EventId(f.Key), Name: f.Name, StartsAt: fixtureStartsAt}
+ if err := insert().Omit("TicketTypes").Create(&event).Error; err != nil {
+ return err
+ }
+ for i := 0; i < f.TicketTypes; i++ {
+ tt := entity.TicketType{
+ Id: TicketTypeId(f.Key, i),
+ EventId: event.Id,
+ Name: fmt.Sprintf("Tier %d", i+1),
+ Price: fixturePrice,
+ Capacity: f.Capacity,
+ Available: f.Capacity,
+ }
+ if err := insert().Create(&tt).Error; err != nil {
+ return err
+ }
+ }
+ }
+
+ seeded = true
+ return tx.Create(&entity.SeedMarker{Version: DatasetVersion, SeededAt: time.Now().UTC()}).Error
+ })
+ return seeded, err
+}
+
+// Export writes the files the pipeline needs, using the same IDs Ensure seeds.
+func Export(dir string) error {
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ return err
+ }
+
+ f, err := os.Create(filepath.Join(dir, "users.csv"))
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ w := csv.NewWriter(f)
+ for i := 1; i <= UserCount; i++ {
+ if err := w.Write([]string{UserId(i).String()}); err != nil {
+ return err
+ }
+ }
+ w.Flush()
+ if err := w.Error(); err != nil {
+ return err
+ }
+
+ p, err := os.Create(filepath.Join(dir, "event.properties"))
+ if err != nil {
+ return err
+ }
+ defer p.Close()
+ fmt.Fprintf(p, "dataset_version=%s\n", DatasetVersion)
+ for _, ev := range fixtureEvents {
+ switch ev.Key {
+ case "load":
+ fmt.Fprintf(p, "event_id=%s\nticket_type_count=%d\n", EventId(ev.Key), ev.TicketTypes)
+ for i := 0; i < ev.TicketTypes; i++ {
+ fmt.Fprintf(p, "ticket_type_id_%d=%s\n", i, TicketTypeId(ev.Key, i))
+ }
+ default:
+ fmt.Fprintf(p, "%s_event_id=%s\n%s_ticket_type_id=%s\n%s_tickets=%d\n",
+ ev.Key, EventId(ev.Key), ev.Key, TicketTypeId(ev.Key, 0), ev.Key, ev.Capacity)
+ }
+ }
+ return nil
+}
diff --git a/cmd/seed/seed_test.go b/cmd/seed/seed_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..583adb426a828996fcbc0d0aafc6924bdf095fa6
--- /dev/null
+++ b/cmd/seed/seed_test.go
@@ -0,0 +1,67 @@
+package main
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "abdanhafidz.com/event-booking-api/config"
+ entity "abdanhafidz.com/event-booking-api/models/entity"
+)
+
+func TestExportMatchesSeededIds(t *testing.T) {
+ dir := t.TempDir()
+ if err := Export(dir); err != nil {
+ t.Fatal(err)
+ }
+ props, _ := os.ReadFile(filepath.Join(dir, "event.properties"))
+ for _, want := range []string{
+ "event_id=" + EventId("load").String(),
+ "ticket_type_id_4=" + TicketTypeId("load", 4).String(),
+ "flash_ticket_type_id=" + TicketTypeId("flash", 0).String(),
+ "flash_tickets=500",
+ "smoke_ticket_type_id=" + TicketTypeId("smoke", 0).String(),
+ } {
+ if !strings.Contains(string(props), want+"\n") {
+ t.Errorf("event.properties missing %q", want)
+ }
+ }
+ users, _ := os.ReadFile(filepath.Join(dir, "users.csv"))
+ if lines := strings.Count(string(users), "\n"); lines != UserCount {
+ t.Errorf("users.csv: want %d lines, got %d", UserCount, lines)
+ }
+}
+
+// Needs TEST_DATABASE_URL. The second call must skip and change nothing.
+func TestEnsureSeedsOnceThenSkips(t *testing.T) {
+ dsn := os.Getenv("TEST_DATABASE_URL")
+ if dsn == "" {
+ t.Skip("TEST_DATABASE_URL not set")
+ }
+ dbConfig := config.NewDatabaseConfigFromDSN(dsn, 5)
+ if err := dbConfig.AutoMigrateAll(entity.AllEntities()...); err != nil {
+ t.Fatal(err)
+ }
+ db := dbConfig.GetInstance()
+ db.Exec("DELETE FROM seed_markers WHERE version = ?", DatasetVersion)
+
+ if _, err := Ensure(context.Background(), db); err != nil {
+ t.Fatal(err)
+ }
+ var available int
+ db.Raw("SELECT available FROM ticket_types WHERE id = ?", TicketTypeId("smoke", 0)).Scan(&available)
+ db.Exec("UPDATE ticket_types SET available = available - 1 WHERE id = ?", TicketTypeId("smoke", 0))
+
+ seeded, err := Ensure(context.Background(), db)
+ if err != nil || seeded {
+ t.Fatalf("second run: want skip, got seeded=%v err=%v", seeded, err)
+ }
+ var after int
+ db.Raw("SELECT available FROM ticket_types WHERE id = ?", TicketTypeId("smoke", 0)).Scan(&after)
+ if after != available-1 {
+ t.Fatalf("skip must not touch existing data: available %d, want %d", after, available-1)
+ }
+ db.Exec("UPDATE ticket_types SET available = available + 1 WHERE id = ?", TicketTypeId("smoke", 0))
+}
diff --git a/config/booking_config.go b/config/booking_config.go
new file mode 100644
index 0000000000000000000000000000000000000000..a948d2300154f8e672a93cd74ae404a4b2ec8d4a
--- /dev/null
+++ b/config/booking_config.go
@@ -0,0 +1,41 @@
+package config
+
+import "time"
+
+// BookingConfig holds the booking rules that tests need to shorten (hold time,
+// sweep interval) and the mock payment behaviour.
+type BookingConfig interface {
+ GetHoldTTL() time.Duration
+ GetSweepInterval() time.Duration
+ IsSweeperEnabled() bool
+ GetPaymentTimeout() time.Duration
+ GetMockPayLatency() time.Duration
+ GetIdempotencyTTL() time.Duration
+}
+
+type bookingConfig struct {
+ holdTTL time.Duration
+ sweepInterval time.Duration
+ sweeperEnabled bool
+ paymentTimeout time.Duration
+ mockPayLatency time.Duration
+ idempotencyTTL time.Duration
+}
+
+func NewBookingConfig(holdTTL, sweepInterval time.Duration, sweeperEnabled bool, paymentTimeout, mockPayLatency, idempotencyTTL time.Duration) BookingConfig {
+ return &bookingConfig{
+ holdTTL: holdTTL,
+ sweepInterval: sweepInterval,
+ sweeperEnabled: sweeperEnabled,
+ paymentTimeout: paymentTimeout,
+ mockPayLatency: mockPayLatency,
+ idempotencyTTL: idempotencyTTL,
+ }
+}
+
+func (c *bookingConfig) GetHoldTTL() time.Duration { return c.holdTTL }
+func (c *bookingConfig) GetSweepInterval() time.Duration { return c.sweepInterval }
+func (c *bookingConfig) IsSweeperEnabled() bool { return c.sweeperEnabled }
+func (c *bookingConfig) GetPaymentTimeout() time.Duration { return c.paymentTimeout }
+func (c *bookingConfig) GetMockPayLatency() time.Duration { return c.mockPayLatency }
+func (c *bookingConfig) GetIdempotencyTTL() time.Duration { return c.idempotencyTTL }
diff --git a/config/database_config.go b/config/database_config.go
new file mode 100644
index 0000000000000000000000000000000000000000..8fdbc6118dd9595f8eaf0af69005a67a9642d379
--- /dev/null
+++ b/config/database_config.go
@@ -0,0 +1,65 @@
+package config
+
+import (
+ "fmt"
+ "log"
+ "strings"
+
+ "gorm.io/driver/postgres"
+ "gorm.io/gorm"
+ "gorm.io/gorm/logger"
+)
+
+type DatabaseConfig interface {
+ AutoMigrateAll(entities ...interface{}) error
+ GetInstance() *gorm.DB
+}
+type databaseConfig struct {
+ db *gorm.DB
+}
+
+func NewDatabaseConfig(host, user, password, name, port, sslMode string, poolSize int) DatabaseConfig {
+ // Values are quoted: an empty or space-containing password would otherwise
+ // swallow the next key (password= dbname=x makes "dbname=x" the password).
+ // TimeZone=UTC so every timestamp the API returns is UTC, as the RFC specifies.
+ dsn := fmt.Sprintf(
+ "host=%s user=%s password=%s dbname=%s port=%s sslmode=%s TimeZone=UTC",
+ quoteDSN(host), quoteDSN(user), quoteDSN(password), quoteDSN(name), quoteDSN(port), quoteDSN(sslMode),
+ )
+ return NewDatabaseConfigFromDSN(dsn, poolSize)
+}
+
+func quoteDSN(v string) string {
+ return "'" + strings.NewReplacer(`\`, `\\`, `'`, `\'`).Replace(v) + "'"
+}
+
+func NewDatabaseConfigFromDSN(dsn string, poolSize int) DatabaseConfig {
+ db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
+ TranslateError: true,
+ Logger: logger.Default.LogMode(logger.Warn),
+ })
+ if err != nil {
+ log.Fatal("Failed to connect to database:", err)
+ }
+
+ db = db.Session(&gorm.Session{
+ PrepareStmt: false,
+ })
+
+ sqlDB, err := db.DB()
+ if err != nil {
+ log.Fatal("Failed to get database handle:", err)
+ }
+ sqlDB.SetMaxOpenConns(poolSize)
+ sqlDB.SetMaxIdleConns(poolSize)
+
+ return &databaseConfig{db: db}
+}
+
+func (cfg *databaseConfig) AutoMigrateAll(entities ...interface{}) error {
+ return cfg.db.AutoMigrate(entities...)
+}
+
+func (cfg *databaseConfig) GetInstance() *gorm.DB {
+ return cfg.db
+}
diff --git a/config/database_config_test.go b/config/database_config_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..c597435d24c6b2904f7d32e09a42feb406529146
--- /dev/null
+++ b/config/database_config_test.go
@@ -0,0 +1,20 @@
+package config
+
+import (
+ "testing"
+
+ "github.com/jackc/pgx/v5"
+)
+
+func TestDSNQuotingSurvivesEmptyAndSpecialPasswords(t *testing.T) {
+ for _, password := range []string{"", "with space", `it's\tricky`} {
+ dsn := "host=" + quoteDSN("localhost") + " password=" + quoteDSN(password) + " dbname=" + quoteDSN("booking_test")
+ cfg, err := pgx.ParseConfig(dsn)
+ if err != nil {
+ t.Fatalf("%q: %v", password, err)
+ }
+ if cfg.Password != password || cfg.Database != "booking_test" {
+ t.Fatalf("%q: got password %q, database %q", password, cfg.Password, cfg.Database)
+ }
+ }
+}
diff --git a/config/env_config.go b/config/env_config.go
new file mode 100644
index 0000000000000000000000000000000000000000..75137891d5fffb227c37c400ab3cdc62fa32a630
--- /dev/null
+++ b/config/env_config.go
@@ -0,0 +1,91 @@
+package config
+
+import (
+ "strconv"
+ "time"
+
+ "abdanhafidz.com/event-booking-api/utils"
+ "github.com/joho/godotenv"
+)
+
+type EnvConfig interface {
+ GetTCPAddress() string
+ GetDatabaseHost() string
+ GetDatabasePort() string
+ GetDatabaseUser() string
+ GetDatabasePassword() string
+ GetDatabaseName() string
+ GetDatabaseSSLMode() string
+ GetDatabasePoolSize() int
+ GetHoldTTL() time.Duration
+ GetSweepInterval() time.Duration
+ IsSweeperEnabled() bool
+ GetPaymentTimeout() time.Duration
+ GetMockPayLatency() time.Duration
+ GetIdempotencyTTL() time.Duration
+ GetRequestTimeout() time.Duration
+}
+
+type envConfig struct{}
+
+func NewEnvConfig() EnvConfig {
+ godotenv.Load()
+ return &envConfig{}
+}
+
+func (e *envConfig) GetTCPAddress() string {
+ return getOr("HOST_ADDRESS", "0.0.0.0") + ":" + getOr("HOST_PORT", "8080")
+}
+
+func (e *envConfig) GetDatabaseHost() string { return getOr("DB_HOST", "localhost") }
+func (e *envConfig) GetDatabasePort() string { return getOr("DB_PORT", "5432") }
+func (e *envConfig) GetDatabaseUser() string { return getOr("DB_USER", "postgres") }
+func (e *envConfig) GetDatabasePassword() string { return utils.GetEnv("DB_PASSWORD") }
+func (e *envConfig) GetDatabaseName() string { return getOr("DB_NAME", "postgres") }
+func (e *envConfig) GetDatabaseSSLMode() string { return getOr("DB_SSLMODE", "disable") }
+
+func (e *envConfig) GetDatabasePoolSize() int {
+ n, err := strconv.Atoi(getOr("DB_POOL_SIZE", "20"))
+ if err != nil || n < 1 {
+ return 20
+ }
+ return n
+}
+
+func (e *envConfig) GetHoldTTL() time.Duration { return durationOr("HOLD_TTL", 10*time.Minute) }
+func (e *envConfig) GetSweepInterval() time.Duration {
+ return durationOr("SWEEP_INTERVAL", 5*time.Second)
+}
+func (e *envConfig) IsSweeperEnabled() bool { return getOr("SWEEPER_ENABLED", "true") == "true" }
+func (e *envConfig) GetPaymentTimeout() time.Duration {
+ return durationOr("PAYMENT_TIMEOUT", 2*time.Second)
+}
+func (e *envConfig) GetIdempotencyTTL() time.Duration {
+ return durationOr("IDEMPOTENCY_TTL", 24*time.Hour)
+}
+func (e *envConfig) GetRequestTimeout() time.Duration {
+ return durationOr("REQUEST_TIMEOUT", 4*time.Second)
+}
+
+func (e *envConfig) GetMockPayLatency() time.Duration {
+ ms, err := strconv.Atoi(getOr("MOCKPAY_LATENCY_MS", "0"))
+ if err != nil || ms < 0 {
+ return 0
+ }
+ return time.Duration(ms) * time.Millisecond
+}
+
+func getOr(key, fallback string) string {
+ if v := utils.GetEnv(key); v != "" {
+ return v
+ }
+ return fallback
+}
+
+func durationOr(key string, fallback time.Duration) time.Duration {
+ d, err := time.ParseDuration(utils.GetEnv(key))
+ if err != nil {
+ return fallback
+ }
+ return d
+}
diff --git a/controllers/booking_controller.go b/controllers/booking_controller.go
new file mode 100644
index 0000000000000000000000000000000000000000..702c97b6df0cdf6e384d3cab8561f89e21177527
--- /dev/null
+++ b/controllers/booking_controller.go
@@ -0,0 +1,130 @@
+package controllers
+
+import (
+ "abdanhafidz.com/event-booking-api/models/dto"
+ http_error "abdanhafidz.com/event-booking-api/models/error"
+ "abdanhafidz.com/event-booking-api/services"
+ "abdanhafidz.com/event-booking-api/utils"
+ "github.com/gin-gonic/gin"
+)
+
+type BookingController interface {
+ Create(ctx *gin.Context)
+ Get(ctx *gin.Context)
+ Pay(ctx *gin.Context)
+ Cancel(ctx *gin.Context)
+}
+
+type bookingController struct {
+ bookingService services.BookingService
+}
+
+func NewBookingController(bookingService services.BookingService) BookingController {
+ return &bookingController{bookingService: bookingService}
+}
+
+// Create Booking godoc
+// @Summary Reserve tickets
+// @Description Reserves tickets all-or-nothing and starts the payment hold
+// @Tags Booking
+// @Accept json
+// @Produce json
+// @Param X-User-Id header string true "Caller user ID"
+// @Param Idempotency-Key header string true "Idempotency key"
+// @Param request body dto.CreateBookingRequest true "Booking request"
+// @Success 201 {object} dto.SuccessResponse[dto.BookingResponse]
+// @Failure 400 {object} dto.ErrorResponse
+// @Failure 401 {object} dto.ErrorResponse
+// @Failure 404 {object} dto.ErrorResponse
+// @Failure 409 {object} dto.ErrorResponse
+// @Failure 422 {object} dto.ErrorResponse
+// @Router /v1/bookings [post]
+func (c *bookingController) Create(ctx *gin.Context) {
+ key, ok := RequireIdempotencyKey(ctx)
+ if !ok {
+ return
+ }
+ req := RequestJSON[dto.CreateBookingRequest](ctx)
+ if ctx.IsAborted() {
+ return
+ }
+ res, replayed, err := c.bookingService.Create(ctx.Request.Context(), ParseUserId(ctx), key, req)
+ markReplayed(ctx, replayed)
+ if err != nil {
+ ResponseJSON[any, any](ctx, nil, res, err)
+ return
+ }
+ utils.ResponseCreated[any, any](ctx, nil, res)
+ ctx.Abort()
+}
+
+// Get Booking godoc
+// @Summary Get one of your bookings
+// @Tags Booking
+// @Produce json
+// @Param X-User-Id header string true "Caller user ID"
+// @Param id path string true "Booking ID"
+// @Success 200 {object} dto.SuccessResponse[dto.BookingResponse]
+// @Failure 404 {object} dto.ErrorResponse
+// @Router /v1/bookings/{id} [get]
+func (c *bookingController) Get(ctx *gin.Context) {
+ id, ok := ParseUUIDParam(ctx, "id", http_error.BOOKING_NOT_FOUND)
+ if !ok {
+ return
+ }
+ res, err := c.bookingService.Get(ctx.Request.Context(), ParseUserId(ctx), id)
+ ResponseJSON[any, any](ctx, nil, res, err)
+}
+
+// Pay Booking godoc
+// @Summary Pay for a booking with the mock gateway
+// @Description tok_success confirms; tok_decline and tok_timeout fail the booking and release its tickets
+// @Tags Booking
+// @Accept json
+// @Produce json
+// @Param X-User-Id header string true "Caller user ID"
+// @Param Idempotency-Key header string true "Idempotency key"
+// @Param id path string true "Booking ID"
+// @Param request body dto.PayBookingRequest true "Payment request"
+// @Success 200 {object} dto.SuccessResponse[dto.BookingResponse]
+// @Failure 402 {object} dto.ErrorResponse
+// @Failure 404 {object} dto.ErrorResponse
+// @Failure 409 {object} dto.ErrorResponse
+// @Failure 422 {object} dto.ErrorResponse
+// @Router /v1/bookings/{id}/pay [post]
+func (c *bookingController) Pay(ctx *gin.Context) {
+ id, ok := ParseUUIDParam(ctx, "id", http_error.BOOKING_NOT_FOUND)
+ if !ok {
+ return
+ }
+ key, ok := RequireIdempotencyKey(ctx)
+ if !ok {
+ return
+ }
+ req := RequestJSON[dto.PayBookingRequest](ctx)
+ if ctx.IsAborted() {
+ return
+ }
+ res, replayed, err := c.bookingService.Pay(ctx.Request.Context(), ParseUserId(ctx), id, key, req)
+ markReplayed(ctx, replayed)
+ ResponseJSON[any, any](ctx, nil, res, err)
+}
+
+// Cancel Booking godoc
+// @Summary Cancel a pending or confirmed booking before the event starts
+// @Tags Booking
+// @Produce json
+// @Param X-User-Id header string true "Caller user ID"
+// @Param id path string true "Booking ID"
+// @Success 200 {object} dto.SuccessResponse[dto.BookingResponse]
+// @Failure 404 {object} dto.ErrorResponse
+// @Failure 409 {object} dto.ErrorResponse
+// @Router /v1/bookings/{id}/cancel [post]
+func (c *bookingController) Cancel(ctx *gin.Context) {
+ id, ok := ParseUUIDParam(ctx, "id", http_error.BOOKING_NOT_FOUND)
+ if !ok {
+ return
+ }
+ res, err := c.bookingService.Cancel(ctx.Request.Context(), ParseUserId(ctx), id)
+ ResponseJSON[any, any](ctx, nil, res, err)
+}
diff --git a/controllers/controller.go b/controllers/controller.go
new file mode 100644
index 0000000000000000000000000000000000000000..e3744ee8f10d018c6367ce72878be8ebd2c02a71
--- /dev/null
+++ b/controllers/controller.go
@@ -0,0 +1,85 @@
+package controllers
+
+import (
+ "encoding/json"
+ "errors"
+ "regexp"
+
+ http_error "abdanhafidz.com/event-booking-api/models/error"
+ "abdanhafidz.com/event-booking-api/utils"
+ "github.com/gin-gonic/gin"
+ "github.com/go-playground/validator/v10"
+ uuid "github.com/google/uuid"
+)
+
+var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`)
+
+// ParseUserId reads the caller set by the user middleware.
+func ParseUserId(ctx *gin.Context) uuid.UUID {
+ id, _ := ctx.Get("user_id")
+ userId, _ := id.(uuid.UUID)
+ return userId
+}
+
+// ParseUUIDParam parses a path parameter. A malformed ID cannot match any row,
+// so it is reported with the resource's not-found error.
+func ParseUUIDParam(ctx *gin.Context, name string, notFound error) (uuid.UUID, bool) {
+ id, err := uuid.Parse(ctx.Param(name))
+ if err != nil {
+ utils.ResponseFAILED[any](ctx, nil, notFound)
+ ctx.Abort()
+ return uuid.UUID{}, false
+ }
+ return id, true
+}
+
+// RequireIdempotencyKey enforces BR-09 before the body is read.
+func RequireIdempotencyKey(ctx *gin.Context) (string, bool) {
+ key := ctx.GetHeader("Idempotency-Key")
+ if key == "" {
+ utils.ResponseFAILED[any](ctx, nil, http_error.IDEMPOTENCY_KEY_REQUIRED)
+ ctx.Abort()
+ return "", false
+ }
+ if !idempotencyKeyPattern.MatchString(key) {
+ utils.ResponseFAILED[any](ctx, nil, http_error.VALIDATION_ERROR.WithDetails(map[string]any{
+ "field": "Idempotency-Key", "reason": "1-64 characters from A-Z a-z 0-9 _ -",
+ }))
+ ctx.Abort()
+ return "", false
+ }
+ return key, true
+}
+
+// RequestJSON binds and validates the body. On failure it writes a
+// VALIDATION_ERROR naming the field and aborts; callers must check IsAborted.
+func RequestJSON[TRequest any](ctx *gin.Context) TRequest {
+ var request TRequest
+ if err := ctx.ShouldBindJSON(&request); err != nil {
+ utils.ResponseFAILED[any](ctx, nil, http_error.VALIDATION_ERROR.WithDetails(validationDetails(err)))
+ ctx.Abort()
+ }
+ return request
+}
+
+func validationDetails(err error) map[string]any {
+ var verrs validator.ValidationErrors
+ if errors.As(err, &verrs) && len(verrs) > 0 {
+ return map[string]any{"field": verrs[0].Field(), "reason": verrs[0].Tag()}
+ }
+ var typeErr *json.UnmarshalTypeError
+ if errors.As(err, &typeErr) {
+ return map[string]any{"field": typeErr.Field, "reason": "must be " + typeErr.Type.String()}
+ }
+ return map[string]any{"reason": "malformed JSON body"}
+}
+
+func ResponseJSON[TResponse any, TMetaData any](ctx *gin.Context, metaData TMetaData, res TResponse, err error) {
+ utils.SendResponse(ctx, metaData, res, err)
+}
+
+func markReplayed(ctx *gin.Context, replayed bool) {
+ if replayed {
+ ctx.Header("Idempotent-Replayed", "true")
+ }
+}
diff --git a/controllers/event_controller.go b/controllers/event_controller.go
new file mode 100644
index 0000000000000000000000000000000000000000..bd7e874a3e45d774c78b0ccbced1b8f83953ee23
--- /dev/null
+++ b/controllers/event_controller.go
@@ -0,0 +1,41 @@
+package controllers
+
+import (
+ "abdanhafidz.com/event-booking-api/models/dto"
+ http_error "abdanhafidz.com/event-booking-api/models/error"
+ "abdanhafidz.com/event-booking-api/services"
+ "github.com/gin-gonic/gin"
+)
+
+// Referenced by the swagger annotations below.
+var _ dto.EventResponse
+
+type EventController interface {
+ Get(ctx *gin.Context)
+}
+
+type eventController struct {
+ eventService services.EventService
+}
+
+func NewEventController(eventService services.EventService) EventController {
+ return &eventController{eventService: eventService}
+}
+
+// Get Event godoc
+// @Summary Get an event
+// @Description Event with its ticket types and live availability
+// @Tags Event
+// @Produce json
+// @Param id path string true "Event ID"
+// @Success 200 {object} dto.SuccessResponse[dto.EventResponse]
+// @Failure 404 {object} dto.ErrorResponse
+// @Router /v1/events/{id} [get]
+func (c *eventController) Get(ctx *gin.Context) {
+ id, ok := ParseUUIDParam(ctx, "id", http_error.EVENT_NOT_FOUND)
+ if !ok {
+ return
+ }
+ res, err := c.eventService.Get(ctx.Request.Context(), id)
+ ResponseJSON[any, any](ctx, nil, res, err)
+}
diff --git a/docker-compose.yml b/docker-compose.yml
new file mode 100644
index 0000000000000000000000000000000000000000..862accaa19681227a525d3adafa59eb759931ce7
--- /dev/null
+++ b/docker-compose.yml
@@ -0,0 +1,27 @@
+# Local stack: API + PostgreSQL. For the QA environment the API runs on
+# Hugging Face Spaces and the database is Supabase.
+services:
+ db:
+ image: postgres:16
+ environment:
+ POSTGRES_PASSWORD: postgres
+ POSTGRES_DB: booking
+ ports: ["5432:5432"]
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U postgres"]
+ interval: 2s
+ retries: 30
+
+ api:
+ build: .
+ depends_on:
+ db: { condition: service_healthy }
+ environment:
+ DB_HOST: db
+ DB_PORT: "5432"
+ DB_USER: postgres
+ DB_PASSWORD: postgres
+ DB_NAME: booking
+ DB_SSLMODE: disable
+ MOCKPAY_LATENCY_MS: "100"
+ ports: ["8080:7860"]
diff --git a/entrypoint.sh b/entrypoint.sh
new file mode 100644
index 0000000000000000000000000000000000000000..71eab9d9cc61dd18f85fb6286bd372bc4fce00e9
--- /dev/null
+++ b/entrypoint.sh
@@ -0,0 +1,11 @@
+#!/bin/sh
+# Container startup: load the QA dataset if this version is not there yet
+# (the seeder checks and skips on its own), then start the API.
+# Set SEED_ON_STARTUP=false to start without seeding (for example in production).
+set -e
+
+if [ "${SEED_ON_STARTUP:-true}" = "true" ]; then
+ /app/seed
+fi
+
+exec /app/app
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000000000000000000000000000000000000..32954331c93f3934dc77f8018bf671c515ae777d
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,66 @@
+module abdanhafidz.com/event-booking-api
+
+go 1.26.0
+
+require (
+ github.com/gin-gonic/gin v1.12.0
+ github.com/go-playground/validator/v10 v10.30.5
+ github.com/google/uuid v1.6.0
+ github.com/jackc/pgx/v5 v5.10.0
+ github.com/joho/godotenv v1.5.1
+ github.com/swaggo/files v1.0.1
+ github.com/swaggo/gin-swagger v1.6.1
+ github.com/swaggo/swag v1.16.6
+ gorm.io/driver/postgres v1.6.3
+ gorm.io/gorm v1.31.2
+)
+
+require (
+ github.com/KyleBanks/depth v1.2.1 // indirect
+ github.com/PuerkitoBio/purell v1.1.1 // indirect
+ github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect
+ github.com/bytedance/gopkg v0.1.3 // indirect
+ github.com/bytedance/sonic v1.15.0 // indirect
+ github.com/bytedance/sonic/loader v0.5.0 // indirect
+ github.com/cloudwego/base64x v0.1.6 // indirect
+ github.com/gabriel-vasile/mimetype v1.4.15 // indirect
+ github.com/gin-contrib/sse v1.1.0 // indirect
+ github.com/go-openapi/jsonpointer v0.19.5 // indirect
+ github.com/go-openapi/jsonreference v0.19.6 // indirect
+ github.com/go-openapi/spec v0.20.4 // indirect
+ github.com/go-openapi/swag v0.19.15 // indirect
+ github.com/go-playground/locales v0.14.1 // indirect
+ github.com/go-playground/universal-translator v0.18.1 // indirect
+ github.com/goccy/go-json v0.10.5 // indirect
+ github.com/goccy/go-yaml v1.19.2 // indirect
+ github.com/jackc/pgpassfile v1.0.0 // indirect
+ github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
+ github.com/jackc/puddle/v2 v2.2.2 // indirect
+ github.com/jinzhu/inflection v1.0.0 // indirect
+ github.com/jinzhu/now v1.1.5 // indirect
+ github.com/josharian/intern v1.0.0 // indirect
+ github.com/json-iterator/go v1.1.12 // indirect
+ github.com/klauspost/cpuid/v2 v2.3.0 // indirect
+ github.com/leodido/go-urn v1.5.0 // indirect
+ github.com/mailru/easyjson v0.7.6 // indirect
+ github.com/mattn/go-isatty v0.0.20 // indirect
+ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
+ github.com/modern-go/reflect2 v1.0.2 // indirect
+ github.com/pelletier/go-toml/v2 v2.2.4 // indirect
+ github.com/quic-go/qpack v0.6.0 // indirect
+ github.com/quic-go/quic-go v0.63.0 // indirect
+ github.com/rogpeppe/go-internal v1.16.0 // indirect
+ github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
+ github.com/ugorji/go/codec v1.3.1 // indirect
+ go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
+ golang.org/x/arch v0.22.0 // indirect
+ golang.org/x/crypto v0.58.0 // indirect
+ golang.org/x/mod v0.41.0 // indirect
+ golang.org/x/net v0.61.0 // indirect
+ golang.org/x/sync v0.24.0 // indirect
+ golang.org/x/sys v0.49.0 // indirect
+ golang.org/x/text v0.43.0 // indirect
+ golang.org/x/tools v0.51.0 // indirect
+ google.golang.org/protobuf v1.36.10 // indirect
+ gopkg.in/yaml.v2 v2.4.0 // indirect
+)
diff --git a/go.sum b/go.sum
new file mode 100644
index 0000000000000000000000000000000000000000..9b43c44a7276efc6ccb5be547bfbaea292a4470a
--- /dev/null
+++ b/go.sum
@@ -0,0 +1,202 @@
+github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=
+github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=
+github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI=
+github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
+github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M=
+github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
+github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
+github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
+github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=
+github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k=
+github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE=
+github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
+github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
+github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
+github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI=
+github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ=
+github.com/gin-contrib/gzip v0.0.6 h1:NjcunTcGAj5CO1gn4N8jHOSIeRFHIbn51z6K+xaN4d4=
+github.com/gin-contrib/gzip v0.0.6/go.mod h1:QOJlmV2xmayAjkNS2Y8NQsMneuRShOU/kjovCXNuzzk=
+github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
+github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
+github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=
+github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=
+github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
+github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY=
+github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
+github.com/go-openapi/jsonreference v0.19.6 h1:UBIxjkht+AWIgYzCDSv2GN+E/togfwXUJFRTWhl2Jjs=
+github.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns=
+github.com/go-openapi/spec v0.20.4 h1:O8hJrt0UMnhHcluhIdUgCLRWyM2x7QkBXRvOs7m+O1M=
+github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7FOEWeq8I=
+github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk=
+github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM=
+github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ=
+github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
+github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
+github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
+github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
+github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
+github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
+github.com/go-playground/validator/v10 v10.30.5 h1:YyCXvVShZbs2Sm3Mb53eNOlhRXctSOzW5QJAouCTZL4=
+github.com/go-playground/validator/v10 v10.30.5/go.mod h1:wEqiaov48pXX1kjhc3Da8y0M0Dtg/BK7gurFBLgwFrQ=
+github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
+github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
+github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
+github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
+github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
+github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
+github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
+github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
+github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
+github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
+github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
+github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
+github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
+github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
+github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
+github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
+github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
+github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
+github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
+github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
+github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
+github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
+github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
+github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
+github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
+github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
+github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
+github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
+github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
+github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
+github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
+github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
+github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
+github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA=
+github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
+github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
+github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
+github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
+github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
+github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
+github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
+github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/quic-go/go-ossfuzz-seeds v0.1.0 h1:APacT+iIaNF6fd8AGEiN3bT/Jtkd2jz4v4TzM7MFjy0=
+github.com/quic-go/go-ossfuzz-seeds v0.1.0/go.mod h1:3IOHRbJIc+L6YKMwfDtJAM9Vj9k0YY4muhuyUYk5tbk=
+github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
+github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
+github.com/quic-go/quic-go v0.63.0 h1:LIFGHI4PFUhhw2dDD1ARHdCff143ffMHwZtbnbuJ78A=
+github.com/quic-go/quic-go v0.63.0/go.mod h1:RAro2j2yN9a9EiPACLHT9IB2NXCvGQmmo/alT0yYI0w=
+github.com/rogpeppe/go-internal v1.16.0 h1:O9DK+vNMDVGLr2BeZqmpLeMjiMNkuXfcqntWbZV6S5g=
+github.com/rogpeppe/go-internal v1.16.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs=
+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
+github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
+github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
+github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
+github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
+github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
+github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
+github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
+github.com/swaggo/files v1.0.1 h1:J1bVJ4XHZNq0I46UU90611i9/YzdrF7x92oX1ig5IdE=
+github.com/swaggo/files v1.0.1/go.mod h1:0qXmMNH6sXNf+73t65aKeB+ApmgxdnkQzVTAj2uaMUg=
+github.com/swaggo/gin-swagger v1.6.1 h1:Ri06G4gc9N4t4k8hekMigJ9zKTFSlqj/9paAQCQs7cY=
+github.com/swaggo/gin-swagger v1.6.1/go.mod h1:LQ+hJStHakCWRiK/YNYtJOu4mR2FP+pxLnILT/qNiTw=
+github.com/swaggo/swag v1.16.6 h1:qBNcx53ZaX+M5dxVyTrgQ0PJ/ACK+NzhwcbieTt+9yI=
+github.com/swaggo/swag v1.16.6/go.mod h1:ngP2etMK5a0P3QBizic5MEwpRmluJZPHjXcMoj4Xesg=
+github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
+github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
+github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
+github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
+github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
+go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
+go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
+go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
+go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
+go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
+go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
+golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=
+golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
+golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
+golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
+golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
+golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
+golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
+golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
+golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
+golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
+golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM=
+golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
+golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
+golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw=
+golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
+golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
+golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
+golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
+golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
+golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
+golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
+golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
+golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
+golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
+golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
+golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
+golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
+golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
+golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI=
+golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA=
+golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
+google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
+gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
+gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
+gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gorm.io/driver/postgres v1.6.3 h1:bAn6O2pUa8LtpWEvL5NFU4+52Tfx8Ut7IVaIacCLcI0=
+gorm.io/driver/postgres v1.6.3/go.mod h1:0c4fQA44XhOklXDkgtuKqysHCycTa5i9e3EIpDGCwXk=
+gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
+gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
+gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo=
+gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
diff --git a/main.go b/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..b1fa13c3b744d41f8e451c25cca3294ddb67d281
--- /dev/null
+++ b/main.go
@@ -0,0 +1,15 @@
+package main
+
+import (
+ "log/slog"
+ "os"
+
+ "abdanhafidz.com/event-booking-api/provider"
+ "abdanhafidz.com/event-booking-api/router"
+)
+
+func main() {
+ slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, nil)))
+ appProvider := provider.NewAppProvider()
+ router.RunRouter(appProvider)
+}
diff --git a/middleware/request_middleware.go b/middleware/request_middleware.go
new file mode 100644
index 0000000000000000000000000000000000000000..f0a9c8f9994f1c82621b83eb37d59049fb5f793a
--- /dev/null
+++ b/middleware/request_middleware.go
@@ -0,0 +1,57 @@
+package middleware
+
+import (
+ "context"
+ "log/slog"
+ "time"
+
+ "github.com/gin-gonic/gin"
+ "github.com/google/uuid"
+)
+
+type RequestMiddleware interface {
+ Log(ctx *gin.Context)
+ Timeout(ctx *gin.Context)
+}
+
+type requestMiddleware struct {
+ timeout time.Duration
+}
+
+func NewRequestMiddleware(timeout time.Duration) RequestMiddleware {
+ return &requestMiddleware{timeout: timeout}
+}
+
+// Log writes one JSON line per request (NFR-05) and tags it with a request ID.
+func (m *requestMiddleware) Log(c *gin.Context) {
+ start := time.Now()
+ requestId := c.GetHeader("X-Request-Id")
+ if requestId == "" {
+ requestId = uuid.NewString()
+ }
+ c.Set("request_id", requestId)
+ c.Header("X-Request-Id", requestId)
+
+ c.Next()
+
+ route := c.FullPath()
+ if route == "" {
+ route = "unmatched"
+ }
+ slog.Info("request",
+ "request_id", requestId,
+ "method", c.Request.Method,
+ "route", route,
+ "status", c.Writer.Status(),
+ "duration_ms", time.Since(start).Milliseconds(),
+ )
+}
+
+// Timeout bounds each request. A request still waiting for a database
+// connection when it fires is answered with 503 instead of hanging.
+func (m *requestMiddleware) Timeout(c *gin.Context) {
+ ctx, cancel := context.WithTimeout(c.Request.Context(), m.timeout)
+ defer cancel()
+ c.Request = c.Request.WithContext(ctx)
+ c.Next()
+}
diff --git a/middleware/user_middleware.go b/middleware/user_middleware.go
new file mode 100644
index 0000000000000000000000000000000000000000..dea660cd76db2c35fd1062ca923e38ee81358d82
--- /dev/null
+++ b/middleware/user_middleware.go
@@ -0,0 +1,53 @@
+package middleware
+
+import (
+ "sync"
+
+ http_error "abdanhafidz.com/event-booking-api/models/error"
+ "abdanhafidz.com/event-booking-api/repositories"
+ "abdanhafidz.com/event-booking-api/utils"
+ "github.com/gin-gonic/gin"
+ "github.com/google/uuid"
+)
+
+// UserMiddleware resolves the caller from X-User-Id. There is no real auth in
+// this project (PRD A1); the header only has to name a seeded user.
+type UserMiddleware interface {
+ RequireUser(ctx *gin.Context)
+}
+
+type userMiddleware struct {
+ userRepo repositories.UserRepository
+ // Users are never deleted, so a positive lookup is cached for the life of
+ // the process. This saves one database round trip per request under load.
+ known sync.Map
+}
+
+func NewUserMiddleware(userRepo repositories.UserRepository) UserMiddleware {
+ return &userMiddleware{userRepo: userRepo}
+}
+
+func (m *userMiddleware) RequireUser(c *gin.Context) {
+ userId, err := uuid.Parse(c.GetHeader("X-User-Id"))
+ if err != nil {
+ utils.ResponseFAILED[any](c, nil, http_error.UNAUTHENTICATED)
+ c.Abort()
+ return
+ }
+ if _, ok := m.known.Load(userId); !ok {
+ exists, err := m.userRepo.Exists(c.Request.Context(), userId)
+ if err != nil {
+ utils.ResponseFAILED[any](c, nil, err)
+ c.Abort()
+ return
+ }
+ if !exists {
+ utils.ResponseFAILED[any](c, nil, http_error.UNAUTHENTICATED)
+ c.Abort()
+ return
+ }
+ m.known.Store(userId, struct{}{})
+ }
+ c.Set("user_id", userId)
+ c.Next()
+}
diff --git a/models/dto/booking_dto.go b/models/dto/booking_dto.go
new file mode 100644
index 0000000000000000000000000000000000000000..104cca731074b6981361fb2cb25fd2f6c036c173
--- /dev/null
+++ b/models/dto/booking_dto.go
@@ -0,0 +1,47 @@
+package dto
+
+import (
+ "time"
+
+ entity "abdanhafidz.com/event-booking-api/models/entity"
+ "github.com/google/uuid"
+)
+
+type CreateBookingRequest struct {
+ TicketTypeId uuid.UUID `json:"ticket_type_id" binding:"required"`
+ Quantity int `json:"quantity" binding:"required,min=1,max=6"`
+}
+
+type PayBookingRequest struct {
+ PaymentToken string `json:"payment_token" binding:"required,max=64"`
+}
+
+type BookingResponse struct {
+ Id uuid.UUID `json:"id"`
+ EventId uuid.UUID `json:"event_id"`
+ TicketTypeId uuid.UUID `json:"ticket_type_id"`
+ Quantity int `json:"quantity"`
+ UnitPrice int64 `json:"unit_price"`
+ TotalAmount int64 `json:"total_amount"`
+ Currency string `json:"currency"`
+ Status string `json:"status"`
+ ExpiresAt time.Time `json:"expires_at"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
+}
+
+func NewBookingResponse(b entity.Booking) BookingResponse {
+ return BookingResponse{
+ Id: b.Id,
+ EventId: b.EventId,
+ TicketTypeId: b.TicketTypeId,
+ Quantity: b.Quantity,
+ UnitPrice: b.UnitPrice,
+ TotalAmount: b.TotalAmount,
+ Currency: b.Currency,
+ Status: b.Status,
+ ExpiresAt: b.ExpiresAt.UTC(),
+ CreatedAt: b.CreatedAt.UTC(),
+ UpdatedAt: b.UpdatedAt.UTC(),
+ }
+}
diff --git a/models/dto/event_dto.go b/models/dto/event_dto.go
new file mode 100644
index 0000000000000000000000000000000000000000..cf56ce55b49dc2539c863c482e9f27ba3c66d68e
--- /dev/null
+++ b/models/dto/event_dto.go
@@ -0,0 +1,44 @@
+package dto
+
+import (
+ "time"
+
+ entity "abdanhafidz.com/event-booking-api/models/entity"
+ "github.com/google/uuid"
+)
+
+type TicketTypeResponse struct {
+ Id uuid.UUID `json:"id"`
+ Name string `json:"name"`
+ Price int64 `json:"price"`
+ Capacity int `json:"capacity"`
+ Available int `json:"available"`
+}
+
+type EventResponse struct {
+ Id uuid.UUID `json:"id"`
+ Name string `json:"name"`
+ StartsAt time.Time `json:"starts_at"`
+ Currency string `json:"currency"`
+ TicketTypes []TicketTypeResponse `json:"ticket_types"`
+}
+
+func NewEventResponse(e entity.Event) EventResponse {
+ res := EventResponse{
+ Id: e.Id,
+ Name: e.Name,
+ StartsAt: e.StartsAt.UTC(),
+ Currency: entity.DefaultCurrency,
+ TicketTypes: make([]TicketTypeResponse, 0, len(e.TicketTypes)),
+ }
+ for _, t := range e.TicketTypes {
+ res.TicketTypes = append(res.TicketTypes, TicketTypeResponse{
+ Id: t.Id,
+ Name: t.Name,
+ Price: t.Price,
+ Capacity: t.Capacity,
+ Available: t.Available,
+ })
+ }
+ return res
+}
diff --git a/models/dto/http_response_dto.go b/models/dto/http_response_dto.go
new file mode 100644
index 0000000000000000000000000000000000000000..16bd63b97cf65d9162fd1b2750e17813a4c16cae
--- /dev/null
+++ b/models/dto/http_response_dto.go
@@ -0,0 +1,18 @@
+package dto
+
+type SuccessResponse[TResponse any] struct {
+ Status string `json:"status"`
+ Data TResponse `json:"data"`
+ Message any `json:"message"`
+ MetaData any `json:"meta_data"`
+}
+
+// ErrorResponse keeps the starter's envelope and adds a stable machine-readable
+// code. Errors carries the error details (for example available tickets).
+type ErrorResponse struct {
+ Status string `json:"status"`
+ Code string `json:"code"`
+ Errors any `json:"errors"`
+ Message any `json:"message"`
+ MetaData any `json:"meta_data"`
+}
diff --git a/models/entity/constant.go b/models/entity/constant.go
new file mode 100644
index 0000000000000000000000000000000000000000..2f811f2e2553bf7bc4e9dce6b2a027c2134c1060
--- /dev/null
+++ b/models/entity/constant.go
@@ -0,0 +1,24 @@
+package models
+
+const (
+ BookingStatusPendingPayment = "PENDING_PAYMENT"
+ BookingStatusConfirmed = "CONFIRMED"
+ BookingStatusPaymentFailed = "PAYMENT_FAILED"
+ BookingStatusExpired = "EXPIRED"
+ BookingStatusCancelled = "CANCELLED"
+)
+
+const (
+ PaymentStatusSucceeded = "SUCCEEDED"
+ PaymentStatusDeclined = "DECLINED"
+ PaymentStatusTimeout = "TIMEOUT"
+)
+
+// Mock payment tokens. Any unknown token is treated as a decline.
+const (
+ PaymentTokenSuccess = "tok_success"
+ PaymentTokenDecline = "tok_decline"
+ PaymentTokenTimeout = "tok_timeout"
+)
+
+const DefaultCurrency = "IDR"
diff --git a/models/entity/entity.go b/models/entity/entity.go
new file mode 100644
index 0000000000000000000000000000000000000000..da8917cd7cccfb4878e3f44083e25cc194a55a39
--- /dev/null
+++ b/models/entity/entity.go
@@ -0,0 +1,105 @@
+package models
+
+import (
+ "time"
+
+ "github.com/google/uuid"
+)
+
+type User struct {
+ Id uuid.UUID `gorm:"type:uuid;primary_key" json:"id"`
+ Name string `gorm:"not null" json:"name"`
+ CreatedAt time.Time `json:"created_at"`
+}
+
+func (User) TableName() string { return "users" }
+
+type Event struct {
+ Id uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
+ Name string `gorm:"not null" json:"name"`
+ StartsAt time.Time `gorm:"not null;index" json:"starts_at"`
+ CreatedAt time.Time `json:"created_at"`
+ TicketTypes []TicketType `gorm:"foreignKey:EventId" json:"ticket_types,omitempty"`
+}
+
+func (Event) TableName() string { return "events" }
+
+// TicketType holds the stock counter. The CHECK on available is the last line
+// of defence against overselling (BR-10); the service never relies on it alone.
+type TicketType struct {
+ Id uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
+ EventId uuid.UUID `gorm:"type:uuid;not null;index" json:"event_id"`
+ Name string `gorm:"not null" json:"name"`
+ Price int64 `gorm:"not null;check:chk_ticket_types_price,price >= 0" json:"price"`
+ Capacity int `gorm:"not null;check:chk_ticket_types_capacity,capacity > 0" json:"capacity"`
+ Available int `gorm:"not null;check:chk_ticket_types_available,available BETWEEN 0 AND capacity" json:"available"`
+}
+
+func (TicketType) TableName() string { return "ticket_types" }
+
+type Booking struct {
+ Id uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
+ UserId uuid.UUID `gorm:"type:uuid;not null;index" json:"user_id"`
+ EventId uuid.UUID `gorm:"type:uuid;not null" json:"event_id"`
+ TicketTypeId uuid.UUID `gorm:"type:uuid;not null;index" json:"ticket_type_id"`
+ Quantity int `gorm:"type:smallint;not null;check:chk_bookings_quantity,quantity BETWEEN 1 AND 6" json:"quantity"`
+ UnitPrice int64 `gorm:"not null" json:"unit_price"`
+ TotalAmount int64 `gorm:"not null;check:chk_bookings_total,total_amount = unit_price * quantity" json:"total_amount"`
+ Currency string `gorm:"type:char(3);not null;default:'IDR'" json:"currency"`
+ Status string `gorm:"type:text;not null;check:chk_bookings_status,status IN ('PENDING_PAYMENT','CONFIRMED','PAYMENT_FAILED','EXPIRED','CANCELLED')" json:"status"`
+ ExpiresAt time.Time `gorm:"not null;index:idx_bookings_to_expire,where:status = 'PENDING_PAYMENT'" json:"expires_at"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
+ User *User `gorm:"foreignKey:UserId" json:"-"`
+ Event *Event `gorm:"foreignKey:EventId" json:"-"`
+ TicketType *TicketType `gorm:"foreignKey:TicketTypeId" json:"-"`
+}
+
+func (Booking) TableName() string { return "bookings" }
+
+// Payment records every mock charge attempt. The partial unique index makes a
+// second successful payment for one booking impossible (BR-07).
+type Payment struct {
+ Id uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
+ BookingId uuid.UUID `gorm:"type:uuid;not null;index;uniqueIndex:one_success_per_booking,where:status = 'SUCCEEDED'" json:"booking_id"`
+ Amount int64 `gorm:"not null" json:"amount"`
+ Status string `gorm:"type:text;not null;check:chk_payments_status,status IN ('SUCCEEDED','DECLINED','TIMEOUT')" json:"status"`
+ CreatedAt time.Time `json:"created_at"`
+ Booking *Booking `gorm:"foreignKey:BookingId" json:"-"`
+}
+
+func (Payment) TableName() string { return "payments" }
+
+// IdempotencyKey stores the outcome of a create or pay request so a retry with
+// the same key replays it instead of acting again (BR-09).
+type IdempotencyKey struct {
+ UserId uuid.UUID `gorm:"type:uuid;primary_key" json:"user_id"`
+ Key string `gorm:"primary_key" json:"key"`
+ RequestHash string `gorm:"not null" json:"request_hash"`
+ ResponseCode string `gorm:"not null;default:''" json:"response_code"`
+ ResponseBody []byte `gorm:"type:jsonb" json:"response_body"`
+ ExpiresAt time.Time `gorm:"not null" json:"expires_at"`
+}
+
+func (IdempotencyKey) TableName() string { return "idempotency_keys" }
+
+func AllEntities() []interface{} {
+ return []interface{}{
+ &User{},
+ &Event{},
+ &TicketType{},
+ &Booking{},
+ &Payment{},
+ &IdempotencyKey{},
+ &SeedMarker{},
+ }
+}
+
+// SeedMarker records that a version of the fixed QA dataset has been loaded,
+// so the startup seeder can skip instead of re-seeding.
+type SeedMarker struct {
+ Version string `gorm:"primary_key" json:"version"`
+ SeededAt time.Time `gorm:"not null" json:"seeded_at"`
+}
+
+func (SeedMarker) TableName() string { return "seed_markers" }
diff --git a/models/error/error.go b/models/error/error.go
new file mode 100644
index 0000000000000000000000000000000000000000..9db5de3d01cc2cdf14e00d09d7221383ea1ad8c1
--- /dev/null
+++ b/models/error/error.go
@@ -0,0 +1,85 @@
+package http_error
+
+import (
+ "errors"
+ "net/http"
+)
+
+// AppError is a business error with a stable code that clients and tests can
+// assert on. Copies made by WithDetails still match the original with errors.Is.
+type AppError struct {
+ Status int
+ Code string
+ Message string
+ Details map[string]any
+}
+
+func (e *AppError) Error() string { return e.Message }
+
+func (e *AppError) Is(target error) bool {
+ t, ok := target.(*AppError)
+ return ok && t.Code == e.Code
+}
+
+func (e *AppError) WithDetails(details map[string]any) *AppError {
+ c := *e
+ c.Details = details
+ return &c
+}
+
+var registry = map[string]*AppError{}
+
+func newAppError(status int, code, message string) *AppError {
+ e := &AppError{Status: status, Code: code, Message: message}
+ registry[code] = e
+ return e
+}
+
+// Lookup returns the catalogue entry for a code, used when replaying a stored
+// idempotent response.
+func Lookup(code string) *AppError {
+ if e, ok := registry[code]; ok {
+ return e
+ }
+ return INTERNAL_SERVER_ERROR
+}
+
+var (
+ // ================= GENERAL =================
+ VALIDATION_ERROR = newAppError(http.StatusBadRequest, "VALIDATION_ERROR", "Request validation failed")
+ ROUTE_NOT_FOUND = newAppError(http.StatusNotFound, "ROUTE_NOT_FOUND", "Route not found")
+ SERVICE_UNAVAILABLE = newAppError(http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "Service is overloaded, retry shortly")
+ INTERNAL_SERVER_ERROR = newAppError(http.StatusInternalServerError, "INTERNAL_ERROR", "Internal server error")
+
+ // ================= IDENTITY =================
+ UNAUTHENTICATED = newAppError(http.StatusUnauthorized, "UNAUTHENTICATED", "Missing or unknown X-User-Id")
+
+ // ================= IDEMPOTENCY =================
+ IDEMPOTENCY_KEY_REQUIRED = newAppError(http.StatusBadRequest, "IDEMPOTENCY_KEY_REQUIRED", "Idempotency-Key header is required")
+ IDEMPOTENCY_KEY_REUSED = newAppError(http.StatusUnprocessableEntity, "IDEMPOTENCY_KEY_REUSED", "Idempotency-Key was already used with a different request")
+
+ // ================= CATALOGUE =================
+ EVENT_NOT_FOUND = newAppError(http.StatusNotFound, "EVENT_NOT_FOUND", "Event not found")
+ TICKET_TYPE_NOT_FOUND = newAppError(http.StatusNotFound, "TICKET_TYPE_NOT_FOUND", "Ticket type not found")
+
+ // ================= BOOKING =================
+ BOOKING_NOT_FOUND = newAppError(http.StatusNotFound, "BOOKING_NOT_FOUND", "Booking not found")
+ SALES_CLOSED = newAppError(http.StatusConflict, "SALES_CLOSED", "Ticket sales for this event have closed")
+ INSUFFICIENT_TICKETS = newAppError(http.StatusConflict, "INSUFFICIENT_TICKETS", "Not enough tickets remain")
+ BOOKING_EXPIRED = newAppError(http.StatusConflict, "BOOKING_EXPIRED", "The booking hold has expired")
+ BOOKING_NOT_PAYABLE = newAppError(http.StatusConflict, "BOOKING_NOT_PAYABLE", "The booking cannot be paid in its current status")
+ BOOKING_NOT_CANCELLABLE = newAppError(http.StatusConflict, "BOOKING_NOT_CANCELLABLE", "The booking cannot be cancelled in its current status")
+
+ // ================= PAYMENT =================
+ PAYMENT_DECLINED = newAppError(http.StatusPaymentRequired, "PAYMENT_DECLINED", "Payment was declined")
+ PAYMENT_TIMEOUT = newAppError(http.StatusPaymentRequired, "PAYMENT_TIMEOUT", "Payment provider did not respond in time")
+)
+
+// AsAppError reports whether err is a business error and returns it.
+func AsAppError(err error) (*AppError, bool) {
+ var appErr *AppError
+ if errors.As(err, &appErr) {
+ return appErr, true
+ }
+ return nil, false
+}
diff --git a/perf/jmeter/booking.jmx b/perf/jmeter/booking.jmx
new file mode 100644
index 0000000000000000000000000000000000000000..0cea577dbacc609178211daaa857e4af5d950288
--- /dev/null
+++ b/perf/jmeter/booking.jmx
@@ -0,0 +1,335 @@
+
+
+
+
+
+
+
+
+ false
+ false
+ true
+
+
+
+
+
+
+ ${__P(host,localhost)}
+ ${__P(port,8080)}
+ ${__P(protocol,http)}
+ UTF-8
+ HttpClient4
+ 5000
+ 5000
+
+
+
+
+
+ Content-Type
+ application/json
+
+
+ X-User-Id
+ ${USER_ID}
+
+
+
+
+
+ ${__P(users_csv,users.csv)}
+ UTF-8
+ USER_ID
+ false
+ ,
+ false
+ true
+ false
+ shareMode.all
+
+
+
+
+
+ continue
+
+ -1
+ false
+
+ ${__P(browsers,0)}
+ ${__P(ramp_s,1)}
+ true
+ ${__P(duration_s,60)}
+ 0
+ true
+
+
+
+ ${__P(think_min_ms,500)}
+ ${__P(think_range_ms,1000)}
+
+
+
+
+
+
+ /v1/events/${__P(event_id)}
+ GET
+ true
+
+
+
+
+ 200
+
+
+ Assertion.response_code
+ true
+ 8
+
+
+
+
+
+
+
+ start_next_loop
+
+ ${__P(buyer_loops,-1)}
+ false
+
+ ${__P(buyers,0)}
+ ${__P(ramp_s,1)}
+ true
+ ${__P(duration_s,60)}
+ 0
+ false
+
+
+
+ ${__P(think_min_ms,500)}
+ ${__P(think_range_ms,1000)}
+
+
+
+ groovy
+
+
+ true
+ // Runs before every sampler in this group; values are only re-picked per iteration.
+if (vars.get("PICKED_ITER") != String.valueOf(vars.getIteration())) {
+ def rnd = java.util.concurrent.ThreadLocalRandom.current()
+ int count = (props.getProperty("ticket_type_count") ?: "1") as int
+ vars.put("TT", props.getProperty("ticket_type_id_" + rnd.nextInt(count)))
+ vars.put("QTY", String.valueOf(1 + rnd.nextInt(2)))
+ vars.put("TOKEN", rnd.nextInt(10) == 0 ? "tok_decline" : "tok_success")
+ vars.put("PICKED_ITER", String.valueOf(vars.getIteration()))
+}
+
+
+
+
+
+
+ /v1/events/${__P(event_id)}
+ GET
+ true
+
+
+
+
+ 200
+
+
+ Assertion.response_code
+ true
+ 8
+
+
+
+
+ true
+
+
+
+ false
+ {"ticket_type_id":"${TT}","quantity":${QTY}}
+ =
+
+
+
+ /v1/bookings
+ POST
+ true
+
+
+
+
+
+ Idempotency-Key
+ ${__UUID()}
+
+
+
+
+
+
+ 201
+
+
+ Assertion.response_code
+ true
+ 8
+
+
+
+ BOOKING_ID
+ $.data.id
+ 1
+ NONE
+
+
+
+
+ true
+
+
+
+ false
+ {"payment_token":"${TOKEN}"}
+ =
+
+
+
+ /v1/bookings/${BOOKING_ID}/pay
+ POST
+ true
+
+
+
+
+
+ Idempotency-Key
+ ${__UUID()}
+
+
+
+
+
+
+ ^(200|402)$
+
+
+ Assertion.response_code
+ true
+ 1
+
+
+
+
+
+
+
+ /v1/bookings/${BOOKING_ID}
+ GET
+ true
+
+
+
+
+ 200
+
+
+ Assertion.response_code
+ true
+ 8
+
+
+
+
+
+
+
+ continue
+
+ 1
+ false
+
+ ${__P(flash_users,0)}
+ ${__P(flash_ramp_s,30)}
+ false
+
+
+ true
+
+
+
+ true
+
+
+
+ false
+ {"ticket_type_id":"${__P(flash_ticket_type_id)}","quantity":1}
+ =
+
+
+
+ /v1/bookings
+ POST
+ true
+
+
+
+ ${__P(flash_users,0)}
+ 120000
+
+
+
+
+
+ Idempotency-Key
+ ${__UUID()}
+
+
+
+
+
+
+ ^(201|409)$
+
+
+ Assertion.response_code
+ true
+ 1
+
+
+
+
+ "status":"success"|"code":"INSUFFICIENT_TICKETS"
+
+
+ Assertion.response_data
+ false
+ 2
+
+
+
+
+
+
+
diff --git a/perf/scenarios.json b/perf/scenarios.json
new file mode 100644
index 0000000000000000000000000000000000000000..b4b42d8918cbc39f8c9d819974948c3cdd8fedf1
--- /dev/null
+++ b/perf/scenarios.json
@@ -0,0 +1,27 @@
+{
+ "PT-01": {
+ "description": "Baseline: one buyer, no think time, 50 journeys",
+ "timeout_min": 20,
+ "properties": { "buyers": 1, "browsers": 0, "buyer_loops": 50, "duration_s": 900, "ramp_s": 1, "think_min_ms": 0, "think_range_ms": 0, "flash_users": 0 }
+ },
+ "PT-02": {
+ "description": "Normal load: 50 VUs (30 browsers, 20 buyers), 2 min ramp, 15 min steady",
+ "timeout_min": 30,
+ "properties": { "buyers": 20, "browsers": 30, "buyer_loops": -1, "duration_s": 1020, "ramp_s": 120, "think_min_ms": 500, "think_range_ms": 1000, "flash_users": 0 }
+ },
+ "PT-03": {
+ "description": "Peak load: 150 VUs (90 browsers, 60 buyers), 2 min ramp, 10 min steady",
+ "timeout_min": 25,
+ "properties": { "buyers": 60, "browsers": 90, "buyer_loops": -1, "duration_s": 720, "ramp_s": 120, "think_min_ms": 500, "think_range_ms": 1000, "flash_users": 0 }
+ },
+ "PT-04": {
+ "description": "Stress: linear ramp to 600 VUs over 20 min, then 5 min at peak",
+ "timeout_min": 40,
+ "properties": { "buyers": 240, "browsers": 360, "buyer_loops": -1, "duration_s": 1500, "ramp_s": 1200, "think_min_ms": 500, "think_range_ms": 1000, "flash_users": 0 }
+ },
+ "PT-05": {
+ "description": "Flash sale: 2,000 users book 1 ticket each at the same moment on the 500-ticket flash fixture",
+ "timeout_min": 15,
+ "properties": { "buyers": 0, "browsers": 0, "buyer_loops": 1, "duration_s": 300, "ramp_s": 1, "think_min_ms": 0, "think_range_ms": 0, "flash_users": 2000, "flash_ramp_s": 30 }
+ }
+}
diff --git a/perf/thresholds.json b/perf/thresholds.json
new file mode 100644
index 0000000000000000000000000000000000000000..c59be6b853bb6ae061dc417a98eb51e5ed0eb5a5
--- /dev/null
+++ b/perf/thresholds.json
@@ -0,0 +1,40 @@
+{
+ "_comment": "strict gates always fail the build. targets fail it only when enforce is true, which is set after calibration (three runs per scenario on the QA environment).",
+ "PT-01": {
+ "enforce": false,
+ "strict": { "max_error_pct": 0 },
+ "targets": {
+ "p95_ms": { "GET /events/{id}": 50, "POST /bookings": 100, "POST /bookings/{id}/pay": 250 }
+ }
+ },
+ "PT-02": {
+ "enforce": false,
+ "strict": {},
+ "targets": {
+ "max_error_pct": 0.5,
+ "min_rps": 45,
+ "p95_ms": { "GET /events/{id}": 300, "POST /bookings": 300, "POST /bookings/{id}/pay": 500 },
+ "p99_ms": { "ALL": 800 }
+ }
+ },
+ "PT-03": {
+ "enforce": false,
+ "strict": {},
+ "targets": {
+ "max_error_pct": 1,
+ "min_rps": 130,
+ "p95_ms": { "GET /events/{id}": 800, "POST /bookings": 800, "POST /bookings/{id}/pay": 1000 },
+ "p99_ms": { "ALL": 1500 }
+ }
+ },
+ "PT-04": {
+ "enforce": false,
+ "strict": {},
+ "targets": {}
+ },
+ "PT-05": {
+ "enforce": false,
+ "strict": { "max_error_pct": 0, "expect_samples": { "POST /bookings (flash)": 2000 } },
+ "targets": { "p95_ms": { "POST /bookings (flash)": 2000 } }
+ }
+}
diff --git a/provider/config_provider.go b/provider/config_provider.go
new file mode 100644
index 0000000000000000000000000000000000000000..d4817ab034a42fe603408f0904eb81b71c4fb5c7
--- /dev/null
+++ b/provider/config_provider.go
@@ -0,0 +1,53 @@
+package provider
+
+import (
+ "abdanhafidz.com/event-booking-api/config"
+)
+
+type ConfigProvider interface {
+ ProvideDatabaseConfig() config.DatabaseConfig
+ ProvideEnvConfig() config.EnvConfig
+ ProvideBookingConfig() config.BookingConfig
+}
+
+type configProvider struct {
+ databaseConfig config.DatabaseConfig
+ envConfig config.EnvConfig
+ bookingConfig config.BookingConfig
+}
+
+func NewConfigProvider() ConfigProvider {
+ envConfig := config.NewEnvConfig()
+ databaseConfig := config.NewDatabaseConfig(
+ envConfig.GetDatabaseHost(), envConfig.GetDatabaseUser(), envConfig.GetDatabasePassword(),
+ envConfig.GetDatabaseName(), envConfig.GetDatabasePort(), envConfig.GetDatabaseSSLMode(),
+ envConfig.GetDatabasePoolSize(),
+ )
+ bookingConfig := config.NewBookingConfig(
+ envConfig.GetHoldTTL(), envConfig.GetSweepInterval(), envConfig.IsSweeperEnabled(),
+ envConfig.GetPaymentTimeout(), envConfig.GetMockPayLatency(), envConfig.GetIdempotencyTTL(),
+ )
+ return NewConfigProviderWith(envConfig, databaseConfig, bookingConfig)
+}
+
+// NewConfigProviderWith lets integration tests supply their own database and
+// booking rules (for example a 2-second hold).
+func NewConfigProviderWith(envConfig config.EnvConfig, databaseConfig config.DatabaseConfig, bookingConfig config.BookingConfig) ConfigProvider {
+ return &configProvider{
+ databaseConfig: databaseConfig,
+ envConfig: envConfig,
+ bookingConfig: bookingConfig,
+ }
+}
+
+func (c *configProvider) ProvideDatabaseConfig() config.DatabaseConfig {
+ return c.databaseConfig
+}
+
+func (c *configProvider) ProvideEnvConfig() config.EnvConfig {
+ return c.envConfig
+}
+
+func (c *configProvider) ProvideBookingConfig() config.BookingConfig {
+ return c.bookingConfig
+}
diff --git a/provider/controller_provider.go b/provider/controller_provider.go
new file mode 100644
index 0000000000000000000000000000000000000000..bbf662fc1ea687875127b12f082bfe6cdb889296
--- /dev/null
+++ b/provider/controller_provider.go
@@ -0,0 +1,28 @@
+package provider
+
+import "abdanhafidz.com/event-booking-api/controllers"
+
+type ControllerProvider interface {
+ ProvideEventController() controllers.EventController
+ ProvideBookingController() controllers.BookingController
+}
+
+type controllerProvider struct {
+ eventController controllers.EventController
+ bookingController controllers.BookingController
+}
+
+func NewControllerProvider(servicesProvider ServicesProvider) ControllerProvider {
+ return &controllerProvider{
+ eventController: controllers.NewEventController(servicesProvider.ProvideEventService()),
+ bookingController: controllers.NewBookingController(servicesProvider.ProvideBookingService()),
+ }
+}
+
+func (c *controllerProvider) ProvideEventController() controllers.EventController {
+ return c.eventController
+}
+
+func (c *controllerProvider) ProvideBookingController() controllers.BookingController {
+ return c.bookingController
+}
diff --git a/provider/middleware_provider.go b/provider/middleware_provider.go
new file mode 100644
index 0000000000000000000000000000000000000000..a1147c967f65984ddea208e89c4a3456e89efee8
--- /dev/null
+++ b/provider/middleware_provider.go
@@ -0,0 +1,28 @@
+package provider
+
+import "abdanhafidz.com/event-booking-api/middleware"
+
+type MiddlewareProvider interface {
+ ProvideUserMiddleware() middleware.UserMiddleware
+ ProvideRequestMiddleware() middleware.RequestMiddleware
+}
+
+type middlewareProvider struct {
+ userMiddleware middleware.UserMiddleware
+ requestMiddleware middleware.RequestMiddleware
+}
+
+func NewMiddlewareProvider(repoProvider RepositoriesProvider, configProvider ConfigProvider) MiddlewareProvider {
+ return &middlewareProvider{
+ userMiddleware: middleware.NewUserMiddleware(repoProvider.ProvideUserRepository()),
+ requestMiddleware: middleware.NewRequestMiddleware(configProvider.ProvideEnvConfig().GetRequestTimeout()),
+ }
+}
+
+func (p *middlewareProvider) ProvideUserMiddleware() middleware.UserMiddleware {
+ return p.userMiddleware
+}
+
+func (p *middlewareProvider) ProvideRequestMiddleware() middleware.RequestMiddleware {
+ return p.requestMiddleware
+}
diff --git a/provider/provider.go b/provider/provider.go
new file mode 100644
index 0000000000000000000000000000000000000000..54bc4b3aa9fe3547e82ac9a2f22616a92877292b
--- /dev/null
+++ b/provider/provider.go
@@ -0,0 +1,86 @@
+package provider
+
+import (
+ "log"
+
+ entity "abdanhafidz.com/event-booking-api/models/entity"
+ "github.com/gin-gonic/gin"
+)
+
+type AppProvider interface {
+ ProvideRouter() *gin.Engine
+ ProvideConfig() ConfigProvider
+ ProvideRepositories() RepositoriesProvider
+ ProvideServices() ServicesProvider
+ ProvideControllers() ControllerProvider
+ ProvideMiddlewares() MiddlewareProvider
+}
+type appProvider struct {
+ ginRouter *gin.Engine
+ configProvider ConfigProvider
+ repositoriesProvider RepositoriesProvider
+ servicesProvider ServicesProvider
+ controllerProvider ControllerProvider
+ middlewareProvider MiddlewareProvider
+}
+
+func NewAppProvider() AppProvider {
+ log.Println("[BOOT] Initializing Config Provider")
+ return NewAppProviderWith(NewConfigProvider())
+}
+
+func NewAppProviderWith(configProvider ConfigProvider) AppProvider {
+ log.Println("[BOOT] Initializing App Provider...")
+
+ // gin.New instead of gin.Default: the request middleware does the logging
+ // as one JSON line per request (NFR-05).
+ ginRouter := gin.New()
+ ginRouter.Use(gin.Recovery())
+
+ repositoriesProvider := NewRepositoriesProvider(configProvider)
+ servicesProvider := NewServicesProvider(repositoriesProvider, configProvider)
+ controllerProvider := NewControllerProvider(servicesProvider)
+ middlewareProvider := NewMiddlewareProvider(repositoriesProvider, configProvider)
+
+ log.Println("[BOOT][DB] Starting database migration...")
+ if err := Migrate(configProvider); err != nil {
+ log.Fatalf("[BOOT][DB] ❌ Database migration failed: %v", err)
+ }
+ log.Println("[BOOT][DB] ✅ Database migration completed")
+
+ return &appProvider{
+ ginRouter: ginRouter,
+ configProvider: configProvider,
+ repositoriesProvider: repositoriesProvider,
+ servicesProvider: servicesProvider,
+ controllerProvider: controllerProvider,
+ middlewareProvider: middlewareProvider,
+ }
+}
+
+func Migrate(configProvider ConfigProvider) error {
+ return configProvider.ProvideDatabaseConfig().AutoMigrateAll(entity.AllEntities()...)
+}
+
+func (a *appProvider) ProvideRouter() *gin.Engine {
+ return a.ginRouter
+}
+func (a *appProvider) ProvideConfig() ConfigProvider {
+ return a.configProvider
+}
+
+func (a *appProvider) ProvideRepositories() RepositoriesProvider {
+ return a.repositoriesProvider
+}
+
+func (a *appProvider) ProvideServices() ServicesProvider {
+ return a.servicesProvider
+}
+
+func (a *appProvider) ProvideControllers() ControllerProvider {
+ return a.controllerProvider
+}
+
+func (a *appProvider) ProvideMiddlewares() MiddlewareProvider {
+ return a.middlewareProvider
+}
diff --git a/provider/repositories_provider.go b/provider/repositories_provider.go
new file mode 100644
index 0000000000000000000000000000000000000000..1d1a4dd9407366a251d9a34bb0eab2fd463f8162
--- /dev/null
+++ b/provider/repositories_provider.go
@@ -0,0 +1,65 @@
+package provider
+
+import "abdanhafidz.com/event-booking-api/repositories"
+
+type RepositoriesProvider interface {
+ ProvideTransactor() repositories.Transactor
+ ProvideUserRepository() repositories.UserRepository
+ ProvideEventRepository() repositories.EventRepository
+ ProvideTicketTypeRepository() repositories.TicketTypeRepository
+ ProvideBookingRepository() repositories.BookingRepository
+ ProvidePaymentRepository() repositories.PaymentRepository
+ ProvideIdempotencyRepository() repositories.IdempotencyRepository
+}
+
+type repositoriesProvider struct {
+ transactor repositories.Transactor
+ userRepository repositories.UserRepository
+ eventRepository repositories.EventRepository
+ ticketTypeRepository repositories.TicketTypeRepository
+ bookingRepository repositories.BookingRepository
+ paymentRepository repositories.PaymentRepository
+ idempotencyRepository repositories.IdempotencyRepository
+}
+
+func NewRepositoriesProvider(cfg ConfigProvider) RepositoriesProvider {
+ db := cfg.ProvideDatabaseConfig().GetInstance()
+
+ return &repositoriesProvider{
+ transactor: repositories.NewTransactor(db),
+ userRepository: repositories.NewUserRepository(db),
+ eventRepository: repositories.NewEventRepository(db),
+ ticketTypeRepository: repositories.NewTicketTypeRepository(db),
+ bookingRepository: repositories.NewBookingRepository(db),
+ paymentRepository: repositories.NewPaymentRepository(db),
+ idempotencyRepository: repositories.NewIdempotencyRepository(db),
+ }
+}
+
+func (r *repositoriesProvider) ProvideTransactor() repositories.Transactor {
+ return r.transactor
+}
+
+func (r *repositoriesProvider) ProvideUserRepository() repositories.UserRepository {
+ return r.userRepository
+}
+
+func (r *repositoriesProvider) ProvideEventRepository() repositories.EventRepository {
+ return r.eventRepository
+}
+
+func (r *repositoriesProvider) ProvideTicketTypeRepository() repositories.TicketTypeRepository {
+ return r.ticketTypeRepository
+}
+
+func (r *repositoriesProvider) ProvideBookingRepository() repositories.BookingRepository {
+ return r.bookingRepository
+}
+
+func (r *repositoriesProvider) ProvidePaymentRepository() repositories.PaymentRepository {
+ return r.paymentRepository
+}
+
+func (r *repositoriesProvider) ProvideIdempotencyRepository() repositories.IdempotencyRepository {
+ return r.idempotencyRepository
+}
diff --git a/provider/services_provider.go b/provider/services_provider.go
new file mode 100644
index 0000000000000000000000000000000000000000..9c64773906490fc60aed9720ef99d63c1a731aa4
--- /dev/null
+++ b/provider/services_provider.go
@@ -0,0 +1,62 @@
+package provider
+
+import (
+ "abdanhafidz.com/event-booking-api/services"
+)
+
+type ServicesProvider interface {
+ ProvidePaymentGatewayService() services.PaymentGatewayService
+ ProvideEventService() services.EventService
+ ProvideBookingService() services.BookingService
+ ProvideExpiryService() services.ExpiryService
+}
+
+type servicesProvider struct {
+ paymentGatewayService services.PaymentGatewayService
+ eventService services.EventService
+ bookingService services.BookingService
+ expiryService services.ExpiryService
+}
+
+func NewServicesProvider(repoProvider RepositoriesProvider, configProvider ConfigProvider) ServicesProvider {
+ bookingConfig := configProvider.ProvideBookingConfig()
+
+ paymentGatewayService := services.NewMockPaymentGatewayService(bookingConfig.GetMockPayLatency(), bookingConfig.GetPaymentTimeout())
+ eventService := services.NewEventService(repoProvider.ProvideEventRepository())
+ bookingService := services.NewBookingService(
+ repoProvider.ProvideTransactor(),
+ repoProvider.ProvideBookingRepository(),
+ repoProvider.ProvideTicketTypeRepository(),
+ repoProvider.ProvidePaymentRepository(),
+ repoProvider.ProvideIdempotencyRepository(),
+ paymentGatewayService,
+ bookingConfig,
+ )
+ expiryService := services.NewExpiryService(
+ repoProvider.ProvideTransactor(),
+ repoProvider.ProvideBookingRepository(),
+ repoProvider.ProvideTicketTypeRepository(),
+ )
+ return &servicesProvider{
+ paymentGatewayService: paymentGatewayService,
+ eventService: eventService,
+ bookingService: bookingService,
+ expiryService: expiryService,
+ }
+}
+
+func (s *servicesProvider) ProvidePaymentGatewayService() services.PaymentGatewayService {
+ return s.paymentGatewayService
+}
+
+func (s *servicesProvider) ProvideEventService() services.EventService {
+ return s.eventService
+}
+
+func (s *servicesProvider) ProvideBookingService() services.BookingService {
+ return s.bookingService
+}
+
+func (s *servicesProvider) ProvideExpiryService() services.ExpiryService {
+ return s.expiryService
+}
diff --git a/repositories/booking_repository.go b/repositories/booking_repository.go
new file mode 100644
index 0000000000000000000000000000000000000000..e1c18697d043500d6f3541e5f1b507dd0a0ad28d
--- /dev/null
+++ b/repositories/booking_repository.go
@@ -0,0 +1,112 @@
+package repositories
+
+import (
+ "context"
+ "time"
+
+ entity "abdanhafidz.com/event-booking-api/models/entity"
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+// LockedBooking is a booking held under FOR UPDATE, with its time checks
+// evaluated against the database clock.
+type LockedBooking struct {
+ entity.Booking `gorm:"embedded"`
+ HoldPassed bool
+ EventStarted bool
+}
+
+type ExpiredBooking struct {
+ TicketTypeId uuid.UUID
+ Quantity int
+}
+
+type BookingRepository interface {
+ Create(ctx context.Context, booking entity.Booking, hold time.Duration) (entity.Booking, error)
+ GetForUser(ctx context.Context, id, userId uuid.UUID) (entity.Booking, error)
+ LockForUpdate(ctx context.Context, id uuid.UUID) (LockedBooking, error)
+ TransitionStatus(ctx context.Context, id uuid.UUID, from, to string) (entity.Booking, bool, error)
+ ExpireDue(ctx context.Context, limit int) ([]ExpiredBooking, error)
+}
+
+type bookingRepository struct {
+ db *gorm.DB
+}
+
+func NewBookingRepository(db *gorm.DB) BookingRepository {
+ return &bookingRepository{db: db}
+}
+
+func (r *bookingRepository) Create(ctx context.Context, b entity.Booking, hold time.Duration) (entity.Booking, error) {
+ var rows []entity.Booking
+ err := conn(ctx, r.db).Raw(`
+ INSERT INTO bookings (id, user_id, event_id, ticket_type_id, quantity, unit_price, total_amount,
+ currency, status, expires_at, created_at, updated_at)
+ VALUES (gen_random_uuid(), ?, ?, ?, ?, ?, ?, ?, ?, now() + make_interval(secs => ?), now(), now())
+ RETURNING *`,
+ b.UserId, b.EventId, b.TicketTypeId, b.Quantity, b.UnitPrice, b.TotalAmount,
+ b.Currency, entity.BookingStatusPendingPayment, hold.Seconds(),
+ ).Scan(&rows).Error
+ if err != nil {
+ return entity.Booking{}, err
+ }
+ return rows[0], nil
+}
+
+func (r *bookingRepository) GetForUser(ctx context.Context, id, userId uuid.UUID) (entity.Booking, error) {
+ var b entity.Booking
+ err := conn(ctx, r.db).First(&b, "id = ? AND user_id = ?", id, userId).Error
+ return b, err
+}
+
+func (r *bookingRepository) LockForUpdate(ctx context.Context, id uuid.UUID) (LockedBooking, error) {
+ var rows []LockedBooking
+ err := conn(ctx, r.db).Raw(`
+ SELECT b.*, b.expires_at <= now() AS hold_passed, e.starts_at <= now() AS event_started
+ FROM bookings b JOIN events e ON e.id = b.event_id
+ WHERE b.id = ?
+ FOR UPDATE OF b`, id).Scan(&rows).Error
+ if err != nil {
+ return LockedBooking{}, err
+ }
+ if len(rows) == 0 {
+ return LockedBooking{}, gorm.ErrRecordNotFound
+ }
+ return rows[0], nil
+}
+
+// TransitionStatus is a compare-and-set: it only moves a booking that is still
+// in the expected status, and reports false if another request got there first.
+func (r *bookingRepository) TransitionStatus(ctx context.Context, id uuid.UUID, from, to string) (entity.Booking, bool, error) {
+ var rows []entity.Booking
+ err := conn(ctx, r.db).Raw(`
+ UPDATE bookings SET status = ?, updated_at = now()
+ WHERE id = ? AND status = ?
+ RETURNING *`, to, id, from).Scan(&rows).Error
+ if err != nil || len(rows) == 0 {
+ return entity.Booking{}, false, err
+ }
+ return rows[0], true, nil
+}
+
+// ExpireDue moves up to limit overdue PENDING_PAYMENT bookings to EXPIRED.
+// SKIP LOCKED leaves alone bookings that a pay or cancel request is holding,
+// and makes the sweeper safe to run on several instances.
+func (r *bookingRepository) ExpireDue(ctx context.Context, limit int) ([]ExpiredBooking, error) {
+ var rows []ExpiredBooking
+ err := conn(ctx, r.db).Raw(`
+ WITH due AS (
+ SELECT id FROM bookings
+ WHERE status = ? AND expires_at <= now()
+ ORDER BY expires_at
+ LIMIT ?
+ FOR UPDATE SKIP LOCKED
+ )
+ UPDATE bookings b SET status = ?, updated_at = now()
+ FROM due WHERE b.id = due.id
+ RETURNING b.ticket_type_id, b.quantity`,
+ entity.BookingStatusPendingPayment, limit, entity.BookingStatusExpired,
+ ).Scan(&rows).Error
+ return rows, err
+}
diff --git a/repositories/event_repository.go b/repositories/event_repository.go
new file mode 100644
index 0000000000000000000000000000000000000000..51fb06421b9a5a76ec1e902c9b42a015b14d23bf
--- /dev/null
+++ b/repositories/event_repository.go
@@ -0,0 +1,29 @@
+package repositories
+
+import (
+ "context"
+
+ entity "abdanhafidz.com/event-booking-api/models/entity"
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+type EventRepository interface {
+ GetWithTicketTypes(ctx context.Context, id uuid.UUID) (entity.Event, error)
+}
+
+type eventRepository struct {
+ db *gorm.DB
+}
+
+func NewEventRepository(db *gorm.DB) EventRepository {
+ return &eventRepository{db: db}
+}
+
+func (r *eventRepository) GetWithTicketTypes(ctx context.Context, id uuid.UUID) (entity.Event, error) {
+ var event entity.Event
+ err := conn(ctx, r.db).
+ Preload("TicketTypes", func(db *gorm.DB) *gorm.DB { return db.Order("name") }).
+ First(&event, "id = ?", id).Error
+ return event, err
+}
diff --git a/repositories/idempotency_repository.go b/repositories/idempotency_repository.go
new file mode 100644
index 0000000000000000000000000000000000000000..1b22de99866f3d8737b07063ffb9a9d754c0928a
--- /dev/null
+++ b/repositories/idempotency_repository.go
@@ -0,0 +1,56 @@
+package repositories
+
+import (
+ "context"
+ "time"
+
+ entity "abdanhafidz.com/event-booking-api/models/entity"
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+type IdempotencyRepository interface {
+ Claim(ctx context.Context, userId uuid.UUID, key, requestHash string, ttl time.Duration) (bool, error)
+ Get(ctx context.Context, userId uuid.UUID, key string) (entity.IdempotencyKey, error)
+ SaveResponse(ctx context.Context, userId uuid.UUID, key, code string, body []byte) error
+}
+
+type idempotencyRepository struct {
+ db *gorm.DB
+}
+
+func NewIdempotencyRepository(db *gorm.DB) IdempotencyRepository {
+ return &idempotencyRepository{db: db}
+}
+
+// Claim inserts the key, or takes over one that has expired. It must be the
+// first statement of the business transaction: a second request with the same
+// live key blocks on this insert until the first transaction ends, then gets
+// false and replays the stored response. That is what serialises duplicates.
+func (r *idempotencyRepository) Claim(ctx context.Context, userId uuid.UUID, key, requestHash string, ttl time.Duration) (bool, error) {
+ var claimed []uuid.UUID
+ err := conn(ctx, r.db).Raw(`
+ INSERT INTO idempotency_keys (user_id, key, request_hash, response_code, response_body, expires_at)
+ VALUES (?, ?, ?, '', NULL, now() + make_interval(secs => ?))
+ ON CONFLICT (user_id, key) DO UPDATE
+ SET request_hash = EXCLUDED.request_hash, response_code = '', response_body = NULL,
+ expires_at = EXCLUDED.expires_at
+ WHERE idempotency_keys.expires_at <= now()
+ RETURNING user_id`,
+ userId, key, requestHash, ttl.Seconds(),
+ ).Scan(&claimed).Error
+ return len(claimed) == 1, err
+}
+
+func (r *idempotencyRepository) Get(ctx context.Context, userId uuid.UUID, key string) (entity.IdempotencyKey, error) {
+ var k entity.IdempotencyKey
+ err := conn(ctx, r.db).First(&k, "user_id = ? AND key = ?", userId, key).Error
+ return k, err
+}
+
+func (r *idempotencyRepository) SaveResponse(ctx context.Context, userId uuid.UUID, key, code string, body []byte) error {
+ return conn(ctx, r.db).Exec(
+ `UPDATE idempotency_keys SET response_code = ?, response_body = ? WHERE user_id = ? AND key = ?`,
+ code, body, userId, key,
+ ).Error
+}
diff --git a/repositories/payment_repository.go b/repositories/payment_repository.go
new file mode 100644
index 0000000000000000000000000000000000000000..b7549664220ee2137acfd404dc1eeb1ebae15534
--- /dev/null
+++ b/repositories/payment_repository.go
@@ -0,0 +1,27 @@
+package repositories
+
+import (
+ "context"
+
+ entity "abdanhafidz.com/event-booking-api/models/entity"
+ "gorm.io/gorm"
+)
+
+type PaymentRepository interface {
+ Create(ctx context.Context, payment entity.Payment) (entity.Payment, error)
+}
+
+type paymentRepository struct {
+ db *gorm.DB
+}
+
+func NewPaymentRepository(db *gorm.DB) PaymentRepository {
+ return &paymentRepository{db: db}
+}
+
+func (r *paymentRepository) Create(ctx context.Context, payment entity.Payment) (entity.Payment, error) {
+ if err := conn(ctx, r.db).Create(&payment).Error; err != nil {
+ return entity.Payment{}, err
+ }
+ return payment, nil
+}
diff --git a/repositories/repository.go b/repositories/repository.go
new file mode 100644
index 0000000000000000000000000000000000000000..1df045706fa9e64f9ecf07914d50fa0c8409f95c
--- /dev/null
+++ b/repositories/repository.go
@@ -0,0 +1,41 @@
+package repositories
+
+import (
+ "context"
+
+ "gorm.io/gorm"
+)
+
+type txKey struct{}
+
+// Transactor runs a function inside one database transaction. Repositories pick
+// the transaction up from the context, so services control transaction
+// boundaries without importing GORM.
+type Transactor interface {
+ WithinTransaction(ctx context.Context, fn func(ctx context.Context) error) error
+}
+
+type transactor struct {
+ db *gorm.DB
+}
+
+func NewTransactor(db *gorm.DB) Transactor {
+ return &transactor{db: db}
+}
+
+func (t *transactor) WithinTransaction(ctx context.Context, fn func(ctx context.Context) error) error {
+ if _, ok := ctx.Value(txKey{}).(*gorm.DB); ok {
+ return fn(ctx)
+ }
+ return t.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ return fn(context.WithValue(ctx, txKey{}, tx))
+ })
+}
+
+// conn returns the transaction carried by ctx, or the plain connection pool.
+func conn(ctx context.Context, db *gorm.DB) *gorm.DB {
+ if tx, ok := ctx.Value(txKey{}).(*gorm.DB); ok {
+ return tx
+ }
+ return db.WithContext(ctx)
+}
diff --git a/repositories/ticket_type_repository.go b/repositories/ticket_type_repository.go
new file mode 100644
index 0000000000000000000000000000000000000000..caf545d76c8632b5857eb0f9b04563b760ae5ee1
--- /dev/null
+++ b/repositories/ticket_type_repository.go
@@ -0,0 +1,86 @@
+package repositories
+
+import (
+ "context"
+ "sort"
+
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+// TicketTypeForSale is a ticket type with the event fields a booking needs,
+// evaluated against the database clock.
+type TicketTypeForSale struct {
+ Id uuid.UUID
+ EventId uuid.UUID
+ Price int64
+ OnSale bool
+}
+
+type TicketTypeRepository interface {
+ GetForSale(ctx context.Context, id uuid.UUID) (TicketTypeForSale, error)
+ Reserve(ctx context.Context, id uuid.UUID, quantity int) (bool, error)
+ GetAvailable(ctx context.Context, id uuid.UUID) (int, error)
+ Release(ctx context.Context, quantities map[uuid.UUID]int) error
+}
+
+type ticketTypeRepository struct {
+ db *gorm.DB
+}
+
+func NewTicketTypeRepository(db *gorm.DB) TicketTypeRepository {
+ return &ticketTypeRepository{db: db}
+}
+
+func (r *ticketTypeRepository) GetForSale(ctx context.Context, id uuid.UUID) (TicketTypeForSale, error) {
+ var rows []TicketTypeForSale
+ err := conn(ctx, r.db).Raw(`
+ SELECT t.id, t.event_id, t.price, e.starts_at > now() AS on_sale
+ FROM ticket_types t JOIN events e ON e.id = t.event_id
+ WHERE t.id = ?`, id).Scan(&rows).Error
+ if err != nil {
+ return TicketTypeForSale{}, err
+ }
+ if len(rows) == 0 {
+ return TicketTypeForSale{}, gorm.ErrRecordNotFound
+ }
+ return rows[0], nil
+}
+
+// Reserve is the overselling guard (BR-03). Concurrent reservations of one
+// ticket type queue on its row lock, and each re-checks available >= quantity
+// against the committed value, so the last ticket cannot be sold twice.
+func (r *ticketTypeRepository) Reserve(ctx context.Context, id uuid.UUID, quantity int) (bool, error) {
+ res := conn(ctx, r.db).Exec(
+ `UPDATE ticket_types SET available = available - ? WHERE id = ? AND available >= ?`,
+ quantity, id, quantity,
+ )
+ return res.RowsAffected == 1, res.Error
+}
+
+func (r *ticketTypeRepository) GetAvailable(ctx context.Context, id uuid.UUID) (int, error) {
+ var available int
+ err := conn(ctx, r.db).Raw(`SELECT available FROM ticket_types WHERE id = ?`, id).Scan(&available).Error
+ return available, err
+}
+
+// Release returns stock. Ticket types are updated in ascending ID order so two
+// transactions releasing several types never deadlock.
+func (r *ticketTypeRepository) Release(ctx context.Context, quantities map[uuid.UUID]int) error {
+ ids := make([]uuid.UUID, 0, len(quantities))
+ for id := range quantities {
+ ids = append(ids, id)
+ }
+ sort.Slice(ids, func(i, j int) bool { return ids[i].String() < ids[j].String() })
+
+ for _, id := range ids {
+ err := conn(ctx, r.db).Exec(
+ `UPDATE ticket_types SET available = available + ? WHERE id = ?`,
+ quantities[id], id,
+ ).Error
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/repositories/user_repository.go b/repositories/user_repository.go
new file mode 100644
index 0000000000000000000000000000000000000000..a49bd19ee0525fef38cb4c6aafe904306aa86ec2
--- /dev/null
+++ b/repositories/user_repository.go
@@ -0,0 +1,27 @@
+package repositories
+
+import (
+ "context"
+
+ entity "abdanhafidz.com/event-booking-api/models/entity"
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+type UserRepository interface {
+ Exists(ctx context.Context, id uuid.UUID) (bool, error)
+}
+
+type userRepository struct {
+ db *gorm.DB
+}
+
+func NewUserRepository(db *gorm.DB) UserRepository {
+ return &userRepository{db: db}
+}
+
+func (r *userRepository) Exists(ctx context.Context, id uuid.UUID) (bool, error) {
+ var count int64
+ err := conn(ctx, r.db).Model(&entity.User{}).Where("id = ?", id).Limit(1).Count(&count).Error
+ return count > 0, err
+}
diff --git a/router/booking_router.go b/router/booking_router.go
new file mode 100644
index 0000000000000000000000000000000000000000..b3d53c393311711757eb580a982b9ca2784ed0a1
--- /dev/null
+++ b/router/booking_router.go
@@ -0,0 +1,18 @@
+package router
+
+import (
+ "abdanhafidz.com/event-booking-api/provider"
+ "github.com/gin-gonic/gin"
+)
+
+func BookingRouter(router *gin.Engine, middleware provider.MiddlewareProvider, controller provider.ControllerProvider) {
+ bookingController := controller.ProvideBookingController()
+ routerGroup := router.Group("/v1/bookings")
+ routerGroup.Use(middleware.ProvideUserMiddleware().RequireUser)
+ {
+ routerGroup.POST("", bookingController.Create)
+ routerGroup.GET("/:id", bookingController.Get)
+ routerGroup.POST("/:id/pay", bookingController.Pay)
+ routerGroup.POST("/:id/cancel", bookingController.Cancel)
+ }
+}
diff --git a/router/event_router.go b/router/event_router.go
new file mode 100644
index 0000000000000000000000000000000000000000..c46065ec772094119680af85c422bed77ab09fb5
--- /dev/null
+++ b/router/event_router.go
@@ -0,0 +1,14 @@
+package router
+
+import (
+ "abdanhafidz.com/event-booking-api/provider"
+ "github.com/gin-gonic/gin"
+)
+
+func EventRouter(router *gin.Engine, controller provider.ControllerProvider) {
+ eventController := controller.ProvideEventController()
+ routerGroup := router.Group("/v1/events")
+ {
+ routerGroup.GET("/:id", eventController.Get)
+ }
+}
diff --git a/router/router.go b/router/router.go
new file mode 100644
index 0000000000000000000000000000000000000000..66399b7d3d3e12bfb63b188ac7cdd5909a943a37
--- /dev/null
+++ b/router/router.go
@@ -0,0 +1,76 @@
+package router
+
+import (
+ "context"
+ "reflect"
+ "strings"
+
+ http_error "abdanhafidz.com/event-booking-api/models/error"
+ "abdanhafidz.com/event-booking-api/provider"
+ "abdanhafidz.com/event-booking-api/utils"
+ "github.com/gin-gonic/gin"
+ "github.com/gin-gonic/gin/binding"
+ "github.com/go-playground/validator/v10"
+)
+
+// Version is set at build time (-ldflags "-X .../router.Version=") so the
+// pipeline can tell when a new deployment is live.
+var Version = "dev"
+
+// SetupRouter registers every route. Integration tests call it directly and
+// serve the engine with httptest.
+func SetupRouter(appProvider provider.AppProvider) *gin.Engine {
+ router, controller, middleware := appProvider.ProvideRouter(), appProvider.ProvideControllers(), appProvider.ProvideMiddlewares()
+ db := appProvider.ProvideConfig().ProvideDatabaseConfig().GetInstance()
+
+ useJSONFieldNames()
+
+ requestMiddleware := middleware.ProvideRequestMiddleware()
+ router.Use(requestMiddleware.Log, requestMiddleware.Timeout)
+
+ router.GET("/health", func(ctx *gin.Context) {
+ sqlDB, err := db.DB()
+ if err == nil {
+ err = sqlDB.PingContext(ctx.Request.Context())
+ }
+ if err != nil {
+ ctx.JSON(503, gin.H{"status": "DOWN", "db": "unreachable", "version": Version})
+ return
+ }
+ ctx.JSON(200, gin.H{"status": "OK", "db": "ok", "version": Version})
+ })
+
+ EventRouter(router, controller)
+ BookingRouter(router, middleware, controller)
+ SwaggerRouter(router)
+
+ router.NoRoute(func(ctx *gin.Context) {
+ utils.ResponseFAILED[any](ctx, nil, http_error.ROUTE_NOT_FOUND)
+ })
+ return router
+}
+
+func RunRouter(appProvider provider.AppProvider) {
+ router := SetupRouter(appProvider)
+
+ bookingConfig := appProvider.ProvideConfig().ProvideBookingConfig()
+ if bookingConfig.IsSweeperEnabled() {
+ appProvider.ProvideServices().ProvideExpiryService().Start(context.Background(), bookingConfig.GetSweepInterval())
+ }
+
+ router.Run(appProvider.ProvideConfig().ProvideEnvConfig().GetTCPAddress())
+}
+
+// useJSONFieldNames makes validation errors name the JSON field
+// (ticket_type_id) instead of the Go field (TicketTypeId).
+func useJSONFieldNames() {
+ if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
+ v.RegisterTagNameFunc(func(f reflect.StructField) string {
+ name := strings.SplitN(f.Tag.Get("json"), ",", 2)[0]
+ if name == "-" {
+ return ""
+ }
+ return name
+ })
+ }
+}
diff --git a/router/swagger_router.go b/router/swagger_router.go
new file mode 100644
index 0000000000000000000000000000000000000000..c3b04feff440f6ec88a08586ce58dcc1878bb2b4
--- /dev/null
+++ b/router/swagger_router.go
@@ -0,0 +1,14 @@
+package router
+
+import (
+ _ "abdanhafidz.com/event-booking-api/swagger/docs"
+ "github.com/gin-gonic/gin"
+ swaggerFiles "github.com/swaggo/files"
+ ginSwagger "github.com/swaggo/gin-swagger"
+)
+
+// SwaggerRouter serves the UI at /swagger/index.html and the OpenAPI document
+// at /swagger/doc.json, which the CI smoke test reads.
+func SwaggerRouter(router *gin.Engine) {
+ router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
+}
diff --git a/scripts/hf_deploy.py b/scripts/hf_deploy.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b627d6879eb9281a5b919e471ed554b2ce1a15d
--- /dev/null
+++ b/scripts/hf_deploy.py
@@ -0,0 +1,53 @@
+"""Deploy the API to a Hugging Face Docker Space.
+
+Usage: python scripts/hf_deploy.py
+
+Database credentials live only in GitHub secrets; this script copies them into
+the Space as Space secrets on every deploy, then mirrors the folder into the
+Space repository, which triggers a rebuild.
+"""
+import os
+import sys
+
+from huggingface_hub import HfApi
+
+SECRETS = ["DB_HOST", "DB_PORT", "DB_USER", "DB_PASSWORD", "DB_NAME"]
+VARIABLES = {
+ "DB_SSLMODE": "require",
+ "MOCKPAY_LATENCY_MS": "100",
+ "HOLD_TTL": "10m",
+ "SWEEPER_ENABLED": "true",
+ # The container seeds the fixed QA dataset at startup and skips if present.
+ "SEED_ON_STARTUP": "true",
+}
+
+
+def main() -> None:
+ folder = sys.argv[1]
+ space = os.environ["HF_SPACE"]
+ sha = os.environ.get("GITHUB_SHA", "manual")[:7]
+ api = HfApi(token=os.environ["HF_TOKEN"])
+
+ missing = [name for name in SECRETS if not os.environ.get(name)]
+ if missing:
+ sys.exit(f"missing database settings: {', '.join(missing)}")
+
+ for name in SECRETS:
+ api.add_space_secret(space, name, os.environ[name])
+ for name, value in VARIABLES.items():
+ api.add_space_variable(space, name, value)
+
+ # delete_patterns mirrors the folder: files removed from the repo are removed
+ # from the Space in the same commit.
+ api.upload_folder(
+ repo_id=space,
+ repo_type="space",
+ folder_path=folder,
+ commit_message=f"Deploy {sha}",
+ delete_patterns=["*"],
+ )
+ print(f"pushed {sha} to space {space}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/perf/blazemeter_run.sh b/scripts/perf/blazemeter_run.sh
new file mode 100644
index 0000000000000000000000000000000000000000..efeda818033ea634e63de132dfde833650059a85
--- /dev/null
+++ b/scripts/perf/blazemeter_run.sh
@@ -0,0 +1,58 @@
+#!/usr/bin/env bash
+# Upload the test files to an existing BlazeMeter test, start it, wait for it to
+# end, and download the aggregate report.
+#
+# One-time setup in BlazeMeter: create a performance test of type Taurus whose
+# main file is bzt-test.yml (upload the files from build_taurus.sh once), choose
+# the load location, and put its ID in the BLAZEMETER_TEST_ID variable. Each run
+# re-uploads the same file names, which replaces them.
+#
+# Usage: scripts/perf/blazemeter_run.sh
+set -euo pipefail
+
+files="$1"
+timeout_min="$2"
+out="$3"
+api="https://a.blazemeter.com/api/v4"
+auth="$BLAZEMETER_API_KEY_ID:$BLAZEMETER_API_KEY_SECRET"
+test_id="$BLAZEMETER_TEST_ID"
+mkdir -p "$out"
+
+bzm() { curl -fsS --retry 3 -u "$auth" "$@"; }
+
+for f in "$files"/*; do
+ echo "uploading $(basename "$f")"
+ bzm -F "file=@$f" "$api/tests/$test_id/files" > /dev/null
+done
+
+master="$(bzm -X POST "$api/tests/$test_id/start" | jq -r '.result.id')"
+if [[ -z "$master" || "$master" == "null" ]]; then
+ echo "::error::BlazeMeter did not start the test"
+ exit 1
+fi
+report_url="https://a.blazemeter.com/app/#/masters/$master"
+echo "$report_url" > "$out/report_url.txt"
+echo "started BlazeMeter run $master: $report_url"
+
+deadline=$(( $(date +%s) + timeout_min * 60 ))
+while true; do
+ status="$(bzm "$api/masters/$master/status" | jq -r '.result.status')"
+ echo "$(date -u +%H:%M:%S) status: $status"
+ [[ "$status" == "ENDED" ]] && break
+ if (( $(date +%s) > deadline )); then
+ bzm -X POST "$api/masters/$master/terminate" > /dev/null || true
+ echo "::error::BlazeMeter run exceeded ${timeout_min} minutes and was terminated"
+ exit 1
+ fi
+ sleep 30
+done
+
+bzm "$api/masters/$master" > "$out/master.json"
+bzm "$api/masters/$master/reports/aggregatereport/data" > "$out/aggregate.json"
+
+{
+ echo "## BlazeMeter run: ${SCENARIO:-scenario}"
+ echo
+ echo "Report: $report_url"
+ echo
+} >> "${GITHUB_STEP_SUMMARY:-/dev/null}"
diff --git a/scripts/perf/build_taurus.sh b/scripts/perf/build_taurus.sh
new file mode 100644
index 0000000000000000000000000000000000000000..c341c2cc649134f095738f4b875366c8bce9b84b
--- /dev/null
+++ b/scripts/perf/build_taurus.sh
@@ -0,0 +1,40 @@
+#!/usr/bin/env bash
+# Build the files uploaded to BlazeMeter: the JMeter plan, the users CSV and a
+# Taurus config (bzt-test.yml) carrying the target host, the seeded IDs and the
+# scenario's load properties. JSON is valid YAML, so the config is written as JSON.
+# Usage: scripts/perf/build_taurus.sh
+set -euo pipefail
+
+scenario="$1"
+base_url="${2%/}"
+seed_dir="$3"
+out="$4"
+mkdir -p "$out"
+
+protocol="${base_url%%://*}"
+host="$(echo "$base_url" | sed -E 's#^[a-z]+://##; s#[:/].*$##')"
+port=443
+[[ "$protocol" == "http" ]] && port=80
+
+cp perf/jmeter/booking.jmx "$out/booking.jmx"
+cp "$seed_dir/users.csv" "$out/users.csv"
+
+seeded="$(grep -v '^\s*$' "$seed_dir/event.properties" | tr -d '\r' | jq -R 'split("=") | {(.[0]): .[1]}' | jq -s 'add')"
+load="$(jq --arg s "$scenario" '.[$s].properties | with_entries(.value |= tostring)' perf/scenarios.json)"
+
+jq -n \
+ --arg protocol "$protocol" --arg host "$host" --arg port "$port" --arg scenario "$scenario" \
+ --argjson seeded "$seeded" --argjson load "$load" '{
+ execution: [{ executor: "jmeter", scenario: "booking" }],
+ scenarios: {
+ booking: {
+ script: "booking.jmx",
+ properties: ({ protocol: $protocol, host: $host, port: $port, scenario: $scenario, users_csv: "users.csv" }
+ + $seeded + $load)
+ }
+ },
+ modules: { jmeter: { version: "5.6.3" } }
+ }' > "$out/bzt-test.yml"
+
+echo "BlazeMeter files for $scenario:"
+ls -l "$out"
diff --git a/scripts/perf/check_thresholds.py b/scripts/perf/check_thresholds.py
new file mode 100644
index 0000000000000000000000000000000000000000..6575ecaa07a97ac478612faeb6458d8ae7c9bae5
--- /dev/null
+++ b/scripts/perf/check_thresholds.py
@@ -0,0 +1,80 @@
+"""Compare a load test report with perf/thresholds.json.
+
+Usage: python scripts/perf/check_thresholds.py
+
+ is either BlazeMeter's aggregate report (aggregatereport/data) or
+JMeter's dashboard statistics.json, so local and BlazeMeter runs share one gate.
+Prints a Markdown table. Exits 1 when a strict gate fails, or when a target
+fails and the scenario has "enforce": true.
+"""
+import json
+import sys
+
+
+def normalise(report):
+ """Return {label: {samples, errors, p95, p99, rps}}; the overall row is "ALL"."""
+ rows = {}
+ if isinstance(report, dict) and "result" in report: # BlazeMeter
+ for r in report["result"]:
+ rows[r["labelName"]] = {
+ "samples": r.get("samples", 0),
+ "errors": r.get("errorsCount", 0),
+ "p95": r.get("95line"),
+ "p99": r.get("99line"),
+ "rps": r.get("avgThroughput"),
+ }
+ else: # JMeter statistics.json
+ for label, r in report.items():
+ rows["ALL" if label == "Total" else label] = {
+ "samples": r.get("sampleCount", 0),
+ "errors": r.get("errorCount", 0),
+ "p95": r.get("pct2ResTime"),
+ "p99": r.get("pct3ResTime"),
+ "rps": r.get("throughput"),
+ }
+ return rows
+
+
+def evaluate(rows, gates):
+ """Yield (check, limit, actual, ok) for each gate."""
+ overall = rows.get("ALL", {"samples": 0, "errors": 0})
+ if "max_error_pct" in gates:
+ pct = 100.0 * overall["errors"] / overall["samples"] if overall["samples"] else 100.0
+ yield "unexpected errors %", f"<= {gates['max_error_pct']}", round(pct, 3), pct <= gates["max_error_pct"]
+ if "min_rps" in gates:
+ rps = overall.get("rps") or 0
+ yield "throughput req/s", f">= {gates['min_rps']}", round(rps, 1), rps >= gates["min_rps"]
+ for pct_key, name in (("p95_ms", "p95"), ("p99_ms", "p99")):
+ for label, limit in gates.get(pct_key, {}).items():
+ value = rows.get(label, {}).get(name)
+ ok = value is not None and value <= limit
+ yield f"{name} {label} (ms)", f"<= {limit}", value, ok
+ for label, want in gates.get("expect_samples", {}).items():
+ got = rows.get(label, {}).get("samples", 0)
+ yield f"samples {label}", f"= {want}", got, got == want
+
+
+def main():
+ scenario, report_path, thresholds_path = sys.argv[1:4]
+ with open(report_path, encoding="utf-8") as f:
+ rows = normalise(json.load(f))
+ with open(thresholds_path, encoding="utf-8") as f:
+ config = json.load(f)[scenario]
+
+ enforce = config.get("enforce", False)
+ failed = False
+ print(f"### Thresholds for {scenario} (targets {'enforced' if enforce else 'reported only until calibrated'})\n")
+ print("| Gate | Check | Limit | Actual | Result |")
+ print("| --- | --- | --- | --- | --- |")
+ for kind, gates in (("strict", config.get("strict", {})), ("target", config.get("targets", {}))):
+ for check, limit, actual, ok in evaluate(rows, gates):
+ blocking = kind == "strict" or enforce
+ result = "pass" if ok else ("**FAIL**" if blocking else "warn")
+ failed |= (not ok) and blocking
+ print(f"| {kind} | {check} | {limit} | {actual} | {result} |")
+ print()
+ sys.exit(1 if failed else 0)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/perf/correctness.sh b/scripts/perf/correctness.sh
new file mode 100644
index 0000000000000000000000000000000000000000..f294342ef7ba9cce7daeb2348425aa61ce34e242
--- /dev/null
+++ b/scripts/perf/correctness.sh
@@ -0,0 +1,34 @@
+#!/usr/bin/env bash
+# Server-side correctness checks after a performance run. These are never
+# calibrated: any violation fails the job.
+# 1. Inventory invariant for every ticket type of the run's events
+# 2. No booking with more than one successful payment
+# 3. No PENDING_PAYMENT booking more than 15 s past its hold
+# 4. PT-05: exactly flash_tickets active bookings and 0 available
+# Usage: scripts/perf/correctness.sh
+set -euo pipefail
+
+scenario="$1"
+props="$2"
+prop() { grep "^$1=" "$props" | cut -d= -f2 | tr -d '\r' || true; }
+
+# Check both load and flash fixtures; the exact flash-sale count only after PT-05.
+events="$(prop event_id),$(prop flash_event_id)"
+flash_tt=""
+flash_tickets="0"
+if [[ "$scenario" == "PT-05" ]]; then
+ flash_tt="$(prop flash_ticket_type_id)"
+ flash_tickets="$(prop flash_tickets)"
+fi
+
+export PGHOST="$DB_HOST" PGPORT="${DB_PORT:-5432}" PGUSER="$DB_USER" PGPASSWORD="$DB_PASSWORD" \
+ PGDATABASE="${DB_NAME:-postgres}" PGSSLMODE="${DB_SSLMODE:-require}"
+
+psql -X -v ON_ERROR_STOP=1 -v events="$events" -v flash_tt="$flash_tt" -v flash_tickets="$flash_tickets" \
+ -f scripts/perf/correctness.sql
+
+echo "correctness checks passed"
+{
+ echo
+ echo "Correctness checks: **passed** (inventory invariant, single payment, holds released$([[ -n "$flash_tt" ]] && echo ", flash sale exact"))."
+} >> "${GITHUB_STEP_SUMMARY:-/dev/null}"
diff --git a/scripts/perf/correctness.sql b/scripts/perf/correctness.sql
new file mode 100644
index 0000000000000000000000000000000000000000..2d319a7825a03871b27f813ed5a59842594cd793
--- /dev/null
+++ b/scripts/perf/correctness.sql
@@ -0,0 +1,73 @@
+-- Run by correctness.sh. psql variables cannot be read inside a DO block, so
+-- they are passed through session settings.
+SELECT set_config('perf.events', :'events', false),
+ set_config('perf.flash_tt', :'flash_tt', false),
+ set_config('perf.flash_tickets', :'flash_tickets', false)
+\gset ignored_
+
+\echo 'Inventory per ticket type:'
+SELECT t.id AS ticket_type, t.capacity, t.available,
+ COALESCE(SUM(b.quantity) FILTER (WHERE b.status IN ('PENDING_PAYMENT', 'CONFIRMED')), 0) AS held,
+ COUNT(b.id) FILTER (WHERE b.status = 'CONFIRMED') AS confirmed_bookings
+FROM ticket_types t
+LEFT JOIN bookings b ON b.ticket_type_id = t.id
+WHERE t.event_id = ANY (string_to_array(current_setting('perf.events'), ',')::uuid[])
+GROUP BY t.id
+ORDER BY t.id;
+
+DO $$
+DECLARE
+ run_events uuid[] := string_to_array(current_setting('perf.events'), ',')::uuid[];
+ bad int;
+ flash_available int;
+ flash_active int;
+BEGIN
+ SELECT count(*) INTO bad FROM (
+ SELECT t.id
+ FROM ticket_types t
+ LEFT JOIN bookings b ON b.ticket_type_id = t.id
+ WHERE t.event_id = ANY (run_events)
+ GROUP BY t.id, t.capacity, t.available
+ HAVING t.available < 0
+ OR t.capacity <> t.available + COALESCE(SUM(b.quantity) FILTER (
+ WHERE b.status IN ('PENDING_PAYMENT', 'CONFIRMED')), 0)
+ ) v;
+ IF bad > 0 THEN
+ RAISE EXCEPTION 'inventory invariant violated for % ticket type(s)', bad;
+ END IF;
+
+ SELECT count(*) INTO bad FROM (
+ SELECT p.booking_id
+ FROM payments p
+ JOIN bookings b ON b.id = p.booking_id
+ WHERE b.event_id = ANY (run_events) AND p.status = 'SUCCEEDED'
+ GROUP BY p.booking_id
+ HAVING count(*) > 1
+ ) v;
+ IF bad > 0 THEN
+ RAISE EXCEPTION '% booking(s) were paid more than once', bad;
+ END IF;
+
+ SELECT count(*) INTO bad
+ FROM bookings b
+ WHERE b.event_id = ANY (run_events)
+ AND b.status = 'PENDING_PAYMENT'
+ AND b.expires_at < now() - interval '15 seconds';
+ IF bad > 0 THEN
+ RAISE EXCEPTION '% expired hold(s) were not released within 15 s', bad;
+ END IF;
+
+ IF current_setting('perf.flash_tt') <> '' THEN
+ SELECT t.available,
+ COALESCE(SUM(b.quantity) FILTER (WHERE b.status IN ('PENDING_PAYMENT', 'CONFIRMED')), 0)
+ INTO flash_available, flash_active
+ FROM ticket_types t
+ LEFT JOIN bookings b ON b.ticket_type_id = t.id
+ WHERE t.id = current_setting('perf.flash_tt')::uuid
+ GROUP BY t.id, t.available;
+ IF flash_available <> 0 OR flash_active <> current_setting('perf.flash_tickets')::int THEN
+ RAISE EXCEPTION 'flash sale: % tickets held and % available, expected % held and 0 available',
+ flash_active, flash_available, current_setting('perf.flash_tickets');
+ END IF;
+ END IF;
+END $$;
diff --git a/scripts/perf/wait_for_stock.sh b/scripts/perf/wait_for_stock.sh
new file mode 100644
index 0000000000000000000000000000000000000000..2f1bde41897844fe7921db4f1bc28c4a0dba4b69
--- /dev/null
+++ b/scripts/perf/wait_for_stock.sh
@@ -0,0 +1,32 @@
+#!/usr/bin/env bash
+# Wait until a fixture ticket type is back at full stock. PT-05 leaves its
+# bookings unpaid, so the sweeper releases them when the 10-minute hold ends;
+# the next run waits for that instead of re-seeding.
+# Usage: scripts/perf/wait_for_stock.sh
+set -euo pipefail
+
+base="${1%/}"
+props="$2"
+key="$3"
+timeout="${4:-720}"
+prop() { grep "^$1=" "$props" | cut -d= -f2 | tr -d '\r'; }
+
+event_id="$(prop "${key}_event_id")"
+ticket_type="$(prop "${key}_ticket_type_id")"
+want="$(prop "${key}_tickets")"
+deadline=$(( $(date +%s) + timeout ))
+
+while true; do
+ available="$(curl -fsS --max-time 10 "$base/v1/events/$event_id" \
+ | jq -r --arg tt "$ticket_type" '.data.ticket_types[] | select(.id == $tt) | .available' || echo "?")"
+ if [[ "$available" == "$want" ]]; then
+ echo "$key stock is full: $available/$want"
+ exit 0
+ fi
+ if (( $(date +%s) > deadline )); then
+ echo "::error::$key stock still $available/$want after ${timeout}s; earlier holds were not released"
+ exit 1
+ fi
+ echo "waiting for $key stock: $available/$want available"
+ sleep 20
+done
diff --git a/scripts/smoke_test.sh b/scripts/smoke_test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..1a0c8f1d871b04127f0a0db71a5b94d2d22f177b
--- /dev/null
+++ b/scripts/smoke_test.sh
@@ -0,0 +1,104 @@
+#!/usr/bin/env bash
+# Smoke test driven by the deployed OpenAPI document.
+# 1. Every path and method in /swagger/doc.json is routed (no ROUTE_NOT_FOUND, no 5xx).
+# 2. A journey on the fixed smoke fixture (5 tickets) behaves as documented.
+# Everything it books is released again, so the fixture is reusable and
+# never needs re-seeding.
+# Usage: scripts/smoke_test.sh
+set -uo pipefail
+
+base="${1%/}"
+seed_dir="$2"
+report="$seed_dir/smoke-results.md"
+failures=0
+
+prop() { grep "^$1=" "$seed_dir/event.properties" | cut -d= -f2 | tr -d '\r'; }
+event_id="$(prop smoke_event_id)"
+ticket_type="$(prop smoke_ticket_type_id)"
+user="$(head -1 "$seed_dir/users.csv" | tr -d '\r')"
+
+echo "| Check | Expected | Got | Result |" > "$report"
+echo "| --- | --- | --- | --- |" >> "$report"
+
+record() { # name expected got
+ local result="pass"
+ if [[ "$2" != "$3" ]]; then result="**FAIL**"; failures=$((failures + 1)); fi
+ echo "| $1 | $2 | $3 | $result |" >> "$report"
+ echo "$result $1: expected $2, got $3"
+}
+
+# call METHOD PATH [IDEMPOTENCY_KEY] [BODY] -> sets CODE, BODY, HEADERS
+call() {
+ local args=(-s -o /tmp/smoke_body -D /tmp/smoke_headers -w '%{http_code}' -X "$1" "$base$2"
+ -H "X-User-Id: $user" -H "Content-Type: application/json")
+ [[ -n "${3:-}" ]] && args+=(-H "Idempotency-Key: $3")
+ [[ -n "${4:-}" ]] && args+=(-d "$4")
+ CODE="$(curl "${args[@]}")"
+ BODY="$(cat /tmp/smoke_body)"
+ HEADERS="$(cat /tmp/smoke_headers)"
+}
+field() { echo "$BODY" | jq -r "$1"; }
+
+# ---------- 1. health and OpenAPI coverage ----------
+call GET /health
+record "GET /health" "200 OK" "$CODE $(field .status)"
+
+spec="$(curl -fsS "$base/swagger/doc.json")" || { echo "::error::cannot fetch /swagger/doc.json"; exit 1; }
+while IFS=$'\t' read -r method path; do
+ concrete="${path//\{id\}/00000000-0000-0000-0000-000000000000}"
+ call "${method^^}" "$concrete" "smoke-route-$RANDOM$RANDOM" '{}'
+ code="$(field '.code // empty')"
+ routed="routed"
+ if [[ "$code" == "ROUTE_NOT_FOUND" || "$CODE" -ge 500 ]]; then routed="$CODE $code"; fi
+ record "${method^^} $path is routed" "routed" "$routed"
+done < <(echo "$spec" | jq -r '.paths | to_entries[] | .key as $p | .value | keys[] | [., $p] | @tsv')
+
+# ---------- 2. journey on the smoke fixture ----------
+available_now() {
+ curl -fsS "$base/v1/events/$event_id" | jq -r --arg tt "$ticket_type" '.data.ticket_types[] | select(.id == $tt) | .available'
+}
+call GET "/v1/events/$event_id"
+record "GET smoke event" "200" "$CODE"
+start="$(available_now)"
+# A run cancelled halfway may leave a hold for up to 10 minutes; 3 tickets is all this journey needs.
+if (( start < 3 )); then
+ record "Smoke stock available" ">= 3" "$start"
+fi
+
+key="smoke-book-${GITHUB_RUN_ID:-local}-$RANDOM"
+call POST /v1/bookings "$key" "{\"ticket_type_id\":\"$ticket_type\",\"quantity\":2}"
+booking="$(field .data.id)"
+record "POST booking" "201 PENDING_PAYMENT" "$CODE $(field .data.status)"
+
+call POST /v1/bookings "$key" "{\"ticket_type_id\":\"$ticket_type\",\"quantity\":2}"
+replayed="$(echo "$HEADERS" | grep -i '^Idempotent-Replayed:' | tr -d '\r' | awk '{print $2}')"
+record "Replay booking (same key)" "201 $booking true" "$CODE $(field .data.id) ${replayed:-false}"
+
+call POST "/v1/bookings/$booking/pay" "smoke-pay-$RANDOM$RANDOM" '{"payment_token":"tok_success"}'
+record "Pay tok_success" "200 CONFIRMED" "$CODE $(field .data.status)"
+
+call POST /v1/bookings "smoke-book2-$RANDOM$RANDOM" "{\"ticket_type_id\":\"$ticket_type\",\"quantity\":1}"
+declined="$(field .data.id)"
+call POST "/v1/bookings/$declined/pay" "smoke-pay2-$RANDOM$RANDOM" '{"payment_token":"tok_decline"}'
+record "Pay tok_decline releases tickets" "402 PAYMENT_DECLINED" "$CODE $(field .code)"
+
+# At most 3 of the 5 tickets remain, so 6 can never fit.
+call POST /v1/bookings "smoke-big-$RANDOM$RANDOM" "{\"ticket_type_id\":\"$ticket_type\",\"quantity\":6}"
+record "Insufficient tickets" "409 INSUFFICIENT_TICKETS" "$CODE $(field .code)"
+
+call POST "/v1/bookings/$booking/cancel"
+record "Cancel confirmed booking" "200 CANCELLED" "$CODE $(field .data.status)"
+
+record "Stock restored after journey" "$start" "$(available_now)"
+
+{
+ echo "## OpenAPI smoke test"
+ echo
+ cat "$report"
+} >> "${GITHUB_STEP_SUMMARY:-/dev/null}"
+
+if (( failures > 0 )); then
+ echo "::error::$failures smoke check(s) failed"
+ exit 1
+fi
+echo "all smoke checks passed"
diff --git a/scripts/wait_for_version.sh b/scripts/wait_for_version.sh
new file mode 100644
index 0000000000000000000000000000000000000000..a760c35c222c530b6999ac63823c5cbd6995db99
--- /dev/null
+++ b/scripts/wait_for_version.sh
@@ -0,0 +1,25 @@
+#!/usr/bin/env bash
+# Wait until /health reports , i.e. the new build is live.
+# Usage: scripts/wait_for_version.sh
+set -euo pipefail
+
+base_url="${1%/}"
+want="$2"
+timeout="${3:-900}"
+deadline=$(( $(date +%s) + timeout ))
+
+while true; do
+ body="$(curl -fsS --max-time 10 "$base_url/health" 2>/dev/null || true)"
+ version="$(echo "$body" | jq -r '.version // empty' 2>/dev/null || true)"
+ status="$(echo "$body" | jq -r '.status // empty' 2>/dev/null || true)"
+ if [[ "$version" == "$want" && "$status" == "OK" ]]; then
+ echo "live: version $version, database reachable"
+ exit 0
+ fi
+ if (( $(date +%s) > deadline )); then
+ echo "::error::$base_url did not report version $want within ${timeout}s (last: ${body:-no response})"
+ exit 1
+ fi
+ echo "waiting: live version '${version:-none}', status '${status:-none}'"
+ sleep 15
+done
diff --git a/services/booking_service.go b/services/booking_service.go
new file mode 100644
index 0000000000000000000000000000000000000000..62050815774e402eb8db4e1bd9e60c73c4d3d465
--- /dev/null
+++ b/services/booking_service.go
@@ -0,0 +1,310 @@
+package services
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+
+ "abdanhafidz.com/event-booking-api/config"
+ dto "abdanhafidz.com/event-booking-api/models/dto"
+ entity "abdanhafidz.com/event-booking-api/models/entity"
+ http_error "abdanhafidz.com/event-booking-api/models/error"
+ "abdanhafidz.com/event-booking-api/repositories"
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+type BookingService interface {
+ // Create and Pay also report whether the result was replayed from an
+ // earlier request with the same Idempotency-Key.
+ Create(ctx context.Context, userId uuid.UUID, idempotencyKey string, req dto.CreateBookingRequest) (dto.BookingResponse, bool, error)
+ Get(ctx context.Context, userId, bookingId uuid.UUID) (dto.BookingResponse, error)
+ Pay(ctx context.Context, userId, bookingId uuid.UUID, idempotencyKey string, req dto.PayBookingRequest) (dto.BookingResponse, bool, error)
+ Cancel(ctx context.Context, userId, bookingId uuid.UUID) (dto.BookingResponse, error)
+}
+
+type bookingService struct {
+ transactor repositories.Transactor
+ bookingRepo repositories.BookingRepository
+ ticketTypeRepo repositories.TicketTypeRepository
+ paymentRepo repositories.PaymentRepository
+ idempotencyRepo repositories.IdempotencyRepository
+ paymentGateway PaymentGatewayService
+ bookingConfig config.BookingConfig
+}
+
+func NewBookingService(
+ transactor repositories.Transactor,
+ bookingRepo repositories.BookingRepository,
+ ticketTypeRepo repositories.TicketTypeRepository,
+ paymentRepo repositories.PaymentRepository,
+ idempotencyRepo repositories.IdempotencyRepository,
+ paymentGateway PaymentGatewayService,
+ bookingConfig config.BookingConfig,
+) BookingService {
+ return &bookingService{
+ transactor: transactor,
+ bookingRepo: bookingRepo,
+ ticketTypeRepo: ticketTypeRepo,
+ paymentRepo: paymentRepo,
+ idempotencyRepo: idempotencyRepo,
+ paymentGateway: paymentGateway,
+ bookingConfig: bookingConfig,
+ }
+}
+
+func (s *bookingService) Create(ctx context.Context, userId uuid.UUID, key string, req dto.CreateBookingRequest) (dto.BookingResponse, bool, error) {
+ return s.idempotent(ctx, userId, key, "POST /v1/bookings", req, func(ctx context.Context) (dto.BookingResponse, error) {
+ tt, err := s.ticketTypeRepo.GetForSale(ctx, req.TicketTypeId)
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return dto.BookingResponse{}, http_error.TICKET_TYPE_NOT_FOUND
+ }
+ if err != nil {
+ return dto.BookingResponse{}, err
+ }
+ if !tt.OnSale {
+ return dto.BookingResponse{}, http_error.SALES_CLOSED
+ }
+
+ reserved, err := s.ticketTypeRepo.Reserve(ctx, tt.Id, req.Quantity)
+ if err != nil {
+ return dto.BookingResponse{}, err
+ }
+ if !reserved {
+ available, err := s.ticketTypeRepo.GetAvailable(ctx, tt.Id)
+ if err != nil {
+ return dto.BookingResponse{}, err
+ }
+ return dto.BookingResponse{}, http_error.INSUFFICIENT_TICKETS.WithDetails(map[string]any{"available": available})
+ }
+
+ booking, err := s.bookingRepo.Create(ctx, entity.Booking{
+ UserId: userId,
+ EventId: tt.EventId,
+ TicketTypeId: tt.Id,
+ Quantity: req.Quantity,
+ UnitPrice: tt.Price,
+ TotalAmount: tt.Price * int64(req.Quantity),
+ Currency: entity.DefaultCurrency,
+ }, s.bookingConfig.GetHoldTTL())
+ if err != nil {
+ return dto.BookingResponse{}, err
+ }
+ return dto.NewBookingResponse(booking), nil
+ })
+}
+
+func (s *bookingService) Get(ctx context.Context, userId, bookingId uuid.UUID) (dto.BookingResponse, error) {
+ booking, err := s.bookingRepo.GetForUser(ctx, bookingId, userId)
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return dto.BookingResponse{}, http_error.BOOKING_NOT_FOUND
+ }
+ if err != nil {
+ return dto.BookingResponse{}, err
+ }
+ return dto.NewBookingResponse(booking), nil
+}
+
+// Pay runs in one transaction with the booking row locked, so a second pay or
+// a cancel for the same booking waits and then sees the new status. The mock
+// is called inside the transaction; that is safe only because the mock never
+// charges on timeout (see the RFC trade-offs).
+func (s *bookingService) Pay(ctx context.Context, userId, bookingId uuid.UUID, key string, req dto.PayBookingRequest) (dto.BookingResponse, bool, error) {
+ route := "POST /v1/bookings/" + bookingId.String() + "/pay"
+ return s.idempotent(ctx, userId, key, route, req, func(ctx context.Context) (dto.BookingResponse, error) {
+ locked, err := s.lockOwned(ctx, userId, bookingId)
+ if err != nil {
+ return dto.BookingResponse{}, err
+ }
+
+ if locked.Status == entity.BookingStatusExpired {
+ return dto.BookingResponse{}, http_error.BOOKING_EXPIRED
+ }
+ if locked.Status == entity.BookingStatusPendingPayment && locked.HoldPassed {
+ if err := s.transitionAndRelease(ctx, locked.Booking, entity.BookingStatusExpired); err != nil {
+ return dto.BookingResponse{}, err
+ }
+ return dto.BookingResponse{}, http_error.BOOKING_EXPIRED
+ }
+ if locked.Status != entity.BookingStatusPendingPayment {
+ return dto.BookingResponse{}, http_error.BOOKING_NOT_PAYABLE.WithDetails(map[string]any{"status": locked.Status})
+ }
+
+ result, err := s.paymentGateway.Charge(ctx, locked.TotalAmount, req.PaymentToken)
+ if err != nil {
+ return dto.BookingResponse{}, err
+ }
+ if _, err := s.paymentRepo.Create(ctx, entity.Payment{
+ BookingId: locked.Id,
+ Amount: locked.TotalAmount,
+ Status: result,
+ }); err != nil {
+ return dto.BookingResponse{}, err
+ }
+
+ if result == entity.PaymentStatusSucceeded {
+ confirmed, ok, err := s.bookingRepo.TransitionStatus(ctx, locked.Id, entity.BookingStatusPendingPayment, entity.BookingStatusConfirmed)
+ if err != nil {
+ return dto.BookingResponse{}, err
+ }
+ if !ok {
+ return dto.BookingResponse{}, http_error.INTERNAL_SERVER_ERROR
+ }
+ return dto.NewBookingResponse(confirmed), nil
+ }
+
+ if err := s.transitionAndRelease(ctx, locked.Booking, entity.BookingStatusPaymentFailed); err != nil {
+ return dto.BookingResponse{}, err
+ }
+ details := map[string]any{"booking_status": entity.BookingStatusPaymentFailed}
+ if result == entity.PaymentStatusTimeout {
+ return dto.BookingResponse{}, http_error.PAYMENT_TIMEOUT.WithDetails(details)
+ }
+ return dto.BookingResponse{}, http_error.PAYMENT_DECLINED.WithDetails(details)
+ })
+}
+
+func (s *bookingService) Cancel(ctx context.Context, userId, bookingId uuid.UUID) (dto.BookingResponse, error) {
+ var res dto.BookingResponse
+ err := s.transactor.WithinTransaction(ctx, func(ctx context.Context) error {
+ locked, err := s.lockOwned(ctx, userId, bookingId)
+ if err != nil {
+ return err
+ }
+ cancellable := locked.Status == entity.BookingStatusPendingPayment || locked.Status == entity.BookingStatusConfirmed
+ if !cancellable || locked.EventStarted {
+ return http_error.BOOKING_NOT_CANCELLABLE.WithDetails(map[string]any{"status": locked.Status})
+ }
+ cancelled, ok, err := s.bookingRepo.TransitionStatus(ctx, locked.Id, locked.Status, entity.BookingStatusCancelled)
+ if err != nil {
+ return err
+ }
+ if !ok {
+ return http_error.INTERNAL_SERVER_ERROR
+ }
+ if err := s.ticketTypeRepo.Release(ctx, map[uuid.UUID]int{locked.TicketTypeId: locked.Quantity}); err != nil {
+ return err
+ }
+ res = dto.NewBookingResponse(cancelled)
+ return nil
+ })
+ return res, err
+}
+
+func (s *bookingService) lockOwned(ctx context.Context, userId, bookingId uuid.UUID) (repositories.LockedBooking, error) {
+ locked, err := s.bookingRepo.LockForUpdate(ctx, bookingId)
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return locked, http_error.BOOKING_NOT_FOUND
+ }
+ if err != nil {
+ return locked, err
+ }
+ // Someone else's booking is reported as missing so its ID is not confirmed (BR-11).
+ if locked.UserId != userId {
+ return locked, http_error.BOOKING_NOT_FOUND
+ }
+ return locked, nil
+}
+
+// transitionAndRelease moves a pending booking to a final status and returns
+// its tickets in the same transaction.
+func (s *bookingService) transitionAndRelease(ctx context.Context, b entity.Booking, to string) error {
+ _, ok, err := s.bookingRepo.TransitionStatus(ctx, b.Id, entity.BookingStatusPendingPayment, to)
+ if err != nil || !ok {
+ return err
+ }
+ return s.ticketTypeRepo.Release(ctx, map[uuid.UUID]int{b.TicketTypeId: b.Quantity})
+}
+
+const outcomeOK = "OK"
+
+// idempotent runs fn exactly once per (user, key). The key claim, the business
+// writes and the stored outcome commit together. Business errors are stored
+// and committed like successes, so a retry gets the same answer; unexpected
+// errors roll everything back, freeing the key for a retry.
+func (s *bookingService) idempotent(
+ ctx context.Context, userId uuid.UUID, key, route string, req any,
+ fn func(ctx context.Context) (dto.BookingResponse, error),
+) (dto.BookingResponse, bool, error) {
+ hash, err := requestHash(route, req)
+ if err != nil {
+ return dto.BookingResponse{}, false, err
+ }
+
+ var (
+ result dto.BookingResponse
+ outcome error
+ replayed bool
+ )
+ err = s.transactor.WithinTransaction(ctx, func(ctx context.Context) error {
+ claimed, err := s.idempotencyRepo.Claim(ctx, userId, key, hash, s.bookingConfig.GetIdempotencyTTL())
+ if err != nil {
+ return err
+ }
+ if !claimed {
+ stored, err := s.idempotencyRepo.Get(ctx, userId, key)
+ if err != nil {
+ return err
+ }
+ if stored.RequestHash != hash {
+ outcome = http_error.IDEMPOTENCY_KEY_REUSED
+ return nil
+ }
+ replayed = true
+ result, outcome, err = decodeOutcome(stored)
+ return err
+ }
+
+ result, outcome = fn(ctx)
+ if outcome != nil {
+ if _, isBusiness := http_error.AsAppError(outcome); !isBusiness {
+ return outcome
+ }
+ }
+ code, body, err := encodeOutcome(result, outcome)
+ if err != nil {
+ return err
+ }
+ return s.idempotencyRepo.SaveResponse(ctx, userId, key, code, body)
+ })
+ if err != nil {
+ return dto.BookingResponse{}, false, err
+ }
+ return result, replayed, outcome
+}
+
+func requestHash(route string, req any) (string, error) {
+ body, err := json.Marshal(req)
+ if err != nil {
+ return "", err
+ }
+ sum := sha256.Sum256(append([]byte(route+"\n"), body...))
+ return hex.EncodeToString(sum[:]), nil
+}
+
+func encodeOutcome(result dto.BookingResponse, outcome error) (string, []byte, error) {
+ if outcome == nil {
+ body, err := json.Marshal(result)
+ return outcomeOK, body, err
+ }
+ appErr, _ := http_error.AsAppError(outcome)
+ body, err := json.Marshal(appErr.Details)
+ return appErr.Code, body, err
+}
+
+func decodeOutcome(stored entity.IdempotencyKey) (dto.BookingResponse, error, error) {
+ var result dto.BookingResponse
+ if stored.ResponseCode == outcomeOK {
+ err := json.Unmarshal(stored.ResponseBody, &result)
+ return result, nil, err
+ }
+ var details map[string]any
+ if len(stored.ResponseBody) > 0 {
+ if err := json.Unmarshal(stored.ResponseBody, &details); err != nil {
+ return result, nil, err
+ }
+ }
+ return result, http_error.Lookup(stored.ResponseCode).WithDetails(details), nil
+}
diff --git a/services/event_service.go b/services/event_service.go
new file mode 100644
index 0000000000000000000000000000000000000000..f1ed8612738026405b460d3997f0795bfadc8eb0
--- /dev/null
+++ b/services/event_service.go
@@ -0,0 +1,35 @@
+package services
+
+import (
+ "context"
+ "errors"
+
+ dto "abdanhafidz.com/event-booking-api/models/dto"
+ http_error "abdanhafidz.com/event-booking-api/models/error"
+ "abdanhafidz.com/event-booking-api/repositories"
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+type EventService interface {
+ Get(ctx context.Context, id uuid.UUID) (dto.EventResponse, error)
+}
+
+type eventService struct {
+ eventRepo repositories.EventRepository
+}
+
+func NewEventService(eventRepo repositories.EventRepository) EventService {
+ return &eventService{eventRepo: eventRepo}
+}
+
+func (s *eventService) Get(ctx context.Context, id uuid.UUID) (dto.EventResponse, error) {
+ event, err := s.eventRepo.GetWithTicketTypes(ctx, id)
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return dto.EventResponse{}, http_error.EVENT_NOT_FOUND
+ }
+ if err != nil {
+ return dto.EventResponse{}, err
+ }
+ return dto.NewEventResponse(event), nil
+}
diff --git a/services/expiry_service.go b/services/expiry_service.go
new file mode 100644
index 0000000000000000000000000000000000000000..891ac1b4cb2870bf5e4607807b7cd74fe0e07a69
--- /dev/null
+++ b/services/expiry_service.go
@@ -0,0 +1,81 @@
+package services
+
+import (
+ "context"
+ "log/slog"
+ "time"
+
+ "abdanhafidz.com/event-booking-api/repositories"
+ "github.com/google/uuid"
+)
+
+const sweepBatchSize = 200
+
+// ExpiryService releases tickets held by unpaid bookings once their hold has
+// passed (BR-04).
+type ExpiryService interface {
+ SweepOnce(ctx context.Context) (int, error)
+ Start(ctx context.Context, interval time.Duration)
+}
+
+type expiryService struct {
+ transactor repositories.Transactor
+ bookingRepo repositories.BookingRepository
+ ticketTypeRepo repositories.TicketTypeRepository
+}
+
+func NewExpiryService(
+ transactor repositories.Transactor,
+ bookingRepo repositories.BookingRepository,
+ ticketTypeRepo repositories.TicketTypeRepository,
+) ExpiryService {
+ return &expiryService{transactor: transactor, bookingRepo: bookingRepo, ticketTypeRepo: ticketTypeRepo}
+}
+
+// SweepOnce expires overdue bookings in batches until none are left, and
+// returns how many it expired.
+func (s *expiryService) SweepOnce(ctx context.Context) (int, error) {
+ total := 0
+ for {
+ var batch int
+ err := s.transactor.WithinTransaction(ctx, func(ctx context.Context) error {
+ expired, err := s.bookingRepo.ExpireDue(ctx, sweepBatchSize)
+ if err != nil {
+ return err
+ }
+ batch = len(expired)
+ release := make(map[uuid.UUID]int)
+ for _, b := range expired {
+ release[b.TicketTypeId] += b.Quantity
+ }
+ return s.ticketTypeRepo.Release(ctx, release)
+ })
+ if err != nil {
+ return total, err
+ }
+ total += batch
+ if batch < sweepBatchSize {
+ return total, nil
+ }
+ }
+}
+
+func (s *expiryService) Start(ctx context.Context, interval time.Duration) {
+ go func() {
+ ticker := time.NewTicker(interval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ n, err := s.SweepOnce(ctx)
+ if err != nil {
+ slog.Error("expiry sweep failed", "error", err.Error())
+ } else if n > 0 {
+ slog.Info("expired bookings", "count", n)
+ }
+ }
+ }
+ }()
+}
diff --git a/services/payment_gateway_service.go b/services/payment_gateway_service.go
new file mode 100644
index 0000000000000000000000000000000000000000..cd24a08a91e2713623e799dcc23e04ad97f8130e
--- /dev/null
+++ b/services/payment_gateway_service.go
@@ -0,0 +1,51 @@
+package services
+
+import (
+ "context"
+ "time"
+
+ entity "abdanhafidz.com/event-booking-api/models/entity"
+)
+
+// PaymentGatewayService is the only seam tests vary: latency and outcome. The
+// implementation is a mock; the token picks the result.
+type PaymentGatewayService interface {
+ Charge(ctx context.Context, amount int64, token string) (string, error)
+}
+
+type mockPaymentGateway struct {
+ latency time.Duration
+ timeout time.Duration
+}
+
+func NewMockPaymentGatewayService(latency, timeout time.Duration) PaymentGatewayService {
+ return &mockPaymentGateway{latency: latency, timeout: timeout}
+}
+
+// Charge returns SUCCEEDED, DECLINED or TIMEOUT. tok_timeout waits past the
+// client timeout, so the caller sees a timeout and no charge is recorded.
+func (g *mockPaymentGateway) Charge(ctx context.Context, amount int64, token string) (string, error) {
+ callCtx, cancel := context.WithTimeout(ctx, g.timeout)
+ defer cancel()
+
+ delay := g.latency
+ if token == entity.PaymentTokenTimeout {
+ delay = g.timeout + time.Second
+ }
+
+ timer := time.NewTimer(delay)
+ defer timer.Stop()
+ select {
+ case <-timer.C:
+ case <-callCtx.Done():
+ if ctx.Err() != nil {
+ return "", ctx.Err()
+ }
+ return entity.PaymentStatusTimeout, nil
+ }
+
+ if token == entity.PaymentTokenSuccess {
+ return entity.PaymentStatusSucceeded, nil
+ }
+ return entity.PaymentStatusDeclined, nil
+}
diff --git a/services/payment_gateway_service_test.go b/services/payment_gateway_service_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..af374d8f118f88e5681b4d48a0de51f036722fc9
--- /dev/null
+++ b/services/payment_gateway_service_test.go
@@ -0,0 +1,69 @@
+package services
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ dto "abdanhafidz.com/event-booking-api/models/dto"
+ entity "abdanhafidz.com/event-booking-api/models/entity"
+ http_error "abdanhafidz.com/event-booking-api/models/error"
+ "github.com/google/uuid"
+)
+
+func TestMockGatewayOutcomes(t *testing.T) {
+ g := NewMockPaymentGatewayService(0, 50*time.Millisecond)
+ cases := map[string]string{
+ entity.PaymentTokenSuccess: entity.PaymentStatusSucceeded,
+ entity.PaymentTokenDecline: entity.PaymentStatusDeclined,
+ "tok_unknown": entity.PaymentStatusDeclined,
+ entity.PaymentTokenTimeout: entity.PaymentStatusTimeout,
+ }
+ for token, want := range cases {
+ got, err := g.Charge(context.Background(), 1000, token)
+ if err != nil || got != want {
+ t.Errorf("%s: want %s, got %s (err %v)", token, want, got, err)
+ }
+ }
+}
+
+func TestMockGatewayTimeoutIsBoundedByClientTimeout(t *testing.T) {
+ g := NewMockPaymentGatewayService(0, 100*time.Millisecond)
+ start := time.Now()
+ got, _ := g.Charge(context.Background(), 1000, entity.PaymentTokenTimeout)
+ if got != entity.PaymentStatusTimeout || time.Since(start) > 500*time.Millisecond {
+ t.Fatalf("want TIMEOUT after ~100ms, got %s after %v", got, time.Since(start))
+ }
+}
+
+func TestMockGatewayHonoursCallerCancellation(t *testing.T) {
+ g := NewMockPaymentGatewayService(time.Second, 5*time.Second)
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
+ defer cancel()
+ if _, err := g.Charge(ctx, 1000, entity.PaymentTokenSuccess); err == nil {
+ t.Fatal("want the caller's context error, got nil")
+ }
+}
+
+func TestRequestHashDependsOnRouteAndBody(t *testing.T) {
+ tt := uuid.New()
+ a, _ := requestHash("POST /v1/bookings", dto.CreateBookingRequest{TicketTypeId: tt, Quantity: 2})
+ b, _ := requestHash("POST /v1/bookings", dto.CreateBookingRequest{TicketTypeId: tt, Quantity: 2})
+ c, _ := requestHash("POST /v1/bookings", dto.CreateBookingRequest{TicketTypeId: tt, Quantity: 3})
+ d, _ := requestHash("POST /v1/bookings/x/pay", dto.CreateBookingRequest{TicketTypeId: tt, Quantity: 2})
+ if a != b || a == c || a == d {
+ t.Fatalf("hash: same=%v differentBody=%v differentRoute=%v", a == b, a != c, a != d)
+ }
+}
+
+func TestStoredOutcomeRoundTrip(t *testing.T) {
+ code, body, err := encodeOutcome(dto.BookingResponse{}, http_error.INSUFFICIENT_TICKETS.WithDetails(map[string]any{"available": 3}))
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, outcome, err := decodeOutcome(entity.IdempotencyKey{ResponseCode: code, ResponseBody: body})
+ appErr, ok := http_error.AsAppError(outcome)
+ if err != nil || !ok || appErr.Code != "INSUFFICIENT_TICKETS" || appErr.Details["available"] != float64(3) {
+ t.Fatalf("round trip lost the outcome: %v %v", outcome, err)
+ }
+}
diff --git a/swagger/README.md b/swagger/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..0c1fe41d543d2b42bd665481bebc084280620b11
--- /dev/null
+++ b/swagger/README.md
@@ -0,0 +1,6 @@
+# Swagger Quzuu Ready
+
+1. Copy folder `swagger/` to your project root
+2. Import `_ "your_module/swagger/docs"` in main.go
+3. Run: swag init --parseDependency --parseInternal
+4. Open: /swagger/index.html
diff --git a/swagger/docs/docs.go b/swagger/docs/docs.go
new file mode 100644
index 0000000000000000000000000000000000000000..d00bcbf629fea62a54b1189be01f811359ff709c
--- /dev/null
+++ b/swagger/docs/docs.go
@@ -0,0 +1,475 @@
+// Package docs Code generated by swaggo/swag. DO NOT EDIT
+package docs
+
+import "github.com/swaggo/swag"
+
+const docTemplate = `{
+ "schemes": {{ marshal .Schemes }},
+ "swagger": "2.0",
+ "info": {
+ "description": "{{escape .Description}}",
+ "title": "{{.Title}}",
+ "contact": {
+ "name": "Abdan Hafidz"
+ },
+ "license": {
+ "name": "MIT",
+ "url": "https://opensource.org/licenses/MIT"
+ },
+ "version": "{{.Version}}"
+ },
+ "host": "{{.Host}}",
+ "basePath": "{{.BasePath}}",
+ "paths": {
+ "/v1/bookings": {
+ "post": {
+ "description": "Reserves tickets all-or-nothing and starts the payment hold",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Booking"
+ ],
+ "summary": "Reserve tickets",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "Caller user ID",
+ "name": "X-User-Id",
+ "in": "header",
+ "required": true
+ },
+ {
+ "type": "string",
+ "description": "Idempotency key",
+ "name": "Idempotency-Key",
+ "in": "header",
+ "required": true
+ },
+ {
+ "description": "Booking request",
+ "name": "request",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/dto.CreateBookingRequest"
+ }
+ }
+ ],
+ "responses": {
+ "201": {
+ "description": "Created",
+ "schema": {
+ "$ref": "#/definitions/dto.SuccessResponse-dto_BookingResponse"
+ }
+ },
+ "400": {
+ "description": "Bad Request",
+ "schema": {
+ "$ref": "#/definitions/dto.ErrorResponse"
+ }
+ },
+ "401": {
+ "description": "Unauthorized",
+ "schema": {
+ "$ref": "#/definitions/dto.ErrorResponse"
+ }
+ },
+ "404": {
+ "description": "Not Found",
+ "schema": {
+ "$ref": "#/definitions/dto.ErrorResponse"
+ }
+ },
+ "409": {
+ "description": "Conflict",
+ "schema": {
+ "$ref": "#/definitions/dto.ErrorResponse"
+ }
+ },
+ "422": {
+ "description": "Unprocessable Entity",
+ "schema": {
+ "$ref": "#/definitions/dto.ErrorResponse"
+ }
+ }
+ }
+ }
+ },
+ "/v1/bookings/{id}": {
+ "get": {
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Booking"
+ ],
+ "summary": "Get one of your bookings",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "Caller user ID",
+ "name": "X-User-Id",
+ "in": "header",
+ "required": true
+ },
+ {
+ "type": "string",
+ "description": "Booking ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "$ref": "#/definitions/dto.SuccessResponse-dto_BookingResponse"
+ }
+ },
+ "404": {
+ "description": "Not Found",
+ "schema": {
+ "$ref": "#/definitions/dto.ErrorResponse"
+ }
+ }
+ }
+ }
+ },
+ "/v1/bookings/{id}/cancel": {
+ "post": {
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Booking"
+ ],
+ "summary": "Cancel a pending or confirmed booking before the event starts",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "Caller user ID",
+ "name": "X-User-Id",
+ "in": "header",
+ "required": true
+ },
+ {
+ "type": "string",
+ "description": "Booking ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "$ref": "#/definitions/dto.SuccessResponse-dto_BookingResponse"
+ }
+ },
+ "404": {
+ "description": "Not Found",
+ "schema": {
+ "$ref": "#/definitions/dto.ErrorResponse"
+ }
+ },
+ "409": {
+ "description": "Conflict",
+ "schema": {
+ "$ref": "#/definitions/dto.ErrorResponse"
+ }
+ }
+ }
+ }
+ },
+ "/v1/bookings/{id}/pay": {
+ "post": {
+ "description": "tok_success confirms; tok_decline and tok_timeout fail the booking and release its tickets",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Booking"
+ ],
+ "summary": "Pay for a booking with the mock gateway",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "Caller user ID",
+ "name": "X-User-Id",
+ "in": "header",
+ "required": true
+ },
+ {
+ "type": "string",
+ "description": "Idempotency key",
+ "name": "Idempotency-Key",
+ "in": "header",
+ "required": true
+ },
+ {
+ "type": "string",
+ "description": "Booking ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ },
+ {
+ "description": "Payment request",
+ "name": "request",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/dto.PayBookingRequest"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "$ref": "#/definitions/dto.SuccessResponse-dto_BookingResponse"
+ }
+ },
+ "402": {
+ "description": "Payment Required",
+ "schema": {
+ "$ref": "#/definitions/dto.ErrorResponse"
+ }
+ },
+ "404": {
+ "description": "Not Found",
+ "schema": {
+ "$ref": "#/definitions/dto.ErrorResponse"
+ }
+ },
+ "409": {
+ "description": "Conflict",
+ "schema": {
+ "$ref": "#/definitions/dto.ErrorResponse"
+ }
+ },
+ "422": {
+ "description": "Unprocessable Entity",
+ "schema": {
+ "$ref": "#/definitions/dto.ErrorResponse"
+ }
+ }
+ }
+ }
+ },
+ "/v1/events/{id}": {
+ "get": {
+ "description": "Event with its ticket types and live availability",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Event"
+ ],
+ "summary": "Get an event",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "Event ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "$ref": "#/definitions/dto.SuccessResponse-dto_EventResponse"
+ }
+ },
+ "404": {
+ "description": "Not Found",
+ "schema": {
+ "$ref": "#/definitions/dto.ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ },
+ "definitions": {
+ "dto.BookingResponse": {
+ "type": "object",
+ "properties": {
+ "created_at": {
+ "type": "string"
+ },
+ "currency": {
+ "type": "string"
+ },
+ "event_id": {
+ "type": "string"
+ },
+ "expires_at": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "quantity": {
+ "type": "integer"
+ },
+ "status": {
+ "type": "string"
+ },
+ "ticket_type_id": {
+ "type": "string"
+ },
+ "total_amount": {
+ "type": "integer"
+ },
+ "unit_price": {
+ "type": "integer"
+ },
+ "updated_at": {
+ "type": "string"
+ }
+ }
+ },
+ "dto.CreateBookingRequest": {
+ "type": "object",
+ "required": [
+ "quantity",
+ "ticket_type_id"
+ ],
+ "properties": {
+ "quantity": {
+ "type": "integer",
+ "maximum": 6,
+ "minimum": 1
+ },
+ "ticket_type_id": {
+ "type": "string"
+ }
+ }
+ },
+ "dto.ErrorResponse": {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "string"
+ },
+ "errors": {},
+ "message": {},
+ "meta_data": {},
+ "status": {
+ "type": "string"
+ }
+ }
+ },
+ "dto.EventResponse": {
+ "type": "object",
+ "properties": {
+ "currency": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "starts_at": {
+ "type": "string"
+ },
+ "ticket_types": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/dto.TicketTypeResponse"
+ }
+ }
+ }
+ },
+ "dto.PayBookingRequest": {
+ "type": "object",
+ "required": [
+ "payment_token"
+ ],
+ "properties": {
+ "payment_token": {
+ "type": "string",
+ "maxLength": 64
+ }
+ }
+ },
+ "dto.SuccessResponse-dto_BookingResponse": {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/dto.BookingResponse"
+ },
+ "message": {},
+ "meta_data": {},
+ "status": {
+ "type": "string"
+ }
+ }
+ },
+ "dto.SuccessResponse-dto_EventResponse": {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/dto.EventResponse"
+ },
+ "message": {},
+ "meta_data": {},
+ "status": {
+ "type": "string"
+ }
+ }
+ },
+ "dto.TicketTypeResponse": {
+ "type": "object",
+ "properties": {
+ "available": {
+ "type": "integer"
+ },
+ "capacity": {
+ "type": "integer"
+ },
+ "id": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "price": {
+ "type": "integer"
+ }
+ }
+ }
+ }
+}`
+
+// SwaggerInfo holds exported Swagger Info so clients can modify it
+var SwaggerInfo = &swag.Spec{
+ Version: "1.0.0",
+ Host: "",
+ BasePath: "/",
+ Schemes: []string{"http", "https"},
+ Title: "Event Ticket Booking API",
+ Description: "Minimal booking API built for integration and performance testing. Callers identify themselves with X-User-Id; payment is a mock selected by token (tok_success, tok_decline, tok_timeout).",
+ InfoInstanceName: "swagger",
+ SwaggerTemplate: docTemplate,
+ LeftDelim: "{{",
+ RightDelim: "}}",
+}
+
+func init() {
+ swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo)
+}
diff --git a/swagger/docs/swagger.json b/swagger/docs/swagger.json
new file mode 100644
index 0000000000000000000000000000000000000000..91bbf353a0a4bdf54d0a4d19e5417a5b0b9e0628
--- /dev/null
+++ b/swagger/docs/swagger.json
@@ -0,0 +1,454 @@
+{
+ "schemes": [
+ "http",
+ "https"
+ ],
+ "swagger": "2.0",
+ "info": {
+ "description": "Minimal booking API built for integration and performance testing. Callers identify themselves with X-User-Id; payment is a mock selected by token (tok_success, tok_decline, tok_timeout).",
+ "title": "Event Ticket Booking API",
+ "contact": {
+ "name": "Abdan Hafidz"
+ },
+ "license": {
+ "name": "MIT",
+ "url": "https://opensource.org/licenses/MIT"
+ },
+ "version": "1.0.0"
+ },
+ "basePath": "/",
+ "paths": {
+ "/v1/bookings": {
+ "post": {
+ "description": "Reserves tickets all-or-nothing and starts the payment hold",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Booking"
+ ],
+ "summary": "Reserve tickets",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "Caller user ID",
+ "name": "X-User-Id",
+ "in": "header",
+ "required": true
+ },
+ {
+ "type": "string",
+ "description": "Idempotency key",
+ "name": "Idempotency-Key",
+ "in": "header",
+ "required": true
+ },
+ {
+ "description": "Booking request",
+ "name": "request",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/dto.CreateBookingRequest"
+ }
+ }
+ ],
+ "responses": {
+ "201": {
+ "description": "Created",
+ "schema": {
+ "$ref": "#/definitions/dto.SuccessResponse-dto_BookingResponse"
+ }
+ },
+ "400": {
+ "description": "Bad Request",
+ "schema": {
+ "$ref": "#/definitions/dto.ErrorResponse"
+ }
+ },
+ "401": {
+ "description": "Unauthorized",
+ "schema": {
+ "$ref": "#/definitions/dto.ErrorResponse"
+ }
+ },
+ "404": {
+ "description": "Not Found",
+ "schema": {
+ "$ref": "#/definitions/dto.ErrorResponse"
+ }
+ },
+ "409": {
+ "description": "Conflict",
+ "schema": {
+ "$ref": "#/definitions/dto.ErrorResponse"
+ }
+ },
+ "422": {
+ "description": "Unprocessable Entity",
+ "schema": {
+ "$ref": "#/definitions/dto.ErrorResponse"
+ }
+ }
+ }
+ }
+ },
+ "/v1/bookings/{id}": {
+ "get": {
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Booking"
+ ],
+ "summary": "Get one of your bookings",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "Caller user ID",
+ "name": "X-User-Id",
+ "in": "header",
+ "required": true
+ },
+ {
+ "type": "string",
+ "description": "Booking ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "$ref": "#/definitions/dto.SuccessResponse-dto_BookingResponse"
+ }
+ },
+ "404": {
+ "description": "Not Found",
+ "schema": {
+ "$ref": "#/definitions/dto.ErrorResponse"
+ }
+ }
+ }
+ }
+ },
+ "/v1/bookings/{id}/cancel": {
+ "post": {
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Booking"
+ ],
+ "summary": "Cancel a pending or confirmed booking before the event starts",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "Caller user ID",
+ "name": "X-User-Id",
+ "in": "header",
+ "required": true
+ },
+ {
+ "type": "string",
+ "description": "Booking ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "$ref": "#/definitions/dto.SuccessResponse-dto_BookingResponse"
+ }
+ },
+ "404": {
+ "description": "Not Found",
+ "schema": {
+ "$ref": "#/definitions/dto.ErrorResponse"
+ }
+ },
+ "409": {
+ "description": "Conflict",
+ "schema": {
+ "$ref": "#/definitions/dto.ErrorResponse"
+ }
+ }
+ }
+ }
+ },
+ "/v1/bookings/{id}/pay": {
+ "post": {
+ "description": "tok_success confirms; tok_decline and tok_timeout fail the booking and release its tickets",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Booking"
+ ],
+ "summary": "Pay for a booking with the mock gateway",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "Caller user ID",
+ "name": "X-User-Id",
+ "in": "header",
+ "required": true
+ },
+ {
+ "type": "string",
+ "description": "Idempotency key",
+ "name": "Idempotency-Key",
+ "in": "header",
+ "required": true
+ },
+ {
+ "type": "string",
+ "description": "Booking ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ },
+ {
+ "description": "Payment request",
+ "name": "request",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/dto.PayBookingRequest"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "$ref": "#/definitions/dto.SuccessResponse-dto_BookingResponse"
+ }
+ },
+ "402": {
+ "description": "Payment Required",
+ "schema": {
+ "$ref": "#/definitions/dto.ErrorResponse"
+ }
+ },
+ "404": {
+ "description": "Not Found",
+ "schema": {
+ "$ref": "#/definitions/dto.ErrorResponse"
+ }
+ },
+ "409": {
+ "description": "Conflict",
+ "schema": {
+ "$ref": "#/definitions/dto.ErrorResponse"
+ }
+ },
+ "422": {
+ "description": "Unprocessable Entity",
+ "schema": {
+ "$ref": "#/definitions/dto.ErrorResponse"
+ }
+ }
+ }
+ }
+ },
+ "/v1/events/{id}": {
+ "get": {
+ "description": "Event with its ticket types and live availability",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Event"
+ ],
+ "summary": "Get an event",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "Event ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "$ref": "#/definitions/dto.SuccessResponse-dto_EventResponse"
+ }
+ },
+ "404": {
+ "description": "Not Found",
+ "schema": {
+ "$ref": "#/definitions/dto.ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ },
+ "definitions": {
+ "dto.BookingResponse": {
+ "type": "object",
+ "properties": {
+ "created_at": {
+ "type": "string"
+ },
+ "currency": {
+ "type": "string"
+ },
+ "event_id": {
+ "type": "string"
+ },
+ "expires_at": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "quantity": {
+ "type": "integer"
+ },
+ "status": {
+ "type": "string"
+ },
+ "ticket_type_id": {
+ "type": "string"
+ },
+ "total_amount": {
+ "type": "integer"
+ },
+ "unit_price": {
+ "type": "integer"
+ },
+ "updated_at": {
+ "type": "string"
+ }
+ }
+ },
+ "dto.CreateBookingRequest": {
+ "type": "object",
+ "required": [
+ "quantity",
+ "ticket_type_id"
+ ],
+ "properties": {
+ "quantity": {
+ "type": "integer",
+ "maximum": 6,
+ "minimum": 1
+ },
+ "ticket_type_id": {
+ "type": "string"
+ }
+ }
+ },
+ "dto.ErrorResponse": {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "string"
+ },
+ "errors": {},
+ "message": {},
+ "meta_data": {},
+ "status": {
+ "type": "string"
+ }
+ }
+ },
+ "dto.EventResponse": {
+ "type": "object",
+ "properties": {
+ "currency": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "starts_at": {
+ "type": "string"
+ },
+ "ticket_types": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/dto.TicketTypeResponse"
+ }
+ }
+ }
+ },
+ "dto.PayBookingRequest": {
+ "type": "object",
+ "required": [
+ "payment_token"
+ ],
+ "properties": {
+ "payment_token": {
+ "type": "string",
+ "maxLength": 64
+ }
+ }
+ },
+ "dto.SuccessResponse-dto_BookingResponse": {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/dto.BookingResponse"
+ },
+ "message": {},
+ "meta_data": {},
+ "status": {
+ "type": "string"
+ }
+ }
+ },
+ "dto.SuccessResponse-dto_EventResponse": {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/dto.EventResponse"
+ },
+ "message": {},
+ "meta_data": {},
+ "status": {
+ "type": "string"
+ }
+ }
+ },
+ "dto.TicketTypeResponse": {
+ "type": "object",
+ "properties": {
+ "available": {
+ "type": "integer"
+ },
+ "capacity": {
+ "type": "integer"
+ },
+ "id": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "price": {
+ "type": "integer"
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/swagger/docs/swagger.yaml b/swagger/docs/swagger.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..759177be349f38bbeb6bcc48f03a7cdf65405f0a
--- /dev/null
+++ b/swagger/docs/swagger.yaml
@@ -0,0 +1,306 @@
+basePath: /
+definitions:
+ dto.BookingResponse:
+ properties:
+ created_at:
+ type: string
+ currency:
+ type: string
+ event_id:
+ type: string
+ expires_at:
+ type: string
+ id:
+ type: string
+ quantity:
+ type: integer
+ status:
+ type: string
+ ticket_type_id:
+ type: string
+ total_amount:
+ type: integer
+ unit_price:
+ type: integer
+ updated_at:
+ type: string
+ type: object
+ dto.CreateBookingRequest:
+ properties:
+ quantity:
+ maximum: 6
+ minimum: 1
+ type: integer
+ ticket_type_id:
+ type: string
+ required:
+ - quantity
+ - ticket_type_id
+ type: object
+ dto.ErrorResponse:
+ properties:
+ code:
+ type: string
+ errors: {}
+ message: {}
+ meta_data: {}
+ status:
+ type: string
+ type: object
+ dto.EventResponse:
+ properties:
+ currency:
+ type: string
+ id:
+ type: string
+ name:
+ type: string
+ starts_at:
+ type: string
+ ticket_types:
+ items:
+ $ref: '#/definitions/dto.TicketTypeResponse'
+ type: array
+ type: object
+ dto.PayBookingRequest:
+ properties:
+ payment_token:
+ maxLength: 64
+ type: string
+ required:
+ - payment_token
+ type: object
+ dto.SuccessResponse-dto_BookingResponse:
+ properties:
+ data:
+ $ref: '#/definitions/dto.BookingResponse'
+ message: {}
+ meta_data: {}
+ status:
+ type: string
+ type: object
+ dto.SuccessResponse-dto_EventResponse:
+ properties:
+ data:
+ $ref: '#/definitions/dto.EventResponse'
+ message: {}
+ meta_data: {}
+ status:
+ type: string
+ type: object
+ dto.TicketTypeResponse:
+ properties:
+ available:
+ type: integer
+ capacity:
+ type: integer
+ id:
+ type: string
+ name:
+ type: string
+ price:
+ type: integer
+ type: object
+info:
+ contact:
+ name: Abdan Hafidz
+ description: Minimal booking API built for integration and performance testing.
+ Callers identify themselves with X-User-Id; payment is a mock selected by token
+ (tok_success, tok_decline, tok_timeout).
+ license:
+ name: MIT
+ url: https://opensource.org/licenses/MIT
+ title: Event Ticket Booking API
+ version: 1.0.0
+paths:
+ /v1/bookings:
+ post:
+ consumes:
+ - application/json
+ description: Reserves tickets all-or-nothing and starts the payment hold
+ parameters:
+ - description: Caller user ID
+ in: header
+ name: X-User-Id
+ required: true
+ type: string
+ - description: Idempotency key
+ in: header
+ name: Idempotency-Key
+ required: true
+ type: string
+ - description: Booking request
+ in: body
+ name: request
+ required: true
+ schema:
+ $ref: '#/definitions/dto.CreateBookingRequest'
+ produces:
+ - application/json
+ responses:
+ "201":
+ description: Created
+ schema:
+ $ref: '#/definitions/dto.SuccessResponse-dto_BookingResponse'
+ "400":
+ description: Bad Request
+ schema:
+ $ref: '#/definitions/dto.ErrorResponse'
+ "401":
+ description: Unauthorized
+ schema:
+ $ref: '#/definitions/dto.ErrorResponse'
+ "404":
+ description: Not Found
+ schema:
+ $ref: '#/definitions/dto.ErrorResponse'
+ "409":
+ description: Conflict
+ schema:
+ $ref: '#/definitions/dto.ErrorResponse'
+ "422":
+ description: Unprocessable Entity
+ schema:
+ $ref: '#/definitions/dto.ErrorResponse'
+ summary: Reserve tickets
+ tags:
+ - Booking
+ /v1/bookings/{id}:
+ get:
+ parameters:
+ - description: Caller user ID
+ in: header
+ name: X-User-Id
+ required: true
+ type: string
+ - description: Booking ID
+ in: path
+ name: id
+ required: true
+ type: string
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: OK
+ schema:
+ $ref: '#/definitions/dto.SuccessResponse-dto_BookingResponse'
+ "404":
+ description: Not Found
+ schema:
+ $ref: '#/definitions/dto.ErrorResponse'
+ summary: Get one of your bookings
+ tags:
+ - Booking
+ /v1/bookings/{id}/cancel:
+ post:
+ parameters:
+ - description: Caller user ID
+ in: header
+ name: X-User-Id
+ required: true
+ type: string
+ - description: Booking ID
+ in: path
+ name: id
+ required: true
+ type: string
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: OK
+ schema:
+ $ref: '#/definitions/dto.SuccessResponse-dto_BookingResponse'
+ "404":
+ description: Not Found
+ schema:
+ $ref: '#/definitions/dto.ErrorResponse'
+ "409":
+ description: Conflict
+ schema:
+ $ref: '#/definitions/dto.ErrorResponse'
+ summary: Cancel a pending or confirmed booking before the event starts
+ tags:
+ - Booking
+ /v1/bookings/{id}/pay:
+ post:
+ consumes:
+ - application/json
+ description: tok_success confirms; tok_decline and tok_timeout fail the booking
+ and release its tickets
+ parameters:
+ - description: Caller user ID
+ in: header
+ name: X-User-Id
+ required: true
+ type: string
+ - description: Idempotency key
+ in: header
+ name: Idempotency-Key
+ required: true
+ type: string
+ - description: Booking ID
+ in: path
+ name: id
+ required: true
+ type: string
+ - description: Payment request
+ in: body
+ name: request
+ required: true
+ schema:
+ $ref: '#/definitions/dto.PayBookingRequest'
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: OK
+ schema:
+ $ref: '#/definitions/dto.SuccessResponse-dto_BookingResponse'
+ "402":
+ description: Payment Required
+ schema:
+ $ref: '#/definitions/dto.ErrorResponse'
+ "404":
+ description: Not Found
+ schema:
+ $ref: '#/definitions/dto.ErrorResponse'
+ "409":
+ description: Conflict
+ schema:
+ $ref: '#/definitions/dto.ErrorResponse'
+ "422":
+ description: Unprocessable Entity
+ schema:
+ $ref: '#/definitions/dto.ErrorResponse'
+ summary: Pay for a booking with the mock gateway
+ tags:
+ - Booking
+ /v1/events/{id}:
+ get:
+ description: Event with its ticket types and live availability
+ parameters:
+ - description: Event ID
+ in: path
+ name: id
+ required: true
+ type: string
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: OK
+ schema:
+ $ref: '#/definitions/dto.SuccessResponse-dto_EventResponse'
+ "404":
+ description: Not Found
+ schema:
+ $ref: '#/definitions/dto.ErrorResponse'
+ summary: Get an event
+ tags:
+ - Event
+schemes:
+- http
+- https
+swagger: "2.0"
diff --git a/swagger/swagger_info.go b/swagger/swagger_info.go
new file mode 100644
index 0000000000000000000000000000000000000000..8a4426333f5de7e5a1c85301ffed9fe4a3e21571
--- /dev/null
+++ b/swagger/swagger_info.go
@@ -0,0 +1,17 @@
+package swagger
+
+// =====================
+// Swagger Global Config
+// =====================
+
+// @title Event Ticket Booking API
+// @version 1.0.0
+// @description Minimal booking API built for integration and performance testing. Callers identify themselves with X-User-Id; payment is a mock selected by token (tok_success, tok_decline, tok_timeout).
+
+// @contact.name Abdan Hafidz
+
+// @license.name MIT
+// @license.url https://opensource.org/licenses/MIT
+
+// @BasePath /
+// @schemes http https
diff --git a/tests/integration/booking_test.go b/tests/integration/booking_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..c4516edd4fb5cafb75fa22914f3d3a9a04a6a48b
--- /dev/null
+++ b/tests/integration/booking_test.go
@@ -0,0 +1,108 @@
+package integration
+
+import (
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+func TestBookingCreatesPendingHold(t *testing.T) { // IT-BK-01
+ a := newApp(t)
+ tt, u := a.ticketType(100), a.user()
+
+ res := a.createBooking(u, tt, 2, key())
+ expectCode(t, res, 201, "")
+ b := res.booking(t)
+ expectEqual(t, "status", "PENDING_PAYMENT", b.Status)
+ expectEqual(t, "unit_price", int64(150000), b.UnitPrice)
+ expectEqual(t, "total_amount", int64(300000), b.TotalAmount)
+ hold := b.ExpiresAt.Sub(b.CreatedAt)
+ if hold < 599*time.Second || hold > 601*time.Second {
+ t.Fatalf("hold: want 600s ±1s, got %v", hold)
+ }
+ expectEqual(t, "available", 98, a.available(tt))
+}
+
+func TestBookingRejectsInvalidQuantity(t *testing.T) { // IT-BK-02
+ a := newApp(t)
+ tt, u := a.ticketType(100), a.user()
+
+ bodies := []string{
+ `{"ticket_type_id":"` + tt.String() + `","quantity":0}`,
+ `{"ticket_type_id":"` + tt.String() + `","quantity":7}`,
+ `{"ticket_type_id":"` + tt.String() + `","quantity":1.5}`,
+ `{"ticket_type_id":"` + tt.String() + `","quantity":"2"}`,
+ `{"ticket_type_id":"` + tt.String() + `"}`,
+ }
+ for _, body := range bodies {
+ res := a.request("POST", "/v1/bookings", u, key(), body)
+ expectCode(t, res, 400, "VALIDATION_ERROR")
+ expectEqual(t, "errors.field for "+body, any("quantity"), res.Errors["field"])
+ }
+ expectEqual(t, "available", 100, a.available(tt))
+ expectEqual(t, "bookings", 0, a.bookingsFor(tt))
+}
+
+func TestBookingUnknownTicketType(t *testing.T) { // IT-BK-03
+ a := newApp(t)
+ expectCode(t, a.createBooking(a.user(), uuid.New(), 1, key()), 404, "TICKET_TYPE_NOT_FOUND")
+}
+
+func TestBookingSalesClosedAfterEventStart(t *testing.T) { // IT-BK-04
+ a := newApp(t)
+ _, ids := a.event(-time.Second, 10)
+ expectCode(t, a.createBooking(a.user(), ids[0], 1, key()), 409, "SALES_CLOSED")
+ expectEqual(t, "available", 10, a.available(ids[0]))
+}
+
+func TestBookingOwnershipAndIdentity(t *testing.T) { // IT-BK-05
+ a := newApp(t)
+ tt := a.ticketType(100)
+ owner, other := a.user(), a.user()
+ b := a.book(owner, tt, 2)
+
+ expectCode(t, a.request("GET", "/v1/bookings/"+b.Id.String(), other, "", nil), 404, "BOOKING_NOT_FOUND")
+ expectCode(t, a.pay(other, b.Id, "tok_success", key()), 404, "BOOKING_NOT_FOUND")
+ expectCode(t, a.cancel(other, b.Id), 404, "BOOKING_NOT_FOUND")
+ expectEqual(t, "status", "PENDING_PAYMENT", a.status(b.Id))
+
+ expectCode(t, a.request("GET", "/v1/bookings/"+b.Id.String(), uuid.Nil, "", nil), 401, "UNAUTHENTICATED")
+ expectCode(t, a.request("GET", "/v1/bookings/"+b.Id.String(), uuid.New(), "", nil), 401, "UNAUTHENTICATED")
+
+ res := a.request("GET", "/v1/bookings/"+b.Id.String(), owner, "", nil)
+ expectCode(t, res, 200, "")
+ expectEqual(t, "id", b.Id, res.booking(t).Id)
+}
+
+func TestAvailabilityLastTickets(t *testing.T) { // IT-AV-01
+ a := newApp(t)
+ tt := a.ticketType(5)
+ a.book(a.user(), tt, 5)
+
+ res := a.createBooking(a.user(), tt, 1, key())
+ expectCode(t, res, 409, "INSUFFICIENT_TICKETS")
+ expectEqual(t, "errors.available", any(float64(0)), res.Errors["available"])
+}
+
+func TestAvailabilityNoPartialReservation(t *testing.T) { // IT-AV-02
+ a := newApp(t)
+ tt := a.ticketType(5)
+ a.book(a.user(), tt, 2)
+
+ res := a.createBooking(a.user(), tt, 4, key())
+ expectCode(t, res, 409, "INSUFFICIENT_TICKETS")
+ expectEqual(t, "errors.available", any(float64(3)), res.Errors["available"])
+ expectEqual(t, "available", 3, a.available(tt))
+}
+
+func TestEventShowsLiveAvailability(t *testing.T) {
+ a := newApp(t)
+ ev, ids := a.event(7*24*time.Hour, 10, 20)
+ a.book(a.user(), ids[0], 3)
+
+ res := a.request("GET", "/v1/events/"+ev.String(), uuid.Nil, "", nil)
+ expectCode(t, res, 200, "")
+ expectCode(t, a.request("GET", "/v1/events/"+uuid.NewString(), uuid.Nil, "", nil), 404, "EVENT_NOT_FOUND")
+ expectEqual(t, "available", 7, a.available(ids[0]))
+}
diff --git a/tests/integration/concurrency_test.go b/tests/integration/concurrency_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..3c8101419187b6fa4062cb3f3fc8653dbbebe8da
--- /dev/null
+++ b/tests/integration/concurrency_test.go
@@ -0,0 +1,84 @@
+package integration
+
+import (
+ "testing"
+ "time"
+)
+
+// Run these with -count=20 in CI: a race that fails one run in twenty is still a bug.
+
+func TestConcurrentBookingsNeverOversell(t *testing.T) { // IT-CC-01
+ a := newApp(t)
+ tt := a.ticketType(50)
+ users := a.users(200)
+
+ results := parallel(200, func(i int) response { return a.createBooking(users[i], tt, 1, key()) })
+ counts := countCodes(results)
+ expectEqual(t, "201 Created", 50, counts["Created"])
+ expectEqual(t, "INSUFFICIENT_TICKETS", 150, counts["INSUFFICIENT_TICKETS"])
+ expectEqual(t, "available", 0, a.available(tt))
+}
+
+func TestConcurrentMixedQuantities(t *testing.T) { // IT-CC-02
+ a := newApp(t)
+ tt := a.ticketType(10)
+ users := a.users(20)
+
+ results := parallel(20, func(i int) response { return a.createBooking(users[i], tt, i%3+1, key()) })
+ booked := 0
+ for i, r := range results {
+ switch {
+ case r.Code == 201:
+ booked += i%3 + 1
+ case r.ErrCode != "INSUFFICIENT_TICKETS":
+ t.Fatalf("unexpected response %d %s", r.Code, r.RawBody)
+ }
+ }
+ if booked > 10 {
+ t.Fatalf("oversold: %d of 10", booked)
+ }
+ expectEqual(t, "available", 10-booked, a.available(tt))
+}
+
+func TestConcurrentPayAndCancel(t *testing.T) { // IT-CC-03
+ a := newApp(t, withLatency(200*time.Millisecond))
+ tt := a.ticketType(100)
+ users := a.users(50)
+ bookings := make([]booking, 50)
+ for i, u := range users {
+ bookings[i] = a.book(u, tt, 1)
+ }
+
+ results := parallel(100, func(i int) response {
+ b, u := bookings[i/2], users[i/2]
+ if i%2 == 0 {
+ return a.pay(u, b.Id, "tok_success", key())
+ }
+ return a.cancel(u, b.Id)
+ })
+
+ for i, b := range bookings {
+ pay, cancel := results[2*i], results[2*i+1]
+ expectCode(t, cancel, 200, "") // cancel works on both pending and confirmed bookings
+ if pay.Code != 200 && pay.ErrCode != "BOOKING_NOT_PAYABLE" {
+ t.Fatalf("pay: unexpected %d %s", pay.Code, pay.RawBody)
+ }
+ expectEqual(t, "final status", "CANCELLED", a.status(b.Id))
+ if n := a.payments(b.Id, "SUCCEEDED"); n > 1 {
+ t.Fatalf("booking %s paid %d times", b.Id, n)
+ }
+ }
+ expectEqual(t, "available", 100, a.available(tt))
+}
+
+func TestConcurrentPaysWithDifferentKeys(t *testing.T) { // IT-CC-04
+ a := newApp(t, withLatency(500*time.Millisecond))
+ tt, u := a.ticketType(100), a.user()
+ b := a.book(u, tt, 1)
+
+ results := parallel(5, func(int) response { return a.pay(u, b.Id, "tok_success", key()) })
+ counts := countCodes(results)
+ expectEqual(t, "200 OK", 1, counts["OK"])
+ expectEqual(t, "BOOKING_NOT_PAYABLE", 4, counts["BOOKING_NOT_PAYABLE"])
+ expectEqual(t, "succeeded payments", 1, a.payments(b.Id, "SUCCEEDED"))
+}
diff --git a/tests/integration/harness_test.go b/tests/integration/harness_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..ac17f191c0a1f3959ff298201c957232b7ff1c39
--- /dev/null
+++ b/tests/integration/harness_test.go
@@ -0,0 +1,366 @@
+// Package integration runs the API in-process against a real PostgreSQL
+// database. Set TEST_DATABASE_URL to run it, for example:
+//
+// TEST_DATABASE_URL="host=localhost port=5433 user=postgres dbname=booking_test sslmode=disable" go test ./tests/integration/...
+package integration
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "sync"
+ "testing"
+ "time"
+
+ "abdanhafidz.com/event-booking-api/config"
+ entity "abdanhafidz.com/event-booking-api/models/entity"
+ "abdanhafidz.com/event-booking-api/provider"
+ "abdanhafidz.com/event-booking-api/router"
+ "github.com/gin-gonic/gin"
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+func TestMain(m *testing.M) {
+ gin.SetMode(gin.TestMode)
+ slog.SetDefault(slog.New(slog.NewTextHandler(io.Discard, nil)))
+ os.Exit(m.Run())
+}
+
+type options struct {
+ hold time.Duration
+ latency time.Duration
+ sweeper bool
+ sweepInterval time.Duration
+ idempotencyTTL time.Duration
+}
+
+type option func(*options)
+
+func withHold(d time.Duration) option { return func(o *options) { o.hold = d } }
+func withLatency(d time.Duration) option { return func(o *options) { o.latency = d } }
+func withIdempotencyTTL(d time.Duration) option { return func(o *options) { o.idempotencyTTL = d } }
+func withSweeper(interval time.Duration) option {
+ return func(o *options) { o.sweeper = true; o.sweepInterval = interval }
+}
+
+type app struct {
+ t *testing.T
+ srv *httptest.Server
+ db *gorm.DB
+ provider provider.AppProvider
+ client *http.Client
+ mu sync.Mutex
+ ticketTypes []uuid.UUID
+}
+
+// newApp starts the API with its own configuration. After the test it checks
+// the inventory invariant (BR-10) for every ticket type the test created.
+func newApp(t *testing.T, opts ...option) *app {
+ t.Helper()
+ dsn := os.Getenv("TEST_DATABASE_URL")
+ if dsn == "" {
+ t.Skip("TEST_DATABASE_URL not set")
+ }
+ o := options{hold: 10 * time.Minute, sweepInterval: 5 * time.Second, idempotencyTTL: 24 * time.Hour}
+ for _, fn := range opts {
+ fn(&o)
+ }
+
+ dbConfig := config.NewDatabaseConfigFromDSN(dsn, 100)
+ bookingConfig := config.NewBookingConfig(o.hold, o.sweepInterval, o.sweeper, 2*time.Second, o.latency, o.idempotencyTTL)
+ p := provider.NewAppProviderWith(provider.NewConfigProviderWith(config.NewEnvConfig(), dbConfig, bookingConfig))
+ srv := httptest.NewServer(router.SetupRouter(p))
+
+ a := &app{
+ t: t,
+ srv: srv,
+ db: dbConfig.GetInstance(),
+ provider: p,
+ client: &http.Client{
+ Timeout: 10 * time.Second,
+ Transport: &http.Transport{MaxIdleConns: 400, MaxIdleConnsPerHost: 400},
+ },
+ }
+
+ ctx, cancel := context.WithCancel(context.Background())
+ if o.sweeper {
+ p.ProvideServices().ProvideExpiryService().Start(ctx, o.sweepInterval)
+ }
+
+ t.Cleanup(func() {
+ cancel()
+ srv.Close()
+ if sqlDB, err := a.db.DB(); err == nil {
+ sqlDB.Close()
+ }
+ })
+ t.Cleanup(a.checkInvariant)
+ return a
+}
+
+func (a *app) checkInvariant() {
+ a.t.Helper()
+ for _, id := range a.ticketTypes {
+ var row struct {
+ Capacity int
+ Available int
+ Held int
+ }
+ err := a.db.Raw(`
+ SELECT t.capacity, t.available, COALESCE(SUM(b.quantity) FILTER (
+ WHERE b.status IN ('PENDING_PAYMENT', 'CONFIRMED')), 0) AS held
+ FROM ticket_types t LEFT JOIN bookings b ON b.ticket_type_id = t.id
+ WHERE t.id = ? GROUP BY t.id`, id).Scan(&row).Error
+ if err != nil {
+ a.t.Errorf("invariant query: %v", err)
+ continue
+ }
+ if row.Capacity != row.Available+row.Held || row.Available < 0 {
+ a.t.Errorf("BR-10 violated for ticket type %s: capacity=%d available=%d held=%d",
+ id, row.Capacity, row.Available, row.Held)
+ }
+ }
+}
+
+// ---------- fixtures ----------
+
+func (a *app) user() uuid.UUID {
+ a.t.Helper()
+ u := entity.User{Id: uuid.New(), Name: "it-user"}
+ if err := a.db.Create(&u).Error; err != nil {
+ a.t.Fatalf("create user: %v", err)
+ }
+ return u.Id
+}
+
+func (a *app) users(n int) []uuid.UUID {
+ a.t.Helper()
+ list := make([]entity.User, n)
+ ids := make([]uuid.UUID, n)
+ for i := range list {
+ ids[i] = uuid.New()
+ list[i] = entity.User{Id: ids[i], Name: "it-user"}
+ }
+ if err := a.db.CreateInBatches(&list, 500).Error; err != nil {
+ a.t.Fatalf("create users: %v", err)
+ }
+ return ids
+}
+
+// event creates an event starting after startsIn, with one ticket type per
+// capacity, priced at 150,000 IDR.
+func (a *app) event(startsIn time.Duration, capacities ...int) (uuid.UUID, []uuid.UUID) {
+ a.t.Helper()
+ ev := entity.Event{Name: "it-" + a.t.Name(), StartsAt: time.Now().Add(startsIn)}
+ for i, c := range capacities {
+ ev.TicketTypes = append(ev.TicketTypes, entity.TicketType{
+ Name: "Tier " + string(rune('A'+i)), Price: 150000, Capacity: c, Available: c,
+ })
+ }
+ if err := a.db.Create(&ev).Error; err != nil {
+ a.t.Fatalf("create event: %v", err)
+ }
+ ids := make([]uuid.UUID, len(ev.TicketTypes))
+ for i, tt := range ev.TicketTypes {
+ ids[i] = tt.Id
+ }
+ a.mu.Lock()
+ a.ticketTypes = append(a.ticketTypes, ids...)
+ a.mu.Unlock()
+ return ev.Id, ids
+}
+
+// ticketType is the shared setup: one ticket type R with the given capacity on
+// an event 7 days away.
+func (a *app) ticketType(capacity int) uuid.UUID {
+ _, ids := a.event(7*24*time.Hour, capacity)
+ return ids[0]
+}
+
+func (a *app) available(tt uuid.UUID) int {
+ a.t.Helper()
+ var n int
+ if err := a.db.Raw(`SELECT available FROM ticket_types WHERE id = ?`, tt).Scan(&n).Error; err != nil {
+ a.t.Fatalf("available: %v", err)
+ }
+ return n
+}
+
+func (a *app) status(booking uuid.UUID) string {
+ a.t.Helper()
+ var s string
+ if err := a.db.Raw(`SELECT status FROM bookings WHERE id = ?`, booking).Scan(&s).Error; err != nil {
+ a.t.Fatalf("status: %v", err)
+ }
+ return s
+}
+
+func (a *app) payments(booking uuid.UUID, status string) int {
+ a.t.Helper()
+ var n int
+ if err := a.db.Raw(`SELECT count(*) FROM payments WHERE booking_id = ? AND status = ?`, booking, status).Scan(&n).Error; err != nil {
+ a.t.Fatalf("payments: %v", err)
+ }
+ return n
+}
+
+func (a *app) bookingsFor(tt uuid.UUID) int {
+ a.t.Helper()
+ var n int
+ if err := a.db.Raw(`SELECT count(*) FROM bookings WHERE ticket_type_id = ?`, tt).Scan(&n).Error; err != nil {
+ a.t.Fatalf("bookings: %v", err)
+ }
+ return n
+}
+
+func (a *app) exec(sql string, args ...any) {
+ a.t.Helper()
+ if err := a.db.Exec(sql, args...).Error; err != nil {
+ a.t.Fatalf("exec: %v", err)
+ }
+}
+
+func (a *app) sweep() {
+ a.t.Helper()
+ if _, err := a.provider.ProvideServices().ProvideExpiryService().SweepOnce(context.Background()); err != nil {
+ a.t.Fatalf("sweep: %v", err)
+ }
+}
+
+// ---------- HTTP ----------
+
+type response struct {
+ Code int
+ Header http.Header
+ Status string `json:"status"`
+ ErrCode string `json:"code"`
+ Data json.RawMessage `json:"data"`
+ Errors map[string]any `json:"errors"`
+ RawBody []byte
+ Duration time.Duration
+}
+
+type booking struct {
+ Id uuid.UUID `json:"id"`
+ Quantity int `json:"quantity"`
+ UnitPrice int64 `json:"unit_price"`
+ TotalAmount int64 `json:"total_amount"`
+ Status string `json:"status"`
+ ExpiresAt time.Time `json:"expires_at"`
+ CreatedAt time.Time `json:"created_at"`
+}
+
+func (r response) booking(t *testing.T) booking {
+ t.Helper()
+ var b booking
+ if err := json.Unmarshal(r.Data, &b); err != nil {
+ t.Fatalf("decode booking: %v (body %s)", err, r.RawBody)
+ }
+ return b
+}
+
+// request sends a request; user and key are omitted when zero/empty.
+func (a *app) request(method, path string, user uuid.UUID, key string, body any) response {
+ a.t.Helper()
+ var reader io.Reader
+ if body != nil {
+ switch b := body.(type) {
+ case string:
+ reader = bytes.NewBufferString(b)
+ default:
+ raw, _ := json.Marshal(b)
+ reader = bytes.NewBuffer(raw)
+ }
+ }
+ req, _ := http.NewRequest(method, a.srv.URL+path, reader)
+ req.Header.Set("Content-Type", "application/json")
+ if user != uuid.Nil {
+ req.Header.Set("X-User-Id", user.String())
+ }
+ if key != "" {
+ req.Header.Set("Idempotency-Key", key)
+ }
+ start := time.Now()
+ res, err := a.client.Do(req)
+ if err != nil {
+ a.t.Errorf("%s %s: %v", method, path, err)
+ return response{}
+ }
+ defer res.Body.Close()
+ raw, _ := io.ReadAll(res.Body)
+ out := response{Code: res.StatusCode, Header: res.Header, RawBody: raw, Duration: time.Since(start)}
+ _ = json.Unmarshal(raw, &out)
+ return out
+}
+
+func key() string { return uuid.NewString() }
+
+func (a *app) createBooking(user, tt uuid.UUID, quantity int, idemKey string) response {
+ return a.request("POST", "/v1/bookings", user, idemKey, map[string]any{"ticket_type_id": tt, "quantity": quantity})
+}
+
+func (a *app) pay(user, b uuid.UUID, token, idemKey string) response {
+ return a.request("POST", "/v1/bookings/"+b.String()+"/pay", user, idemKey, map[string]any{"payment_token": token})
+}
+
+func (a *app) cancel(user, b uuid.UUID) response {
+ return a.request("POST", "/v1/bookings/"+b.String()+"/cancel", user, "", nil)
+}
+
+// book creates a booking and fails the test unless it is 201.
+func (a *app) book(user, tt uuid.UUID, quantity int) booking {
+ a.t.Helper()
+ res := a.createBooking(user, tt, quantity, key())
+ expectCode(a.t, res, 201, "")
+ return res.booking(a.t)
+}
+
+func expectCode(t *testing.T, res response, httpCode int, errCode string) {
+ t.Helper()
+ if res.Code != httpCode || res.ErrCode != errCode {
+ t.Fatalf("want %d %q, got %d %q: %s", httpCode, errCode, res.Code, res.ErrCode, res.RawBody)
+ }
+}
+
+func expectEqual[T comparable](t *testing.T, what string, want, got T) {
+ t.Helper()
+ if want != got {
+ t.Fatalf("%s: want %v, got %v", what, want, got)
+ }
+}
+
+// parallel runs n calls at once, released together, and returns their results.
+func parallel(n int, fn func(i int) response) []response {
+ results := make([]response, n)
+ start := make(chan struct{})
+ var wg sync.WaitGroup
+ for i := 0; i < n; i++ {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ <-start
+ results[i] = fn(i)
+ }(i)
+ }
+ close(start)
+ wg.Wait()
+ return results
+}
+
+func countCodes(results []response) map[string]int {
+ counts := map[string]int{}
+ for _, r := range results {
+ k := http.StatusText(r.Code)
+ if r.ErrCode != "" {
+ k = r.ErrCode
+ }
+ counts[k]++
+ }
+ return counts
+}
diff --git a/tests/integration/idempotency_test.go b/tests/integration/idempotency_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..e2d04e2e82703d28bc197d86eaf46b8188b82b32
--- /dev/null
+++ b/tests/integration/idempotency_test.go
@@ -0,0 +1,87 @@
+package integration
+
+import (
+ "bytes"
+ "testing"
+ "time"
+)
+
+func TestIdempotentCreateReplays(t *testing.T) { // IT-ID-01
+ a := newApp(t)
+ tt, u, k := a.ticketType(100), a.user(), key()
+
+ first := a.createBooking(u, tt, 2, k)
+ second := a.createBooking(u, tt, 2, k)
+ expectCode(t, first, 201, "")
+ expectCode(t, second, 201, "")
+ if !bytes.Equal(first.Data, second.Data) {
+ t.Fatalf("replayed body differs:\n%s\n%s", first.Data, second.Data)
+ }
+ expectEqual(t, "first replayed header", "", first.Header.Get("Idempotent-Replayed"))
+ expectEqual(t, "second replayed header", "true", second.Header.Get("Idempotent-Replayed"))
+ expectEqual(t, "bookings", 1, a.bookingsFor(tt))
+ expectEqual(t, "available", 98, a.available(tt))
+}
+
+func TestIdempotencyKeyReusedWithDifferentBody(t *testing.T) { // IT-ID-02
+ a := newApp(t)
+ tt, u, k := a.ticketType(100), a.user(), key()
+
+ expectCode(t, a.createBooking(u, tt, 2, k), 201, "")
+ expectCode(t, a.createBooking(u, tt, 3, k), 422, "IDEMPOTENCY_KEY_REUSED")
+ expectEqual(t, "available", 98, a.available(tt))
+}
+
+func TestIdempotentPayReplays(t *testing.T) { // IT-ID-03
+ a := newApp(t)
+ tt, u, k := a.ticketType(100), a.user(), key()
+ b := a.book(u, tt, 2)
+
+ first := a.pay(u, b.Id, "tok_success", k)
+ second := a.pay(u, b.Id, "tok_success", k)
+ expectCode(t, first, 200, "")
+ expectCode(t, second, 200, "")
+ if !bytes.Equal(first.Data, second.Data) {
+ t.Fatalf("replayed body differs:\n%s\n%s", first.Data, second.Data)
+ }
+ expectEqual(t, "replayed header", "true", second.Header.Get("Idempotent-Replayed"))
+ expectEqual(t, "succeeded payments", 1, a.payments(b.Id, "SUCCEEDED"))
+}
+
+func TestIdempotencyKeyRequired(t *testing.T) { // IT-ID-04
+ a := newApp(t)
+ tt, u := a.ticketType(100), a.user()
+ b := a.book(u, tt, 1)
+
+ expectCode(t, a.createBooking(u, tt, 1, ""), 400, "IDEMPOTENCY_KEY_REQUIRED")
+ expectCode(t, a.pay(u, b.Id, "tok_success", ""), 400, "IDEMPOTENCY_KEY_REQUIRED")
+ expectEqual(t, "available", 99, a.available(tt))
+}
+
+func TestIdempotentConcurrentDuplicates(t *testing.T) { // IT-ID-05
+ a := newApp(t)
+ tt, u, k := a.ticketType(100), a.user(), key()
+
+ results := parallel(10, func(int) response { return a.createBooking(u, tt, 2, k) })
+ first := results[0].booking(t)
+ for _, r := range results {
+ expectCode(t, r, 201, "")
+ expectEqual(t, "booking id", first.Id, r.booking(t).Id)
+ }
+ expectEqual(t, "bookings", 1, a.bookingsFor(tt))
+ expectEqual(t, "available", 98, a.available(tt))
+}
+
+func TestIdempotencyKeyExpires(t *testing.T) {
+ a := newApp(t, withIdempotencyTTL(time.Second))
+ tt, u, k := a.ticketType(100), a.user(), key()
+
+ first := a.createBooking(u, tt, 1, k)
+ time.Sleep(1500 * time.Millisecond)
+ second := a.createBooking(u, tt, 1, k)
+ expectCode(t, second, 201, "")
+ if first.booking(t).Id == second.booking(t).Id {
+ t.Fatalf("expired key should create a new booking")
+ }
+ expectEqual(t, "replayed header", "", second.Header.Get("Idempotent-Replayed"))
+}
diff --git a/tests/integration/payment_test.go b/tests/integration/payment_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..08c732669fccb19792315bcba2fc504981deda53
--- /dev/null
+++ b/tests/integration/payment_test.go
@@ -0,0 +1,142 @@
+package integration
+
+import (
+ "testing"
+ "time"
+)
+
+func TestPaySuccessConfirms(t *testing.T) { // IT-PY-01
+ a := newApp(t)
+ tt, u := a.ticketType(100), a.user()
+ b := a.book(u, tt, 2)
+
+ res := a.pay(u, b.Id, "tok_success", key())
+ expectCode(t, res, 200, "")
+ expectEqual(t, "status", "CONFIRMED", res.booking(t).Status)
+ expectEqual(t, "succeeded payments", 1, a.payments(b.Id, "SUCCEEDED"))
+ expectEqual(t, "available", 98, a.available(tt))
+}
+
+func TestPayDeclineFailsAndReleases(t *testing.T) { // IT-PY-02
+ a := newApp(t)
+ tt, u := a.ticketType(100), a.user()
+ b := a.book(u, tt, 2)
+
+ res := a.pay(u, b.Id, "tok_decline", key())
+ expectCode(t, res, 402, "PAYMENT_DECLINED")
+ expectEqual(t, "errors.booking_status", any("PAYMENT_FAILED"), res.Errors["booking_status"])
+ expectEqual(t, "status", "PAYMENT_FAILED", a.status(b.Id))
+ expectEqual(t, "available", 100, a.available(tt))
+}
+
+func TestPayTimeoutFailsAndReleases(t *testing.T) { // IT-PY-03
+ a := newApp(t)
+ tt, u := a.ticketType(100), a.user()
+ b := a.book(u, tt, 2)
+
+ res := a.pay(u, b.Id, "tok_timeout", key())
+ expectCode(t, res, 402, "PAYMENT_TIMEOUT")
+ if res.Duration < 2*time.Second || res.Duration > 3*time.Second {
+ t.Fatalf("timeout should fire after the 2s client timeout, took %v", res.Duration)
+ }
+ expectEqual(t, "status", "PAYMENT_FAILED", a.status(b.Id))
+ expectEqual(t, "succeeded payments", 0, a.payments(b.Id, "SUCCEEDED"))
+ expectEqual(t, "available", 100, a.available(tt))
+}
+
+func TestPayAfterHoldExpires(t *testing.T) { // IT-PY-04
+ a := newApp(t, withHold(2*time.Second))
+ tt, u := a.ticketType(100), a.user()
+ b := a.book(u, tt, 2)
+
+ time.Sleep(3 * time.Second) // sweeper is off: the pay request must notice expiry itself
+ expectCode(t, a.pay(u, b.Id, "tok_success", key()), 409, "BOOKING_EXPIRED")
+ expectEqual(t, "status", "EXPIRED", a.status(b.Id))
+ expectEqual(t, "available", 100, a.available(tt))
+ expectEqual(t, "payment attempts", 0, a.payments(b.Id, "SUCCEEDED")+a.payments(b.Id, "DECLINED"))
+}
+
+func TestPayNonPendingBooking(t *testing.T) { // IT-PY-05
+ a := newApp(t)
+ tt, u := a.ticketType(100), a.user()
+
+ confirmed := a.book(u, tt, 1)
+ expectCode(t, a.pay(u, confirmed.Id, "tok_success", key()), 200, "")
+ res := a.pay(u, confirmed.Id, "tok_success", key())
+ expectCode(t, res, 409, "BOOKING_NOT_PAYABLE")
+ expectEqual(t, "errors.status", any("CONFIRMED"), res.Errors["status"])
+ expectEqual(t, "succeeded payments", 1, a.payments(confirmed.Id, "SUCCEEDED"))
+
+ failed := a.book(u, tt, 1)
+ expectCode(t, a.pay(u, failed.Id, "tok_decline", key()), 402, "PAYMENT_DECLINED")
+ expectCode(t, a.pay(u, failed.Id, "tok_success", key()), 409, "BOOKING_NOT_PAYABLE")
+ expectEqual(t, "succeeded payments", 0, a.payments(failed.Id, "SUCCEEDED"))
+}
+
+func TestCancelPending(t *testing.T) { // IT-CN-01
+ a := newApp(t)
+ tt, u := a.ticketType(100), a.user()
+ b := a.book(u, tt, 2)
+
+ res := a.cancel(u, b.Id)
+ expectCode(t, res, 200, "")
+ expectEqual(t, "status", "CANCELLED", res.booking(t).Status)
+ expectEqual(t, "available", 100, a.available(tt))
+}
+
+func TestCancelConfirmed(t *testing.T) { // IT-CN-02
+ a := newApp(t)
+ tt, u := a.ticketType(100), a.user()
+ b := a.book(u, tt, 2)
+ expectCode(t, a.pay(u, b.Id, "tok_success", key()), 200, "")
+
+ expectCode(t, a.cancel(u, b.Id), 200, "")
+ expectEqual(t, "status", "CANCELLED", a.status(b.Id))
+ expectEqual(t, "available", 100, a.available(tt))
+}
+
+func TestCancelNotAllowed(t *testing.T) { // IT-CN-03
+ a := newApp(t, withHold(time.Second))
+ ev, ids := a.event(7*24*time.Hour, 100)
+ tt, u := ids[0], a.user()
+
+ cancelled := a.book(u, tt, 1)
+ expectCode(t, a.cancel(u, cancelled.Id), 200, "")
+
+ failed := a.book(u, tt, 1)
+ expectCode(t, a.pay(u, failed.Id, "tok_decline", key()), 402, "PAYMENT_DECLINED")
+
+ expired := a.book(u, tt, 1)
+ time.Sleep(1500 * time.Millisecond)
+ a.sweep()
+ expectEqual(t, "expired status", "EXPIRED", a.status(expired.Id))
+
+ for _, b := range []booking{cancelled, failed, expired} {
+ expectCode(t, a.cancel(u, b.Id), 409, "BOOKING_NOT_CANCELLABLE")
+ }
+
+ // A confirmed booking whose event has already started.
+ started := a.book(u, tt, 1)
+ expectCode(t, a.pay(u, started.Id, "tok_success", key()), 200, "")
+ a.exec(`UPDATE events SET starts_at = now() - interval '1 second' WHERE id = ?`, ev)
+ expectCode(t, a.cancel(u, started.Id), 409, "BOOKING_NOT_CANCELLABLE")
+ expectEqual(t, "available", 99, a.available(tt))
+}
+
+func TestSweeperExpiresUnpaidBookings(t *testing.T) { // IT-EX-01
+ a := newApp(t, withHold(2*time.Second), withSweeper(5*time.Second))
+ tt, u := a.ticketType(100), a.user()
+ pending := a.book(u, tt, 2)
+ confirmed := a.book(u, tt, 1)
+ expectCode(t, a.pay(u, confirmed.Id, "tok_success", key()), 200, "")
+
+ deadline := pending.ExpiresAt.Add(15 * time.Second)
+ for a.status(pending.Id) != "EXPIRED" {
+ if time.Now().After(deadline) {
+ t.Fatalf("booking not expired within 15s of expires_at")
+ }
+ time.Sleep(500 * time.Millisecond)
+ }
+ expectEqual(t, "available", 99, a.available(tt))
+ expectEqual(t, "confirmed untouched", "CONFIRMED", a.status(confirmed.Id))
+}
diff --git a/utils/response_util.go b/utils/response_util.go
new file mode 100644
index 0000000000000000000000000000000000000000..340f4b9f01c7cf55ce7a2c390497f746c4b3909d
--- /dev/null
+++ b/utils/response_util.go
@@ -0,0 +1,64 @@
+package utils
+
+import (
+ "context"
+ "errors"
+ "log/slog"
+ "net/http"
+
+ "abdanhafidz.com/event-booking-api/models/dto"
+ http_error "abdanhafidz.com/event-booking-api/models/error"
+ "github.com/gin-gonic/gin"
+)
+
+func ResponseOK[Tdata any, TMetaData any](c *gin.Context, metaData TMetaData, data Tdata) {
+ respond(c, http.StatusOK, metaData, data)
+}
+
+func ResponseCreated[Tdata any, TMetaData any](c *gin.Context, metaData TMetaData, data Tdata) {
+ respond(c, http.StatusCreated, metaData, data)
+}
+
+func respond[Tdata any, TMetaData any](c *gin.Context, status int, metaData TMetaData, data Tdata) {
+ c.JSON(status, dto.SuccessResponse[Tdata]{
+ Status: "success",
+ Data: data,
+ Message: "Request processed successfully",
+ MetaData: metaData,
+ })
+}
+
+// ResponseFAILED maps an error to its HTTP status. Business errors carry their
+// own status and code; a request that ran out of time (usually waiting for a
+// database connection) is reported as 503; anything else is a 500 and is logged.
+func ResponseFAILED[TMetaData any](c *gin.Context, metaData TMetaData, err error) {
+ appErr, ok := http_error.AsAppError(err)
+ if !ok {
+ if errors.Is(err, context.DeadlineExceeded) || errors.Is(c.Request.Context().Err(), context.DeadlineExceeded) {
+ appErr = http_error.SERVICE_UNAVAILABLE
+ c.Header("Retry-After", "1")
+ } else {
+ slog.Error("unhandled error", "error", err.Error(), "path", c.FullPath(), "request_id", c.GetString("request_id"))
+ appErr = http_error.INTERNAL_SERVER_ERROR
+ }
+ }
+ c.JSON(appErr.Status, dto.ErrorResponse{
+ Status: "error",
+ Code: appErr.Code,
+ Errors: appErr.Details,
+ Message: appErr.Message,
+ MetaData: metaData,
+ })
+}
+
+func SendResponse[Tdata any, TMetaData any](c *gin.Context, metaData TMetaData, data Tdata, err error) {
+ if c.IsAborted() {
+ return
+ }
+ if err != nil {
+ ResponseFAILED(c, metaData, err)
+ } else {
+ ResponseOK(c, metaData, data)
+ }
+ c.Abort()
+}
diff --git a/utils/utils.go b/utils/utils.go
new file mode 100644
index 0000000000000000000000000000000000000000..d804c18e0dc4a68cd363f10e1c91eee5cf20f2ee
--- /dev/null
+++ b/utils/utils.go
@@ -0,0 +1,29 @@
+package utils
+
+import (
+ "os"
+ "strings"
+)
+
+func Ptr[T any](v T) *T {
+ return &v
+}
+
+func GetEnv(key string) string {
+ // 1. Normal env
+ if val := os.Getenv(key); val != "" {
+ return val
+ }
+
+ // 2. File-based secret
+ if file := os.Getenv(key + "_FILE"); file != "" {
+ data, err := os.ReadFile(file)
+ if err == nil {
+ return strings.TrimSpace(string(data))
+ } else {
+ panic(err)
+ }
+ }
+
+ return ""
+}