Compare commits

...
4 Commits
Author SHA1 Message Date
s.hajizadeh 3ad66aa4dc documentation 2026-10-20 10:52:26 +03:30
s.alikhani 9ee9081b11 ci(deployment): automate esg development deployment
Deploy latest remote main from a clean app checkout, build the development Compose app, wait for readiness after TypeORM migrations, and notify Rocket.Chat using short commit links.
2026-10-17 16:42:01 +03:30
s.hajizadeh 011068854b Merge pull request 'lock' (#21) from s.hajizadeh/esg:main into main
Reviewed-on: Shared/esg#21
2026-10-17 16:11:52 +03:30
s.hajizadeh c65846a501 Merge pull request 'package.json' (#20) from s.hajizadeh/esg:main into main
Reviewed-on: Shared/esg#20
2026-10-17 16:09:28 +03:30
5 changed files with 356 additions and 18 deletions
+179
View File
@@ -0,0 +1,179 @@
# Shared/esg — development deployment (Deploy-Develop)
# Manual tasks: see ci-cd/TASK.md
# Requires: repo marked Trusted in Woodpecker (host volume mounts)
when:
- event: push
branch: main
- event: manual
branch: main
skip_clone: true
# Per-run metadata stays outside the host checkout.
workspace:
base: /woodpecker
path: esg-deploy
variables:
- &host_workspace /data/infra-deploy/shared-esg/app
- &workspace_volume /data/infra-deploy/shared-esg/app:/workspace
- &glue_volume /data/infra-deploy/shared-esg:/data/infra-deploy/shared-esg
- &host_ssh /home/talieh/.ssh:/root/.ssh:ro
- &pipeline_env
WORKSPACE: *host_workspace
PROJECT_NAME: ESG
ENVIRONMENT: Development
APPLICATION_URL: https://esg.ittalie.ir
GIT_COMMIT_URL: https://git.ittalie.com/Shared/esg/commit/
GIT_BRANCH: main
COMPOSE_FILE: compose.dev.yaml
COMPOSE_PROJECT_NAME: shared-esg
SUCCESS_COLOR: "#36a64f"
FAILURE_COLOR: "#dc3545"
steps:
pull:
image: docker.arvancloud.ir/alpine/git:latest
environment:
<<: *pipeline_env
GIT_SSH_COMMAND: ssh -o BatchMode=yes -o StrictHostKeyChecking=yes
volumes:
- *workspace_volume
- *host_ssh
commands:
- git config --global --add safe.directory /workspace
- cd /workspace
- |
set -eu
date +%s > /woodpecker/esg-deploy/start
if [ "$(git branch --show-current)" != main ]; then
echo "App checkout must be on main" >&2
exit 1
fi
if [ -n "$(git status --porcelain --untracked-files=all)" ]; then
echo "App checkout has uncommitted changes; commit or move them before retrying" >&2
git status --short
exit 1
fi
git fetch origin main
if ! git merge-base --is-ancestor HEAD FETCH_HEAD; then
echo "Local main has commits outside remote main; reconcile manually" >&2
exit 1
fi
git merge --ff-only FETCH_HEAD
git rev-parse HEAD > /woodpecker/esg-deploy/commit
git log -3 --pretty=format:'• %s' > /woodpecker/esg-deploy/changes
echo "Building latest main at $(cat /woodpecker/esg-deploy/commit)"
deploy:
image: docker.arvancloud.ir/docker:24-cli
environment:
<<: *pipeline_env
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- *glue_volume
commands:
- cd /data/infra-deploy/shared-esg
- test -d app/.git && test -f app/Dockerfile && test -f .env
- docker compose -f compose.dev.yaml config --quiet
- docker compose -f compose.dev.yaml build app
- docker compose -f compose.dev.yaml up -d --no-deps --wait --wait-timeout 300 app
- touch /woodpecker/esg-deploy/deployed
notify-success:
image: docker.arvancloud.ir/alpine:3.20
environment:
<<: *pipeline_env
ROCKETCHAT_WEBHOOK:
from_secret: rocketchat_webhook
volumes:
- *workspace_volume
when:
- status: success
commands:
- apk add --no-cache curl jq git > /dev/null
- |
set -euo pipefail
# Reject a token/partial URL without exposing the secret in logs.
if ! printf '%s' "$ROCKETCHAT_WEBHOOK" | grep -Eq '^https?://[^/[:space:]]+/hooks/[^/[:space:]]+/[^/[:space:]]+$'; then
echo "rocketchat_webhook must contain the complete Rocket.Chat incoming webhook URL (https://host/hooks/id/token)" >&2
exit 1
fi
git config --global --add safe.directory /workspace
cd /workspace
COMMIT_HASH="$(cut -c1-7 /woodpecker/esg-deploy/commit)"
DEPLOY_START="$(cat /woodpecker/esg-deploy/start)"
DEPLOY_END="$(date +%s)"
DEPLOY_DURATION="$((DEPLOY_END - DEPLOY_START))"
CHANGES="$(cat /woodpecker/esg-deploy/changes)"
TITLE="✅ $PROJECT_NAME - $ENVIRONMENT ✅"
TEXT="🌐 **URL**: $APPLICATION_URL
🔖 **Commit Hash**: [$COMMIT_HASH]($GIT_COMMIT_URL$COMMIT_HASH)
📝 **Recent Changes**:
$CHANGES
⏱️ **Deployment Duration**: $${DEPLOY_DURATION}s"
payload="$(jq -n \
--arg title "$TITLE" \
--arg text "$TEXT" \
--arg color "$SUCCESS_COLOR" \
'{text: $title, attachments: [{text: $text, color: $color}]}')"
curl -fsS --connect-timeout 10 --max-time 30 -H "Content-Type: application/json" -d "$payload" "$ROCKETCHAT_WEBHOOK" >/dev/null
notify-failure:
image: docker.arvancloud.ir/alpine:3.20
environment:
<<: *pipeline_env
ROCKETCHAT_WEBHOOK:
from_secret: rocketchat_webhook
volumes:
- *workspace_volume
when:
- status: failure
commands:
- apk add --no-cache curl jq git > /dev/null
- |
set -euo pipefail
if [ -f /woodpecker/esg-deploy/deployed ]; then
echo "Deployment succeeded; see notify-success for notification delivery failure" >&2
exit 0
fi
# Reject a token/partial URL without exposing the secret in logs.
if ! printf '%s' "$ROCKETCHAT_WEBHOOK" | grep -Eq '^https?://[^/[:space:]]+/hooks/[^/[:space:]]+/[^/[:space:]]+$'; then
echo "rocketchat_webhook must contain the complete Rocket.Chat incoming webhook URL (https://host/hooks/id/token)" >&2
exit 1
fi
git config --global --add safe.directory /workspace
cd /workspace
COMMIT_HASH="$(cat /woodpecker/esg-deploy/commit 2>/dev/null || echo not-selected)"
TITLE="💥 $PROJECT_NAME - $ENVIRONMENT 💥"
TEXT="━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🌐 **Application URL**
$APPLICATION_URL
🔖 **Commit**
\`$COMMIT_HASH\`
⚠️ **Pipeline failed** — check Woodpecker for the failing step.
Commit above is the selected build revision, not a claim of successful deployment.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
payload="$(jq -n \
--arg title "$TITLE" \
--arg text "$TEXT" \
--arg color "$FAILURE_COLOR" \
'{text: $title, attachments: [{text: $text, color: $color}]}')"
curl -fsS --connect-timeout 10 --max-time 30 -H "Content-Type: application/json" -d "$payload" "$ROCKETCHAT_WEBHOOK" >/dev/null
+29 -15
View File
@@ -1,6 +1,6 @@
# Inquiry Gateway # Inquiry Gateway
Production-grade **NestJS + MongoDB** unified inquiry gateway for external service providers. Production-grade **NestJS + PostgreSQL** unified inquiry gateway for external service providers.
## 📚 Documentation ## 📚 Documentation
@@ -18,7 +18,7 @@ Client → POST /inquiries/person (unified)
→ ProviderFactory → Hamta | Moallem | TejaratNou → ProviderFactory → Hamta | Moallem | TejaratNou
→ LegacyApiProvider (shared base for identical APIs) → LegacyApiProvider (shared base for identical APIs)
→ BaseProvider (retry, timeout, logging, error normalization) → BaseProvider (retry, timeout, logging, error normalization)
→ MongoDB inquiry_logs → PostgreSQL inquiry logs
``` ```
### Provider vs Authentication Service ### Provider vs Authentication Service
@@ -50,9 +50,9 @@ src/
├── users/ # Unified users (ADMIN / USER / SUPER_ADMIN) ├── users/ # Unified users (ADMIN / USER / SUPER_ADMIN)
├── audit/ # Security audit logs ├── audit/ # Security audit logs
├── rate-limit/ # Global + per-user throttling ├── rate-limit/ # Global + per-user throttling
├── logging/ # MongoDB inquiry audit logs ├── logging/ # PostgreSQL inquiry audit logs
├── health/ # Liveness and MongoDB readiness probes ├── health/ # Liveness, readiness, and admin inquiry diagnostics
├── idempotency/ # Mongo-backed idempotency keys for inquiry retries ├── idempotency/ # Database-backed idempotency keys for inquiry retries
├── providers/ # BaseProvider, LegacyApiProvider, factory, orchestrator ├── providers/ # BaseProvider, LegacyApiProvider, factory, orchestrator
└── inquiry/ # Unified controllers & services └── inquiry/ # Unified controllers & services
``` ```
@@ -60,8 +60,8 @@ src/
## Quick start ## Quick start
```bash ```bash
cp .env.example .env cp .env.example .local.env
# Edit .env with your provider credentials (see Environment Configuration Guide) # Edit .local.env with your provider credentials (see Environment Configuration Guide)
npm install npm install
npm run cli:create-super-admin # interactive — creates SUPER_ADMIN npm run cli:create-super-admin # interactive — creates SUPER_ADMIN
npm run start:dev npm run start:dev
@@ -70,8 +70,9 @@ npm run start:dev
- API: `http://localhost:8085` - API: `http://localhost:8085`
- Operations dashboard: `http://localhost:8085/dashboard/` (SUPER_ADMIN only) - Operations dashboard: `http://localhost:8085/dashboard/` (SUPER_ADMIN only)
- Swagger: `http://localhost:8085/api/docs` - Swagger: `http://localhost:8085/api/docs`
- Liveness: `GET /health/live` (process-level probe; no MongoDB dependency) - Liveness: `GET /health/live` (process-level probe; no database dependency)
- Readiness: `GET /health/ready` (MongoDB, heap, and disk checks; returns `503` when a dependency is unavailable) - Readiness: `GET /health/ready` (PostgreSQL, heap, and disk checks; returns `503` when a dependency is unavailable)
- Admin inquiry diagnostics: `POST /health/inquiries/check` for one live provider check; `POST /health/inquiries/check/batch` starts 1–50 sequential checks and `GET /health/inquiries/check/batch/:jobId` returns progress and results. These endpoints require an ADMIN or SUPER_ADMIN JWT. Batch jobs run in memory, only one can run at a time, and completed reports expire after one hour.
The dashboard is served by the same process and uses the existing JWT login flow. It does not expose a second credential store: only a user whose profile role is `SUPER_ADMIN` can enter it, and the inquiry-log/metrics endpoints enforce that role server-side as well. It provides readiness details, recent audit logs, metrics, manual inquiry execution, and formatted JSON/XML output. Metrics separate valid provider no-match results from operational failures: success rate is calculated over evaluated requests (successes plus operational failures), while no-match results remain visible as their own count. Dashboard panels can be collapsed independently, with their open/closed state remembered in the browser. Typed inquiry routes render field-based forms with examples matching their Swagger DTO definitions; legal-person remains an advanced JSON payload because its controller accepts a provider-specific object. The dashboard is served by the same process and uses the existing JWT login flow. It does not expose a second credential store: only a user whose profile role is `SUPER_ADMIN` can enter it, and the inquiry-log/metrics endpoints enforce that role server-side as well. It provides readiness details, recent audit logs, metrics, manual inquiry execution, and formatted JSON/XML output. Metrics separate valid provider no-match results from operational failures: success rate is calculated over evaluated requests (successes plus operational failures), while no-match results remain visible as their own count. Dashboard panels can be collapsed independently, with their open/closed state remembered in the browser. Typed inquiry routes render field-based forms with examples matching their Swagger DTO definitions; legal-person remains an advanced JSON payload because its controller accepts a provider-specific object.
@@ -178,7 +179,7 @@ See [API Documentation](docs/API_DOCUMENTATION.md) for detailed request/response
## Token management ## Token management
- **Token refresh**: Every 20 minutes automatically - **Token refresh**: Every 20 minutes automatically
- **Distributed refresh lock**: MongoDB lease lock prevents concurrent replicas from refreshing the same token - **Distributed refresh lock**: PostgreSQL lease lock prevents concurrent replicas from refreshing the same token
- **Token expiration**: Daily at 23:59:59 Tehran time - **Token expiration**: Daily at 23:59:59 Tehran time
- **Retry logic**: Automatic retry on transient network failures and HTTP 404/408/499/5xx responses (legacy gateways can return 404 transiently); exhausted attempts retain the provider HTTP/SOAP code for diagnosis - **Retry logic**: Automatic retry on transient network failures and HTTP 404/408/499/5xx responses (legacy gateways can return 404 transiently); exhausted attempts retain the provider HTTP/SOAP code for diagnosis
- **Error handling**: Graceful fallback to alternative providers - **Error handling**: Graceful fallback to alternative providers
@@ -197,7 +198,7 @@ See [API Documentation](docs/API_DOCUMENTATION.md) for detailed request/response
2. Create request/response DTOs with `class-validator` in `src/inquiry/dto/` 2. Create request/response DTOs with `class-validator` in `src/inquiry/dto/`
3. Add `POST /inquiries/<type>` in `InquiryController` 3. Add `POST /inquiries/<type>` in `InquiryController`
4. Implement service method using `ProviderOrchestratorService` 4. Implement service method using `ProviderOrchestratorService`
5. Configure routing and credentials in `.env` 5. Configure routing and credentials in `.local.env`
## Security ## Security
@@ -206,7 +207,7 @@ See [API Documentation](docs/API_DOCUMENTATION.md) for detailed request/response
- **Inquiry access**: `allowedInquiries` + `InquiryAccessGuard` (e.g. `PERSON_INQUIRY`) - **Inquiry access**: `allowedInquiries` + `InquiryAccessGuard` (e.g. `PERSON_INQUIRY`)
- **Rate limiting**: global throttler + per-user `requestLimitPerMinute` / `requestLimitPerDay` - **Rate limiting**: global throttler + per-user `requestLimitPerMinute` / `requestLimitPerDay`
- **Audit**: `audit_logs` for login, user lifecycle events - **Audit**: `audit_logs` for login, user lifecycle events
- **Request logging**: All inquiries logged to MongoDB with masked sensitive data - **Request logging**: All inquiries logged to PostgreSQL with masked sensitive data
## Error handling ## Error handling
@@ -223,7 +224,7 @@ The system provides comprehensive error handling:
## Monitoring & observability ## Monitoring & observability
- **OpenTelemetry**: Distributed tracing support - **OpenTelemetry**: Distributed tracing support
- **Inquiry logs**: MongoDB collection with full request/response audit trail - **Inquiry logs**: PostgreSQL tables with full request/response audit trail
- **Audit logs**: Security events and user actions - **Audit logs**: Security events and user actions
- **Performance metrics**: Request duration, provider response times - **Performance metrics**: Request duration, provider response times
- **Error tracking**: Normalized error codes and messages - **Error tracking**: Normalized error codes and messages
@@ -252,7 +253,20 @@ npm run format
## Environment variables ## Environment variables
Key environment variables (see `.env.example` for complete list): All local settings live in `.local.env`, grouped into shared application settings,
routing, AMITIS authentication, and one section per client. Copy `.env.example`
to `.local.env` for a new checkout and fill in the credentials.
The app, telemetry, admin CLI, and migration CLI load `.local.env` automatically
from the project root. Shell/container variables take priority, followed by
`.local.env`, then `.env` as a legacy fallback. The split `env/*.env` files and
the differently named `.env.local` are inactive. Restart after editing settings.
Docker Compose continues to inject settings from the single `.production.env`
file; it no longer mounts the split `env/` directory. Keep real environment files
out of Git and Docker images.
Key environment variables:
```env ```env
# Application # Application
@@ -261,7 +275,7 @@ PORT=8085
API_PREFIX=api API_PREFIX=api
# Database # Database
MONGODB_URI=mongodb://localhost:27017/inquiry-gateway DATABASE_URL=postgresql://esg:esg@localhost:5432/inquiry_gateway
# JWT # JWT
JWT_SECRET=your-secret-key JWT_SECRET=your-secret-key
+53
View File
@@ -0,0 +1,53 @@
# ESG development CI
Workflow: `.woodpecker.yml` in `Shared/esg`.
Pushes to main and manual runs on main fetch and deploy latest remote main.
The selected revision is saved in the per-run workspace; notifications use
seven-character commit links and may differ from the triggering commit.
## Enable once
1. Update `/data/infra-deploy/shared-esg/app` to include this workflow.
The checkout must be on main and clean. Resolve local changes explicitly;
CI does not discard or stash them and refuses locally advanced/divergent main.
2. Enable `Shared/esg` in Woodpecker with `.woodpecker.yml` as the workflow path.
An administrator must enable **Trusted volumes** for host mounts/socket.
3. Use the Deploy-Develop agent with `WOODPECKER_MAX_WORKFLOWS=1` and repository
concurrency 1. With multiple agents, configure labels to select this host.
Let active deployments finish instead of automatically canceling on new pushes.
4. Configure `rocketchat_webhook` with the complete incoming webhook URL for the
existing deployment channel. No quotes, Markdown, or whitespace.
5. Ensure `/home/talieh/.ssh` can fetch Shared/esg and known_hosts trusts
git.ittalie.com. CI mounts SSH read-only with strict host checking.
6. Run a manual workflow on main and inspect pull, deploy and notification logs.
## Runtime
Glue: `/data/infra-deploy/shared-esg`, Compose project: `shared-esg`.
Required files: `compose.dev.yaml`, populated `.env`, and `app/Dockerfile`.
Secrets stay in the parent glue `.env`, outside the app checkout.
The Dockerfile's `production` target is used by the development Compose stack;
it is a build-stage name, not a customer production deployment.
Only `app` is built and deployed. TypeORM runs PostgreSQL migrations at startup.
Compose waits up to 300 seconds for `/health/ready`, which checks database
connectivity, heap usage and disk space. This is not a provider smoke test.
No separate Laravel scheduler or schedule:list step exists for this Nest app.
No database service, UI, production deployment or BNP publishing is included.
The full selected revision and timing live in the per-run CI workspace, not in
the host checkout. Notification delivery errors fail visibly and do not roll
back a successful deployment. Code rollback does not undo database migrations.
Opsctl stays independent; no shared lock prevents manual operations racing CI.
Glue updates remain a separate Infra/deploy operation.
## Troubleshooting
```sh
cd /data/infra-deploy/shared-esg
docker compose -f compose.dev.yaml ps app
docker compose -f compose.dev.yaml logs --tail=100 app
```
Check that DATABASE_URL is configured without exposing its value in logs.
Do not share full webhook URLs or credentials in issue reports.
+78
View File
@@ -9,6 +9,7 @@ Complete API reference for the ESG Inquiry Gateway with request/response example
- [Shahkar Inquiry](#shahkar-inquiry) - [Shahkar Inquiry](#shahkar-inquiry)
- [Postal Code Inquiry](#postal-code-inquiry) - [Postal Code Inquiry](#postal-code-inquiry)
- [Sheba Inquiry](#sheba-inquiry) - [Sheba Inquiry](#sheba-inquiry)
- [Health and Diagnostic Checks](#health-and-diagnostic-checks)
- [Error Responses](#error-responses) - [Error Responses](#error-responses)
## Base URL ## Base URL
@@ -32,6 +33,83 @@ X-API-Key: your-api-key-here
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
``` ```
## Health and Diagnostic Checks
### Liveness and readiness
`GET /health/live` reports whether the process is responding. `GET /health/ready`
checks PostgreSQL connectivity, heap usage, and disk usage. A failed readiness
check returns HTTP `503`; both probes are intended for deployment monitoring and
do not require a user JWT.
### Run one diagnostic inquiry
These administrative endpoints make a real request to the configured provider
using the supplied sample payload. They require a JWT for a user with the
`ADMIN` or `SUPER_ADMIN` role. Use the request body expected by the selected
inquiry type. The report includes provider, duration, tracking code, attempt
summary, and error details, but does not include the inquiry response data.
```http
POST /health/inquiries/check
Authorization: Bearer <accessToken>
Content-Type: application/json
```
```json
{
"inquiryType": "SHAHKAR",
"sampleData": {
"nationalCode": "4311402422",
"mobileNo": "09226187419"
}
}
```
The response reports `healthy: true` for a successful lookup or a valid no-match
result. Provider or operational errors report `healthy: false`.
### Run a batch of diagnostic inquiries
Submit between 1 and 50 checks. They run sequentially in the background. The
endpoint immediately returns a report with a `jobId`; poll that job to see
progress and the final per-check results.
```http
POST /health/inquiries/check/batch
Authorization: Bearer <accessToken>
Content-Type: application/json
```
```json
{
"checks": [
{
"caseId": "shahkar-row-1",
"inquiryType": "SHAHKAR",
"sampleData": {
"nationalCode": "4311402422",
"mobileNo": "09226187419"
}
}
]
}
```
The start request returns HTTP `202 Accepted`. Only one batch may be queued or
running at a time; another start request receives `409 Conflict`. Batch state is
held in process memory, and completed reports expire after one hour.
```http
GET /health/inquiries/check/batch/{jobId}
Authorization: Bearer <accessToken>
```
The report contains `status` (`QUEUED`, `RUNNING`, `COMPLETED`, or `FAILED`),
`totalChecks`, `completedChecks`, healthy/failed counts, a percentage, timestamps,
and per-check outcomes (`SUCCESS`, `NO_MATCH`, or `FAILURE`). A missing or expired
job returns `404 Not Found`.
## Person Inquiry ## Person Inquiry
Query person information using national code and birth date. Query person information using national code and birth date.
+17 -3
View File
@@ -2,6 +2,16 @@
This guide explains all environment variables used in the ESG Inquiry Gateway system. This guide explains all environment variables used in the ESG Inquiry Gateway system.
All local settings are in `.local.env`, organized into shared settings, routing,
AMITIS authentication, and sections for Asia, Hamta, Moallem, Parsian and Tejaratnou.
Copy `.env.example` to `.local.env` for a new installation.
The app and CLI commands load the file from the project root. Shell/container
variables override `.local.env`, which overrides `.env` as a legacy fallback.
Split files under `env/` and `.env.local` are no longer loaded. Restart after changes.
Docker Compose uses the single `.production.env` file and does not mount `env/`.
## Table of Contents ## Table of Contents
- [Application Settings](#application-settings) - [Application Settings](#application-settings)
- [Database Configuration](#database-configuration) - [Database Configuration](#database-configuration)
@@ -27,11 +37,15 @@ OTEL_NODE_RESOURCE_DETECTORS=env,host,os
## Database Configuration ## Database Configuration
### MongoDB ### PostgreSQL
```env ```env
MONGODB_URI=mongodb://localhost:27017/inquiry-gateway DATABASE_URL=postgresql://esg:esg@localhost:5432/inquiry_gateway
``` ```
The application, TypeORM data source, and readiness probe use PostgreSQL. Run
pending TypeORM migrations with `npm run migration:run`; use
`npm run migration:revert` to revert the most recent migration.
## Authentication & Security ## Authentication & Security
### API Authentication ### API Authentication
@@ -458,7 +472,7 @@ REAL_ESTATE_FALLBACK_ENABLED=false
## Security Best Practices ## Security Best Practices
1. **Never commit `.env` to git** - Use `.env.example` as template 1. **Never commit environment files containing secrets** - Use `.env.example` as template
2. **Rotate credentials regularly** - Update passwords every 90 days 2. **Rotate credentials regularly** - Update passwords every 90 days
3. **Use strong secrets** - Generate random strings for JWT secrets 3. **Use strong secrets** - Generate random strings for JWT secrets
4. **Limit API key distribution** - One key per client application 4. **Limit API key distribution** - One key per client application