Spaces:
Runtime error
Runtime error
Deploy 4b73e19
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .env.exampleAdded+21
- .gitattributesAdded+1
- .github/dependabot.ymlAdded+11
- .github/workflows/ci-2.ymlAdded+54
- .github/workflows/ci.ymlAdded+54
- .github/workflows/pipeline-2.ymlAdded+239
- .github/workflows/pipeline.ymlAdded+239
- .gitignoreAdded+8
- DockerfileAdded+44
- README.mdAdded+152
- VERSIONAdded+1
- cmd/compile_swagger.ps1Added+1
- cmd/do_inject_config.ps1Added+435
- cmd/do_inject_controllers.ps1Added+310
- cmd/do_inject_middleware.ps1Added+312
- cmd/do_inject_repository.ps1Added+327
- cmd/do_inject_services.ps1Added+383
- cmd/seed/fixtures.goAdded+53
- cmd/seed/main.goAdded+150
- cmd/seed/seed_test.goAdded+67
- config/booking_config.goAdded+41
- config/database_config.goAdded+65
- config/database_config_test.goAdded+20
- config/env_config.goAdded+91
- controllers/booking_controller.goAdded+130
- controllers/controller.goAdded+85
- controllers/event_controller.goAdded+41
- docker-compose.ymlAdded+27
- entrypoint.shAdded+11
- go.modAdded+66
- go.sumAdded+202
- main.goAdded+15
- middleware/request_middleware.goAdded+57
- middleware/user_middleware.goAdded+53
- models/dto/booking_dto.goAdded+47
- models/dto/event_dto.goAdded+44
- models/dto/http_response_dto.goAdded+18
- models/entity/constant.goAdded+24
- models/entity/entity.goAdded+105
- models/error/error.goAdded+85
- perf/jmeter/booking.jmxAdded+335
- perf/scenarios.jsonAdded+27
- perf/thresholds.jsonAdded+40
- provider/config_provider.goAdded+53
- provider/controller_provider.goAdded+28
- provider/middleware_provider.goAdded+28
- provider/provider.goAdded+86
- provider/repositories_provider.goAdded+65
- provider/services_provider.goAdded+62
- repositories/booking_repository.goAdded+112
123456789101112131415161718192021# ServerHOST_ADDRESS=0.0.0.0HOST_PORT=8080
# Database (Supabase: use the Session pooler, port 5432)DB_HOST=DB_PORT=5432DB_USER=DB_PASSWORD=DB_NAME=postgresDB_SSLMODE=requireDB_POOL_SIZE=20
# Booking rulesHOLD_TTL=10mSWEEP_INTERVAL=5sSWEEPER_ENABLED=truePAYMENT_TIMEOUT=2sMOCKPAY_LATENCY_MS=0IDEMPOTENCY_TTL=24hREQUEST_TIMEOUT=4s1*.sh text eol=lf1234567891011version: 2updates: - package-ecosystem: gomod directory: / schedule: { interval: weekly } - package-ecosystem: github-actions directory: / schedule: { interval: weekly } - package-ecosystem: docker directory: / schedule: { interval: weekly }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354name: 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 }} .123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354name: 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 }} .123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239# 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/null123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239# 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/null12345678*.env.env*.exe*.logvendor/out/perf/data/__pycache__/1234567891011121314151617181920212223242526272829303132333435363738394041424344# =====================# 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.shRUN 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"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152---title: Event Booking APIsdk: dockerapp_port: 7860pinned: 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.14b73e190ab6513c1f3f928a165cbc383438909941swag init -g swagger/swagger_info.go -o swagger/docs --parseDependency --parseInternal123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435#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.SupportsVirtualTerminalfunction 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 structuresclass 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}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310#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.SupportsVirtualTerminalfunction 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 structuresclass 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}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312#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.SupportsVirtualTerminalfunction 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 structuresclass 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}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327#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.SupportsVirtualTerminalfunction 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 structuresclass 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}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383#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.SupportsVirtualTerminalfunction 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 structuresclass 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}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253package 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 = 150000123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150// 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 neededpackage 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}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667package 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))}1234567891011121314151617181920212223242526272829303132333435363738394041package 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 }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465package 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}1234567891011121314151617181920package 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) } }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091package 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}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130package 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)}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485package 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") }}1234567891011121314151617181920212223242526272829303132333435363738394041package 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)}123456789101112131415161718192021222324252627# 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"]1234567891011#!/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/seedfi
exec /app/app123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566module 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202github.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=123456789101112131415package 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)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657package 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()}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253package 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()}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647package 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(), }}1234567891011121314151617181920212223242526272829303132333435363738394041424344package 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}123456789101112131415161718package 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"`}123456789101112131415161718192021222324package 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"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105package 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" }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485package 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}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335<?xml version="1.0" encoding="UTF-8"?><!-- Event Booking API load plan. Everything is driven by JMeter properties (see perf/scenarios.json); thread groups with 0 threads do not run. host, port, protocol target event_id, ticket_type_count, ticket_type_id_0..N seeded load event (cmd/seed event.properties) flash_ticket_type_id seeded flash-sale ticket type (PT-05) users_csv seeded user IDs, one per line browsers, buyers, flash_users thread counts ramp_s, duration_s, buyer_loops timing think_min_ms, think_range_ms uniform think time Local run: jmeter -n -t perf/jmeter/booking.jmx -q perf/data/event.properties -Jhost=localhost -Jport=8080 \ -Jusers_csv=perf/data/users.csv -Jbuyers=1 -Jbuyer_loops=50 -l out/results.jtl -e -o out/report--><jmeterTestPlan version="1.2" properties="5.0" jmeter="5.6.3"> <hashTree> <TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="Event Booking API"> <elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments"> <collectionProp name="Arguments.arguments"/> </elementProp> <boolProp name="TestPlan.functional_mode">false</boolProp> <boolProp name="TestPlan.serialize_threadgroups">false</boolProp> <boolProp name="TestPlan.tearDown_on_shutdown">true</boolProp> </TestPlan> <hashTree> <ConfigTestElement guiclass="HttpDefaultsGui" testclass="ConfigTestElement" testname="HTTP Request Defaults"> <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments"> <collectionProp name="Arguments.arguments"/> </elementProp> <stringProp name="HTTPSampler.domain">${__P(host,localhost)}</stringProp> <stringProp name="HTTPSampler.port">${__P(port,8080)}</stringProp> <stringProp name="HTTPSampler.protocol">${__P(protocol,http)}</stringProp> <stringProp name="HTTPSampler.contentEncoding">UTF-8</stringProp> <stringProp name="HTTPSampler.implementation">HttpClient4</stringProp> <stringProp name="HTTPSampler.connect_timeout">5000</stringProp> <stringProp name="HTTPSampler.response_timeout">5000</stringProp> </ConfigTestElement> <hashTree/> <HeaderManager guiclass="HeaderPanel" testclass="HeaderManager" testname="Common headers"> <collectionProp name="HeaderManager.headers"> <elementProp name="" elementType="Header"> <stringProp name="Header.name">Content-Type</stringProp> <stringProp name="Header.value">application/json</stringProp> </elementProp> <elementProp name="" elementType="Header"> <stringProp name="Header.name">X-User-Id</stringProp> <stringProp name="Header.value">${USER_ID}</stringProp> </elementProp> </collectionProp> </HeaderManager> <hashTree/> <CSVDataSet guiclass="TestBeanGUI" testclass="CSVDataSet" testname="Seeded users"> <stringProp name="filename">${__P(users_csv,users.csv)}</stringProp> <stringProp name="fileEncoding">UTF-8</stringProp> <stringProp name="variableNames">USER_ID</stringProp> <boolProp name="ignoreFirstLine">false</boolProp> <stringProp name="delimiter">,</stringProp> <boolProp name="quotedData">false</boolProp> <boolProp name="recycle">true</boolProp> <boolProp name="stopThread">false</boolProp> <stringProp name="shareMode">shareMode.all</stringProp> </CSVDataSet> <hashTree/>
<!-- ===================== Browsers: read the event repeatedly ===================== --> <ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Browsers"> <stringProp name="ThreadGroup.on_sample_error">continue</stringProp> <elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController"> <stringProp name="LoopController.loops">-1</stringProp> <boolProp name="LoopController.continue_forever">false</boolProp> </elementProp> <stringProp name="ThreadGroup.num_threads">${__P(browsers,0)}</stringProp> <stringProp name="ThreadGroup.ramp_time">${__P(ramp_s,1)}</stringProp> <boolProp name="ThreadGroup.scheduler">true</boolProp> <stringProp name="ThreadGroup.duration">${__P(duration_s,60)}</stringProp> <stringProp name="ThreadGroup.delay">0</stringProp> <boolProp name="ThreadGroup.same_user_on_next_iteration">true</boolProp> </ThreadGroup> <hashTree> <UniformRandomTimer guiclass="UniformRandomTimerGui" testclass="UniformRandomTimer" testname="Think time"> <stringProp name="ConstantTimer.delay">${__P(think_min_ms,500)}</stringProp> <stringProp name="RandomTimer.range">${__P(think_range_ms,1000)}</stringProp> </UniformRandomTimer> <hashTree/> <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="GET /events/{id}"> <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments"> <collectionProp name="Arguments.arguments"/> </elementProp> <stringProp name="HTTPSampler.path">/v1/events/${__P(event_id)}</stringProp> <stringProp name="HTTPSampler.method">GET</stringProp> <boolProp name="HTTPSampler.use_keepalive">true</boolProp> </HTTPSamplerProxy> <hashTree> <ResponseAssertion guiclass="AssertionGui" testclass="ResponseAssertion" testname="Expect 200"> <collectionProp name="Asserion.test_strings"> <stringProp name="49586">200</stringProp> </collectionProp> <stringProp name="Assertion.custom_message"></stringProp> <stringProp name="Assertion.test_field">Assertion.response_code</stringProp> <boolProp name="Assertion.assume_success">true</boolProp> <intProp name="Assertion.test_type">8</intProp> </ResponseAssertion> <hashTree/> </hashTree> </hashTree>
<!-- ===================== Buyers: read, book, pay, check ===================== --> <ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Buyers"> <stringProp name="ThreadGroup.on_sample_error">start_next_loop</stringProp> <elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController"> <stringProp name="LoopController.loops">${__P(buyer_loops,-1)}</stringProp> <boolProp name="LoopController.continue_forever">false</boolProp> </elementProp> <stringProp name="ThreadGroup.num_threads">${__P(buyers,0)}</stringProp> <stringProp name="ThreadGroup.ramp_time">${__P(ramp_s,1)}</stringProp> <boolProp name="ThreadGroup.scheduler">true</boolProp> <stringProp name="ThreadGroup.duration">${__P(duration_s,60)}</stringProp> <stringProp name="ThreadGroup.delay">0</stringProp> <boolProp name="ThreadGroup.same_user_on_next_iteration">false</boolProp> </ThreadGroup> <hashTree> <UniformRandomTimer guiclass="UniformRandomTimerGui" testclass="UniformRandomTimer" testname="Think time"> <stringProp name="ConstantTimer.delay">${__P(think_min_ms,500)}</stringProp> <stringProp name="RandomTimer.range">${__P(think_range_ms,1000)}</stringProp> </UniformRandomTimer> <hashTree/> <JSR223PreProcessor guiclass="TestBeanGUI" testclass="JSR223PreProcessor" testname="Pick ticket type, quantity and token"> <stringProp name="scriptLanguage">groovy</stringProp> <stringProp name="parameters"></stringProp> <stringProp name="filename"></stringProp> <stringProp name="cacheKey">true</stringProp> <stringProp name="script">// 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()))}</stringProp> </JSR223PreProcessor> <hashTree/> <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="GET /events/{id}"> <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments"> <collectionProp name="Arguments.arguments"/> </elementProp> <stringProp name="HTTPSampler.path">/v1/events/${__P(event_id)}</stringProp> <stringProp name="HTTPSampler.method">GET</stringProp> <boolProp name="HTTPSampler.use_keepalive">true</boolProp> </HTTPSamplerProxy> <hashTree> <ResponseAssertion guiclass="AssertionGui" testclass="ResponseAssertion" testname="Expect 200"> <collectionProp name="Asserion.test_strings"> <stringProp name="49586">200</stringProp> </collectionProp> <stringProp name="Assertion.custom_message"></stringProp> <stringProp name="Assertion.test_field">Assertion.response_code</stringProp> <boolProp name="Assertion.assume_success">true</boolProp> <intProp name="Assertion.test_type">8</intProp> </ResponseAssertion> <hashTree/> </hashTree> <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="POST /bookings"> <boolProp name="HTTPSampler.postBodyRaw">true</boolProp> <elementProp name="HTTPsampler.Arguments" elementType="Arguments"> <collectionProp name="Arguments.arguments"> <elementProp name="" elementType="HTTPArgument"> <boolProp name="HTTPArgument.always_encode">false</boolProp> <stringProp name="Argument.value">{"ticket_type_id":"${TT}","quantity":${QTY}}</stringProp> <stringProp name="Argument.metadata">=</stringProp> </elementProp> </collectionProp> </elementProp> <stringProp name="HTTPSampler.path">/v1/bookings</stringProp> <stringProp name="HTTPSampler.method">POST</stringProp> <boolProp name="HTTPSampler.use_keepalive">true</boolProp> </HTTPSamplerProxy> <hashTree> <HeaderManager guiclass="HeaderPanel" testclass="HeaderManager" testname="Idempotency key"> <collectionProp name="HeaderManager.headers"> <elementProp name="" elementType="Header"> <stringProp name="Header.name">Idempotency-Key</stringProp> <stringProp name="Header.value">${__UUID()}</stringProp> </elementProp> </collectionProp> </HeaderManager> <hashTree/> <ResponseAssertion guiclass="AssertionGui" testclass="ResponseAssertion" testname="Expect 201"> <collectionProp name="Asserion.test_strings"> <stringProp name="49587">201</stringProp> </collectionProp> <stringProp name="Assertion.custom_message"></stringProp> <stringProp name="Assertion.test_field">Assertion.response_code</stringProp> <boolProp name="Assertion.assume_success">true</boolProp> <intProp name="Assertion.test_type">8</intProp> </ResponseAssertion> <hashTree/> <JSONPostProcessor guiclass="JSONPostProcessorGui" testclass="JSONPostProcessor" testname="Booking ID"> <stringProp name="JSONPostProcessor.referenceNames">BOOKING_ID</stringProp> <stringProp name="JSONPostProcessor.jsonPathExprs">$.data.id</stringProp> <stringProp name="JSONPostProcessor.match_numbers">1</stringProp> <stringProp name="JSONPostProcessor.defaultValues">NONE</stringProp> </JSONPostProcessor> <hashTree/> </hashTree> <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="POST /bookings/{id}/pay"> <boolProp name="HTTPSampler.postBodyRaw">true</boolProp> <elementProp name="HTTPsampler.Arguments" elementType="Arguments"> <collectionProp name="Arguments.arguments"> <elementProp name="" elementType="HTTPArgument"> <boolProp name="HTTPArgument.always_encode">false</boolProp> <stringProp name="Argument.value">{"payment_token":"${TOKEN}"}</stringProp> <stringProp name="Argument.metadata">=</stringProp> </elementProp> </collectionProp> </elementProp> <stringProp name="HTTPSampler.path">/v1/bookings/${BOOKING_ID}/pay</stringProp> <stringProp name="HTTPSampler.method">POST</stringProp> <boolProp name="HTTPSampler.use_keepalive">true</boolProp> </HTTPSamplerProxy> <hashTree> <HeaderManager guiclass="HeaderPanel" testclass="HeaderManager" testname="Idempotency key"> <collectionProp name="HeaderManager.headers"> <elementProp name="" elementType="Header"> <stringProp name="Header.name">Idempotency-Key</stringProp> <stringProp name="Header.value">${__UUID()}</stringProp> </elementProp> </collectionProp> </HeaderManager> <hashTree/> <ResponseAssertion guiclass="AssertionGui" testclass="ResponseAssertion" testname="Expect 200 or 402 (declined)"> <collectionProp name="Asserion.test_strings"> <stringProp name="1">^(200|402)$</stringProp> </collectionProp> <stringProp name="Assertion.custom_message"></stringProp> <stringProp name="Assertion.test_field">Assertion.response_code</stringProp> <boolProp name="Assertion.assume_success">true</boolProp> <intProp name="Assertion.test_type">1</intProp> </ResponseAssertion> <hashTree/> </hashTree> <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="GET /bookings/{id}"> <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments"> <collectionProp name="Arguments.arguments"/> </elementProp> <stringProp name="HTTPSampler.path">/v1/bookings/${BOOKING_ID}</stringProp> <stringProp name="HTTPSampler.method">GET</stringProp> <boolProp name="HTTPSampler.use_keepalive">true</boolProp> </HTTPSamplerProxy> <hashTree> <ResponseAssertion guiclass="AssertionGui" testclass="ResponseAssertion" testname="Expect 200"> <collectionProp name="Asserion.test_strings"> <stringProp name="49586">200</stringProp> </collectionProp> <stringProp name="Assertion.custom_message"></stringProp> <stringProp name="Assertion.test_field">Assertion.response_code</stringProp> <boolProp name="Assertion.assume_success">true</boolProp> <intProp name="Assertion.test_type">8</intProp> </ResponseAssertion> <hashTree/> </hashTree> </hashTree>
<!-- ===================== Flash sale: everyone books 1 at the same moment ===================== --> <ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Flash sale"> <stringProp name="ThreadGroup.on_sample_error">continue</stringProp> <elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController"> <stringProp name="LoopController.loops">1</stringProp> <boolProp name="LoopController.continue_forever">false</boolProp> </elementProp> <stringProp name="ThreadGroup.num_threads">${__P(flash_users,0)}</stringProp> <stringProp name="ThreadGroup.ramp_time">${__P(flash_ramp_s,30)}</stringProp> <boolProp name="ThreadGroup.scheduler">false</boolProp> <stringProp name="ThreadGroup.duration"></stringProp> <stringProp name="ThreadGroup.delay"></stringProp> <boolProp name="ThreadGroup.same_user_on_next_iteration">true</boolProp> </ThreadGroup> <hashTree> <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="POST /bookings (flash)"> <boolProp name="HTTPSampler.postBodyRaw">true</boolProp> <elementProp name="HTTPsampler.Arguments" elementType="Arguments"> <collectionProp name="Arguments.arguments"> <elementProp name="" elementType="HTTPArgument"> <boolProp name="HTTPArgument.always_encode">false</boolProp> <stringProp name="Argument.value">{"ticket_type_id":"${__P(flash_ticket_type_id)}","quantity":1}</stringProp> <stringProp name="Argument.metadata">=</stringProp> </elementProp> </collectionProp> </elementProp> <stringProp name="HTTPSampler.path">/v1/bookings</stringProp> <stringProp name="HTTPSampler.method">POST</stringProp> <boolProp name="HTTPSampler.use_keepalive">true</boolProp> </HTTPSamplerProxy> <hashTree> <SyncTimer guiclass="TestBeanGUI" testclass="SyncTimer" testname="Release all requests together"> <stringProp name="groupSize">${__P(flash_users,0)}</stringProp> <longProp name="timeoutInMs">120000</longProp> </SyncTimer> <hashTree/> <HeaderManager guiclass="HeaderPanel" testclass="HeaderManager" testname="Idempotency key"> <collectionProp name="HeaderManager.headers"> <elementProp name="" elementType="Header"> <stringProp name="Header.name">Idempotency-Key</stringProp> <stringProp name="Header.value">${__UUID()}</stringProp> </elementProp> </collectionProp> </HeaderManager> <hashTree/> <ResponseAssertion guiclass="AssertionGui" testclass="ResponseAssertion" testname="Expect 201 or 409 INSUFFICIENT_TICKETS"> <collectionProp name="Asserion.test_strings"> <stringProp name="1">^(201|409)$</stringProp> </collectionProp> <stringProp name="Assertion.custom_message"></stringProp> <stringProp name="Assertion.test_field">Assertion.response_code</stringProp> <boolProp name="Assertion.assume_success">true</boolProp> <intProp name="Assertion.test_type">1</intProp> </ResponseAssertion> <hashTree/> <ResponseAssertion guiclass="AssertionGui" testclass="ResponseAssertion" testname="A 409 must be INSUFFICIENT_TICKETS"> <collectionProp name="Asserion.test_strings"> <stringProp name="1">"status":"success"|"code":"INSUFFICIENT_TICKETS"</stringProp> </collectionProp> <stringProp name="Assertion.custom_message"></stringProp> <stringProp name="Assertion.test_field">Assertion.response_data</stringProp> <boolProp name="Assertion.assume_success">false</boolProp> <intProp name="Assertion.test_type">2</intProp> </ResponseAssertion> <hashTree/> </hashTree> </hashTree> </hashTree> </hashTree></jmeterTestPlan>123456789101112131415161718192021222324252627{
"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 }
}
}12345678910111213141516171819202122232425262728293031323334353637383940{ "_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 } } }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253package 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}12345678910111213141516171819202122232425262728package 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}12345678910111213141516171819202122232425262728package 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}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586package 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}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465package 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}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162package 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}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112package 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}.env.exampleAdded+21
.gitattributesAdded+1
.github/dependabot.ymlAdded+11
.github/workflows/ci-2.ymlAdded+54
.github/workflows/ci.ymlAdded+54
.github/workflows/pipeline-2.ymlAdded+239
.github/workflows/pipeline.ymlAdded+239
.gitignoreAdded+8
DockerfileAdded+44
README.mdAdded+152
VERSIONAdded+1
cmd/compile_swagger.ps1Added+1
cmd/do_inject_config.ps1Added+435
cmd/do_inject_controllers.ps1Added+310
cmd/do_inject_middleware.ps1Added+312
cmd/do_inject_repository.ps1Added+327
cmd/do_inject_services.ps1Added+383
cmd/seed/fixtures.goAdded+53
cmd/seed/main.goAdded+150
cmd/seed/seed_test.goAdded+67
config/booking_config.goAdded+41
config/database_config.goAdded+65
config/database_config_test.goAdded+20
config/env_config.goAdded+91
controllers/booking_controller.goAdded+130
controllers/controller.goAdded+85
controllers/event_controller.goAdded+41
docker-compose.ymlAdded+27
entrypoint.shAdded+11
go.modAdded+66
go.sumAdded+202
main.goAdded+15
middleware/request_middleware.goAdded+57
middleware/user_middleware.goAdded+53
models/dto/booking_dto.goAdded+47
models/dto/event_dto.goAdded+44
models/dto/http_response_dto.goAdded+18
models/entity/constant.goAdded+24
models/entity/entity.goAdded+105
models/error/error.goAdded+85
perf/jmeter/booking.jmxAdded+335
perf/scenarios.jsonAdded+27
perf/thresholds.jsonAdded+40
provider/config_provider.goAdded+53
provider/controller_provider.goAdded+28
provider/middleware_provider.goAdded+28
provider/provider.goAdded+86
provider/repositories_provider.goAdded+65
provider/services_provider.goAdded+62
repositories/booking_repository.goAdded+112