forked from Shared/esg
Add health check and retry logic and circuit breaker
This commit is contained in:
+19
-4
@@ -18,15 +18,30 @@ JWT_ENABLED=true
|
||||
BCRYPT_SALT_ROUNDS=12
|
||||
|
||||
# Rate limiting
|
||||
# Set false only for local batch testing; keep enabled in deployed environments.
|
||||
RATE_LIMIT_ENABLED=true
|
||||
THROTTLE_TTL=60
|
||||
THROTTLE_LIMIT=100
|
||||
|
||||
# Route outbound provider API calls through an SSH tunnel (Termius dynamic/SOCKS forward)
|
||||
# Use socks5h so DNS resolves on the remote server. Leave empty for direct access.
|
||||
OUTBOUND_PROXY=socks5h://127.0.0.1:6565
|
||||
# Route outbound provider API calls through a local OpenSSH dynamic forward
|
||||
# (or another SOCKS5 client). Use socks5h so DNS resolves on the remote server.
|
||||
# Leave empty for direct access.
|
||||
OUTBOUND_PROXY=socks5h://127.0.0.1:4030
|
||||
|
||||
# Log every outbound provider HTTP call (request URL, status, response body preview)
|
||||
OUTBOUND_HTTP_DEBUG=true
|
||||
OUTBOUND_HTTP_DEBUG=false
|
||||
|
||||
# Reliability controls
|
||||
IDEMPOTENCY_TTL_MS=86400000
|
||||
PROVIDER_CIRCUIT_FAILURE_THRESHOLD=5
|
||||
PROVIDER_CIRCUIT_OPEN_MS=30000
|
||||
PROVIDER_BULKHEAD_LIMIT=16
|
||||
HEALTH_HEAP_MB=512
|
||||
HEALTH_DISK_THRESHOLD_PERCENT=0.9
|
||||
HEALTH_DISK_PATH=/
|
||||
|
||||
# Destructive local maintenance action; keep disabled outside local testing.
|
||||
INQUIRY_LOG_PURGE_ENABLED=false
|
||||
|
||||
# Provider routing (per inquiry type)
|
||||
PERSON_DEFAULT_PROVIDER=PARSIAN
|
||||
|
||||
@@ -16,6 +16,7 @@ RUN npm ci --omit=dev --ignore-scripts
|
||||
# ─── Stage 3: Production ──────────────────────────────────────────────────────
|
||||
FROM base AS production
|
||||
ENV NODE_ENV=production
|
||||
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
|
||||
COPY --from=builder --chown=appuser:appgroup /app/dist ./dist
|
||||
COPY --from=builder --chown=appuser:appgroup /app/node_modules ./node_modules
|
||||
COPY --from=builder --chown=appuser:appgroup /app/package.json ./package.json
|
||||
|
||||
@@ -6,6 +6,7 @@ Production-grade **NestJS + MongoDB** unified inquiry gateway for external servi
|
||||
|
||||
- **[Environment Configuration Guide](docs/ENVIRONMENT_CONFIGURATION.md)** - Complete guide for configuring providers, authentication, and inquiry routing
|
||||
- **[API Documentation](docs/API_DOCUMENTATION.md)** - Full API reference with examples, Swagger definitions, and best practices
|
||||
- **[Remote Provider Testing](docs/REMOTE_PROVIDER_TESTING.md)** - Test restricted provider integrations through an authorized server using OpenSSH
|
||||
|
||||
## Architecture
|
||||
|
||||
@@ -50,6 +51,8 @@ src/
|
||||
├── audit/ # Security audit logs
|
||||
├── rate-limit/ # Global + per-user throttling
|
||||
├── logging/ # MongoDB inquiry audit logs
|
||||
├── health/ # Liveness and MongoDB readiness probes
|
||||
├── idempotency/ # Mongo-backed idempotency keys for inquiry retries
|
||||
├── providers/ # BaseProvider, LegacyApiProvider, factory, orchestrator
|
||||
└── inquiry/ # Unified controllers & services
|
||||
```
|
||||
@@ -65,7 +68,20 @@ npm run start:dev
|
||||
```
|
||||
|
||||
- API: `http://localhost:8085`
|
||||
- Operations dashboard: `http://localhost:8085/dashboard/` (SUPER_ADMIN only)
|
||||
- Swagger: `http://localhost:8085/api/docs`
|
||||
- Liveness: `GET /health/live` (process-level probe; no MongoDB dependency)
|
||||
- Readiness: `GET /health/ready` (MongoDB, heap, and disk checks; returns `503` when a dependency is unavailable)
|
||||
|
||||
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.
|
||||
|
||||
Health thresholds can be adjusted per deployment with `HEALTH_HEAP_MB`, `HEALTH_DISK_THRESHOLD_PERCENT`, and `HEALTH_DISK_PATH` (see `.env.example`). The liveness and readiness response shapes follow Nest Terminus' standard `{ status, info, error, details }` format.
|
||||
|
||||
The dashboard includes a SUPER_ADMIN-only “clear inquiry logs” action. It is disabled unless `INQUIRY_LOG_PURGE_ENABLED=true`; enable it only for local maintenance/testing. Every purge is also recorded in the separate security audit collection.
|
||||
|
||||
Each expanded inquiry log also shows the outbound provider calls made underneath the gateway (including retries, fallbacks, and authentication calls). The endpoint, HTTP status, response preview, and a copyable **safe cURL** are shown per call. XML request and response bodies have local formatted/raw, XML-to-JSON, and scoped search views for SOAP troubleshooting. Credentials and authorization tokens are redacted intentionally; replace the `<REDACTED>` placeholders before running a copied command manually.
|
||||
|
||||
The **Batch input** panel accepts a JSON/TXT file or pasted JSON. It supports the `data` wrapper used by the current vehicle file, including fields such as `national_code`, `plaque_2`, `letter`, `plaque_3`, and `iran`. For Parsian third-party plate production traffic, `carByPlate` is the canonical one-factor route. `thirdPartyCar` and `policyByPlate` remain available for diagnostics/backward compatibility, but are not used by the sibling API integration. Every batch request uses the normal authenticated inquiry endpoint and creates its normal inquiry log. A delay can be configured to avoid overwhelming restricted provider services.
|
||||
|
||||
## Authentication & users
|
||||
|
||||
@@ -86,12 +102,15 @@ curl -X POST http://localhost:8085/auth/login \
|
||||
-d '{"username":"admin","password":"your-password"}'
|
||||
|
||||
# Person inquiry (JWT)
|
||||
curl -X POST http://localhost:8085/inquiries/person \
|
||||
curl -X POST http://localhost:8085/inquiry/person \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer <accessToken>" \
|
||||
-H "Idempotency-Key: person-lookup-001" \
|
||||
-d '{"nationalCode":"0012345678","birthDate":"1370-05-15"}'
|
||||
```
|
||||
|
||||
`Idempotency-Key` is optional. When supplied, it is scoped to the authenticated caller and route. Reusing it with the same body replays the stored response; reusing it with a different body returns `409`. A duplicate request that is still running also returns `409` with `Retry-After: 1`.
|
||||
|
||||
Response envelope (`BaseInquiryResponseDto`):
|
||||
|
||||
```json
|
||||
@@ -156,8 +175,9 @@ See [API Documentation](docs/API_DOCUMENTATION.md) for detailed request/response
|
||||
## Token management
|
||||
|
||||
- **Token refresh**: Every 20 minutes automatically
|
||||
- **Distributed refresh lock**: MongoDB lease lock prevents concurrent replicas from refreshing the same token
|
||||
- **Token expiration**: Daily at 23:59:59 Tehran time
|
||||
- **Retry logic**: Automatic retry on HTTP 5xx errors and network failures
|
||||
- **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
|
||||
|
||||
## Adding a new provider
|
||||
@@ -189,8 +209,11 @@ See [API Documentation](docs/API_DOCUMENTATION.md) for detailed request/response
|
||||
|
||||
The system provides comprehensive error handling:
|
||||
- Network errors: Automatic retry with exponential backoff
|
||||
- HTTP 5xx errors: Automatic retry (configurable attempts)
|
||||
- Provider failures: Automatic fallback to alternative providers
|
||||
- HTTP 404/408/499/5xx errors: Automatic retry (configurable attempts; 429 is intentionally not retried)
|
||||
- SOAP business no-match responses: Classified as `NO_MATCH`/`CAR_POLICY_NOT_FOUND`, not an operational provider outage; the upstream `<Key>` is preserved as `providerCode`
|
||||
- HTTP/SOAP provider failures: Automatic fallback to alternative providers when configured
|
||||
- Provider isolation: Per-provider circuit breaker and concurrency bulkhead
|
||||
- Request deduplication: Optional Mongo-backed idempotency for inquiry POSTs
|
||||
- Validation errors: Detailed error messages with field-level validation
|
||||
- Authentication errors: Automatic token refresh and retry
|
||||
|
||||
@@ -244,6 +267,9 @@ JWT_REFRESH_SECRET=your-refresh-secret
|
||||
JWT_REFRESH_EXPIRES_IN=7d
|
||||
|
||||
# Rate limiting
|
||||
# Set RATE_LIMIT_ENABLED=false only for local batch testing. This disables both
|
||||
# the global Nest throttler and per-user inquiry limits; it defaults to enabled.
|
||||
RATE_LIMIT_ENABLED=true
|
||||
THROTTLE_TTL=60
|
||||
THROTTLE_LIMIT=100
|
||||
|
||||
|
||||
@@ -8,6 +8,12 @@ services:
|
||||
- "127.0.0.1:3000:3000"
|
||||
env_file:
|
||||
- .production.env
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-qO-", "http://127.0.0.1:3000/health/ready"]
|
||||
interval: 15s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 20s
|
||||
depends_on:
|
||||
mongodb:
|
||||
condition: service_healthy
|
||||
|
||||
@@ -424,6 +424,8 @@ POST /api/inquiry/policyByChassis
|
||||
### Endpoint
|
||||
```
|
||||
POST /api/inquiry/policyByPlate
|
||||
|
||||
For Parsian third-party plate production traffic, use `POST /api/inquiry/carByPlate`. The `policyByPlate` route is retained for legacy/diagnostic callers and is not used by the sibling API integration.
|
||||
```
|
||||
|
||||
### Request Body
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
# Testing providers through an authorized server
|
||||
|
||||
The gateway already supports an outbound SOCKS5 proxy through `OUTBOUND_PROXY`.
|
||||
You can create that proxy locally with standard OpenSSH dynamic forwarding; no
|
||||
Termius installation or application code changes are required on the server.
|
||||
|
||||
## 1. Confirm SSH access
|
||||
|
||||
Use an SSH key through your SSH agent when possible. A password can also be
|
||||
entered interactively by `ssh`, but do not put it in `.env`, a shell command, or
|
||||
the repository.
|
||||
|
||||
```bash
|
||||
ssh your-user@authorized-server.example
|
||||
```
|
||||
|
||||
The authorized server must be allowed to reach the provider URLs configured in
|
||||
your environment. The server does not need a SOCKS daemon; the SSH daemon
|
||||
provides the dynamic forwarding endpoint.
|
||||
|
||||
## 2. Open the local SOCKS tunnel
|
||||
|
||||
From the project root, run this in a dedicated terminal:
|
||||
|
||||
```bash
|
||||
SSH_TUNNEL_HOST=authorized-server.example \
|
||||
SSH_TUNNEL_USER=your-user \
|
||||
SOCKS_PORT=4030 \
|
||||
npm run tunnel:provider
|
||||
```
|
||||
|
||||
Optional variables:
|
||||
|
||||
- `SSH_TUNNEL_PORT` — SSH port, default `22`.
|
||||
- `SSH_IDENTITY_FILE` — private key path when it is not already loaded in the SSH agent.
|
||||
- `SOCKS_BIND_HOST` — keep the default `127.0.0.1`; do not bind the proxy publicly.
|
||||
|
||||
The command is equivalent to:
|
||||
|
||||
```bash
|
||||
ssh -N -D 127.0.0.1:4030 your-user@authorized-server.example
|
||||
```
|
||||
|
||||
Keep the tunnel terminal open. `socks5h` is important because it makes DNS
|
||||
resolution happen through the authorized server rather than on the restricted
|
||||
local network.
|
||||
|
||||
## 3. Configure the local gateway
|
||||
|
||||
In the local `.env` used by the gateway:
|
||||
|
||||
```ini
|
||||
OUTBOUND_PROXY=socks5h://127.0.0.1:4030
|
||||
OUTBOUND_HTTP_DEBUG=false
|
||||
```
|
||||
|
||||
The application’s Axios clients will route provider calls through the tunnel.
|
||||
The gateway itself, MongoDB, and the client used to call the gateway remain
|
||||
local.
|
||||
|
||||
Start the application in a second terminal:
|
||||
|
||||
```bash
|
||||
npm run start:dev
|
||||
```
|
||||
|
||||
Before running a real inquiry, verify that the tunnel can resolve and reach a
|
||||
provider host. For example, if `curl` is available:
|
||||
|
||||
```bash
|
||||
curl --proxy socks5h://127.0.0.1:4030 \
|
||||
--connect-timeout 10 \
|
||||
https://provider-host.example/health
|
||||
```
|
||||
|
||||
Use a real provider URL that is safe to probe; some legacy SOAP endpoints do
|
||||
not expose a health route, in which case a DNS/TCP check is sufficient.
|
||||
|
||||
## 4. Run a smoke inquiry
|
||||
|
||||
The smoke suite calls the local gateway. Only the gateway’s outbound provider
|
||||
requests use the SOCKS tunnel:
|
||||
|
||||
```bash
|
||||
ESG_SMOKE_ENABLED=true \
|
||||
SMOKE_GATEWAY_BASE_URL=http://127.0.0.1:8085 \
|
||||
SMOKE_INQUIRY_PATH=/inquiry/person \
|
||||
SMOKE_ACCESS_TOKEN='your-local-access-token' \
|
||||
SMOKE_INQUIRY_PAYLOAD='{"nationalCode":"0012345678","birthDate":"1370-05-15"}' \
|
||||
npm run smoke
|
||||
```
|
||||
|
||||
If your local gateway uses another port or route prefix, change the smoke
|
||||
variables to match it.
|
||||
|
||||
## Alternative: run the gateway on the authorized server
|
||||
|
||||
If policy allows deployment there, running the gateway itself on the authorized
|
||||
server removes the SOCKS hop. You can still access its HTTP port locally with
|
||||
an ordinary SSH local forward:
|
||||
|
||||
```bash
|
||||
ssh -N -L 8085:127.0.0.1:8085 your-user@authorized-server.example
|
||||
```
|
||||
|
||||
This alternative requires MongoDB and the application environment to be set up
|
||||
on the server. The SOCKS approach is usually simpler for local development.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- `channel open failed`: SSH forwarding may be disabled by server policy; ask the server administrator to allow TCP forwarding.
|
||||
- Provider DNS fails locally but works with `curl --proxy socks5h://...`: ensure `OUTBOUND_PROXY` uses `socks5h`, not `socks5`.
|
||||
- The app ignores the tunnel: restart it after changing `.env`; outbound clients read the proxy setting during process startup.
|
||||
- Port already in use: choose another `SOCKS_PORT` and update `OUTBOUND_PROXY` to the same port.
|
||||
+5
-2
@@ -3,7 +3,10 @@
|
||||
"collection": "@nestjs/schematics",
|
||||
"sourceRoot": "src",
|
||||
"compilerOptions": {
|
||||
"deleteOutDir": false,
|
||||
"assets": [{ "include": "public/**/*", "outDir": "dist" }]
|
||||
"deleteOutDir": true,
|
||||
"assets": [
|
||||
{ "include": "public/**/*", "outDir": "dist" },
|
||||
{ "include": "database/seeds/**/*", "outDir": "dist" }
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+177
-33
@@ -17,6 +17,7 @@
|
||||
"@nestjs/passport": "^11.0.5",
|
||||
"@nestjs/platform-express": "^10.4.15",
|
||||
"@nestjs/swagger": "^8.1.0",
|
||||
"@nestjs/terminus": "^10.3.0",
|
||||
"@nestjs/throttler": "^6.3.0",
|
||||
"@opentelemetry/api": "^1.9.1",
|
||||
"@opentelemetry/api-logs": "^0.218.0",
|
||||
@@ -2335,6 +2336,76 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@nestjs/terminus": {
|
||||
"version": "10.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@nestjs/terminus/-/terminus-10.3.0.tgz",
|
||||
"integrity": "sha512-vOJGCwt1OgrFuuxWQwPoaHqy9m9CfIk2qMUX2mosZLK5dFVJSEjHXrklkh3/Fw9PiUnfzvYFfiAdJRzUaxx+5Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"boxen": "5.1.2",
|
||||
"check-disk-space": "3.4.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@grpc/grpc-js": "*",
|
||||
"@grpc/proto-loader": "*",
|
||||
"@mikro-orm/core": "*",
|
||||
"@mikro-orm/nestjs": "*",
|
||||
"@nestjs/axios": "^1.0.0 || ^2.0.0 || ^3.0.0",
|
||||
"@nestjs/common": "^9.0.0 || ^10.0.0",
|
||||
"@nestjs/core": "^9.0.0 || ^10.0.0",
|
||||
"@nestjs/microservices": "^9.0.0 || ^10.0.0",
|
||||
"@nestjs/mongoose": "^9.0.0 || ^10.0.0",
|
||||
"@nestjs/sequelize": "^9.0.0 || ^10.0.0",
|
||||
"@nestjs/typeorm": "^9.0.0 || ^10.0.0",
|
||||
"@prisma/client": "*",
|
||||
"mongoose": "*",
|
||||
"reflect-metadata": "0.1.x || 0.2.x",
|
||||
"rxjs": "7.x",
|
||||
"sequelize": "*",
|
||||
"typeorm": "*"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@grpc/grpc-js": {
|
||||
"optional": true
|
||||
},
|
||||
"@grpc/proto-loader": {
|
||||
"optional": true
|
||||
},
|
||||
"@mikro-orm/core": {
|
||||
"optional": true
|
||||
},
|
||||
"@mikro-orm/nestjs": {
|
||||
"optional": true
|
||||
},
|
||||
"@nestjs/axios": {
|
||||
"optional": true
|
||||
},
|
||||
"@nestjs/microservices": {
|
||||
"optional": true
|
||||
},
|
||||
"@nestjs/mongoose": {
|
||||
"optional": true
|
||||
},
|
||||
"@nestjs/sequelize": {
|
||||
"optional": true
|
||||
},
|
||||
"@nestjs/typeorm": {
|
||||
"optional": true
|
||||
},
|
||||
"@prisma/client": {
|
||||
"optional": true
|
||||
},
|
||||
"mongoose": {
|
||||
"optional": true
|
||||
},
|
||||
"sequelize": {
|
||||
"optional": true
|
||||
},
|
||||
"typeorm": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@nestjs/testing": {
|
||||
"version": "10.4.22",
|
||||
"resolved": "https://repo.hmirror.ir/artifactory/api/npm/mirror-npm/@nestjs/testing/-/testing-10.4.22.tgz",
|
||||
@@ -5015,6 +5086,15 @@
|
||||
"ajv": "^8.8.2"
|
||||
}
|
||||
},
|
||||
"node_modules/ansi-align": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/ansi-align/-/ansi-align-3.0.1.tgz",
|
||||
"integrity": "sha512-IOfwwBF5iczOjp/WeY4YxyjqAFMQoZufdQWDd19SEExbVLNXqvpzSJ/M7Za4/sCPmQ0+GRquoA7bGcINcxew6w==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"string-width": "^4.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/ansi-colors": {
|
||||
"version": "4.1.3",
|
||||
"resolved": "https://repo.hmirror.ir/artifactory/api/npm/mirror-npm/ansi-colors/-/ansi-colors-4.1.3.tgz",
|
||||
@@ -5406,6 +5486,69 @@
|
||||
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/boxen": {
|
||||
"version": "5.1.2",
|
||||
"resolved": "https://registry.npmjs.org/boxen/-/boxen-5.1.2.tgz",
|
||||
"integrity": "sha512-9gYgQKXx+1nP8mP7CzFyaUARhg7D3n1dF/FnErWmu9l6JvGpNUN278h0aSb+QjoiKSWG+iZ3uHrcqk0qrY9RQQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-align": "^3.0.0",
|
||||
"camelcase": "^6.2.0",
|
||||
"chalk": "^4.1.0",
|
||||
"cli-boxes": "^2.2.1",
|
||||
"string-width": "^4.2.2",
|
||||
"type-fest": "^0.20.2",
|
||||
"widest-line": "^3.1.0",
|
||||
"wrap-ansi": "^7.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/boxen/node_modules/camelcase": {
|
||||
"version": "6.3.0",
|
||||
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz",
|
||||
"integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/boxen/node_modules/type-fest": {
|
||||
"version": "0.20.2",
|
||||
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz",
|
||||
"integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==",
|
||||
"license": "(MIT OR CC0-1.0)",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/boxen/node_modules/wrap-ansi": {
|
||||
"version": "7.0.0",
|
||||
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
|
||||
"integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-styles": "^4.0.0",
|
||||
"string-width": "^4.1.0",
|
||||
"strip-ansi": "^6.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/brace-expansion": {
|
||||
"version": "5.0.6",
|
||||
"resolved": "https://repo.hmirror.ir/artifactory/api/npm/mirror-npm/brace-expansion/-/brace-expansion-5.0.6.tgz",
|
||||
@@ -5677,6 +5820,15 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/check-disk-space": {
|
||||
"version": "3.4.0",
|
||||
"resolved": "https://registry.npmjs.org/check-disk-space/-/check-disk-space-3.4.0.tgz",
|
||||
"integrity": "sha512-drVkSqfwA+TvuEhFipiR1OC9boEGZL5RrWvVsOthdcvQNXyCCuKkEiTOTXZ7qxSf/GLwq4GvzfrQD/Wz325hgw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
}
|
||||
},
|
||||
"node_modules/chokidar": {
|
||||
"version": "3.6.0",
|
||||
"resolved": "https://repo.hmirror.ir/artifactory/api/npm/mirror-npm/chokidar/-/chokidar-3.6.0.tgz",
|
||||
@@ -5752,6 +5904,18 @@
|
||||
"validator": "^13.15.22"
|
||||
}
|
||||
},
|
||||
"node_modules/cli-boxes": {
|
||||
"version": "2.2.1",
|
||||
"resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-2.2.1.tgz",
|
||||
"integrity": "sha512-y4coMcylgSCdVinjiDBuR8PCC2bLjyGTwEmPb9NHR/QaNU6EUOXcTY/s6VjGMD6ENSEaeQYHCY0GNGS5jfMwPw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/cli-cursor": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://repo.hmirror.ir/artifactory/api/npm/mirror-npm/cli-cursor/-/cli-cursor-3.1.0.tgz",
|
||||
@@ -7429,38 +7593,6 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/gaxios": {
|
||||
"version": "5.1.3",
|
||||
"resolved": "https://repo.hmirror.ir/artifactory/api/npm/mirror-npm/gaxios/-/gaxios-5.1.3.tgz",
|
||||
"integrity": "sha512-95hVgBRgEIRQQQHIbnxBXeHbW4TqFk4ZDJW7wmVtvYar72FdhRIo1UGOLS2eRAKCPEdPBWu+M7+A33D9CdX9rA==",
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"extend": "^3.0.2",
|
||||
"https-proxy-agent": "^5.0.0",
|
||||
"is-stream": "^2.0.0",
|
||||
"node-fetch": "^2.6.9"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/gcp-metadata": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://repo.hmirror.ir/artifactory/api/npm/mirror-npm/gcp-metadata/-/gcp-metadata-5.3.0.tgz",
|
||||
"integrity": "sha512-FNTkdNEnBdlqF2oatizolQqNANMrcqJt6AAYt99B3y1aLLC8Hc5IOBb+ZnnzllodEEf6xMBp6wRcBbc16fa65w==",
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"gaxios": "^5.0.0",
|
||||
"json-bigint": "^1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/gensync": {
|
||||
"version": "1.0.0-beta.2",
|
||||
"resolved": "https://repo.hmirror.ir/artifactory/api/npm/mirror-npm/gensync/-/gensync-1.0.0-beta.2.tgz",
|
||||
@@ -8090,7 +8222,7 @@
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://repo.hmirror.ir/artifactory/api/npm/mirror-npm/is-stream/-/is-stream-2.0.1.tgz",
|
||||
"integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==",
|
||||
"devOptional": true,
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
@@ -12386,6 +12518,18 @@
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/widest-line": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/widest-line/-/widest-line-3.1.0.tgz",
|
||||
"integrity": "sha512-NsmoXalsWVDMGupxZ5R08ka9flZjjiLvHVAWYOKtiKM8ujtZWr9cRffak+uSE48+Ob8ObalXpwyeUiyDD6QFgg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"string-width": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/winston-transport": {
|
||||
"version": "4.9.0",
|
||||
"resolved": "https://repo.hmirror.ir/artifactory/api/npm/mirror-npm/winston-transport/-/winston-transport-4.9.0.tgz",
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
"test:cov": "jest --selectProjects unit integration admin --coverage",
|
||||
"smoke": "ESG_SMOKE_ENABLED=true jest --selectProjects smoke --runInBand",
|
||||
"smoke:client": "npm run smoke --",
|
||||
"tunnel:provider": "bash scripts/ssh-socks-tunnel.sh",
|
||||
"cli:create-super-admin": "ts-node -r tsconfig-paths/register src/cli/create-super-admin.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -29,6 +30,7 @@
|
||||
"@nestjs/passport": "^11.0.5",
|
||||
"@nestjs/platform-express": "^10.4.15",
|
||||
"@nestjs/swagger": "^8.1.0",
|
||||
"@nestjs/terminus": "^10.3.0",
|
||||
"@nestjs/throttler": "^6.3.0",
|
||||
"@opentelemetry/api": "^1.9.1",
|
||||
"@opentelemetry/api-logs": "^0.218.0",
|
||||
|
||||
Executable
+37
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
: "${SSH_TUNNEL_HOST:?Set SSH_TUNNEL_HOST to the authorized server hostname or IP}"
|
||||
|
||||
ssh_user="${SSH_TUNNEL_USER:-${USER:-}}"
|
||||
if [[ -z "$ssh_user" ]]; then
|
||||
echo "SSH_TUNNEL_USER is required when the local username cannot be detected." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
ssh_port="${SSH_TUNNEL_PORT:-22}"
|
||||
socks_host="${SOCKS_BIND_HOST:-127.0.0.1}"
|
||||
socks_port="${SOCKS_PORT:-4030}"
|
||||
ssh_target="${ssh_user}@${SSH_TUNNEL_HOST}"
|
||||
|
||||
echo "Opening SOCKS5 tunnel on ${socks_host}:${socks_port} via ${ssh_target}:${ssh_port}"
|
||||
echo "Keep this terminal open while running the gateway. Press Ctrl-C to close the tunnel."
|
||||
|
||||
ssh_args=(
|
||||
-N
|
||||
-D "${socks_host}:${socks_port}"
|
||||
-p "$ssh_port"
|
||||
-o ExitOnForwardFailure=yes
|
||||
-o ServerAliveInterval=30
|
||||
-o ServerAliveCountMax=3
|
||||
)
|
||||
|
||||
if [[ -n "${SSH_IDENTITY_FILE:-}" ]]; then
|
||||
ssh_args+=( -i "$SSH_IDENTITY_FILE" )
|
||||
fi
|
||||
|
||||
# Password authentication, when enabled by the server, is handled by ssh itself
|
||||
# and is intentionally not accepted as an environment variable or command-line
|
||||
# argument.
|
||||
exec ssh "${ssh_args[@]}" "$ssh_target"
|
||||
@@ -12,6 +12,8 @@ import { LoggingModule } from './logging/logging.module';
|
||||
import { ProvidersModule } from './providers/providers.module';
|
||||
import { InquiryModule } from './inquiry/inquiry.module';
|
||||
import { DatabaseSeederModule } from './database/database-seeder.module';
|
||||
import { HealthModule } from './health/health.module';
|
||||
import { IdempotencyModule } from './idempotency/idempotency.module';
|
||||
|
||||
/**
|
||||
* Root application module — wires all feature and infrastructure modules.
|
||||
@@ -34,6 +36,8 @@ import { DatabaseSeederModule } from './database/database-seeder.module';
|
||||
DatabaseSeederModule,
|
||||
ProvidersModule,
|
||||
InquiryModule,
|
||||
HealthModule,
|
||||
IdempotencyModule,
|
||||
],
|
||||
})
|
||||
export class AppModule implements NestModule {
|
||||
|
||||
@@ -198,6 +198,26 @@ export const ERROR_CATALOG = {
|
||||
message: 'User rate limit exceeded',
|
||||
messageFa: 'تعداد درخواستهای مجاز کاربر به پایان رسیده است',
|
||||
},
|
||||
IDEMPOTENCY_KEY_REUSED: {
|
||||
status: HttpStatus.CONFLICT,
|
||||
message: 'Idempotency key was already used with a different request body',
|
||||
messageFa: 'کلید idempotency قبلا با بدنه درخواست دیگری استفاده شده است',
|
||||
},
|
||||
IDEMPOTENCY_REQUEST_IN_PROGRESS: {
|
||||
status: HttpStatus.CONFLICT,
|
||||
message: 'An identical request is already in progress',
|
||||
messageFa: 'درخواست مشابهی در حال پردازش است',
|
||||
},
|
||||
PROVIDER_CIRCUIT_OPEN: {
|
||||
status: HttpStatus.SERVICE_UNAVAILABLE,
|
||||
message: 'Provider is temporarily unavailable',
|
||||
messageFa: 'سرویسدهنده موقتا در دسترس نیست',
|
||||
},
|
||||
PROVIDER_BULKHEAD_FULL: {
|
||||
status: HttpStatus.SERVICE_UNAVAILABLE,
|
||||
message: 'Provider is currently at capacity',
|
||||
messageFa: 'ظرفیت همزمان سرویسدهنده تکمیل است',
|
||||
},
|
||||
SHAHKAR_NO_MATCH: {
|
||||
status: HttpStatus.OK,
|
||||
message: 'No match found between the provided national code and mobile number',
|
||||
@@ -218,6 +238,11 @@ export const ERROR_CATALOG = {
|
||||
message: 'Request failed',
|
||||
messageFa: 'درخواست ناموفق بود',
|
||||
},
|
||||
INQUIRY_LOG_PURGE_DISABLED: {
|
||||
status: HttpStatus.FORBIDDEN,
|
||||
message: 'Inquiry log purge is disabled',
|
||||
messageFa: 'پاکسازی گزارشهای استعلام غیرفعال است',
|
||||
},
|
||||
} as const satisfies Record<string, ErrorCatalogEntry>;
|
||||
|
||||
export type AppErrorCode = keyof typeof ERROR_CATALOG;
|
||||
|
||||
@@ -13,6 +13,9 @@ export class AttemptErrorDto {
|
||||
@ApiProperty({ example: 'PROVIDER_TIMEOUT' })
|
||||
code!: string;
|
||||
|
||||
@ApiPropertyOptional({ example: '503', description: 'Raw provider HTTP or SOAP error code, when supplied' })
|
||||
providerCode?: string;
|
||||
|
||||
@ApiProperty({ example: 1042, description: 'Duration of this attempt in milliseconds' })
|
||||
durationMs!: number;
|
||||
|
||||
|
||||
@@ -7,4 +7,5 @@ export enum AuditEvent {
|
||||
PASSWORD_RESET = 'PASSWORD_RESET',
|
||||
USER_BLOCKED = 'USER_BLOCKED',
|
||||
USER_UNBLOCKED = 'USER_UNBLOCKED',
|
||||
INQUIRY_LOGS_PURGED = 'INQUIRY_LOGS_PURGED',
|
||||
}
|
||||
|
||||
@@ -2,4 +2,19 @@ export enum InquiryStatus {
|
||||
SUCCESS = 'SUCCESS',
|
||||
FAILURE = 'FAILURE',
|
||||
PARTIAL = 'PARTIAL',
|
||||
/** A valid provider response with no matching business record. */
|
||||
NO_MATCH = 'NO_MATCH',
|
||||
}
|
||||
|
||||
export const NO_MATCH_ERROR_CODES = [
|
||||
'INQUIRY_NO_MATCH',
|
||||
'CAR_POLICY_NOT_FOUND',
|
||||
'RECORD_NOT_FOUND',
|
||||
'REAL_ESTATE_NOT_FOUND',
|
||||
'SHAHKAR_NO_MATCH',
|
||||
'SHEBA_MISMATCH',
|
||||
] as const;
|
||||
|
||||
export function isNoMatchErrorCode(code?: string): boolean {
|
||||
return Boolean(code && NO_MATCH_ERROR_CODES.includes(code as (typeof NO_MATCH_ERROR_CODES)[number]));
|
||||
}
|
||||
|
||||
@@ -37,6 +37,9 @@ export class AllExceptionsFilter implements ExceptionFilter {
|
||||
: HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
|
||||
const normalizedError = this.extractNormalizedError(exception);
|
||||
if (normalizedError.code === 'IDEMPOTENCY_REQUEST_IN_PROGRESS') {
|
||||
response.setHeader('Retry-After', '1');
|
||||
}
|
||||
const trackingCode = request.trackingCode ?? 'UNKNOWN';
|
||||
const requestId = request.requestId ?? (request.headers['x-request-id'] as string | undefined) ?? 'unknown';
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import axios, {
|
||||
InternalAxiosRequestConfig,
|
||||
} from 'axios';
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
import type { Agent as HttpAgent } from 'http';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
@@ -13,6 +14,21 @@ const { SocksProxyAgent } = require('socks-proxy-agent');
|
||||
|
||||
const outboundHttpLogger = new Logger('OutboundHTTP');
|
||||
|
||||
export interface OutboundRequestTrace {
|
||||
method: string;
|
||||
url: string;
|
||||
requestHeaders: Record<string, string>;
|
||||
requestBody?: unknown;
|
||||
status?: number;
|
||||
responseBody?: unknown;
|
||||
error?: string;
|
||||
durationMs?: number;
|
||||
curl: string;
|
||||
}
|
||||
|
||||
const outboundTraceStorage = new AsyncLocalStorage<OutboundRequestTrace[]>();
|
||||
const traceInterceptorsInstalled = new WeakSet<object>();
|
||||
|
||||
let cachedSocksAgents: { httpAgent: HttpAgent; httpsAgent: HttpAgent } | undefined;
|
||||
let outboundHttpDebugInstalled = false;
|
||||
|
||||
@@ -41,6 +57,93 @@ function truncate(value: string, max = 800): string {
|
||||
return value.length <= max ? value : `${value.slice(0, max)}...(truncated)`;
|
||||
}
|
||||
|
||||
function truncateTrace(value: string, max = 12000): string {
|
||||
return value.length <= max ? value : `${value.slice(0, max)}...(truncated)`;
|
||||
}
|
||||
|
||||
function redactTraceValue(value: unknown): unknown {
|
||||
if (typeof value === 'string') {
|
||||
return truncateTrace(
|
||||
value
|
||||
.replace(/(<(?:\w+:)?(?:Password|ClientSecret|AccessToken|RefreshToken)[^>]*>)[^<]*(<\/(?:\w+:)?(?:Password|ClientSecret|AccessToken|RefreshToken)>)/gi, '$1REDACTED$2')
|
||||
.replace(/((?:password|client_secret|access_token|refresh_token)=)[^&\s]*/gi, '$1<REDACTED>')
|
||||
.replace(/((?:"|')?(?:password|client_secret|access_token|refresh_token|authorization)(?:"|')?\s*:\s*)("[^"]*"|'[^']*')/gi, '$1"<REDACTED>"'),
|
||||
);
|
||||
}
|
||||
if (value === undefined || value === null || typeof value !== 'object') return value;
|
||||
if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) {
|
||||
return truncateTrace(
|
||||
value
|
||||
.toString()
|
||||
.replace(/((?:password|client_secret|access_token|refresh_token)=)[^&\s]*/gi, '$1<REDACTED>'),
|
||||
);
|
||||
}
|
||||
if (Buffer.isBuffer(value)) return truncateTrace(value.toString('utf8'));
|
||||
if (Array.isArray(value)) return value.map((item) => redactTraceValue(item));
|
||||
|
||||
return Object.fromEntries(
|
||||
Object.entries(value as Record<string, unknown>).map(([key, item]) => [
|
||||
key,
|
||||
/password|secret|authorization|token|client_secret/i.test(key)
|
||||
? '<REDACTED>'
|
||||
: redactTraceValue(item),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
function toTraceString(value: unknown): string {
|
||||
if (typeof value === 'string') return truncateTrace(value);
|
||||
try {
|
||||
return truncateTrace(JSON.stringify(value));
|
||||
} catch {
|
||||
return truncateTrace(String(value));
|
||||
}
|
||||
}
|
||||
|
||||
function shellQuote(value: string): string {
|
||||
return `'${value.replace(/'/g, `'\\''`)}'`;
|
||||
}
|
||||
|
||||
function toHeaderRecord(headers: unknown): Record<string, string> {
|
||||
const source =
|
||||
headers && typeof headers === 'object' && 'toJSON' in headers && typeof headers.toJSON === 'function'
|
||||
? headers.toJSON()
|
||||
: headers;
|
||||
if (!source || typeof source !== 'object') return {};
|
||||
|
||||
return Object.fromEntries(
|
||||
Object.entries(source as Record<string, unknown>)
|
||||
.filter(([key]) => !/^(host|content-length|user-agent|accept-encoding)$/i.test(key))
|
||||
.map(([key, value]) => [
|
||||
key,
|
||||
/authorization|password|secret|token/i.test(key) ? '<REDACTED>' : String(value),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
function buildCurl(
|
||||
method: string,
|
||||
url: string,
|
||||
headers: Record<string, string>,
|
||||
body: unknown,
|
||||
): string {
|
||||
const parts = [`curl --request ${method}`, shellQuote(url)];
|
||||
for (const [key, value] of Object.entries(headers)) {
|
||||
parts.push(`--header ${shellQuote(`${key}: ${value}`)}`);
|
||||
}
|
||||
if (body !== undefined) {
|
||||
parts.push(`--data-raw ${shellQuote(toTraceString(body))}`);
|
||||
}
|
||||
return parts.join(' \\\n ');
|
||||
}
|
||||
|
||||
export function runWithOutboundTrace<T>(
|
||||
trace: OutboundRequestTrace[],
|
||||
callback: () => Promise<T>,
|
||||
): Promise<T> {
|
||||
return outboundTraceStorage.run(trace, callback);
|
||||
}
|
||||
|
||||
function sanitizeForLog(data: unknown): string {
|
||||
if (data === undefined || data === null) {
|
||||
return String(data);
|
||||
@@ -86,6 +189,21 @@ function resolveRequestUrl(config: InternalAxiosRequestConfig): string {
|
||||
return `${base.replace(/\/$/, '')}/${url.replace(/^\//, '')}`;
|
||||
}
|
||||
|
||||
function resolveTraceUrl(config: InternalAxiosRequestConfig): string {
|
||||
const url = resolveRequestUrl(config);
|
||||
if (!config.params || typeof config.params !== 'object') return url;
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
for (const [key, value] of Object.entries(config.params as Record<string, unknown>)) {
|
||||
if (Array.isArray(value)) value.forEach((item) => parsed.searchParams.append(key, String(item)));
|
||||
else if (value !== undefined && value !== null) parsed.searchParams.set(key, String(value));
|
||||
}
|
||||
return parsed.toString();
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
function logOutboundRequest(config: InternalAxiosRequestConfig): void {
|
||||
const method = (config.method ?? 'GET').toUpperCase();
|
||||
const url = resolveRequestUrl(config);
|
||||
@@ -140,27 +258,65 @@ function logOutboundError(error: AxiosError): void {
|
||||
}
|
||||
|
||||
export function installOutboundHttpDebugInterceptors(): void {
|
||||
if (!isOutboundHttpDebugEnabled() || outboundHttpDebugInstalled) {
|
||||
if (outboundHttpDebugInstalled) {
|
||||
return;
|
||||
}
|
||||
|
||||
outboundHttpDebugInstalled = true;
|
||||
if (isOutboundHttpDebugEnabled()) {
|
||||
outboundHttpLogger.log('Outbound HTTP debug logging enabled (OUTBOUND_HTTP_DEBUG=true)');
|
||||
}
|
||||
|
||||
axios.interceptors.request.use((config) => {
|
||||
installOutboundHttpTraceInterceptors(axios);
|
||||
}
|
||||
|
||||
function installOutboundHttpTraceInterceptors(instance: AxiosInstance): void {
|
||||
if (traceInterceptorsInstalled.has(instance)) return;
|
||||
traceInterceptorsInstalled.add(instance);
|
||||
|
||||
instance.interceptors.request.use((config) => {
|
||||
(config as InternalAxiosRequestConfig & { _outboundStart?: number })._outboundStart =
|
||||
Date.now();
|
||||
logOutboundRequest(config);
|
||||
if (isOutboundHttpDebugEnabled()) logOutboundRequest(config);
|
||||
const trace = outboundTraceStorage.getStore();
|
||||
if (trace) {
|
||||
const requestHeaders = toHeaderRecord(config.headers);
|
||||
const requestBody = redactTraceValue(config.data);
|
||||
const item: OutboundRequestTrace = {
|
||||
method: (config.method ?? 'GET').toUpperCase(),
|
||||
url: resolveTraceUrl(config),
|
||||
requestHeaders,
|
||||
requestBody,
|
||||
curl: buildCurl((config.method ?? 'GET').toUpperCase(), resolveTraceUrl(config), requestHeaders, requestBody),
|
||||
};
|
||||
(config as InternalAxiosRequestConfig & { _outboundTrace?: OutboundRequestTrace })._outboundTrace = item;
|
||||
trace.push(item);
|
||||
}
|
||||
return config;
|
||||
});
|
||||
|
||||
axios.interceptors.response.use(
|
||||
instance.interceptors.response.use(
|
||||
(response) => {
|
||||
logOutboundResponse(response);
|
||||
if (isOutboundHttpDebugEnabled()) logOutboundResponse(response);
|
||||
const trace = (response.config as InternalAxiosRequestConfig & { _outboundTrace?: OutboundRequestTrace })._outboundTrace;
|
||||
if (trace) {
|
||||
trace.status = response.status;
|
||||
trace.responseBody = redactTraceValue(response.data);
|
||||
const start = (response.config as InternalAxiosRequestConfig & { _outboundStart?: number })._outboundStart;
|
||||
trace.durationMs = start ? Date.now() - start : undefined;
|
||||
}
|
||||
return response;
|
||||
},
|
||||
(error: AxiosError) => {
|
||||
logOutboundError(error);
|
||||
if (isOutboundHttpDebugEnabled()) logOutboundError(error);
|
||||
const config = error.config as (InternalAxiosRequestConfig & { _outboundTrace?: OutboundRequestTrace; _outboundStart?: number }) | undefined;
|
||||
const trace = config?._outboundTrace;
|
||||
if (trace) {
|
||||
trace.status = error.response?.status;
|
||||
trace.responseBody = redactTraceValue(error.response?.data);
|
||||
trace.error = error.message;
|
||||
trace.durationMs = config?._outboundStart ? Date.now() - config._outboundStart : undefined;
|
||||
}
|
||||
return Promise.reject(error);
|
||||
},
|
||||
);
|
||||
@@ -213,10 +369,12 @@ export function mergeOutboundAxiosConfig(config: AxiosRequestConfig = {}): Axios
|
||||
export function createOutboundAxiosInstance(config: CreateAxiosDefaults = {}): AxiosInstance {
|
||||
const outbound = getOutboundAxiosDefaults();
|
||||
|
||||
return axios.create({
|
||||
const instance = axios.create({
|
||||
...config,
|
||||
httpAgent: config.httpAgent ?? outbound.httpAgent,
|
||||
httpsAgent: config.httpsAgent ?? outbound.httpsAgent,
|
||||
proxy: config.proxy ?? outbound.proxy,
|
||||
});
|
||||
installOutboundHttpTraceInterceptors(instance);
|
||||
return instance;
|
||||
}
|
||||
|
||||
@@ -84,7 +84,9 @@ export function createDeadlineError(label = 'Inquiry'): Error {
|
||||
|
||||
/**
|
||||
* Transport / transient failures only.
|
||||
* Does NOT retry 429 (rate limit / ban risk) or business rejects.
|
||||
* Retries transient HTTP 404s because the configured legacy SOAP gateway is
|
||||
* known to return 404 intermittently for requests that succeed later. Does
|
||||
* NOT retry 429 (rate limit / ban risk) or business rejects.
|
||||
*/
|
||||
export function isTransportRetryable(error: unknown): boolean {
|
||||
if (!error || typeof error !== 'object') {
|
||||
@@ -101,7 +103,7 @@ export function isTransportRetryable(error: unknown): boolean {
|
||||
if ('response' in error) {
|
||||
const status = (error as { response?: { status?: number } }).response?.status;
|
||||
if (typeof status === 'number') {
|
||||
if (status === 408 || status === 499 || (status >= 500 && status < 600)) {
|
||||
if (status === 404 || status === 408 || status === 499 || (status >= 500 && status < 600)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -117,7 +119,7 @@ export function isTransportRetryable(error: unknown): boolean {
|
||||
return normalized.code !== 'INQUIRY_DEADLINE_EXCEEDED';
|
||||
}
|
||||
const providerCode = normalized.providerCode?.trim();
|
||||
if (providerCode && /^(408|499|5\d\d)$/.test(providerCode)) {
|
||||
if (providerCode && /^(404|408|499|5\d\d)$/.test(providerCode)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -149,6 +151,7 @@ export function isAuthTransportRetryable(error: unknown): boolean {
|
||||
|
||||
export function toAttemptErrorFields(error: unknown): {
|
||||
code: string;
|
||||
providerCode?: string;
|
||||
message: string;
|
||||
messageFa?: string;
|
||||
} {
|
||||
@@ -158,6 +161,7 @@ export function toAttemptErrorFields(error: unknown): {
|
||||
);
|
||||
return {
|
||||
code: normalized.code,
|
||||
providerCode: normalized.providerCode,
|
||||
message: normalized.message,
|
||||
messageFa: normalized.messageFa,
|
||||
};
|
||||
@@ -168,7 +172,7 @@ export function toAttemptErrorFields(error: unknown): {
|
||||
const code =
|
||||
error.code === 'ETIMEDOUT' || error.code === 'ECONNABORTED'
|
||||
? 'PROVIDER_TIMEOUT'
|
||||
: status && status >= 500
|
||||
: status
|
||||
? 'PROVIDER_ERROR'
|
||||
: 'PROVIDER_NETWORK_ERROR';
|
||||
const normalized = translateError(
|
||||
@@ -178,6 +182,7 @@ export function toAttemptErrorFields(error: unknown): {
|
||||
);
|
||||
return {
|
||||
code: normalized.code,
|
||||
providerCode: status ? String(status) : undefined,
|
||||
message: normalized.message,
|
||||
messageFa: normalized.messageFa,
|
||||
};
|
||||
@@ -219,6 +224,7 @@ export function recordResilienceAttempt(
|
||||
attempt: trail.totalAttempts,
|
||||
provider,
|
||||
code: fields.code,
|
||||
providerCode: fields.providerCode,
|
||||
durationMs: info.durationMs,
|
||||
message: fields.message,
|
||||
messageFa: fields.messageFa,
|
||||
@@ -239,7 +245,7 @@ export interface RunWithResilienceOptions {
|
||||
* Shared retry + per-attempt timeout + inquiry deadline for all inquiry providers.
|
||||
*/
|
||||
export async function runWithProviderResilience<T>(
|
||||
fn: () => Promise<T>,
|
||||
fn: (signal?: AbortSignal) => Promise<T>,
|
||||
options: RunWithResilienceOptions,
|
||||
): Promise<T> {
|
||||
const {
|
||||
@@ -262,7 +268,14 @@ export async function runWithProviderResilience<T>(
|
||||
throw createDeadlineError(label);
|
||||
}
|
||||
const attemptTimeout = Math.min(timeoutMs, remaining);
|
||||
return withTimeout(fn(), attemptTimeout, label);
|
||||
return withTimeout(
|
||||
(signal) => {
|
||||
context.signal = signal;
|
||||
return fn(signal);
|
||||
},
|
||||
attemptTimeout,
|
||||
label,
|
||||
);
|
||||
},
|
||||
{
|
||||
maxAttempts,
|
||||
|
||||
@@ -8,6 +8,16 @@ function decodeXml(value: string): string {
|
||||
}
|
||||
|
||||
function normalizeSoapTextValue(value: string): string {
|
||||
const keyValueValues = [
|
||||
...value.matchAll(/<(?:[\w]+:)?Value\b[^>]*>([\s\S]*?)<\/(?:[\w]+:)?Value>/gi),
|
||||
]
|
||||
.map((match) => normalizeSoapTextValue(match[1]))
|
||||
.filter(Boolean);
|
||||
|
||||
if (keyValueValues.length > 0) {
|
||||
return keyValueValues.join(', ');
|
||||
}
|
||||
|
||||
if (/i:nil\s*=\s*["']true["']/i.test(value)) {
|
||||
return '';
|
||||
}
|
||||
@@ -22,7 +32,17 @@ function normalizeSoapTextValue(value: string): string {
|
||||
return nestedStrings.join(', ');
|
||||
}
|
||||
|
||||
return decodeXml(value.trim());
|
||||
return decodeXml(value.trim()).replace(/\s+/g, ' ');
|
||||
}
|
||||
|
||||
function isNoPolicyMessage(message: string): boolean {
|
||||
const normalized = message.replace(/\s+/g, ' ').trim().toLowerCase();
|
||||
|
||||
return (
|
||||
/موردی\s*یافت\s*نشد/.test(normalized) ||
|
||||
/رکورد(?:ی)?\s*یافت\s*نشد/.test(normalized) ||
|
||||
/(?:no\s+(?:matching\s+)?(?:policy|record|item)|not\s+found)/i.test(normalized)
|
||||
);
|
||||
}
|
||||
|
||||
function parseSoapFields(block: string): Record<string, string> {
|
||||
@@ -60,7 +80,7 @@ export function parseFirstCarPolicy(soapXml: string): Record<string, string> {
|
||||
export function getCarPolicyProviderError(
|
||||
soapXml: string,
|
||||
policy: Record<string, string>,
|
||||
): { message: string; code: string } | null {
|
||||
): { message: string; code: string; providerCode?: string } | null {
|
||||
const resultMatch = soapXml.match(
|
||||
/<(?:[\w]+:)?(?:CIIWSPolicyChassis|CIIWSPolicyVehicleMeli|CIIWSPolicyNationalId)Result[^>]*>([\s\S]*?)<\/(?:[\w]+:)?(?:CIIWSPolicyChassis|CIIWSPolicyVehicleMeli|CIIWSPolicyNationalId)Result>/i,
|
||||
);
|
||||
@@ -71,14 +91,21 @@ export function getCarPolicyProviderError(
|
||||
);
|
||||
if (errorMatch) {
|
||||
const errorText = normalizeSoapTextValue(errorMatch[1]).trim();
|
||||
const providerCode = errorMatch[1]
|
||||
.match(/<(?:[\w]+:)?Key\b[^>]*>([\s\S]*?)<\/(?:[\w]+:)?Key>/i)?.[1]
|
||||
?.trim();
|
||||
if (errorText) {
|
||||
return { message: errorText, code: 'PROVIDER_ERROR' };
|
||||
return {
|
||||
message: errorText,
|
||||
code: isNoPolicyMessage(errorText) ? 'CAR_POLICY_NOT_FOUND' : 'PROVIDER_ERROR',
|
||||
providerCode,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(policy).length === 0) {
|
||||
return { message: 'No policy record found', code: 'RECORD_NOT_FOUND' };
|
||||
return { message: 'No policy record found', code: 'CAR_POLICY_NOT_FOUND' };
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
@@ -1,24 +1,30 @@
|
||||
/**
|
||||
* Races an async operation against a timeout.
|
||||
* Throws a distinguishable error for BaseProvider normalization.
|
||||
* Runs an async operation with a per-attempt timeout.
|
||||
*
|
||||
* The operation receives an AbortSignal so HTTP clients can stop the actual
|
||||
* in-flight request when the timeout wins. A timeout without cancellation
|
||||
* would only stop awaiting the promise and could leave sockets/slots busy.
|
||||
*/
|
||||
export async function withTimeout<T>(
|
||||
promise: Promise<T>,
|
||||
operation: (signal: AbortSignal) => Promise<T>,
|
||||
timeoutMs: number,
|
||||
label = 'Operation',
|
||||
): Promise<T> {
|
||||
const controller = new AbortController();
|
||||
let timeoutHandle: NodeJS.Timeout;
|
||||
|
||||
const operationPromise = Promise.resolve().then(() => operation(controller.signal));
|
||||
const timeoutPromise = new Promise<never>((_, reject) => {
|
||||
timeoutHandle = setTimeout(() => {
|
||||
const error = new Error(`${label} timed out after ${timeoutMs}ms`);
|
||||
(error as NodeJS.ErrnoException).code = 'ETIMEDOUT';
|
||||
controller.abort();
|
||||
reject(error);
|
||||
}, timeoutMs);
|
||||
});
|
||||
|
||||
try {
|
||||
return await Promise.race([promise, timeoutPromise]);
|
||||
return await Promise.race([operationPromise, timeoutPromise]);
|
||||
} finally {
|
||||
clearTimeout(timeoutHandle!);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { InquiryType } from '../enums/inquiry-type.enum';
|
||||
import { ProviderName } from '../enums/provider-name.enum';
|
||||
import { AttemptTrail } from '../helpers/provider-resilience.helper';
|
||||
import type { OutboundRequestTrace } from '../helpers/http-client.helper';
|
||||
|
||||
/**
|
||||
* Contract every external provider adapter must fulfill.
|
||||
@@ -22,6 +23,10 @@ export interface ProviderExecutionContext {
|
||||
trackingCode: string;
|
||||
/** Absolute timestamp when the inquiry wall-clock budget expires. */
|
||||
deadlineAt?: number;
|
||||
/** Signal for cancelling the currently active provider attempt. */
|
||||
signal?: AbortSignal;
|
||||
/** Mutable trail of HTTP attempts for client summary + logs. */
|
||||
attemptTrail?: AttemptTrail;
|
||||
/** Sanitized outbound HTTP calls made during this inquiry, including retries. */
|
||||
outboundRequests?: OutboundRequestTrace[];
|
||||
}
|
||||
|
||||
@@ -67,6 +67,7 @@ export default () => ({
|
||||
bcryptSaltRounds: parseInt(process.env.BCRYPT_SALT_ROUNDS ?? '12', 10),
|
||||
},
|
||||
throttle: {
|
||||
enabled: process.env.RATE_LIMIT_ENABLED !== 'false',
|
||||
ttl: parseInt(process.env.THROTTLE_TTL ?? '60', 10),
|
||||
limit: parseInt(process.env.THROTTLE_LIMIT ?? '100', 10),
|
||||
},
|
||||
|
||||
@@ -102,8 +102,9 @@ export class DatabaseSeederService implements OnApplicationBootstrap {
|
||||
|
||||
private resolveSeedPath(): string {
|
||||
const candidates = [
|
||||
join(__dirname, '..', 'public', this.usersSeedFile),
|
||||
join(process.cwd(), 'src', 'public', this.usersSeedFile),
|
||||
join(__dirname, 'seeds', this.usersSeedFile),
|
||||
join(process.cwd(), 'src', 'database', 'seeds', this.usersSeedFile),
|
||||
join(process.cwd(), 'dist', 'database', 'seeds', this.usersSeedFile),
|
||||
];
|
||||
|
||||
const seedPath = candidates.find((candidate) => existsSync(candidate));
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import {
|
||||
DiskHealthIndicator,
|
||||
HealthCheck,
|
||||
HealthCheckService,
|
||||
MemoryHealthIndicator,
|
||||
MongooseHealthIndicator,
|
||||
} from '@nestjs/terminus';
|
||||
import { HealthService } from './health.service';
|
||||
|
||||
@Controller('health')
|
||||
export class HealthController {
|
||||
constructor(
|
||||
private readonly health: HealthCheckService,
|
||||
private readonly mongoose: MongooseHealthIndicator,
|
||||
private readonly memory: MemoryHealthIndicator,
|
||||
private readonly disk: DiskHealthIndicator,
|
||||
private readonly healthService: HealthService,
|
||||
) {}
|
||||
|
||||
@Get('live')
|
||||
@HealthCheck({ swaggerDocumentation: false })
|
||||
liveness() {
|
||||
return this.health.check([]);
|
||||
}
|
||||
|
||||
@Get('ready')
|
||||
@HealthCheck({ swaggerDocumentation: false })
|
||||
readiness() {
|
||||
return this.health.check([
|
||||
() => this.mongoose.pingCheck('mongodb', { timeout: 1000 }),
|
||||
() => this.memory.checkHeap('memory_heap', this.healthService.heapThresholdBytes()),
|
||||
() =>
|
||||
this.disk.checkStorage('disk', {
|
||||
path: this.healthService.diskPath(),
|
||||
thresholdPercent: this.healthService.diskThresholdPercent(),
|
||||
}),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MongooseModule } from '@nestjs/mongoose';
|
||||
import { TerminusModule } from '@nestjs/terminus';
|
||||
import { HealthController } from './health.controller';
|
||||
import { HealthService } from './health.service';
|
||||
|
||||
@Module({
|
||||
imports: [TerminusModule.forRoot(), MongooseModule],
|
||||
controllers: [HealthController],
|
||||
providers: [HealthService],
|
||||
})
|
||||
export class HealthModule {}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class HealthService {
|
||||
heapThresholdBytes(): number {
|
||||
return this.readPositiveEnv('HEALTH_HEAP_MB', 512) * 1024 * 1024;
|
||||
}
|
||||
|
||||
diskThresholdPercent(): number {
|
||||
const configured = Number.parseFloat(process.env.HEALTH_DISK_THRESHOLD_PERCENT ?? '');
|
||||
return Number.isFinite(configured) && configured > 0 && configured < 1 ? configured : 0.9;
|
||||
}
|
||||
|
||||
diskPath(): string {
|
||||
return process.env.HEALTH_DISK_PATH ?? '/';
|
||||
}
|
||||
|
||||
private readPositiveEnv(name: string, fallback: number): number {
|
||||
const value = Number.parseInt(process.env[name] ?? '', 10);
|
||||
return Number.isFinite(value) && value > 0 ? value : fallback;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import {
|
||||
CallHandler,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
NestInterceptor,
|
||||
Optional,
|
||||
} from '@nestjs/common';
|
||||
import { Request, Response } from 'express';
|
||||
import { from, Observable, of, throwError } from 'rxjs';
|
||||
import { catchError, map, mergeMap, switchMap } from 'rxjs/operators';
|
||||
import { IdempotencyService } from './idempotency.service';
|
||||
|
||||
type RequestWithIdentity = Request & {
|
||||
user?: { id?: string };
|
||||
requestId?: string;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class IdempotencyInterceptor implements NestInterceptor {
|
||||
constructor(@Optional() private readonly idempotencyService?: IdempotencyService) {}
|
||||
|
||||
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
||||
const http = context.switchToHttp();
|
||||
const request = http.getRequest<RequestWithIdentity>();
|
||||
const response = http.getResponse<Response>();
|
||||
const rawKey = request.headers['idempotency-key'];
|
||||
const idempotencyService = this.idempotencyService;
|
||||
|
||||
if (
|
||||
!idempotencyService ||
|
||||
request.method !== 'POST' ||
|
||||
!rawKey ||
|
||||
Array.isArray(rawKey)
|
||||
) {
|
||||
return next.handle();
|
||||
}
|
||||
|
||||
const key = rawKey.trim();
|
||||
const callerId = request.user?.id ?? `ip:${request.ip}`;
|
||||
const begin = idempotencyService.begin({
|
||||
key,
|
||||
callerId,
|
||||
method: request.method,
|
||||
path: request.path,
|
||||
body: request.body,
|
||||
requestId: request.requestId,
|
||||
});
|
||||
|
||||
return from(begin).pipe(
|
||||
switchMap((reservation) => {
|
||||
if (reservation.replay) {
|
||||
response.status(reservation.replay.responseStatus);
|
||||
response.setHeader('Idempotency-Replayed', 'true');
|
||||
return of(reservation.replay.responseBody);
|
||||
}
|
||||
|
||||
return next.handle().pipe(
|
||||
mergeMap((body) =>
|
||||
from(idempotencyService.complete(reservation.scopeHash, body, response.statusCode)).pipe(
|
||||
map(() => body),
|
||||
catchError(() => of(body)),
|
||||
),
|
||||
),
|
||||
catchError((error: unknown) =>
|
||||
from(idempotencyService.abandon(reservation.scopeHash)).pipe(
|
||||
catchError(() => of(undefined)),
|
||||
mergeMap(() => throwError(() => error)),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MongooseModule } from '@nestjs/mongoose';
|
||||
import { IdempotencyInterceptor } from './idempotency.interceptor';
|
||||
import { IdempotencyService } from './idempotency.service';
|
||||
import {
|
||||
IdempotencyRecord,
|
||||
IdempotencyRecordSchema,
|
||||
} from './schemas/idempotency-record.schema';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
MongooseModule.forFeature([
|
||||
{ name: IdempotencyRecord.name, schema: IdempotencyRecordSchema },
|
||||
]),
|
||||
],
|
||||
providers: [IdempotencyService, IdempotencyInterceptor],
|
||||
exports: [IdempotencyService, IdempotencyInterceptor],
|
||||
})
|
||||
export class IdempotencyModule {}
|
||||
@@ -0,0 +1,161 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectModel } from '@nestjs/mongoose';
|
||||
import { Model } from 'mongoose';
|
||||
import { AppException } from '../common/exceptions/app-exception';
|
||||
import {
|
||||
IdempotencyRecord,
|
||||
IdempotencyRecordDocument,
|
||||
IdempotencyRecordStatus,
|
||||
} from './schemas/idempotency-record.schema';
|
||||
|
||||
export interface IdempotencyBeginInput {
|
||||
key: string;
|
||||
callerId: string;
|
||||
method: string;
|
||||
path: string;
|
||||
body: unknown;
|
||||
requestId?: string;
|
||||
}
|
||||
|
||||
export interface IdempotencyReplay {
|
||||
scopeHash: string;
|
||||
responseStatus: number;
|
||||
responseBody: unknown;
|
||||
}
|
||||
|
||||
export interface IdempotencyBeginResult {
|
||||
scopeHash: string;
|
||||
replay?: IdempotencyReplay;
|
||||
}
|
||||
|
||||
const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
const IN_PROGRESS_TTL_MS = 5 * 60 * 1000;
|
||||
|
||||
@Injectable()
|
||||
export class IdempotencyService {
|
||||
private readonly ttlMs = this.readPositiveEnv('IDEMPOTENCY_TTL_MS', DEFAULT_TTL_MS);
|
||||
|
||||
constructor(
|
||||
@InjectModel(IdempotencyRecord.name)
|
||||
private readonly recordModel: Model<IdempotencyRecordDocument>,
|
||||
) {}
|
||||
|
||||
async begin(input: IdempotencyBeginInput): Promise<IdempotencyBeginResult> {
|
||||
const key = input.key.trim();
|
||||
if (!key || key.length > 256) {
|
||||
throw new AppException('VALIDATION_ERROR', {
|
||||
message: 'Idempotency-Key must be between 1 and 256 characters',
|
||||
});
|
||||
}
|
||||
|
||||
const scopeHash = this.hash(`${input.callerId}:${input.method}:${input.path}:${key}`);
|
||||
const requestFingerprint = this.hash(this.stableStringify(input.body));
|
||||
const now = Date.now();
|
||||
const expiresAt = new Date(now + this.ttlMs);
|
||||
|
||||
let record = await this.recordModel.findOne({ scopeHash }).exec();
|
||||
let created = false;
|
||||
if (!record) {
|
||||
try {
|
||||
record = await this.recordModel.create({
|
||||
scopeHash,
|
||||
requestFingerprint,
|
||||
status: IdempotencyRecordStatus.IN_PROGRESS,
|
||||
expiresAt: new Date(now + Math.min(this.ttlMs, IN_PROGRESS_TTL_MS)),
|
||||
requestId: input.requestId,
|
||||
});
|
||||
created = true;
|
||||
} catch (error) {
|
||||
if (!this.isDuplicateKey(error)) throw error;
|
||||
record = await this.recordModel.findOne({ scopeHash }).exec();
|
||||
}
|
||||
}
|
||||
|
||||
if (!record) {
|
||||
throw new AppException('INTERNAL_ERROR', { message: 'Unable to reserve idempotency key' });
|
||||
}
|
||||
|
||||
if (created) return { scopeHash };
|
||||
|
||||
if (record.requestFingerprint !== requestFingerprint) {
|
||||
throw new AppException('IDEMPOTENCY_KEY_REUSED');
|
||||
}
|
||||
|
||||
if (record.status === IdempotencyRecordStatus.COMPLETED) {
|
||||
return {
|
||||
scopeHash,
|
||||
replay: {
|
||||
scopeHash,
|
||||
responseStatus: record.responseStatus ?? 200,
|
||||
responseBody: record.responseBody,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (record.expiresAt.getTime() <= now) {
|
||||
const reclaimed = await this.recordModel
|
||||
.findOneAndUpdate(
|
||||
{ _id: record._id, expiresAt: { $lte: new Date(now) } },
|
||||
{
|
||||
$set: {
|
||||
requestFingerprint,
|
||||
status: IdempotencyRecordStatus.IN_PROGRESS,
|
||||
expiresAt,
|
||||
requestId: input.requestId,
|
||||
},
|
||||
},
|
||||
{ new: true },
|
||||
)
|
||||
.exec();
|
||||
if (reclaimed) return { scopeHash };
|
||||
}
|
||||
|
||||
throw new AppException('IDEMPOTENCY_REQUEST_IN_PROGRESS');
|
||||
}
|
||||
|
||||
async complete(scopeHash: string, responseBody: unknown, responseStatus = 200): Promise<void> {
|
||||
await this.recordModel
|
||||
.updateOne(
|
||||
{ scopeHash, status: IdempotencyRecordStatus.IN_PROGRESS },
|
||||
{
|
||||
$set: {
|
||||
status: IdempotencyRecordStatus.COMPLETED,
|
||||
responseStatus,
|
||||
responseBody,
|
||||
expiresAt: new Date(Date.now() + this.ttlMs),
|
||||
},
|
||||
},
|
||||
)
|
||||
.exec();
|
||||
}
|
||||
|
||||
async abandon(scopeHash: string): Promise<void> {
|
||||
await this.recordModel
|
||||
.deleteOne({ scopeHash, status: IdempotencyRecordStatus.IN_PROGRESS })
|
||||
.exec();
|
||||
}
|
||||
|
||||
private hash(value: string): string {
|
||||
return createHash('sha256').update(value).digest('hex');
|
||||
}
|
||||
|
||||
private stableStringify(value: unknown): string {
|
||||
if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'undefined';
|
||||
if (Array.isArray(value)) return `[${value.map((item) => this.stableStringify(item)).join(',')}]`;
|
||||
const object = value as Record<string, unknown>;
|
||||
return `{${Object.keys(object)
|
||||
.sort()
|
||||
.map((key) => `${JSON.stringify(key)}:${this.stableStringify(object[key])}`)
|
||||
.join(',')}}`;
|
||||
}
|
||||
|
||||
private isDuplicateKey(error: unknown): boolean {
|
||||
return Boolean(error && typeof error === 'object' && 'code' in error && (error as { code?: number }).code === 11000);
|
||||
}
|
||||
|
||||
private readPositiveEnv(name: string, fallback: number): number {
|
||||
const value = Number.parseInt(process.env[name] ?? '', 10);
|
||||
return Number.isFinite(value) && value > 0 ? value : fallback;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
|
||||
import { HydratedDocument, Schema as MongooseSchema } from 'mongoose';
|
||||
|
||||
export type IdempotencyRecordDocument = HydratedDocument<IdempotencyRecord>;
|
||||
|
||||
export enum IdempotencyRecordStatus {
|
||||
IN_PROGRESS = 'IN_PROGRESS',
|
||||
COMPLETED = 'COMPLETED',
|
||||
}
|
||||
|
||||
@Schema({ timestamps: true, collection: 'idempotency_records' })
|
||||
export class IdempotencyRecord {
|
||||
@Prop({ required: true, unique: true, index: true })
|
||||
scopeHash!: string;
|
||||
|
||||
@Prop({ required: true })
|
||||
requestFingerprint!: string;
|
||||
|
||||
@Prop({ required: true, enum: IdempotencyRecordStatus })
|
||||
status!: IdempotencyRecordStatus;
|
||||
|
||||
@Prop({ required: true })
|
||||
expiresAt!: Date;
|
||||
|
||||
@Prop()
|
||||
responseStatus?: number;
|
||||
|
||||
@Prop({ type: MongooseSchema.Types.Mixed })
|
||||
responseBody?: unknown;
|
||||
|
||||
@Prop()
|
||||
requestId?: string;
|
||||
}
|
||||
|
||||
export const IdempotencyRecordSchema = SchemaFactory.createForClass(IdempotencyRecord);
|
||||
IdempotencyRecordSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 });
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import {
|
||||
ApiBearerAuth,
|
||||
ApiHeader,
|
||||
ApiOperation,
|
||||
ApiResponse,
|
||||
ApiTags,
|
||||
@@ -20,6 +21,7 @@ import { InquiryAccess } from '../auth/decorators/inquiry-access.decorator';
|
||||
import { InquiryType } from '../common/enums/inquiry-type.enum';
|
||||
import { BaseInquiryResponseDto } from '../common/dto/base-inquiry-response.dto';
|
||||
import { ResponseTransformInterceptor } from '../common/interceptors/response-transform.interceptor';
|
||||
import { IdempotencyInterceptor } from '../idempotency/idempotency.interceptor';
|
||||
import { UserRateLimitGuard } from '../rate-limit/user-rate-limit.guard';
|
||||
import { PersonInquiryRequestDto } from './dto/person-inquiry-request.dto';
|
||||
import { PersonInquiryDataDto } from './dto/person-inquiry-data.dto';
|
||||
@@ -41,9 +43,14 @@ import { InquiryService } from './inquiry.service';
|
||||
*/
|
||||
@ApiTags('Inquiries')
|
||||
@ApiBearerAuth()
|
||||
@ApiHeader({
|
||||
name: 'Idempotency-Key',
|
||||
required: false,
|
||||
description: 'Optional key for safely retrying the same inquiry request',
|
||||
})
|
||||
@Controller('inquiry')
|
||||
@UseGuards(JwtAuthGuard, InquiryAccessGuard, UserRateLimitGuard)
|
||||
@UseInterceptors(ResponseTransformInterceptor)
|
||||
@UseInterceptors(ResponseTransformInterceptor, IdempotencyInterceptor)
|
||||
export class InquiryController {
|
||||
constructor(private readonly inquiryService: InquiryService) {}
|
||||
|
||||
|
||||
@@ -3,11 +3,12 @@ import { AuthModule } from '../auth/auth.module';
|
||||
import { LoggingModule } from '../logging/logging.module';
|
||||
import { ProvidersModule } from '../providers/providers.module';
|
||||
import { RateLimitModule } from '../rate-limit/rate-limit.module';
|
||||
import { IdempotencyModule } from '../idempotency/idempotency.module';
|
||||
import { InquiryController } from './inquiry.controller';
|
||||
import { InquiryService } from './inquiry.service';
|
||||
|
||||
@Module({
|
||||
imports: [ProvidersModule, LoggingModule, AuthModule, RateLimitModule],
|
||||
imports: [ProvidersModule, LoggingModule, AuthModule, RateLimitModule, IdempotencyModule],
|
||||
controllers: [InquiryController],
|
||||
providers: [InquiryService],
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InquiryType } from '../common/enums/inquiry-type.enum';
|
||||
import { InquiryStatus } from '../common/enums/inquiry-status.enum';
|
||||
import { InquiryStatus, isNoMatchErrorCode } from '../common/enums/inquiry-status.enum';
|
||||
import { ProviderName } from '../common/enums/provider-name.enum';
|
||||
import { AttemptSummaryDto } from '../common/dto/attempt-summary.dto';
|
||||
import { BaseInquiryResponseDto } from '../common/dto/base-inquiry-response.dto';
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
import { ProviderOrchestratorService } from '../providers/strategy/provider-orchestrator.service';
|
||||
import { PersonInquiryRequestDto } from './dto/person-inquiry-request.dto';
|
||||
import { PersonInquiryDataDto } from './dto/person-inquiry-data.dto';
|
||||
import type { OutboundRequestTrace } from '../common/helpers/http-client.helper';
|
||||
|
||||
@Injectable()
|
||||
export class InquiryService {
|
||||
@@ -49,6 +50,7 @@ export class InquiryService {
|
||||
): Promise<BaseInquiryResponseDto<Record<string, unknown>>> {
|
||||
const trackingCode = generateTrackingCode();
|
||||
const start = Date.now();
|
||||
const outboundRequests: OutboundRequestTrace[] = [];
|
||||
|
||||
try {
|
||||
const result = await this.executeInquiry<LegacyInquiryPayload, unknown>(
|
||||
@@ -56,6 +58,7 @@ export class InquiryService {
|
||||
payload,
|
||||
requestId,
|
||||
trackingCode,
|
||||
outboundRequests,
|
||||
);
|
||||
|
||||
const attemptSummary = this.resolveExposedSummary(true, result.attemptSummary);
|
||||
@@ -80,6 +83,7 @@ export class InquiryService {
|
||||
requestId,
|
||||
trackingCode,
|
||||
attemptSummary: result.attemptSummary,
|
||||
outboundRequests,
|
||||
});
|
||||
|
||||
return response;
|
||||
@@ -103,12 +107,13 @@ export class InquiryService {
|
||||
inquiryType,
|
||||
provider: (provider as ProviderName | undefined) ?? ProviderName.HAMTA,
|
||||
requestPayload: payload,
|
||||
status: InquiryStatus.FAILURE,
|
||||
status: isNoMatchErrorCode(normalized.code) ? InquiryStatus.NO_MATCH : InquiryStatus.FAILURE,
|
||||
duration,
|
||||
requestId,
|
||||
trackingCode,
|
||||
error: normalized as unknown as Record<string, unknown>,
|
||||
attemptSummary,
|
||||
outboundRequests,
|
||||
}).catch(() => undefined);
|
||||
|
||||
return response;
|
||||
@@ -120,10 +125,12 @@ export class InquiryService {
|
||||
payload: TRequest,
|
||||
requestId: string,
|
||||
trackingCode: string,
|
||||
outboundRequests: OutboundRequestTrace[],
|
||||
) {
|
||||
return this.orchestrator.executeWithFallback<TRequest, TResponse>(inquiryType, payload, {
|
||||
requestId,
|
||||
trackingCode,
|
||||
outboundRequests,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -57,6 +57,11 @@ export class InquiryLogQueryDto {
|
||||
@IsString()
|
||||
errorMessage?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Exact inquiry tracking code lookup' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
trackingCode?: string;
|
||||
|
||||
@ApiPropertyOptional({ minimum: 1, maximum: 500, default: 50 })
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
|
||||
@@ -2,7 +2,10 @@ import { Injectable } from '@nestjs/common';
|
||||
import { InjectModel } from '@nestjs/mongoose';
|
||||
import { FilterQuery, Model } from 'mongoose';
|
||||
import { AttemptSummaryDto } from '../common/dto/attempt-summary.dto';
|
||||
import { InquiryStatus } from '../common/enums/inquiry-status.enum';
|
||||
import {
|
||||
InquiryStatus,
|
||||
NO_MATCH_ERROR_CODES,
|
||||
} from '../common/enums/inquiry-status.enum';
|
||||
import { InquiryType } from '../common/enums/inquiry-type.enum';
|
||||
import { ProviderName } from '../common/enums/provider-name.enum';
|
||||
import { maskPayload } from '../common/helpers/mask-payload.helper';
|
||||
@@ -13,6 +16,7 @@ import {
|
||||
LogTimeRangePreset,
|
||||
} from './dto/inquiry-log-query.dto';
|
||||
import { InquiryLog, InquiryLogDocument } from './schemas/inquiry-log.schema';
|
||||
import type { OutboundRequestTrace } from '../common/helpers/http-client.helper';
|
||||
|
||||
export interface CreateInquiryLogInput {
|
||||
inquiryType: InquiryType;
|
||||
@@ -25,6 +29,7 @@ export interface CreateInquiryLogInput {
|
||||
trackingCode: string;
|
||||
error?: Record<string, unknown>;
|
||||
attemptSummary?: AttemptSummaryDto;
|
||||
outboundRequests?: OutboundRequestTrace[];
|
||||
}
|
||||
|
||||
export interface InquiryLogListItem {
|
||||
@@ -38,13 +43,16 @@ export interface InquiryLogListItem {
|
||||
maskedRequest: Record<string, unknown>;
|
||||
responsePayload?: Record<string, unknown>;
|
||||
error?: Record<string, unknown>;
|
||||
outboundRequests?: Record<string, unknown>[];
|
||||
createdAt?: Date;
|
||||
}
|
||||
|
||||
export interface InquiryLogSummary {
|
||||
total: number;
|
||||
evaluated: number;
|
||||
success: number;
|
||||
failure: number;
|
||||
noMatch: number;
|
||||
partial: number;
|
||||
successRate: number;
|
||||
failureRate: number;
|
||||
@@ -97,6 +105,11 @@ export class InquiryLogService {
|
||||
});
|
||||
}
|
||||
|
||||
async purgeAll(): Promise<{ deletedCount: number }> {
|
||||
const result = await this.inquiryLogModel.deleteMany({}).exec();
|
||||
return { deletedCount: result.deletedCount ?? 0 };
|
||||
}
|
||||
|
||||
async findLogs(query: InquiryLogQueryDto): Promise<{
|
||||
data: InquiryLogListItem[];
|
||||
page: number;
|
||||
@@ -114,7 +127,7 @@ export class InquiryLogService {
|
||||
.sort({ createdAt: -1 })
|
||||
.skip(skip)
|
||||
.limit(limit)
|
||||
.select('inquiryType provider status duration requestId trackingCode maskedRequest responsePayload error createdAt')
|
||||
.select('inquiryType provider status duration requestId trackingCode maskedRequest responsePayload error outboundRequests createdAt')
|
||||
.lean()
|
||||
.exec(),
|
||||
this.inquiryLogModel.countDocuments(filter),
|
||||
@@ -132,6 +145,7 @@ export class InquiryLogService {
|
||||
maskedRequest: log.maskedRequest,
|
||||
responsePayload: log.responsePayload,
|
||||
error: log.error,
|
||||
outboundRequests: log.outboundRequests,
|
||||
createdAt: log.createdAt,
|
||||
})),
|
||||
page,
|
||||
@@ -153,6 +167,39 @@ export class InquiryLogService {
|
||||
failure: {
|
||||
$sum: { $cond: [{ $eq: ['$status', InquiryStatus.FAILURE] }, 1, 0] },
|
||||
},
|
||||
noMatch: {
|
||||
$sum: {
|
||||
$cond: [
|
||||
{
|
||||
$or: [
|
||||
{ $eq: ['$status', InquiryStatus.NO_MATCH] },
|
||||
{
|
||||
$and: [
|
||||
{ $eq: ['$status', InquiryStatus.FAILURE] },
|
||||
{ $in: ['$error.code', NO_MATCH_ERROR_CODES] },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
1,
|
||||
0,
|
||||
],
|
||||
},
|
||||
},
|
||||
noMatchFailure: {
|
||||
$sum: {
|
||||
$cond: [
|
||||
{
|
||||
$and: [
|
||||
{ $eq: ['$status', InquiryStatus.FAILURE] },
|
||||
{ $in: ['$error.code', NO_MATCH_ERROR_CODES] },
|
||||
],
|
||||
},
|
||||
1,
|
||||
0,
|
||||
],
|
||||
},
|
||||
},
|
||||
partial: {
|
||||
$sum: { $cond: [{ $eq: ['$status', InquiryStatus.PARTIAL] }, 1, 0] },
|
||||
},
|
||||
@@ -166,13 +213,25 @@ export class InquiryLogService {
|
||||
_id: 0,
|
||||
total: 1,
|
||||
success: 1,
|
||||
failure: 1,
|
||||
failure: { $subtract: ['$failure', '$noMatchFailure'] },
|
||||
evaluated: {
|
||||
$add: ['$success', { $subtract: ['$failure', '$noMatchFailure'] }],
|
||||
},
|
||||
noMatch: 1,
|
||||
partial: 1,
|
||||
successRate: {
|
||||
$cond: [{ $eq: ['$total', 0] }, 0, { $divide: ['$success', '$total'] }],
|
||||
$cond: [
|
||||
{ $eq: [{ $add: ['$success', { $subtract: ['$failure', '$noMatchFailure'] }] }, 0] },
|
||||
0,
|
||||
{ $divide: ['$success', { $add: ['$success', { $subtract: ['$failure', '$noMatchFailure'] }] }] },
|
||||
],
|
||||
},
|
||||
failureRate: {
|
||||
$cond: [{ $eq: ['$total', 0] }, 0, { $divide: ['$failure', '$total'] }],
|
||||
$cond: [
|
||||
{ $eq: [{ $add: ['$success', { $subtract: ['$failure', '$noMatchFailure'] }] }, 0] },
|
||||
0,
|
||||
{ $divide: [{ $subtract: ['$failure', '$noMatchFailure'] }, { $add: ['$success', { $subtract: ['$failure', '$noMatchFailure'] }] }] },
|
||||
],
|
||||
},
|
||||
averageDuration: { $ifNull: ['$averageDuration', 0] },
|
||||
minDuration: { $ifNull: ['$minDuration', 0] },
|
||||
@@ -331,6 +390,9 @@ export class InquiryLogService {
|
||||
if (query.errorMessage) {
|
||||
filter['error.message'] = { $regex: query.errorMessage, $options: 'i' };
|
||||
}
|
||||
if (query.trackingCode) {
|
||||
filter.trackingCode = query.trackingCode;
|
||||
}
|
||||
|
||||
return filter;
|
||||
}
|
||||
@@ -379,8 +441,10 @@ export class InquiryLogService {
|
||||
private emptySummary(): InquiryLogSummary {
|
||||
return {
|
||||
total: 0,
|
||||
evaluated: 0,
|
||||
success: 0,
|
||||
failure: 0,
|
||||
noMatch: 0,
|
||||
partial: 0,
|
||||
successRate: 0,
|
||||
failureRate: 0,
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import { Controller, Get, Query, UseGuards } from '@nestjs/common';
|
||||
import { Controller, Delete, Get, Query, Req, UseGuards } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { Request } from 'express';
|
||||
import { AuditEvent } from '../common/enums/audit-event.enum';
|
||||
import { AppException } from '../common/exceptions/app-exception';
|
||||
import { AuditService } from '../audit/audit.service';
|
||||
import { CurrentUser } from '../auth/decorators/current-user.decorator';
|
||||
import { AuthenticatedUser } from '../auth/interfaces/authenticated-user.interface';
|
||||
import { Roles } from '../auth/decorators/roles.decorator';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { RolesGuard } from '../auth/guards/roles.guard';
|
||||
import { ADMIN_ROLES } from '../common/enums/role.enum';
|
||||
import { Role } from '../common/enums/role.enum';
|
||||
import { InquiryLogQueryDto, InquiryLogTimelineQueryDto } from './dto/inquiry-log-query.dto';
|
||||
import { InquiryLogService } from './inquiry-log.service';
|
||||
|
||||
@@ -11,9 +17,36 @@ import { InquiryLogService } from './inquiry-log.service';
|
||||
@ApiBearerAuth()
|
||||
@Controller('inquiry-logs')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(...ADMIN_ROLES)
|
||||
// Inquiry logs contain operational and potentially sensitive provider payloads.
|
||||
// Keep the dashboard data restricted to the seeded/managed SUPER_ADMIN role.
|
||||
@Roles(Role.SUPER_ADMIN)
|
||||
export class InquiryLogsController {
|
||||
constructor(private readonly inquiryLogService: InquiryLogService) {}
|
||||
constructor(
|
||||
private readonly inquiryLogService: InquiryLogService,
|
||||
private readonly auditService: AuditService,
|
||||
) {}
|
||||
|
||||
@Delete()
|
||||
@ApiOperation({ summary: 'Delete all inquiry request logs (explicitly enabled local maintenance action)' })
|
||||
async purgeAll(
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
@Req() request: Request,
|
||||
): Promise<{ deletedCount: number }> {
|
||||
if (process.env.INQUIRY_LOG_PURGE_ENABLED !== 'true') {
|
||||
throw new AppException('INQUIRY_LOG_PURGE_DISABLED');
|
||||
}
|
||||
|
||||
const result = await this.inquiryLogService.purgeAll();
|
||||
await this.auditService.log(AuditEvent.INQUIRY_LOGS_PURGED, {
|
||||
userId: user.id,
|
||||
username: user.username,
|
||||
ip: request.ip,
|
||||
userAgent: request.headers['user-agent'],
|
||||
metadata: { deletedCount: result.deletedCount },
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'Search inquiry request logs' })
|
||||
|
||||
@@ -44,6 +44,9 @@ export class InquiryLog {
|
||||
@Prop({ type: Object })
|
||||
attemptSummary?: Record<string, unknown>;
|
||||
|
||||
@Prop({ type: [Object] })
|
||||
outboundRequests?: Record<string, unknown>[];
|
||||
|
||||
createdAt?: Date;
|
||||
}
|
||||
|
||||
|
||||
+6
-1
@@ -3,7 +3,8 @@ import { Logger, ValidationPipe } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||
import { NextFunction, Request, Response } from 'express';
|
||||
import { NextFunction, Request, Response, static as serveStatic } from 'express';
|
||||
import { join } from 'node:path';
|
||||
import { AppModule } from './app.module';
|
||||
import { API_KEY_HEADER } from './common/constants/app.constants';
|
||||
import { OpenTelemetryNestLogger } from './otel-nest-logger';
|
||||
@@ -20,6 +21,10 @@ async function bootstrap(): Promise<void> {
|
||||
Logger.overrideLogger(logger);
|
||||
|
||||
const app = await NestFactory.create(AppModule, { logger });
|
||||
app.enableShutdownHooks();
|
||||
const httpServer = app.getHttpAdapter().getInstance();
|
||||
httpServer.use('/dashboard', serveStatic(join(__dirname, 'public')));
|
||||
httpServer.get('/', (_request: Request, response: Response) => response.redirect('/dashboard/'));
|
||||
const configService = app.get(ConfigService);
|
||||
const port = configService.get<number>('app.port', 8085);
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
import { ProviderConfigSlice } from '../interfaces/provider-config.interface';
|
||||
import {
|
||||
AppErrorCode,
|
||||
ERROR_CATALOG,
|
||||
buildNormalizedError,
|
||||
isAppErrorCode,
|
||||
resolveProviderPublicMessage,
|
||||
@@ -132,8 +133,8 @@ export abstract class BaseProvider<TRequest = unknown, TResponse = unknown>
|
||||
code === 'PROVIDER_ERROR'
|
||||
? resolveProviderPublicMessage(partial.providerMessage ?? partial.message)
|
||||
: {
|
||||
message: partial.message ?? 'Provider request failed',
|
||||
messageFa: partial.messageFa,
|
||||
message: partial.message ?? ERROR_CATALOG[code].message,
|
||||
messageFa: partial.messageFa ?? ERROR_CATALOG[code].messageFa,
|
||||
};
|
||||
|
||||
return buildNormalizedError(code, {
|
||||
@@ -159,7 +160,7 @@ export abstract class BaseProvider<TRequest = unknown, TResponse = unknown>
|
||||
providerMessage?: string,
|
||||
providerCode?: string,
|
||||
fallbackMessage = 'Provider request failed',
|
||||
extras?: Pick<NormalizedErrorDto, 'providerTrackingCode' | 'details' | 'conflict'>,
|
||||
extras?: Pick<NormalizedErrorDto, 'providerTrackingCode' | 'providerCode' | 'details' | 'conflict'>,
|
||||
): Error {
|
||||
const message = providerMessage?.trim() || fallbackMessage;
|
||||
const upstreamCode = providerCode?.trim();
|
||||
|
||||
@@ -21,6 +21,7 @@ import { withRetry } from '../../common/helpers/retry.helper';
|
||||
import { AmitisAuthServiceConfig } from '../../config/configuration';
|
||||
import { GeneralTokenDocument } from '../schemas/general-token.schema';
|
||||
import { GeneralTokenService } from '../services/general-token.service';
|
||||
import { DistributedLockService } from '../services/distributed-lock.service';
|
||||
|
||||
interface CentInsurTokenResponse {
|
||||
Token?: string;
|
||||
@@ -64,6 +65,7 @@ export class AmitisProvider {
|
||||
constructor(
|
||||
configService: ConfigService,
|
||||
private readonly generalTokenService: GeneralTokenService,
|
||||
private readonly distributedLockService: DistributedLockService,
|
||||
) {
|
||||
this.config = configService.get<AmitisAuthServiceConfig>('amitis')!;
|
||||
this.httpClient = createOutboundAxiosInstance({
|
||||
@@ -87,6 +89,7 @@ export class AmitisProvider {
|
||||
inquiryType: InquiryType,
|
||||
username: string,
|
||||
password: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> {
|
||||
const tokenKey = this.getTokenKey(providerName, inquiryType);
|
||||
const latestToken = await this.generalTokenService.getLatestToken(tokenKey);
|
||||
@@ -96,10 +99,17 @@ export class AmitisProvider {
|
||||
return latestToken.accessToken;
|
||||
}
|
||||
|
||||
// Try to refresh if we have a refresh token and it's within 24 hours
|
||||
if (latestToken?.refreshToken && this.isWithin24Hours(latestToken)) {
|
||||
return this.distributedLockService.withLock(
|
||||
`provider-token:${tokenKey}`,
|
||||
async () => {
|
||||
const current = await this.generalTokenService.getLatestToken(tokenKey);
|
||||
if (current && !this.isExpired(current) && this.isWithin24Hours(current)) {
|
||||
return current.accessToken;
|
||||
}
|
||||
|
||||
if (current?.refreshToken && this.isWithin24Hours(current)) {
|
||||
try {
|
||||
return await this.refreshAccessToken(latestToken, providerName, inquiryType);
|
||||
return await this.refreshAccessToken(current, providerName, inquiryType, signal);
|
||||
} catch (error) {
|
||||
this.logger.warn(
|
||||
`AMITIS token refresh failed for ${providerName}/${inquiryType}, requesting a new token: ${
|
||||
@@ -109,8 +119,10 @@ export class AmitisProvider {
|
||||
}
|
||||
}
|
||||
|
||||
// Login to get new token
|
||||
return this.login(providerName, inquiryType, username, password);
|
||||
return this.login(providerName, inquiryType, username, password, signal);
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
}
|
||||
|
||||
private async login(
|
||||
@@ -118,6 +130,7 @@ export class AmitisProvider {
|
||||
inquiryType: InquiryType,
|
||||
username: string,
|
||||
password: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> {
|
||||
const loginBody = new URLSearchParams({
|
||||
username: username.toLowerCase(),
|
||||
@@ -138,6 +151,7 @@ export class AmitisProvider {
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
signal,
|
||||
},
|
||||
),
|
||||
);
|
||||
@@ -161,13 +175,14 @@ export class AmitisProvider {
|
||||
latestToken: GeneralTokenDocument,
|
||||
providerName: ProviderName,
|
||||
inquiryType: InquiryType,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> {
|
||||
try {
|
||||
const response = await this.withGentleAuthRetry(() =>
|
||||
this.httpClient.post<CentInsurTokenResponse>(this.config.refreshPath, {
|
||||
Token: latestToken.accessToken,
|
||||
RefreshToken: latestToken.refreshToken,
|
||||
}),
|
||||
}, { signal }),
|
||||
);
|
||||
const token = this.extractToken(response.data, latestToken.refreshToken);
|
||||
|
||||
|
||||
@@ -88,25 +88,25 @@ export class HamtaProvider extends LegacyApiProvider {
|
||||
context: ProviderExecutionContext,
|
||||
): Promise<LegacyInquiryResult> {
|
||||
if (inquiryType === InquiryType.PERSON) {
|
||||
return this.inquireCivilRegistration(payload as CivilRegistrationPayload);
|
||||
return this.inquireCivilRegistration(payload as CivilRegistrationPayload, context.signal);
|
||||
}
|
||||
|
||||
if (inquiryType === InquiryType.POSTAL_CODE) {
|
||||
return this.inquirePostalCode(payload as PostalCodePayload);
|
||||
return this.inquirePostalCode(payload as PostalCodePayload, context.signal);
|
||||
}
|
||||
|
||||
if (inquiryType === InquiryType.SHAHKAR) {
|
||||
return this.inquireShahkar(payload as ShahkarPayload);
|
||||
return this.inquireShahkar(payload as ShahkarPayload, context.signal);
|
||||
}
|
||||
|
||||
if (inquiryType === InquiryType.SHEBA) {
|
||||
return this.inquireSayah(payload as SayahPayload);
|
||||
return this.inquireSayah(payload as SayahPayload, context.signal);
|
||||
}
|
||||
|
||||
return super.callProvider(inquiryType, payload, context);
|
||||
}
|
||||
|
||||
private async inquirePostalCode(payload: PostalCodePayload): Promise<{ raw: unknown }> {
|
||||
private async inquirePostalCode(payload: PostalCodePayload, signal?: AbortSignal): Promise<{ raw: unknown }> {
|
||||
const postalCode = this.getRequiredString(
|
||||
payload.postalCode ?? payload.PostalCode,
|
||||
'postalCode',
|
||||
@@ -119,6 +119,7 @@ export class HamtaProvider extends LegacyApiProvider {
|
||||
InquiryType.POSTAL_CODE,
|
||||
inquiryConfig.username,
|
||||
inquiryConfig.password,
|
||||
signal,
|
||||
);
|
||||
|
||||
try {
|
||||
@@ -128,6 +129,7 @@ export class HamtaProvider extends LegacyApiProvider {
|
||||
params: { PostalCode: postalCode },
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
timeout: this.hamtaConfig.timeout,
|
||||
signal,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -145,6 +147,7 @@ export class HamtaProvider extends LegacyApiProvider {
|
||||
|
||||
private async inquireCivilRegistration(
|
||||
payload: CivilRegistrationPayload,
|
||||
signal?: AbortSignal,
|
||||
): Promise<PersonInquiryResult> {
|
||||
const nationalCode = this.getRequiredString(
|
||||
payload.nationalCode ?? payload.NIN,
|
||||
@@ -171,6 +174,7 @@ export class HamtaProvider extends LegacyApiProvider {
|
||||
},
|
||||
timeout: this.hamtaConfig.timeout,
|
||||
responseType: 'text',
|
||||
signal,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -196,7 +200,7 @@ export class HamtaProvider extends LegacyApiProvider {
|
||||
}
|
||||
}
|
||||
|
||||
private async inquireShahkar(payload: ShahkarPayload): Promise<{ raw: unknown }> {
|
||||
private async inquireShahkar(payload: ShahkarPayload, signal?: AbortSignal): Promise<{ raw: unknown }> {
|
||||
const nationalCode = this.getRequiredString(
|
||||
payload.nationalCode ?? payload.nationalCod ?? payload.NationalCod,
|
||||
'nationalCode',
|
||||
@@ -221,6 +225,7 @@ export class HamtaProvider extends LegacyApiProvider {
|
||||
},
|
||||
timeout: this.hamtaConfig.timeout,
|
||||
responseType: 'text',
|
||||
signal,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -253,7 +258,7 @@ export class HamtaProvider extends LegacyApiProvider {
|
||||
}
|
||||
}
|
||||
|
||||
private async inquireSayah(payload: SayahPayload): Promise<{ raw: unknown }> {
|
||||
private async inquireSayah(payload: SayahPayload, signal?: AbortSignal): Promise<{ raw: unknown }> {
|
||||
const accountOwnerType = payload.accountOwnerType ?? '1';
|
||||
const nationalId = payload.nationalCode ?? '';
|
||||
const legalId = payload.legalId ?? null;
|
||||
@@ -266,6 +271,7 @@ export class HamtaProvider extends LegacyApiProvider {
|
||||
InquiryType.SHEBA,
|
||||
inquiryConfig.username,
|
||||
inquiryConfig.password,
|
||||
signal,
|
||||
);
|
||||
|
||||
try {
|
||||
@@ -283,6 +289,7 @@ export class HamtaProvider extends LegacyApiProvider {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
timeout: this.hamtaConfig.timeout,
|
||||
signal,
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -100,19 +100,19 @@ export class MoallemProvider extends LegacyApiProvider {
|
||||
context: ProviderExecutionContext,
|
||||
): Promise<LegacyInquiryResult> {
|
||||
if (inquiryType === InquiryType.PERSON) {
|
||||
return this.inquireCivilRegistration(payload as CivilRegistrationPayload);
|
||||
return this.inquireCivilRegistration(payload as CivilRegistrationPayload, context.signal);
|
||||
}
|
||||
|
||||
if (inquiryType === InquiryType.POSTAL_CODE) {
|
||||
return this.inquirePostalCode(payload as PostalCodePayload);
|
||||
return this.inquirePostalCode(payload as PostalCodePayload, context.signal);
|
||||
}
|
||||
|
||||
if (inquiryType === InquiryType.SHAHKAR) {
|
||||
return this.inquireShahkar(payload as ShahkarPayload);
|
||||
return this.inquireShahkar(payload as ShahkarPayload, context.signal);
|
||||
}
|
||||
|
||||
if (inquiryType === InquiryType.SHEBA) {
|
||||
return this.inquireSayah(payload as SayahPayload);
|
||||
return this.inquireSayah(payload as SayahPayload, context.signal);
|
||||
}
|
||||
|
||||
if (inquiryType === InquiryType.CAR_BY_PLATE) {
|
||||
@@ -121,6 +121,7 @@ export class MoallemProvider extends LegacyApiProvider {
|
||||
payload as CarPlatePayload,
|
||||
(message, code, fallback, extras) =>
|
||||
this.formatProviderError(message, code, fallback, extras as never),
|
||||
context.signal,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -130,6 +131,7 @@ export class MoallemProvider extends LegacyApiProvider {
|
||||
payload as CarChassisPayload,
|
||||
(message, code, fallback, extras) =>
|
||||
this.formatProviderError(message, code, fallback, extras as never),
|
||||
context.signal,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -139,13 +141,14 @@ export class MoallemProvider extends LegacyApiProvider {
|
||||
payload as CarPlatePayload,
|
||||
(message, code, fallback, extras) =>
|
||||
this.formatProviderError(message, code, fallback, extras as never),
|
||||
context.signal,
|
||||
);
|
||||
}
|
||||
|
||||
return super.callProvider(inquiryType, payload, context);
|
||||
}
|
||||
|
||||
private async inquirePostalCode(payload: PostalCodePayload): Promise<{ raw: unknown }> {
|
||||
private async inquirePostalCode(payload: PostalCodePayload, signal?: AbortSignal): Promise<{ raw: unknown }> {
|
||||
const postalCode = this.getRequiredString(
|
||||
payload.postalCode ?? payload.PostalCode,
|
||||
'postalCode',
|
||||
@@ -157,6 +160,7 @@ export class MoallemProvider extends LegacyApiProvider {
|
||||
InquiryType.POSTAL_CODE,
|
||||
inquiryConfig.username,
|
||||
inquiryConfig.password,
|
||||
signal,
|
||||
);
|
||||
|
||||
try {
|
||||
@@ -166,6 +170,7 @@ export class MoallemProvider extends LegacyApiProvider {
|
||||
params: { PostalCode: postalCode },
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
timeout: this.moallemConfig.timeout,
|
||||
signal,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -183,6 +188,7 @@ export class MoallemProvider extends LegacyApiProvider {
|
||||
|
||||
private async inquireCivilRegistration(
|
||||
payload: CivilRegistrationPayload,
|
||||
signal?: AbortSignal,
|
||||
): Promise<PersonInquiryResult> {
|
||||
const nationalCode = this.getRequiredString(
|
||||
payload.nationalCode ?? payload.NIN,
|
||||
@@ -209,6 +215,7 @@ export class MoallemProvider extends LegacyApiProvider {
|
||||
},
|
||||
timeout: this.moallemConfig.timeout,
|
||||
responseType: 'text',
|
||||
signal,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -234,7 +241,7 @@ export class MoallemProvider extends LegacyApiProvider {
|
||||
}
|
||||
}
|
||||
|
||||
private async inquireShahkar(payload: ShahkarPayload): Promise<{ raw: unknown }> {
|
||||
private async inquireShahkar(payload: ShahkarPayload, signal?: AbortSignal): Promise<{ raw: unknown }> {
|
||||
const nationalCode = this.getRequiredString(
|
||||
payload.nationalCode ?? payload.nationalCod ?? payload.NationalCod,
|
||||
'nationalCode',
|
||||
@@ -259,6 +266,7 @@ export class MoallemProvider extends LegacyApiProvider {
|
||||
},
|
||||
timeout: this.moallemConfig.timeout,
|
||||
responseType: 'text',
|
||||
signal,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -291,7 +299,7 @@ export class MoallemProvider extends LegacyApiProvider {
|
||||
}
|
||||
}
|
||||
|
||||
private async inquireSayah(payload: SayahPayload): Promise<{ raw: unknown }> {
|
||||
private async inquireSayah(payload: SayahPayload, signal?: AbortSignal): Promise<{ raw: unknown }> {
|
||||
const accountOwnerType = payload.accountOwnerType ?? '1';
|
||||
const nationalId = payload.nationalCode ?? '';
|
||||
const legalId = payload.legalId ?? null;
|
||||
@@ -303,6 +311,7 @@ export class MoallemProvider extends LegacyApiProvider {
|
||||
InquiryType.SHEBA,
|
||||
inquiryConfig.username,
|
||||
inquiryConfig.password,
|
||||
signal,
|
||||
);
|
||||
|
||||
try {
|
||||
@@ -320,6 +329,7 @@ export class MoallemProvider extends LegacyApiProvider {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
timeout: this.moallemConfig.timeout,
|
||||
signal,
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -144,18 +144,18 @@ export class ParsianProvider extends BaseProvider<LegacyInquiryPayload, LegacyIn
|
||||
protected async callProvider(
|
||||
inquiryType: InquiryType,
|
||||
payload: LegacyInquiryPayload,
|
||||
_context: ProviderExecutionContext,
|
||||
context: ProviderExecutionContext,
|
||||
): Promise<LegacyInquiryResult> {
|
||||
if (inquiryType === InquiryType.PERSON) {
|
||||
return this.inquireCivilRegistration(payload as ParsianCivilRegistrationPayload);
|
||||
return this.inquireCivilRegistration(payload as ParsianCivilRegistrationPayload, context.signal);
|
||||
}
|
||||
|
||||
if (inquiryType === InquiryType.SHAHKAR) {
|
||||
return this.inquireShahkar(payload as ParsianShahkarPayload);
|
||||
return this.inquireShahkar(payload as ParsianShahkarPayload, context.signal);
|
||||
}
|
||||
|
||||
if (inquiryType === InquiryType.SHEBA) {
|
||||
return this.inquireSayah(payload as ParsianSayahPayload);
|
||||
return this.inquireSayah(payload as ParsianSayahPayload, context.signal);
|
||||
}
|
||||
|
||||
if (inquiryType === InquiryType.CAR_BY_PLATE) {
|
||||
@@ -164,6 +164,7 @@ export class ParsianProvider extends BaseProvider<LegacyInquiryPayload, LegacyIn
|
||||
payload as CarPlatePayload,
|
||||
(message, code, fallback, extras) =>
|
||||
this.formatProviderError(message, code, fallback, extras as never),
|
||||
context.signal,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -173,28 +174,33 @@ export class ParsianProvider extends BaseProvider<LegacyInquiryPayload, LegacyIn
|
||||
payload as CarChassisPayload,
|
||||
(message, code, fallback, extras) =>
|
||||
this.formatProviderError(message, code, fallback, extras as never),
|
||||
context.signal,
|
||||
);
|
||||
}
|
||||
|
||||
if (inquiryType === InquiryType.THIRD_PARTY_CAR) {
|
||||
return this.centInsurCarSupport.inquireThirdPartyCar(
|
||||
// Parsian third-party plate inquiries must use the one-factor plate
|
||||
// lookup. The national-code policy endpoint is not a substitute: it
|
||||
// can return a different vehicle/policy and creates false matches.
|
||||
return this.centInsurCarSupport.inquireCarByPlate(
|
||||
this.config,
|
||||
payload as CarPlatePayload,
|
||||
(message, code, fallback, extras) =>
|
||||
this.formatProviderError(message, code, fallback, extras as never),
|
||||
context.signal,
|
||||
);
|
||||
}
|
||||
|
||||
if (inquiryType === InquiryType.POLICY_BY_CHASSIS) {
|
||||
return this.inquirePolicyByChassis(payload as ParsianPolicyByChassisPayload);
|
||||
return this.inquirePolicyByChassis(payload as ParsianPolicyByChassisPayload, context.signal);
|
||||
}
|
||||
|
||||
if (inquiryType === InquiryType.POLICY_BY_PLATE) {
|
||||
return this.inquirePolicyByPlate(payload as ParsianPolicyByPlatePayload);
|
||||
return this.inquirePolicyByPlate(payload as ParsianPolicyByPlatePayload, context.signal);
|
||||
}
|
||||
|
||||
if (inquiryType === InquiryType.POLICY_BY_NATIONAL_CODE) {
|
||||
return this.inquirePolicyByNationalCode(payload as ParsianPolicyByNationalCodePayload);
|
||||
return this.inquirePolicyByNationalCode(payload as ParsianPolicyByNationalCodePayload, context.signal);
|
||||
}
|
||||
|
||||
throw this.formatProviderError(
|
||||
@@ -204,7 +210,7 @@ export class ParsianProvider extends BaseProvider<LegacyInquiryPayload, LegacyIn
|
||||
);
|
||||
}
|
||||
|
||||
private async inquireShahkar(payload: ParsianShahkarPayload): Promise<{ raw: unknown }> {
|
||||
private async inquireShahkar(payload: ParsianShahkarPayload, signal?: AbortSignal): Promise<{ raw: unknown }> {
|
||||
const nationalCode = this.getRequiredString(
|
||||
payload.nationalCode ?? payload.nationalCod ?? payload.NationalCod,
|
||||
'nationalCode',
|
||||
@@ -236,6 +242,7 @@ export class ParsianProvider extends BaseProvider<LegacyInquiryPayload, LegacyIn
|
||||
'X-PACKAGE-API-KEY': inquiryConfig.apiKey,
|
||||
},
|
||||
timeout: this.config.timeout,
|
||||
signal,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -274,6 +281,7 @@ export class ParsianProvider extends BaseProvider<LegacyInquiryPayload, LegacyIn
|
||||
|
||||
private async inquireCivilRegistration(
|
||||
payload: ParsianCivilRegistrationPayload,
|
||||
signal?: AbortSignal,
|
||||
): Promise<PersonInquiryResult> {
|
||||
const nationalCode = this.getRequiredString(
|
||||
payload.nationalCode ?? payload.NIN,
|
||||
@@ -307,6 +315,7 @@ export class ParsianProvider extends BaseProvider<LegacyInquiryPayload, LegacyIn
|
||||
},
|
||||
timeout: this.config.timeout,
|
||||
responseType: 'text',
|
||||
signal,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -337,12 +346,14 @@ export class ParsianProvider extends BaseProvider<LegacyInquiryPayload, LegacyIn
|
||||
|
||||
private async inquirePolicyByChassis(
|
||||
payload: ParsianPolicyByChassisPayload,
|
||||
signal?: AbortSignal,
|
||||
): Promise<{ raw: unknown }> {
|
||||
const chassisNo = this.getRequiredString(payload.chassisNo, 'chassisNo');
|
||||
const policy = await this.callCarPolicySoap(
|
||||
InquiryType.POLICY_BY_CHASSIS,
|
||||
'CIIWSPolicyChassis',
|
||||
{ ChassisNo: chassisNo },
|
||||
signal,
|
||||
);
|
||||
|
||||
return {
|
||||
@@ -355,12 +366,14 @@ export class ParsianProvider extends BaseProvider<LegacyInquiryPayload, LegacyIn
|
||||
|
||||
private async inquirePolicyByNationalCode(
|
||||
payload: ParsianPolicyByNationalCodePayload,
|
||||
signal?: AbortSignal,
|
||||
): Promise<{ raw: unknown }> {
|
||||
const nationalCode = this.getRequiredString(payload.nationalCode, 'nationalCode');
|
||||
const policy = await this.callCarPolicySoap(
|
||||
InquiryType.POLICY_BY_NATIONAL_CODE,
|
||||
'CIIWSPolicyNationalId',
|
||||
{ NationalId: nationalCode },
|
||||
signal,
|
||||
);
|
||||
|
||||
return {
|
||||
@@ -373,6 +386,7 @@ export class ParsianProvider extends BaseProvider<LegacyInquiryPayload, LegacyIn
|
||||
|
||||
private async inquirePolicyByPlate(
|
||||
payload: ParsianPolicyByPlatePayload,
|
||||
signal?: AbortSignal,
|
||||
): Promise<{ raw: unknown }> {
|
||||
const nationalCode = this.getRequiredString(payload.nationalCode, 'nationalCode');
|
||||
const plk1 = this.getRequiredString(payload.plk1, 'plk1');
|
||||
@@ -383,6 +397,7 @@ export class ParsianProvider extends BaseProvider<LegacyInquiryPayload, LegacyIn
|
||||
InquiryType.POLICY_BY_PLATE,
|
||||
'CIIWSPolicyVehicleMeli',
|
||||
{ Plk1: plk1, Plk2: plk2, Plk3: plk3, PlkSrl: plksrl },
|
||||
signal,
|
||||
);
|
||||
|
||||
assertCarPolicyOwnedBy(nationalCode, policy, (message, code, fallback, extras) =>
|
||||
@@ -405,6 +420,7 @@ export class ParsianProvider extends BaseProvider<LegacyInquiryPayload, LegacyIn
|
||||
inquiryType: InquiryType,
|
||||
methodName: string,
|
||||
fields: Record<string, string>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Record<string, string>> {
|
||||
const inquiryConfig = this.config.inquiries[inquiryType];
|
||||
|
||||
@@ -432,13 +448,16 @@ export class ParsianProvider extends BaseProvider<LegacyInquiryPayload, LegacyIn
|
||||
},
|
||||
timeout: this.config.timeout,
|
||||
responseType: 'text',
|
||||
signal,
|
||||
}),
|
||||
);
|
||||
|
||||
const policy = parseFirstCarPolicy(response.data);
|
||||
const providerError = getCarPolicyProviderError(response.data, policy);
|
||||
if (providerError) {
|
||||
throw this.formatProviderError(providerError.message, providerError.code);
|
||||
throw this.formatProviderError(providerError.message, providerError.code, undefined, {
|
||||
providerCode: providerError.providerCode,
|
||||
});
|
||||
}
|
||||
|
||||
return policy;
|
||||
@@ -453,7 +472,7 @@ export class ParsianProvider extends BaseProvider<LegacyInquiryPayload, LegacyIn
|
||||
}
|
||||
}
|
||||
|
||||
private async inquireSayah(payload: ParsianSayahPayload): Promise<{ raw: unknown }> {
|
||||
private async inquireSayah(payload: ParsianSayahPayload, signal?: AbortSignal): Promise<{ raw: unknown }> {
|
||||
const accountOwnerType = payload.accountOwnerType ?? '1';
|
||||
const nationalId = payload.nationalCode ?? '';
|
||||
const legalId = payload.legalId ?? null;
|
||||
@@ -473,6 +492,7 @@ export class ParsianProvider extends BaseProvider<LegacyInquiryPayload, LegacyIn
|
||||
InquiryType.SHEBA,
|
||||
inquiryConfig.username,
|
||||
inquiryConfig.password,
|
||||
signal,
|
||||
);
|
||||
|
||||
try {
|
||||
@@ -490,6 +510,7 @@ export class ParsianProvider extends BaseProvider<LegacyInquiryPayload, LegacyIn
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
timeout: this.config.timeout,
|
||||
signal,
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -443,7 +443,10 @@ export class TejaratNouProvider implements InquiryProvider<LegacyInquiryPayload,
|
||||
body: Record<string, unknown> | undefined,
|
||||
context: ProviderExecutionContext,
|
||||
): Promise<T> {
|
||||
const token = await this.generalTokenService.getTejaratNouAccessToken(this.config);
|
||||
const token = await this.generalTokenService.getTejaratNouAccessToken(
|
||||
this.config,
|
||||
context.signal,
|
||||
);
|
||||
|
||||
try {
|
||||
const response = await this.httpClient.request<TejaratNouGatewayResponse<T>>({
|
||||
@@ -454,6 +457,7 @@ export class TejaratNouProvider implements InquiryProvider<LegacyInquiryPayload,
|
||||
Authorization: `Bearer ${token}`,
|
||||
Accept: 'text/plain',
|
||||
},
|
||||
signal: context.signal,
|
||||
});
|
||||
|
||||
const envelope = response.data;
|
||||
|
||||
@@ -7,6 +7,7 @@ import { ParsianProvider } from './implementations/parsian.provider';
|
||||
import { TejaratNouProvider } from './implementations/tejaratnou.provider';
|
||||
import { AmitisProvider } from './implementations/amitis.provider';
|
||||
import { ProviderOrchestratorService } from './strategy/provider-orchestrator.service';
|
||||
import { ProviderIsolationService } from './strategy/provider-isolation.service';
|
||||
import { GeneralToken, GeneralTokenSchema } from './schemas/general-token.schema';
|
||||
import {
|
||||
InquiryResultCache,
|
||||
@@ -16,6 +17,8 @@ import { CentInsurCarPolicyClient } from './shared/centinsur-car-policy.client';
|
||||
import { CentInsurCarProviderSupport } from './shared/centinsur-car-provider.support';
|
||||
import { GeneralTokenService } from './services/general-token.service';
|
||||
import { InquiryResultCacheService } from './services/inquiry-result-cache.service';
|
||||
import { DistributedLockService } from './services/distributed-lock.service';
|
||||
import { DistributedLock, DistributedLockSchema } from './schemas/distributed-lock.schema';
|
||||
|
||||
/**
|
||||
* Provider adapters, factory, and orchestration strategy.
|
||||
@@ -25,6 +28,7 @@ import { InquiryResultCacheService } from './services/inquiry-result-cache.servi
|
||||
MongooseModule.forFeature([
|
||||
{ name: GeneralToken.name, schema: GeneralTokenSchema },
|
||||
{ name: InquiryResultCache.name, schema: InquiryResultCacheSchema },
|
||||
{ name: DistributedLock.name, schema: DistributedLockSchema },
|
||||
]),
|
||||
],
|
||||
providers: [
|
||||
@@ -35,16 +39,19 @@ import { InquiryResultCacheService } from './services/inquiry-result-cache.servi
|
||||
AmitisProvider,
|
||||
GeneralTokenService,
|
||||
InquiryResultCacheService,
|
||||
DistributedLockService,
|
||||
CentInsurCarPolicyClient,
|
||||
CentInsurCarProviderSupport,
|
||||
ProviderFactory,
|
||||
ProviderOrchestratorService,
|
||||
ProviderIsolationService,
|
||||
],
|
||||
exports: [
|
||||
ProviderFactory,
|
||||
ProviderOrchestratorService,
|
||||
GeneralTokenService,
|
||||
InquiryResultCacheService,
|
||||
DistributedLockService,
|
||||
],
|
||||
})
|
||||
export class ProvidersModule {}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
|
||||
import { HydratedDocument } from 'mongoose';
|
||||
|
||||
export type DistributedLockDocument = HydratedDocument<DistributedLock>;
|
||||
|
||||
@Schema({ timestamps: true, collection: 'distributed_locks' })
|
||||
export class DistributedLock {
|
||||
@Prop({ required: true, unique: true, index: true })
|
||||
lockKey!: string;
|
||||
|
||||
@Prop({ required: true })
|
||||
ownerId!: string;
|
||||
|
||||
@Prop({ required: true, index: true })
|
||||
leaseUntil!: Date;
|
||||
|
||||
@Prop({ required: true, default: 0 })
|
||||
fencingToken!: number;
|
||||
}
|
||||
|
||||
export const DistributedLockSchema = SchemaFactory.createForClass(DistributedLock);
|
||||
@@ -0,0 +1,144 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectModel } from '@nestjs/mongoose';
|
||||
import { Model } from 'mongoose';
|
||||
import {
|
||||
DistributedLock,
|
||||
DistributedLockDocument,
|
||||
} from '../schemas/distributed-lock.schema';
|
||||
|
||||
export interface LockOptions {
|
||||
leaseMs?: number;
|
||||
waitMs?: number;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export interface LockLease {
|
||||
lockKey: string;
|
||||
ownerId: string;
|
||||
fencingToken: number;
|
||||
}
|
||||
|
||||
const DEFAULT_LEASE_MS = 60_000;
|
||||
const DEFAULT_WAIT_MS = 10_000;
|
||||
|
||||
@Injectable()
|
||||
export class DistributedLockService {
|
||||
constructor(
|
||||
@InjectModel(DistributedLock.name)
|
||||
private readonly lockModel: Model<DistributedLockDocument>,
|
||||
) {}
|
||||
|
||||
async acquire(
|
||||
lockKey: string,
|
||||
ownerId = randomUUID(),
|
||||
leaseMs = DEFAULT_LEASE_MS,
|
||||
): Promise<LockLease | null> {
|
||||
const now = new Date();
|
||||
try {
|
||||
const lock = await this.lockModel
|
||||
.findOneAndUpdate(
|
||||
{
|
||||
lockKey,
|
||||
$or: [{ leaseUntil: { $lte: now } }, { leaseUntil: { $exists: false } }],
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
lockKey,
|
||||
ownerId,
|
||||
leaseUntil: new Date(now.getTime() + leaseMs),
|
||||
},
|
||||
$inc: { fencingToken: 1 },
|
||||
},
|
||||
{ new: true, upsert: true, setDefaultsOnInsert: true },
|
||||
)
|
||||
.exec();
|
||||
|
||||
if (!lock || lock.ownerId !== ownerId) return null;
|
||||
return {
|
||||
lockKey,
|
||||
ownerId,
|
||||
fencingToken: lock.fencingToken,
|
||||
};
|
||||
} catch (error) {
|
||||
if (this.isDuplicateKey(error)) return null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async release(lease: LockLease): Promise<void> {
|
||||
await this.lockModel
|
||||
.updateOne(
|
||||
{ lockKey: lease.lockKey, ownerId: lease.ownerId },
|
||||
{ $set: { leaseUntil: new Date(0) } },
|
||||
)
|
||||
.exec();
|
||||
}
|
||||
|
||||
async withLock<T>(
|
||||
lockKey: string,
|
||||
operation: () => Promise<T>,
|
||||
options: LockOptions = {},
|
||||
): Promise<T> {
|
||||
const leaseMs = options.leaseMs ?? DEFAULT_LEASE_MS;
|
||||
const waitMs = options.waitMs ?? DEFAULT_WAIT_MS;
|
||||
const ownerId = randomUUID();
|
||||
const deadline = Date.now() + waitMs;
|
||||
|
||||
while (Date.now() <= deadline) {
|
||||
if (options.signal?.aborted) {
|
||||
throw this.createAbortError();
|
||||
}
|
||||
|
||||
const lease = await this.acquire(lockKey, ownerId, leaseMs);
|
||||
if (lease) {
|
||||
try {
|
||||
return await operation();
|
||||
} finally {
|
||||
await this.release(lease);
|
||||
}
|
||||
}
|
||||
|
||||
await this.sleep(Math.min(100, Math.max(1, deadline - Date.now())), options.signal);
|
||||
}
|
||||
|
||||
const error = new Error(`Could not acquire distributed lock: ${lockKey}`);
|
||||
(error as NodeJS.ErrnoException).code = 'ELOCKED';
|
||||
throw error;
|
||||
}
|
||||
|
||||
private sleep(ms: number, signal?: AbortSignal): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let timer: NodeJS.Timeout;
|
||||
const cleanup = () => {
|
||||
if (signal) signal.removeEventListener('abort', onAbort);
|
||||
clearTimeout(timer);
|
||||
};
|
||||
const onAbort = () => {
|
||||
cleanup();
|
||||
reject(this.createAbortError());
|
||||
};
|
||||
timer = setTimeout(() => {
|
||||
cleanup();
|
||||
resolve();
|
||||
}, ms);
|
||||
if (!signal) return;
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
private createAbortError(): Error {
|
||||
const error = new Error('Lock acquisition aborted');
|
||||
(error as NodeJS.ErrnoException).code = 'ECANCELED';
|
||||
return error;
|
||||
}
|
||||
|
||||
private isDuplicateKey(error: unknown): boolean {
|
||||
return Boolean(
|
||||
error &&
|
||||
typeof error === 'object' &&
|
||||
'code' in error &&
|
||||
(error as { code?: number }).code === 11000,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
import { withRetry } from '../../common/helpers/retry.helper';
|
||||
import { GeneralToken, GeneralTokenDocument } from '../schemas/general-token.schema';
|
||||
import { TejaratNouConfig } from '../interfaces/tejaratnou-config.interface';
|
||||
import { DistributedLockService } from './distributed-lock.service';
|
||||
|
||||
export interface OAuthTokenResponse {
|
||||
accessToken: string;
|
||||
@@ -29,6 +30,7 @@ export class GeneralTokenService {
|
||||
constructor(
|
||||
@InjectModel(GeneralToken.name)
|
||||
private readonly generalTokenModel: Model<GeneralTokenDocument>,
|
||||
private readonly distributedLockService: DistributedLockService,
|
||||
) {}
|
||||
|
||||
async getLatestToken(serviceProvider: string): Promise<GeneralTokenDocument | null> {
|
||||
@@ -50,12 +52,13 @@ export class GeneralTokenService {
|
||||
*/
|
||||
async getValidAccessToken(
|
||||
serviceProvider: string,
|
||||
fetchNewToken: () => Promise<OAuthTokenResponse>,
|
||||
fetchNewToken: (signal?: AbortSignal) => Promise<OAuthTokenResponse>,
|
||||
persistContext: {
|
||||
url: string;
|
||||
clientId: string;
|
||||
username: string;
|
||||
},
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> {
|
||||
const latest = await this.getLatestToken(serviceProvider);
|
||||
if (latest && !(await this.isTokenExpired(latest))) {
|
||||
@@ -63,7 +66,15 @@ export class GeneralTokenService {
|
||||
return latest.accessToken;
|
||||
}
|
||||
|
||||
const fresh = await fetchNewToken();
|
||||
return this.distributedLockService.withLock(
|
||||
`provider-token:${serviceProvider}`,
|
||||
async () => {
|
||||
const current = await this.getLatestToken(serviceProvider);
|
||||
if (current && !(await this.isTokenExpired(current))) {
|
||||
return current.accessToken;
|
||||
}
|
||||
|
||||
const fresh = await fetchNewToken(signal);
|
||||
const expiresAt = new Date(Date.now() + fresh.expiresIn * 1000);
|
||||
|
||||
await this.generalTokenModel.create({
|
||||
@@ -80,6 +91,9 @@ export class GeneralTokenService {
|
||||
|
||||
this.logger.log(`Stored new ${serviceProvider} token, expires at ${expiresAt.toISOString()}`);
|
||||
return fresh.accessToken;
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
}
|
||||
|
||||
/** Persist a provider token (AMITIS and other non-OAuth flows). Credentials stay in env. */
|
||||
@@ -99,10 +113,13 @@ export class GeneralTokenService {
|
||||
}
|
||||
|
||||
/** OAuth2 password grant for Tejarat No identity gateway. */
|
||||
async getTejaratNouAccessToken(config: TejaratNouConfig): Promise<string> {
|
||||
async getTejaratNouAccessToken(
|
||||
config: TejaratNouConfig,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> {
|
||||
return this.getValidAccessToken(
|
||||
'TejaratNou',
|
||||
async () => {
|
||||
async (requestSignal) => {
|
||||
const response = await withRetry(
|
||||
() =>
|
||||
axios.post(
|
||||
@@ -118,6 +135,7 @@ export class GeneralTokenService {
|
||||
mergeOutboundAxiosConfig({
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
timeout: config.timeout,
|
||||
signal: requestSignal,
|
||||
}),
|
||||
),
|
||||
{
|
||||
@@ -146,6 +164,7 @@ export class GeneralTokenService {
|
||||
clientId: config.clientId,
|
||||
username: config.username,
|
||||
},
|
||||
signal,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ export class CentInsurCarPolicyClient {
|
||||
config: ProviderEnvConfig,
|
||||
inquiryType: InquiryType,
|
||||
chassisNo: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Record<string, string>> {
|
||||
return this.callSoap(
|
||||
config,
|
||||
@@ -28,6 +29,7 @@ export class CentInsurCarPolicyClient {
|
||||
InquiryType.POLICY_BY_CHASSIS,
|
||||
'CIIWSPolicyChassis',
|
||||
{ ChassisNo: chassisNo },
|
||||
signal,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -35,6 +37,7 @@ export class CentInsurCarPolicyClient {
|
||||
config: ProviderEnvConfig,
|
||||
inquiryType: InquiryType,
|
||||
plate: CarPlateSoapFields,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Record<string, string>> {
|
||||
return this.callSoap(
|
||||
config,
|
||||
@@ -47,6 +50,7 @@ export class CentInsurCarPolicyClient {
|
||||
Plk3: plate.plk3,
|
||||
PlkSrl: plate.plksrl,
|
||||
},
|
||||
signal,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -54,6 +58,7 @@ export class CentInsurCarPolicyClient {
|
||||
config: ProviderEnvConfig,
|
||||
inquiryType: InquiryType,
|
||||
nationalCode: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Record<string, string>> {
|
||||
return this.callSoap(
|
||||
config,
|
||||
@@ -61,6 +66,7 @@ export class CentInsurCarPolicyClient {
|
||||
InquiryType.POLICY_BY_NATIONAL_CODE,
|
||||
'CIIWSPolicyNationalId',
|
||||
{ NationalId: nationalCode },
|
||||
signal,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -70,6 +76,7 @@ export class CentInsurCarPolicyClient {
|
||||
fallbackInquiryType: InquiryType,
|
||||
methodName: string,
|
||||
fields: Record<string, string>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Record<string, string>> {
|
||||
const inquiryConfig = this.resolveInquiryConfig(config, inquiryType, fallbackInquiryType);
|
||||
|
||||
@@ -93,6 +100,7 @@ export class CentInsurCarPolicyClient {
|
||||
},
|
||||
timeout: config.timeout,
|
||||
responseType: 'text',
|
||||
signal,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -100,9 +108,10 @@ export class CentInsurCarPolicyClient {
|
||||
const providerError = getCarPolicyProviderError(response.data, policy);
|
||||
if (providerError) {
|
||||
const error = new Error(providerError.message);
|
||||
(error as Error & { normalizedError: { code: string; message: string } }).normalizedError = {
|
||||
(error as Error & { normalizedError: { code: string; message: string; providerCode?: string } }).normalizedError = {
|
||||
code: providerError.code,
|
||||
message: providerError.message,
|
||||
providerCode: providerError.providerCode,
|
||||
};
|
||||
throw error;
|
||||
}
|
||||
@@ -110,11 +119,13 @@ export class CentInsurCarPolicyClient {
|
||||
return policy;
|
||||
} catch (error) {
|
||||
if (error instanceof AxiosError) {
|
||||
const providerStatus = String(error.response?.status ?? 'NETWORK_ERROR');
|
||||
const wrapped = new Error(error.message);
|
||||
(wrapped as Error & { normalizedError: { code: string; message: string } }).normalizedError =
|
||||
(wrapped as Error & { normalizedError: { code: string; message: string; providerCode?: string } }).normalizedError =
|
||||
{
|
||||
code: String(error.response?.status ?? 'NETWORK_ERROR'),
|
||||
code: error.response ? 'PROVIDER_ERROR' : providerStatus,
|
||||
message: error.message,
|
||||
providerCode: error.response ? providerStatus : undefined,
|
||||
};
|
||||
throw wrapped;
|
||||
}
|
||||
|
||||
@@ -34,6 +34,7 @@ export class CentInsurCarProviderSupport {
|
||||
config: ProviderEnvConfig,
|
||||
payload: CarPlatePayload,
|
||||
formatError: ErrorFormatter,
|
||||
signal?: AbortSignal,
|
||||
): Promise<{ raw: unknown }> {
|
||||
const nationalCode = this.getRequiredString(payload.nationalCode, 'nationalCode', formatError);
|
||||
const plate = {
|
||||
@@ -47,6 +48,7 @@ export class CentInsurCarProviderSupport {
|
||||
config,
|
||||
InquiryType.CAR_BY_PLATE,
|
||||
plate,
|
||||
signal,
|
||||
);
|
||||
|
||||
assertCarPolicyOwnedBy(nationalCode, policy, formatError);
|
||||
@@ -64,6 +66,7 @@ export class CentInsurCarProviderSupport {
|
||||
config: ProviderEnvConfig,
|
||||
payload: CarChassisPayload,
|
||||
formatError: ErrorFormatter,
|
||||
signal?: AbortSignal,
|
||||
): Promise<{ raw: unknown }> {
|
||||
const nationalCode = this.getRequiredString(payload.nationalCode, 'nationalCode', formatError);
|
||||
const chassisNo = this.getRequiredString(payload.chassisNo, 'chassisNo', formatError);
|
||||
@@ -71,6 +74,7 @@ export class CentInsurCarProviderSupport {
|
||||
config,
|
||||
InquiryType.CAR_BY_CHASSIS,
|
||||
chassisNo,
|
||||
signal,
|
||||
);
|
||||
|
||||
assertCarPolicyOwnedBy(nationalCode, policy, formatError);
|
||||
@@ -88,6 +92,7 @@ export class CentInsurCarProviderSupport {
|
||||
config: ProviderEnvConfig,
|
||||
payload: CarPlatePayload,
|
||||
formatError: ErrorFormatter,
|
||||
signal?: AbortSignal,
|
||||
): Promise<{ raw: unknown }> {
|
||||
const input = {
|
||||
nationalCode: this.getRequiredString(payload.nationalCode, 'nationalCode', formatError),
|
||||
@@ -99,12 +104,13 @@ export class CentInsurCarProviderSupport {
|
||||
|
||||
const resolved = await resolveThirdPartyCarPolicy(input, {
|
||||
byPlate: async () =>
|
||||
this.carPolicyClient.inquireByPlate(config, InquiryType.THIRD_PARTY_CAR, input),
|
||||
this.carPolicyClient.inquireByPlate(config, InquiryType.THIRD_PARTY_CAR, input, signal),
|
||||
byNationalCode: async () =>
|
||||
this.carPolicyClient.inquireByNationalCode(
|
||||
config,
|
||||
InquiryType.THIRD_PARTY_CAR,
|
||||
input.nationalCode,
|
||||
signal,
|
||||
),
|
||||
});
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ export type LegacyAuthTokenResolver = (
|
||||
inquiryType: InquiryType,
|
||||
username: string,
|
||||
password: string,
|
||||
signal?: AbortSignal,
|
||||
) => Promise<string>;
|
||||
|
||||
/**
|
||||
@@ -69,18 +70,19 @@ export abstract class LegacyApiProvider extends BaseProvider<
|
||||
protected async callProvider(
|
||||
inquiryType: InquiryType,
|
||||
payload: LegacyInquiryPayload,
|
||||
_context: ProviderExecutionContext,
|
||||
context: ProviderExecutionContext,
|
||||
): Promise<LegacyInquiryResult> {
|
||||
if (inquiryType === InquiryType.PERSON) {
|
||||
return this.inquirePerson(payload as unknown as PersonInquiryPayload, inquiryType);
|
||||
return this.inquirePerson(payload as unknown as PersonInquiryPayload, inquiryType, context.signal);
|
||||
}
|
||||
|
||||
return this.inquireGeneric(inquiryType, payload);
|
||||
return this.inquireGeneric(inquiryType, payload, context.signal);
|
||||
}
|
||||
|
||||
protected async inquirePerson(
|
||||
payload: PersonInquiryPayload,
|
||||
inquiryType: InquiryType,
|
||||
signal?: AbortSignal,
|
||||
): Promise<PersonInquiryResult> {
|
||||
const inquiryConfig = this.getInquiryConfig(inquiryType);
|
||||
|
||||
@@ -91,7 +93,7 @@ export abstract class LegacyApiProvider extends BaseProvider<
|
||||
nationalCode: payload.nationalCode,
|
||||
birthDate: payload.birthDate,
|
||||
},
|
||||
await this.buildRequestConfig(inquiryType, inquiryConfig),
|
||||
await this.buildRequestConfig(inquiryType, inquiryConfig, signal),
|
||||
);
|
||||
|
||||
const body = response.data;
|
||||
@@ -121,6 +123,7 @@ export abstract class LegacyApiProvider extends BaseProvider<
|
||||
protected async inquireGeneric(
|
||||
inquiryType: InquiryType,
|
||||
payload: LegacyInquiryPayload,
|
||||
signal?: AbortSignal,
|
||||
): Promise<{ raw: unknown }> {
|
||||
const inquiryConfig = this.getInquiryConfig(inquiryType);
|
||||
|
||||
@@ -131,7 +134,7 @@ export abstract class LegacyApiProvider extends BaseProvider<
|
||||
const response = await this.httpClient.post<LegacyProviderApiResponse>(
|
||||
inquiryConfig.url,
|
||||
requestPayload,
|
||||
await this.buildRequestConfig(inquiryType, inquiryConfig),
|
||||
await this.buildRequestConfig(inquiryType, inquiryConfig, signal),
|
||||
);
|
||||
|
||||
const body = response.data;
|
||||
@@ -239,17 +242,19 @@ export abstract class LegacyApiProvider extends BaseProvider<
|
||||
private async buildRequestConfig(
|
||||
inquiryType: InquiryType,
|
||||
inquiryConfig: InquiryConfig,
|
||||
signal?: AbortSignal,
|
||||
): Promise<{
|
||||
headers?: Record<string, string>;
|
||||
signal?: AbortSignal;
|
||||
}> {
|
||||
// No authentication required
|
||||
if (inquiryConfig.authMethod === 'NONE') {
|
||||
return {};
|
||||
return { signal };
|
||||
}
|
||||
|
||||
// SOAP authentication is handled by subclasses (e.g., Shahkar)
|
||||
if (inquiryConfig.authMethod === 'SOAP') {
|
||||
return {};
|
||||
return { signal };
|
||||
}
|
||||
|
||||
// AMITIS token-based authentication
|
||||
@@ -275,12 +280,14 @@ export abstract class LegacyApiProvider extends BaseProvider<
|
||||
inquiryType,
|
||||
inquiryConfig.username,
|
||||
inquiryConfig.password,
|
||||
signal,
|
||||
);
|
||||
|
||||
return {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
signal,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import { HttpStatus, Injectable } from '@nestjs/common';
|
||||
import { ProviderName } from '../../common/enums/provider-name.enum';
|
||||
import { buildNormalizedError } from '../../common/constants/error-messages';
|
||||
import { InquiryException } from '../../common/exceptions/inquiry.exception';
|
||||
|
||||
interface ProviderState {
|
||||
active: number;
|
||||
consecutiveFailures: number;
|
||||
openUntil: number;
|
||||
halfOpenProbeInFlight: boolean;
|
||||
}
|
||||
|
||||
const DEFAULT_FAILURE_THRESHOLD = 5;
|
||||
const DEFAULT_OPEN_MS = 30_000;
|
||||
const DEFAULT_BULKHEAD_LIMIT = 16;
|
||||
|
||||
/**
|
||||
* Process-local provider isolation. Each deployed gateway has its own provider
|
||||
* boundary, so local bulkheads avoid one slow upstream exhausting this process.
|
||||
* A distributed circuit state is intentionally not required for correctness;
|
||||
* fallbacks remain the source of truth across gateway instances.
|
||||
*/
|
||||
@Injectable()
|
||||
export class ProviderIsolationService {
|
||||
private readonly states = new Map<ProviderName, ProviderState>();
|
||||
private readonly failureThreshold = this.readPositiveEnv(
|
||||
'PROVIDER_CIRCUIT_FAILURE_THRESHOLD',
|
||||
DEFAULT_FAILURE_THRESHOLD,
|
||||
);
|
||||
private readonly openMs = this.readPositiveEnv('PROVIDER_CIRCUIT_OPEN_MS', DEFAULT_OPEN_MS);
|
||||
private readonly bulkheadLimit = this.readPositiveEnv(
|
||||
'PROVIDER_BULKHEAD_LIMIT',
|
||||
DEFAULT_BULKHEAD_LIMIT,
|
||||
);
|
||||
|
||||
async execute<T>(provider: ProviderName, operation: () => Promise<T>): Promise<T> {
|
||||
const state = this.getState(provider);
|
||||
const now = Date.now();
|
||||
|
||||
if (state.active >= this.bulkheadLimit) {
|
||||
throw this.createIsolationError('PROVIDER_BULKHEAD_FULL', provider);
|
||||
}
|
||||
|
||||
if (state.openUntil > now) {
|
||||
throw this.createIsolationError('PROVIDER_CIRCUIT_OPEN', provider);
|
||||
}
|
||||
|
||||
const halfOpen = state.openUntil > 0;
|
||||
if (halfOpen && state.halfOpenProbeInFlight) {
|
||||
throw this.createIsolationError('PROVIDER_CIRCUIT_OPEN', provider);
|
||||
}
|
||||
|
||||
state.active += 1;
|
||||
if (halfOpen) state.halfOpenProbeInFlight = true;
|
||||
|
||||
try {
|
||||
const result = await operation();
|
||||
state.consecutiveFailures = 0;
|
||||
state.openUntil = 0;
|
||||
state.halfOpenProbeInFlight = false;
|
||||
return result;
|
||||
} catch (error) {
|
||||
if (halfOpen) {
|
||||
state.openUntil = Date.now() + this.openMs;
|
||||
} else if (this.shouldCountFailure(error)) {
|
||||
state.consecutiveFailures += 1;
|
||||
if (state.consecutiveFailures >= this.failureThreshold) {
|
||||
state.openUntil = Date.now() + this.openMs;
|
||||
}
|
||||
}
|
||||
state.halfOpenProbeInFlight = false;
|
||||
throw error;
|
||||
} finally {
|
||||
state.active = Math.max(0, state.active - 1);
|
||||
}
|
||||
}
|
||||
|
||||
snapshot(provider: ProviderName): {
|
||||
active: number;
|
||||
consecutiveFailures: number;
|
||||
openUntil: number;
|
||||
} {
|
||||
const state = this.getState(provider);
|
||||
return {
|
||||
active: state.active,
|
||||
consecutiveFailures: state.consecutiveFailures,
|
||||
openUntil: state.openUntil,
|
||||
};
|
||||
}
|
||||
|
||||
private getState(provider: ProviderName): ProviderState {
|
||||
const existing = this.states.get(provider);
|
||||
if (existing) return existing;
|
||||
const state: ProviderState = {
|
||||
active: 0,
|
||||
consecutiveFailures: 0,
|
||||
openUntil: 0,
|
||||
halfOpenProbeInFlight: false,
|
||||
};
|
||||
this.states.set(provider, state);
|
||||
return state;
|
||||
}
|
||||
|
||||
private shouldCountFailure(error: unknown): boolean {
|
||||
if (!error || typeof error !== 'object') return false;
|
||||
const normalized = (error as { normalizedError?: { code?: string } }).normalizedError;
|
||||
const code = normalized?.code;
|
||||
if (code === 'PROVIDER_ERROR') {
|
||||
const providerCode = (normalized as { providerCode?: string } | undefined)?.providerCode;
|
||||
return Boolean(providerCode && /^(408|429|499|5\d\d|ETIMEDOUT|ECONNRESET|NETWORK_ERROR)$/.test(providerCode));
|
||||
}
|
||||
return (
|
||||
code === 'PROVIDER_TIMEOUT' ||
|
||||
code === 'PROVIDER_NETWORK_ERROR' ||
|
||||
code === 'PROVIDER_BAD_RESPONSE'
|
||||
);
|
||||
}
|
||||
|
||||
private createIsolationError(
|
||||
code: 'PROVIDER_CIRCUIT_OPEN' | 'PROVIDER_BULKHEAD_FULL',
|
||||
provider: ProviderName,
|
||||
): InquiryException {
|
||||
return new InquiryException(
|
||||
code === 'PROVIDER_CIRCUIT_OPEN'
|
||||
? `${provider} circuit is open`
|
||||
: `${provider} bulkhead capacity reached`,
|
||||
buildNormalizedError(code, { providerCode: code }),
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
provider,
|
||||
);
|
||||
}
|
||||
|
||||
private readPositiveEnv(name: string, fallback: number): number {
|
||||
const value = Number.parseInt(process.env[name] ?? '', 10);
|
||||
return Number.isFinite(value) && value > 0 ? value : fallback;
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { NormalizedErrorDto } from '../../common/dto/normalized-error.dto';
|
||||
import { ProviderExecutionContext } from '../../common/interfaces/inquiry-provider.interface';
|
||||
import { InquiryException } from '../../common/exceptions/inquiry.exception';
|
||||
import { ProviderFactory } from '../factory/provider.factory';
|
||||
import { ProviderIsolationService } from './provider-isolation.service';
|
||||
import { translateError } from '../../common/helpers/translate-error.helper';
|
||||
import {
|
||||
AppErrorCode,
|
||||
@@ -19,6 +20,7 @@ import {
|
||||
createAttemptTrail,
|
||||
toAttemptErrorFields,
|
||||
} from '../../common/helpers/provider-resilience.helper';
|
||||
import { runWithOutboundTrace } from '../../common/helpers/http-client.helper';
|
||||
|
||||
export interface OrchestrationResult<T> {
|
||||
data: T;
|
||||
@@ -31,6 +33,7 @@ export interface OrchestrationResult<T> {
|
||||
const NON_FALLBACK_ERROR_CODES = new Set<string>([
|
||||
'INQUIRY_NO_MATCH',
|
||||
'RECORD_NOT_FOUND',
|
||||
'CAR_POLICY_NOT_FOUND',
|
||||
'SHEBA_MISMATCH',
|
||||
'VALIDATION_ERROR',
|
||||
'UNSUPPORTED_INQUIRY',
|
||||
@@ -45,7 +48,10 @@ const NON_FALLBACK_ERROR_CODES = new Set<string>([
|
||||
export class ProviderOrchestratorService {
|
||||
private readonly logger = new Logger(ProviderOrchestratorService.name);
|
||||
|
||||
constructor(private readonly providerFactory: ProviderFactory) {}
|
||||
constructor(
|
||||
private readonly providerFactory: ProviderFactory,
|
||||
private readonly providerIsolation: ProviderIsolationService,
|
||||
) {}
|
||||
|
||||
async executeWithFallback<TRequest, TResponse>(
|
||||
inquiryType: InquiryType,
|
||||
@@ -67,6 +73,7 @@ export class ProviderOrchestratorService {
|
||||
...context,
|
||||
deadlineAt,
|
||||
attemptTrail: context.attemptTrail ?? createAttemptTrail(),
|
||||
outboundRequests: context.outboundRequests ?? [],
|
||||
};
|
||||
|
||||
const errors: NormalizedErrorDto[] = [];
|
||||
@@ -85,10 +92,10 @@ export class ProviderOrchestratorService {
|
||||
|
||||
const attemptStart = Date.now();
|
||||
try {
|
||||
const data = (await provider.execute(
|
||||
inquiryType,
|
||||
payload,
|
||||
executionContext,
|
||||
const data = (await this.providerIsolation.execute(provider.name, () =>
|
||||
runWithOutboundTrace(executionContext.outboundRequests!, () =>
|
||||
provider.execute(inquiryType, payload, executionContext),
|
||||
),
|
||||
)) as TResponse;
|
||||
|
||||
const duration = Date.now() - start;
|
||||
|
||||
@@ -0,0 +1,638 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const state = {
|
||||
accessToken: localStorage.getItem('esg.accessToken'),
|
||||
refreshToken: localStorage.getItem('esg.refreshToken'),
|
||||
profile: null,
|
||||
inquirySchema: null,
|
||||
rawMode: false,
|
||||
batchRunning: false,
|
||||
batchStopRequested: false,
|
||||
batchResults: [],
|
||||
};
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
// These examples intentionally mirror the @ApiProperty examples and DTO validation rules.
|
||||
const INQUIRY_FORMS = {
|
||||
person: {
|
||||
description: 'PersonInquiryRequestDto — examples match Swagger.',
|
||||
fields: [
|
||||
{ key: 'nationalCode', label: 'National code', example: '0012345678', required: true, description: 'Iranian national code (10 digits)', pattern: '\\d{10}' },
|
||||
{ key: 'birthDate', label: 'Birth date', example: '1378-11-24', required: true, description: 'Jalali birth date (YYYY-MM-DD)', pattern: '\\d{4}-\\d{2}-\\d{2}' },
|
||||
{ key: 'dateHasPostfix', label: 'Date postfix flag', example: 0, defaultValue: 0, type: 'number', description: 'Optional civil registration date postfix flag' },
|
||||
],
|
||||
},
|
||||
realEstate: {
|
||||
description: 'RealEstateRequestDto — both values must be 10 digits.',
|
||||
fields: [
|
||||
{ key: 'nationalCode', label: 'National code', example: '5098961130', required: true, description: 'Iranian national code (10 digits)', pattern: '\\d{10}' },
|
||||
{ key: 'postalCode', label: 'Postal code', example: '1349689554', required: true, description: 'Postal code (10 digits)', pattern: '\\d{10}' },
|
||||
],
|
||||
},
|
||||
sheba: {
|
||||
description: 'SayahRequestDto — accountOwnerType is 1 for a natural person.',
|
||||
fields: [
|
||||
{ key: 'accountOwnerType', label: 'Account owner type', example: '1', defaultValue: '1', description: '1 for natural person' },
|
||||
{ key: 'nationalCode', label: 'National code', example: '4311402422', required: true, description: 'Iranian national code (10 digits)', pattern: '\\d{10}' },
|
||||
{ key: 'legalId', label: 'Legal entity ID', example: '', includeEmpty: true, description: 'Use an empty string for natural persons' },
|
||||
{ key: 'sheba', label: 'Sheba', example: 'IR800560611828005105117001', required: true, description: 'Iranian Sheba ID (26 characters)', pattern: 'IR\\d{24}' },
|
||||
],
|
||||
},
|
||||
shahkar: {
|
||||
description: 'ShahkarRequestDto — national code and Iranian mobile number.',
|
||||
fields: [
|
||||
{ key: 'nationalCode', label: 'National code', example: '4311402422', required: true, description: 'Iranian national code (10 digits)', pattern: '\\d{10}' },
|
||||
{ key: 'mobileNo', label: 'Mobile number', example: '09226187419', required: true, description: 'Iranian mobile number', pattern: '09\\d{9}' },
|
||||
],
|
||||
},
|
||||
postalCode: {
|
||||
description: 'PostalCodeRequestDto — exactly 10 digits.',
|
||||
fields: [
|
||||
{ key: 'postalCode', label: 'Postal code', example: '1234567890', required: true, description: 'Postal code (10 digits)', pattern: '\\d{10}' },
|
||||
],
|
||||
},
|
||||
legalPerson: {
|
||||
description: 'This endpoint accepts a provider-specific JSON object; use JSON mode.',
|
||||
rawOnly: true,
|
||||
example: {},
|
||||
},
|
||||
carByPlate: {
|
||||
description: 'CarByPlateRequestDto — plate components are sent separately.',
|
||||
fields: [
|
||||
{ key: 'nationalCode', label: 'National code', example: '4311402422', required: true, description: 'Owner national code (10 digits)', pattern: '\\d{10}' },
|
||||
{ key: 'plk1', label: 'Plate left digits', example: '12', required: true, description: 'Two digits on the left side of the plate', pattern: '\\d{2}' },
|
||||
{ key: 'plk2', label: 'Plate letter', example: 'ب', required: true, description: 'Middle plate letter' },
|
||||
{ key: 'plk3', label: 'Plate right digits', example: '345', required: true, description: 'Three digits on the right side of the plate', pattern: '\\d{3}' },
|
||||
{ key: 'plksrl', label: 'Plate serial', example: '67', required: true, description: 'Plate serial / region code' },
|
||||
],
|
||||
},
|
||||
carByChassis: {
|
||||
description: 'CarByChassisRequestDto — owner national code and VIN/chassis.',
|
||||
fields: [
|
||||
{ key: 'nationalCode', label: 'National code', example: '4311402422', required: true, description: 'Owner national code (10 digits)', pattern: '\\d{10}' },
|
||||
{ key: 'chassisNo', label: 'Chassis / VIN', example: 'IRFC89R2VSY976455', required: true, description: 'Vehicle chassis number or VIN' },
|
||||
],
|
||||
},
|
||||
thirdPartyCar: {
|
||||
description: 'Uses CarByPlateRequestDto for the third-party car route.',
|
||||
fields: [
|
||||
{ key: 'nationalCode', label: 'National code', example: '4311402422', required: true, description: 'Owner national code (10 digits)', pattern: '\\d{10}' },
|
||||
{ key: 'plk1', label: 'Plate left digits', example: '12', required: true, description: 'Two digits on the left side of the plate', pattern: '\\d{2}' },
|
||||
{ key: 'plk2', label: 'Plate letter', example: 'ب', required: true, description: 'Middle plate letter' },
|
||||
{ key: 'plk3', label: 'Plate right digits', example: '345', required: true, description: 'Three digits on the right side of the plate', pattern: '\\d{3}' },
|
||||
{ key: 'plksrl', label: 'Plate serial', example: '67', required: true, description: 'Plate serial / region code' },
|
||||
],
|
||||
},
|
||||
policyByChassis: {
|
||||
description: 'PolicyByChassisRequestDto — vehicle chassis number.',
|
||||
fields: [
|
||||
{ key: 'chassisNo', label: 'Chassis number', example: 'NAAM01E15HK123456', required: true, description: 'Vehicle chassis number' },
|
||||
],
|
||||
},
|
||||
policyByPlate: {
|
||||
description: 'PolicyByPlateRequestDto — plate components and owner national code.',
|
||||
fields: [
|
||||
{ key: 'nationalCode', label: 'National code', example: '4311402422', required: true, description: 'Owner national code (10 digits)', pattern: '\\d{10}' },
|
||||
{ key: 'plk1', label: 'Plate left digits', example: '12', required: true, description: 'Two digits on the left side of the plate', pattern: '\\d{2}' },
|
||||
{ key: 'plk2', label: 'Plate letter', example: 'ب', required: true, description: 'Middle plate letter' },
|
||||
{ key: 'plk3', label: 'Plate right digits', example: '345', required: true, description: 'Three digits on the right side of the plate', pattern: '\\d{3}' },
|
||||
{ key: 'plksrl', label: 'Plate serial', example: '67', required: true, description: 'Plate serial' },
|
||||
],
|
||||
},
|
||||
policyByNationalCode: {
|
||||
description: 'PolicyByNationalCodeRequestDto — exactly 10 digits.',
|
||||
fields: [
|
||||
{ key: 'nationalCode', label: 'National code', example: '4311402422', required: true, description: 'Iranian national code (10 digits)', pattern: '\\d{10}' },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
function showError(message, target) { $(target).textContent = message || ''; }
|
||||
function setSession(tokens) {
|
||||
state.accessToken = tokens.accessToken;
|
||||
state.refreshToken = tokens.refreshToken;
|
||||
localStorage.setItem('esg.accessToken', state.accessToken);
|
||||
localStorage.setItem('esg.refreshToken', state.refreshToken);
|
||||
}
|
||||
function clearSession() {
|
||||
state.accessToken = null; state.refreshToken = null; state.profile = null;
|
||||
localStorage.removeItem('esg.accessToken'); localStorage.removeItem('esg.refreshToken');
|
||||
$('loginView').classList.remove('hidden'); $('appView').classList.add('hidden');
|
||||
}
|
||||
async function request(path, options, retried) {
|
||||
const headers = Object.assign({ Accept: 'application/json' }, (options && options.headers) || {});
|
||||
if (options && options.body && !headers['Content-Type']) headers['Content-Type'] = 'application/json';
|
||||
if (state.accessToken) headers.Authorization = 'Bearer ' + state.accessToken;
|
||||
const response = await fetch(path, Object.assign({}, options || {}, { headers }));
|
||||
const text = await response.text();
|
||||
let body; try { body = text ? JSON.parse(text) : null; } catch (_) { body = text; }
|
||||
if (response.status === 401 && state.refreshToken && !retried) {
|
||||
const refreshed = await fetch('/auth/refresh', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ refreshToken: state.refreshToken }) });
|
||||
if (refreshed.ok) { setSession(await refreshed.json()); return request(path, options, true); }
|
||||
clearSession();
|
||||
}
|
||||
if (!response.ok) {
|
||||
const error = new Error(body && body.error && body.error.message ? body.error.message : (body && body.message) || ('Request failed (' + response.status + ')'));
|
||||
error.body = body;
|
||||
error.status = response.status;
|
||||
throw error;
|
||||
}
|
||||
return body;
|
||||
}
|
||||
function pretty(value) {
|
||||
if (typeof value !== 'string') {
|
||||
return JSON.stringify(value, (_, item) => (isXml(item) ? formatXml(item) : item), 2);
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed.startsWith('<')) { try { return JSON.stringify(JSON.parse(trimmed), null, 2); } catch (_) { return value; } }
|
||||
return formatXml(trimmed);
|
||||
}
|
||||
function isXml(value) {
|
||||
return typeof value === 'string' && /^\s*(?:<\?xml\b|<!--[\s\S]*?-->|<[A-Za-z_][\w:.-]*(?:\s[^>]*)?>)/.test(value);
|
||||
}
|
||||
function formatXml(value) {
|
||||
const trimmed = String(value).trim();
|
||||
if (!isXml(trimmed)) return trimmed;
|
||||
const tokens = trimmed
|
||||
.replace(/>\s*</g, '><')
|
||||
.replace(/</g, '\n<')
|
||||
.split('\n')
|
||||
.map((token) => token.trim())
|
||||
.filter(Boolean);
|
||||
let depth = 0;
|
||||
return tokens.map((token) => {
|
||||
const closing = /^<\//.test(token);
|
||||
const selfClosing = /\/\s*>$/.test(token) || /^<\?/.test(token) || /^<!/.test(token);
|
||||
if (closing) depth = Math.max(0, depth - 1);
|
||||
const line = ' '.repeat(depth) + token;
|
||||
if (!closing && !selfClosing && /^<[^>]+>$/.test(token)) depth += 1;
|
||||
return line;
|
||||
}).join('\n');
|
||||
}
|
||||
function xmlToJson(value) {
|
||||
const documentNode = new DOMParser().parseFromString(String(value), 'application/xml');
|
||||
if (documentNode.querySelector('parsererror')) throw new Error('XML could not be parsed.');
|
||||
const convert = (node) => {
|
||||
const attributes = {};
|
||||
for (const attribute of Array.from(node.attributes || [])) attributes[attribute.name] = attribute.value;
|
||||
const children = Array.from(node.childNodes || []).filter((child) => child.nodeType === 1);
|
||||
const text = Array.from(node.childNodes || [])
|
||||
.filter((child) => child.nodeType === 3 || child.nodeType === 4)
|
||||
.map((child) => child.nodeValue || '')
|
||||
.join('')
|
||||
.trim();
|
||||
if (!children.length) {
|
||||
if (!Object.keys(attributes).length) return text;
|
||||
return { '@attributes': attributes, ...(text ? { '#text': text } : {}) };
|
||||
}
|
||||
const result = {};
|
||||
if (Object.keys(attributes).length) result['@attributes'] = attributes;
|
||||
for (const child of children) {
|
||||
const key = child.nodeName;
|
||||
const childValue = convert(child);
|
||||
if (result[key] === undefined) result[key] = childValue;
|
||||
else result[key] = Array.isArray(result[key]) ? [...result[key], childValue] : [result[key], childValue];
|
||||
}
|
||||
if (text) result['#text'] = text;
|
||||
return result;
|
||||
};
|
||||
return { [documentNode.documentElement.nodeName]: convert(documentNode.documentElement) };
|
||||
}
|
||||
function createXmlViewer(label, value) {
|
||||
const section = document.createElement('section'); section.className = 'xml-viewer';
|
||||
const toolbar = document.createElement('div'); toolbar.className = 'xml-toolbar';
|
||||
const title = document.createElement('span'); title.className = 'detail-label'; title.textContent = label;
|
||||
const actions = document.createElement('div'); actions.className = 'xml-actions';
|
||||
const toggle = document.createElement('button'); toggle.type = 'button'; toggle.className = 'ghost';
|
||||
const jsonToggle = document.createElement('button'); jsonToggle.type = 'button'; jsonToggle.className = 'ghost';
|
||||
const output = document.createElement('pre'); output.className = 'xml-output';
|
||||
const searchRow = document.createElement('div'); searchRow.className = 'xml-search';
|
||||
const searchInput = document.createElement('input'); searchInput.type = 'search'; searchInput.placeholder = 'Search this XML…'; searchInput.setAttribute('aria-label', `Search ${label}`);
|
||||
const previous = document.createElement('button'); previous.type = 'button'; previous.className = 'ghost'; previous.textContent = '↑'; previous.title = 'Previous match';
|
||||
const next = document.createElement('button'); next.type = 'button'; next.className = 'ghost'; next.textContent = '↓'; next.title = 'Next match';
|
||||
const matchCount = document.createElement('span'); matchCount.className = 'xml-match-count'; matchCount.textContent = 'No search';
|
||||
let mode = 'formatted';
|
||||
let currentText = '';
|
||||
let activeMatch = 0;
|
||||
const escapeHtml = (text) => text.replace(/[&<>"']/g, (character) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[character]));
|
||||
const escapeRegex = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const renderSearch = () => {
|
||||
const query = searchInput.value.trim();
|
||||
if (!query) { output.textContent = currentText; matchCount.textContent = 'No search'; return; }
|
||||
const expression = new RegExp(escapeRegex(query), 'gi');
|
||||
let count = 0;
|
||||
output.innerHTML = escapeHtml(currentText).replace(expression, (match) => `<mark data-match="${count++}">${match}</mark>`);
|
||||
const matches = Array.from(output.querySelectorAll('mark'));
|
||||
if (!matches.length) { matchCount.textContent = '0 matches'; return; }
|
||||
activeMatch = Math.min(activeMatch, matches.length - 1);
|
||||
matches[activeMatch].classList.add('active-match'); matches[activeMatch].scrollIntoView({ block: 'center' });
|
||||
matchCount.textContent = `${activeMatch + 1} / ${matches.length}`;
|
||||
};
|
||||
const moveMatch = (direction) => {
|
||||
const matches = output.querySelectorAll('mark');
|
||||
if (!matches.length) return;
|
||||
activeMatch = (activeMatch + direction + matches.length) % matches.length;
|
||||
renderSearch();
|
||||
};
|
||||
const render = () => {
|
||||
if (mode === 'json') {
|
||||
try { currentText = JSON.stringify(xmlToJson(value), null, 2); }
|
||||
catch (error) { currentText = `Unable to transform XML to JSON: ${error.message}`; }
|
||||
} else currentText = mode === 'formatted' ? formatXml(value) : String(value);
|
||||
toggle.textContent = mode === 'raw' ? 'Format XML' : 'Show raw XML';
|
||||
jsonToggle.textContent = mode === 'json' ? 'Show XML' : 'Transform to JSON';
|
||||
renderSearch();
|
||||
};
|
||||
toggle.addEventListener('click', (event) => { event.stopPropagation(); mode = mode === 'raw' ? 'formatted' : 'raw'; render(); });
|
||||
jsonToggle.addEventListener('click', (event) => { event.stopPropagation(); mode = mode === 'json' ? 'formatted' : 'json'; render(); });
|
||||
searchInput.addEventListener('input', () => { activeMatch = 0; renderSearch(); });
|
||||
previous.addEventListener('click', (event) => { event.stopPropagation(); moveMatch(-1); });
|
||||
next.addEventListener('click', (event) => { event.stopPropagation(); moveMatch(1); });
|
||||
searchRow.append(searchInput, previous, next, matchCount);
|
||||
actions.append(toggle, jsonToggle); toolbar.append(title, actions); section.append(toolbar, searchRow, output); render();
|
||||
return section;
|
||||
}
|
||||
function newKey() { return 'ui-' + Date.now() + '-' + Math.random().toString(36).slice(2, 9); }
|
||||
function fieldsToPayload() {
|
||||
const payload = {};
|
||||
(state.inquirySchema.fields || []).forEach((field) => {
|
||||
const input = $('inquiryFields').querySelector('[data-field="' + field.key + '"]');
|
||||
if (!input) return;
|
||||
const value = input.value;
|
||||
if (value === '' && !field.includeEmpty) return;
|
||||
payload[field.key] = field.type === 'number' && value !== '' ? Number(value) : value;
|
||||
});
|
||||
return payload;
|
||||
}
|
||||
function syncFieldsToJson() {
|
||||
if (!state.inquirySchema || state.inquirySchema.rawOnly || state.rawMode) return;
|
||||
$('inquiryPayload').value = JSON.stringify(fieldsToPayload(), null, 2);
|
||||
}
|
||||
function applyJsonToFields() {
|
||||
if (!state.inquirySchema || state.inquirySchema.rawOnly) return true;
|
||||
let payload;
|
||||
try { payload = JSON.parse($('inquiryPayload').value || '{}'); } catch (_) { showError('JSON payload is not valid.', 'appError'); return false; }
|
||||
if (!payload || Array.isArray(payload) || typeof payload !== 'object') { showError('JSON payload must be an object.', 'appError'); return false; }
|
||||
(state.inquirySchema.fields || []).forEach((field) => {
|
||||
const input = $('inquiryFields').querySelector('[data-field="' + field.key + '"]');
|
||||
if (input) input.value = payload[field.key] == null ? '' : String(payload[field.key]);
|
||||
});
|
||||
return true;
|
||||
}
|
||||
function setRawMode(enabled) {
|
||||
if (!state.inquirySchema || state.inquirySchema.rawOnly) return;
|
||||
if (enabled) {
|
||||
syncFieldsToJson();
|
||||
state.rawMode = true;
|
||||
$('inquiryFields').querySelectorAll('input').forEach((input) => { input.disabled = true; });
|
||||
$('fieldMode').classList.add('hidden'); $('rawMode').classList.remove('hidden');
|
||||
$('toggleRawButton').textContent = 'Use form fields';
|
||||
return;
|
||||
}
|
||||
if (!applyJsonToFields()) return;
|
||||
state.rawMode = false;
|
||||
$('inquiryFields').querySelectorAll('input').forEach((input) => { input.disabled = false; });
|
||||
$('fieldMode').classList.remove('hidden'); $('rawMode').classList.add('hidden');
|
||||
$('toggleRawButton').textContent = 'Use JSON mode';
|
||||
syncFieldsToJson();
|
||||
}
|
||||
function renderInquiryForm() {
|
||||
const schema = INQUIRY_FORMS[$('inquiryType').value];
|
||||
state.inquirySchema = schema;
|
||||
state.rawMode = Boolean(schema.rawOnly);
|
||||
$('inquiryHint').textContent = schema.description;
|
||||
$('inquiryFields').replaceChildren();
|
||||
$('inquiryPayload').value = JSON.stringify(schema.example || {}, null, 2);
|
||||
$('toggleRawButton').disabled = Boolean(schema.rawOnly);
|
||||
$('applyJsonButton').classList.toggle('hidden', Boolean(schema.rawOnly));
|
||||
if (schema.rawOnly) {
|
||||
$('fieldMode').classList.add('hidden'); $('rawMode').classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
(schema.fields || []).forEach((field) => {
|
||||
const label = document.createElement('label');
|
||||
label.append(document.createTextNode(field.label + (field.required ? ' *' : '')));
|
||||
const input = document.createElement('input');
|
||||
input.type = field.type || 'text';
|
||||
input.dataset.field = field.key;
|
||||
input.value = field.defaultValue == null ? String(field.example ?? '') : String(field.defaultValue);
|
||||
input.placeholder = String(field.example ?? '');
|
||||
input.required = Boolean(field.required);
|
||||
if (field.pattern) input.pattern = field.pattern;
|
||||
input.addEventListener('input', syncFieldsToJson);
|
||||
const hint = document.createElement('small');
|
||||
hint.className = 'field-hint';
|
||||
hint.textContent = field.description + (field.example !== undefined ? ' Example: ' + field.example : '');
|
||||
label.append(input, hint);
|
||||
$('inquiryFields').append(label);
|
||||
});
|
||||
$('fieldMode').classList.remove('hidden'); $('rawMode').classList.add('hidden');
|
||||
$('toggleRawButton').textContent = 'Use JSON mode';
|
||||
syncFieldsToJson();
|
||||
}
|
||||
async function loadHealth() {
|
||||
try {
|
||||
const result = await request('/health/ready');
|
||||
const ok = result.status === 'ok';
|
||||
const dot = $('healthStatus').querySelector('.status-dot');
|
||||
dot.className = 'status-dot ' + (ok ? 'ok' : 'error');
|
||||
$('healthStatus').querySelector('span:last-child').textContent = ok ? 'Ready' : 'Degraded';
|
||||
$('healthOutput').textContent = pretty(result);
|
||||
} catch (error) {
|
||||
const dot = $('healthStatus').querySelector('.status-dot');
|
||||
dot.className = 'status-dot error';
|
||||
$('healthStatus').querySelector('span:last-child').textContent = 'Unavailable';
|
||||
$('healthOutput').textContent = pretty(error.body || error.message);
|
||||
}
|
||||
}
|
||||
async function loadMetrics() {
|
||||
const summary = await request('/inquiry-logs/summary');
|
||||
$('metricTotal').textContent = summary.total ?? '—'; $('metricEvaluated').textContent = summary.evaluated ?? '—'; $('metricSuccess').textContent = summary.successRate == null ? '—' : (Number(summary.successRate) * 100).toFixed(1) + '%'; $('metricFailure').textContent = summary.failure ?? '—'; $('metricNoMatch').textContent = summary.noMatch ?? '—'; $('metricDuration').textContent = summary.averageDuration == null ? '—' : Math.round(summary.averageDuration) + ' ms';
|
||||
}
|
||||
async function loadLogs() {
|
||||
const result = await request('/inquiry-logs?limit=40&page=1'); const body = $('logsBody'); body.replaceChildren();
|
||||
(result.data || []).forEach((log) => {
|
||||
const row = document.createElement('tr');
|
||||
row.className = 'data-row'; row.tabIndex = 0; row.setAttribute('aria-expanded', 'false');
|
||||
[log.createdAt ? new Date(log.createdAt).toLocaleString() : '—', log.inquiryType, log.provider, log.status, log.duration + ' ms', log.trackingCode].forEach((value, index) => {
|
||||
const cell = document.createElement('td');
|
||||
if (index === 0) { const toggle = document.createElement('span'); toggle.className = 'row-toggle'; toggle.textContent = '▶'; toggle.setAttribute('aria-hidden', 'true'); cell.append(toggle); }
|
||||
cell.append(document.createTextNode(value));
|
||||
if (index === 3) cell.className = log.status === 'SUCCESS' ? 'status-success' : (log.status === 'NO_MATCH' ? 'status-neutral' : 'status-failure');
|
||||
row.appendChild(cell);
|
||||
});
|
||||
const detailRow = createDetailRow(6, log);
|
||||
bindDetailToggle(row, detailRow);
|
||||
body.append(row, detailRow);
|
||||
});
|
||||
}
|
||||
function createDetailRow(colspan, value) {
|
||||
const detailRow = document.createElement('tr'); detailRow.className = 'detail-row hidden';
|
||||
const cell = document.createElement('td'); cell.colSpan = colspan;
|
||||
const panel = document.createElement('div'); panel.className = 'detail-panel';
|
||||
detailRow.renderValue = (nextValue) => renderDetailPanel(panel, nextValue);
|
||||
renderDetailPanel(panel, value);
|
||||
cell.appendChild(panel); detailRow.appendChild(cell);
|
||||
return detailRow;
|
||||
}
|
||||
function renderDetailPanel(panel, value) {
|
||||
panel.replaceChildren();
|
||||
const outboundRequests = Array.isArray(value?.outboundRequests) ? value.outboundRequests : [];
|
||||
if (outboundRequests.length) {
|
||||
const heading = document.createElement('p'); heading.className = 'detail-heading';
|
||||
heading.textContent = `Outbound calls (${outboundRequests.length})`;
|
||||
panel.appendChild(heading);
|
||||
outboundRequests.forEach((trace, index) => {
|
||||
const call = document.createElement('section'); call.className = 'outbound-call';
|
||||
const title = document.createElement('div'); title.className = 'outbound-call-title';
|
||||
title.textContent = `${index + 1}. ${(trace.method || 'GET').toUpperCase()} ${trace.url || '—'}${trace.status ? ` · HTTP ${trace.status}` : trace.error ? ` · ${trace.error}` : ''}`;
|
||||
call.appendChild(title);
|
||||
const curlLabel = document.createElement('span'); curlLabel.className = 'detail-label'; curlLabel.textContent = 'Safe cURL (credentials redacted)';
|
||||
call.appendChild(curlLabel);
|
||||
const curlRow = document.createElement('div'); curlRow.className = 'curl-row';
|
||||
const curl = document.createElement('textarea'); curl.readOnly = true; curl.rows = 4; curl.value = trace.curl || `curl --request ${(trace.method || 'GET').toUpperCase()} '${trace.url || ''}'`;
|
||||
const copy = document.createElement('button'); copy.type = 'button'; copy.className = 'ghost copy-curl'; copy.textContent = 'Copy cURL';
|
||||
copy.addEventListener('click', async (event) => {
|
||||
event.stopPropagation();
|
||||
try { await navigator.clipboard.writeText(curl.value); copy.textContent = 'Copied'; } catch (_) {
|
||||
curl.focus(); curl.select(); document.execCommand('copy'); copy.textContent = 'Copied';
|
||||
}
|
||||
window.setTimeout(() => { copy.textContent = 'Copy cURL'; }, 1400);
|
||||
});
|
||||
curlRow.append(curl, copy); call.appendChild(curlRow);
|
||||
if (isXml(trace.requestBody)) call.appendChild(createXmlViewer('Request XML', trace.requestBody));
|
||||
if (trace.responseBody !== undefined || trace.error) {
|
||||
if (isXml(trace.responseBody)) call.appendChild(createXmlViewer('Response XML', trace.responseBody));
|
||||
else {
|
||||
const response = document.createElement('pre'); response.className = 'outbound-response';
|
||||
response.textContent = trace.error ? `${trace.error}\n\n${pretty(trace.responseBody)}` : pretty(trace.responseBody);
|
||||
call.appendChild(response);
|
||||
}
|
||||
}
|
||||
panel.appendChild(call);
|
||||
});
|
||||
}
|
||||
const fullDetails = document.createElement('details'); fullDetails.className = 'full-detail';
|
||||
const summary = document.createElement('summary'); summary.textContent = 'Show complete masked gateway record';
|
||||
const output = document.createElement('pre'); output.textContent = pretty(value);
|
||||
fullDetails.append(summary, output); panel.appendChild(fullDetails);
|
||||
}
|
||||
function bindDetailToggle(row, detailRow, onExpand) {
|
||||
let loaded = false;
|
||||
const toggle = () => {
|
||||
const expanded = row.getAttribute('aria-expanded') === 'true';
|
||||
row.setAttribute('aria-expanded', String(!expanded)); detailRow.classList.toggle('hidden', expanded);
|
||||
if (!expanded && !loaded && onExpand) { loaded = true; onExpand(); }
|
||||
};
|
||||
row.addEventListener('click', toggle);
|
||||
row.addEventListener('keydown', (event) => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); toggle(); } });
|
||||
}
|
||||
function firstValue(source, keys) {
|
||||
for (const key of keys) {
|
||||
if (source && source[key] !== undefined && source[key] !== null && source[key] !== '') return source[key];
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
function normalizeBatchRecord(value, index) {
|
||||
const raw = value && typeof value === 'object' ? value : {};
|
||||
const source = (raw.request && typeof raw.request === 'object' ? raw.request : raw.payload && typeof raw.payload === 'object' ? raw.payload : raw);
|
||||
const plateObject = source.plate && typeof source.plate === 'object' ? source.plate : {};
|
||||
const directPlate = firstValue(source, ['plate', 'Plate', 'licensePlate', 'license_plate']);
|
||||
const plateText = directPlate && typeof directPlate === 'object' ? firstValue(plateObject, ['value', 'number']) : (directPlate ?? firstValue(plateObject, ['value', 'number']));
|
||||
let plk1 = firstValue(source, ['plk1', 'Plk1', 'plk01', 'platePart1', 'plate1', 'plaque_2', 'پلاک1']);
|
||||
let plk2 = firstValue(source, ['plk2', 'Plk2', 'plateLetter', 'plate_letter', 'plate2', 'letter', 'پلاک2']);
|
||||
let plk3 = firstValue(source, ['plk3', 'Plk3', 'platePart3', 'plate3', 'plaque_3', 'پلاک3']);
|
||||
let plksrl = firstValue(source, ['plksrl', 'PlkSrl', 'plkSrl', 'plateSerial', 'plate_serial', 'plate4', 'iran', 'پلاک4']);
|
||||
if (typeof plateText === 'string') {
|
||||
const compactPlate = plateText.replace(/[\s\-_/|]/g, '');
|
||||
const plateMatch = compactPlate.match(/^(\d{2})([^\d])(\d{3})(\d{2})$/u);
|
||||
if (plateMatch) {
|
||||
plk1 = plk1 ?? plateMatch[1]; plk2 = plk2 ?? plateMatch[2]; plk3 = plk3 ?? plateMatch[3]; plksrl = plksrl ?? plateMatch[4];
|
||||
}
|
||||
}
|
||||
const payload = {
|
||||
nationalCode: String(firstValue(source, ['nationalCode', 'NationalCode', 'national_code', 'nationalId', 'NationalId', 'NIN', 'nin', 'کدملی', 'کد ملی']) ?? '').trim(),
|
||||
plk1: String(plk1 ?? firstValue(plateObject, ['plk1', 'Plk1', 'part1']) ?? '').trim(),
|
||||
plk2: String(plk2 ?? firstValue(plateObject, ['plk2', 'Plk2', 'letter']) ?? '').trim(),
|
||||
plk3: String(plk3 ?? firstValue(plateObject, ['plk3', 'Plk3', 'part3']) ?? '').trim(),
|
||||
plksrl: String(plksrl ?? firstValue(plateObject, ['plksrl', 'PlkSrl', 'serial']) ?? '').trim(),
|
||||
};
|
||||
const missing = Object.entries(payload).filter(([, item]) => !item).map(([key]) => key);
|
||||
return {
|
||||
index: index + 1,
|
||||
raw,
|
||||
payload,
|
||||
parseError: missing.length > 0 ? `Missing field(s): ${missing.join(', ')}` : undefined,
|
||||
};
|
||||
}
|
||||
function parseBatchInput(text) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(text);
|
||||
} catch (_) {
|
||||
const lines = text.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
|
||||
if (!lines.length) throw new Error('Batch input is empty.');
|
||||
try { parsed = lines.map((line) => JSON.parse(line)); } catch (_) { throw new Error('Batch input is not valid JSON.'); }
|
||||
}
|
||||
const records = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.records) ? parsed.records : Array.isArray(parsed?.items) ? parsed.items : Array.isArray(parsed?.data) ? parsed.data : [parsed];
|
||||
if (!records.length) throw new Error('Batch input contains no records.');
|
||||
return records.map(normalizeBatchRecord);
|
||||
}
|
||||
function selectedBatchEndpoints() {
|
||||
return Array.from(document.querySelectorAll('input[name="batchEndpoint"]:checked')).map((input) => input.value);
|
||||
}
|
||||
function addBatchResult(result) {
|
||||
state.batchResults.push(result);
|
||||
const row = document.createElement('tr');
|
||||
row.className = 'data-row'; row.tabIndex = 0; row.setAttribute('aria-expanded', 'false');
|
||||
const inputLabel = result.payload ? `${result.payload.nationalCode} / ${result.payload.plk1}${result.payload.plk2}${result.payload.plk3}${result.payload.plksrl}` : '—';
|
||||
const values = [result.index, inputLabel, result.endpoint || '—', result.status, result.trackingCode || '—', result.message || '—'];
|
||||
values.forEach((value, index) => {
|
||||
const cell = document.createElement('td');
|
||||
if (index === 0) { const toggle = document.createElement('span'); toggle.className = 'row-toggle'; toggle.textContent = '▶'; toggle.setAttribute('aria-hidden', 'true'); cell.append(toggle); }
|
||||
cell.append(document.createTextNode(value));
|
||||
if (index === 3) { const noMatch = ['NO_MATCH', 'INQUIRY_NO_MATCH', 'CAR_POLICY_NOT_FOUND', 'RECORD_NOT_FOUND', 'REAL_ESTATE_NOT_FOUND', 'SHAHKAR_NO_MATCH', 'SHEBA_MISMATCH'].includes(result.status); cell.className = result.status === 'SUCCESS' ? 'status-success' : (noMatch ? 'status-neutral' : 'status-failure'); }
|
||||
row.appendChild(cell);
|
||||
});
|
||||
const detailRow = createDetailRow(6, result);
|
||||
bindDetailToggle(row, detailRow, () => {
|
||||
if (!result.trackingCode) return;
|
||||
request(`/inquiry-logs?trackingCode=${encodeURIComponent(result.trackingCode)}&limit=1&page=1`)
|
||||
.then((logResult) => {
|
||||
const log = logResult && logResult.data && logResult.data[0];
|
||||
if (log && typeof detailRow.renderValue === 'function') {
|
||||
detailRow.renderValue({ ...result, outboundRequests: log.outboundRequests, gatewayLog: log });
|
||||
}
|
||||
})
|
||||
.catch(() => undefined);
|
||||
});
|
||||
$('batchResultsBody').append(row, detailRow);
|
||||
}
|
||||
function updateBatchSummary(completed, total) {
|
||||
$('batchProgress').value = total ? completed / total : 0;
|
||||
const success = state.batchResults.filter((item) => item.status === 'SUCCESS').length; const noMatch = state.batchResults.filter((item) => ['NO_MATCH', 'INQUIRY_NO_MATCH', 'CAR_POLICY_NOT_FOUND', 'RECORD_NOT_FOUND', 'REAL_ESTATE_NOT_FOUND', 'SHAHKAR_NO_MATCH', 'SHEBA_MISMATCH'].includes(item.status)).length; const operational = completed - success - noMatch; $('batchSummary').textContent = `${completed} / ${total} completed · ${success} success · ${noMatch} no-match · ${operational} operational failure${operational === 1 ? '' : 's'}`;
|
||||
}
|
||||
function wait(milliseconds) {
|
||||
return milliseconds > 0 ? new Promise((resolve) => setTimeout(resolve, milliseconds)) : Promise.resolve();
|
||||
}
|
||||
async function runBatchTest() {
|
||||
if (state.batchRunning) return;
|
||||
const endpoints = selectedBatchEndpoints();
|
||||
if (!endpoints.length) { showError('Select at least one plate endpoint.', 'appError'); return; }
|
||||
let records;
|
||||
try { records = parseBatchInput($('batchPayload').value.trim()); } catch (error) { showError(error.message, 'appError'); return; }
|
||||
const delay = Math.min(10000, Math.max(0, Number($('batchDelay').value) || 0));
|
||||
const total = records.length * endpoints.length;
|
||||
if (total > 50 && !window.confirm(`Run ${total} requests (${records.length} record(s) × ${endpoints.length} endpoint(s))?`)) return;
|
||||
let completed = 0;
|
||||
state.batchRunning = true; state.batchStopRequested = false; state.batchResults = [];
|
||||
$('batchResultsBody').replaceChildren(); $('batchOutput').textContent = 'Running batch… click any completed row to inspect its response.'; $('batchProgress').classList.remove('hidden'); $('runBatchButton').disabled = true; $('stopBatchButton').classList.remove('hidden');
|
||||
updateBatchSummary(0, total);
|
||||
try {
|
||||
for (const record of records) {
|
||||
for (const endpoint of endpoints) {
|
||||
if (state.batchStopRequested) break;
|
||||
let result;
|
||||
if (record.parseError) {
|
||||
result = { index: record.index, payload: record.payload, endpoint, status: 'INVALID_INPUT', message: record.parseError };
|
||||
} else {
|
||||
try {
|
||||
const body = await request('/inquiry/' + endpoint, { method: 'POST', headers: { 'Idempotency-Key': `batch-${Date.now()}-${record.index}-${endpoint}` }, body: JSON.stringify(record.payload) });
|
||||
result = { index: record.index, payload: record.payload, endpoint, status: body.success ? 'SUCCESS' : (body.error?.code || 'NO_MATCH'), trackingCode: body.trackingCode, message: body.success ? (body.message || 'Completed') : (body.error?.messageFa || body.error?.message || 'Inquiry returned no result'), response: body };
|
||||
} catch (error) {
|
||||
result = { index: record.index, payload: record.payload, endpoint, status: 'REQUEST_ERROR', message: error.message, response: error.body };
|
||||
}
|
||||
}
|
||||
addBatchResult(result); completed += 1; updateBatchSummary(completed, total); await wait(delay);
|
||||
}
|
||||
if (state.batchStopRequested) break;
|
||||
}
|
||||
$('batchOutput').textContent = 'Batch finished. Click any row to inspect its full request and response.';
|
||||
if (state.batchStopRequested) $('batchSummary').textContent += ' · stopped by user';
|
||||
await Promise.allSettled([loadMetrics(), loadLogs()]);
|
||||
} finally {
|
||||
state.batchRunning = false; state.batchStopRequested = false; $('runBatchButton').disabled = false; $('stopBatchButton').disabled = false; $('stopBatchButton').classList.add('hidden');
|
||||
}
|
||||
}
|
||||
async function clearInquiryLogs() {
|
||||
if (!window.confirm('Delete every inquiry log from MongoDB? This cannot be undone.')) return;
|
||||
try {
|
||||
const result = await request('/inquiry-logs', { method: 'DELETE' });
|
||||
$('logsBody').replaceChildren(); $('logOutput').textContent = 'Inquiry logs were cleared.';
|
||||
showError(`Deleted ${result.deletedCount || 0} inquiry log(s).`, 'appError');
|
||||
await loadMetrics();
|
||||
} catch (error) { showError(error.message, 'appError'); }
|
||||
}
|
||||
async function loadDashboard() {
|
||||
showError('', 'appError');
|
||||
const results = await Promise.allSettled([loadHealth(), loadMetrics(), loadLogs()]);
|
||||
const failed = results.find((result) => result.status === 'rejected');
|
||||
if (failed) showError(failed.reason && failed.reason.message ? failed.reason.message : 'Some dashboard data could not be loaded.', 'appError');
|
||||
}
|
||||
function setupCollapsiblePanels() {
|
||||
document.querySelectorAll('#appView .panel').forEach((panel, index) => {
|
||||
const heading = panel.querySelector(':scope > .panel-heading');
|
||||
if (!heading || heading.dataset.collapsibleReady) return;
|
||||
heading.dataset.collapsibleReady = 'true';
|
||||
const title = heading.querySelector('h2')?.textContent?.trim() || `Panel ${index + 1}`;
|
||||
const key = `esg.dashboard.panel.${title.toLowerCase().replace(/[^a-z0-9]+/g, '-')}`;
|
||||
const content = document.createElement('div'); content.className = 'panel-content';
|
||||
let node = heading.nextSibling;
|
||||
while (node) { const next = node.nextSibling; content.appendChild(node); node = next; }
|
||||
panel.appendChild(content);
|
||||
const collapse = document.createElement('button');
|
||||
collapse.type = 'button'; collapse.className = 'icon-button panel-collapse'; collapse.title = `Collapse ${title}`;
|
||||
collapse.setAttribute('aria-label', `Collapse ${title}`);
|
||||
const applyState = (collapsed, persist) => {
|
||||
panel.classList.toggle('panel-collapsed', collapsed); content.hidden = collapsed;
|
||||
collapse.textContent = collapsed ? '+' : '−';
|
||||
collapse.title = `${collapsed ? 'Expand' : 'Collapse'} ${title}`;
|
||||
collapse.setAttribute('aria-label', `${collapsed ? 'Expand' : 'Collapse'} ${title}`);
|
||||
collapse.setAttribute('aria-expanded', String(!collapsed));
|
||||
if (persist) { try { localStorage.setItem(key, collapsed ? 'collapsed' : 'open'); } catch (_) {} }
|
||||
};
|
||||
collapse.addEventListener('click', (event) => { event.stopPropagation(); applyState(!panel.classList.contains('panel-collapsed'), true); });
|
||||
heading.appendChild(collapse);
|
||||
let collapsed = false;
|
||||
try { collapsed = localStorage.getItem(key) === 'collapsed'; } catch (_) {}
|
||||
applyState(collapsed, false);
|
||||
});
|
||||
}
|
||||
async function login(event) {
|
||||
event.preventDefault(); showError('', 'loginError');
|
||||
try { const tokens = await request('/auth/login', { method: 'POST', body: JSON.stringify({ username: $('username').value, password: $('password').value }) }, true); setSession(tokens); const profile = await request('/auth/profile'); if (!profile || profile.role !== 'SUPER_ADMIN') throw new Error('This console is restricted to SUPER_ADMIN.'); state.profile = profile; $('profileLabel').textContent = profile.username + ' · SUPER_ADMIN'; $('loginView').classList.add('hidden'); $('appView').classList.remove('hidden'); $('idempotencyKey').value = newKey(); await loadDashboard(); }
|
||||
catch (error) { clearSession(); showError(error.message, 'loginError'); }
|
||||
}
|
||||
async function submitInquiry(event) {
|
||||
event.preventDefault(); showError('', 'appError');
|
||||
try {
|
||||
const payload = state.rawMode ? JSON.parse($('inquiryPayload').value || '{}') : fieldsToPayload();
|
||||
const result = await request('/inquiry/' + $('inquiryType').value, { method: 'POST', headers: { 'Idempotency-Key': $('idempotencyKey').value || newKey() }, body: JSON.stringify(payload) });
|
||||
$('inquiryOutput').textContent = pretty(result); $('idempotencyKey').value = newKey();
|
||||
await Promise.allSettled([loadMetrics(), loadLogs()]);
|
||||
} catch (error) { $('inquiryOutput').textContent = error.message; showError(error.message, 'appError'); }
|
||||
}
|
||||
$('loginForm').addEventListener('submit', login);
|
||||
$('inquiryForm').addEventListener('submit', submitInquiry);
|
||||
$('inquiryType').addEventListener('change', renderInquiryForm);
|
||||
$('toggleRawButton').addEventListener('click', () => setRawMode(!state.rawMode));
|
||||
$('applyJsonButton').addEventListener('click', () => { if (applyJsonToFields()) setRawMode(false); });
|
||||
$('logoutButton').addEventListener('click', async () => { try { await request('/auth/logout', { method: 'POST' }); } catch (_) {} clearSession(); });
|
||||
$('refreshHealth').addEventListener('click', loadHealth);
|
||||
$('refreshMetrics').addEventListener('click', () => loadMetrics().catch((error) => showError(error.message, 'appError')));
|
||||
$('refreshLogs').addEventListener('click', () => loadLogs().catch((error) => showError(error.message, 'appError')));
|
||||
$('clearLogsButton').addEventListener('click', clearInquiryLogs);
|
||||
$('batchFile').addEventListener('change', async (event) => {
|
||||
const file = event.target.files && event.target.files[0];
|
||||
if (!file) return;
|
||||
try { $('batchPayload').value = await file.text(); $('batchOutput').textContent = `Loaded ${file.name}. Click Run batch test to begin.`; } catch (_) { showError('Unable to read the selected batch file.', 'appError'); }
|
||||
});
|
||||
$('runBatchButton').addEventListener('click', runBatchTest);
|
||||
$('stopBatchButton').addEventListener('click', () => { state.batchStopRequested = true; $('stopBatchButton').disabled = true; });
|
||||
setupCollapsiblePanels();
|
||||
$('idempotencyKey').value = newKey();
|
||||
renderInquiryForm();
|
||||
if (state.accessToken) { request('/auth/profile').then((profile) => { if (profile.role !== 'SUPER_ADMIN') throw new Error('SUPER_ADMIN required'); state.profile = profile; $('profileLabel').textContent = profile.username + ' · SUPER_ADMIN'; $('loginView').classList.add('hidden'); $('appView').classList.remove('hidden'); return loadDashboard(); }).catch(clearSession); }
|
||||
setInterval(() => { if (!document.getElementById('appView').classList.contains('hidden')) loadHealth().catch(() => undefined); }, 30000);
|
||||
})();
|
||||
@@ -0,0 +1,132 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="color-scheme" content="dark light" />
|
||||
<title>Inquiry Gateway Console</title>
|
||||
<link rel="stylesheet" href="/dashboard/styles.css" />
|
||||
<script defer src="/dashboard/app.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<main class="shell">
|
||||
<section id="loginView" class="auth-card">
|
||||
<div class="brand-mark">ESG</div>
|
||||
<p class="eyebrow">External Services Gateway</p>
|
||||
<h1>Operations console</h1>
|
||||
<p class="muted">Sign in with the seeded SUPER_ADMIN account to inspect health, logs, and inquiries.</p>
|
||||
<form id="loginForm" class="stack">
|
||||
<label>Username<input id="username" name="username" autocomplete="username" required /></label>
|
||||
<label>Password<input id="password" name="password" type="password" autocomplete="current-password" required /></label>
|
||||
<button class="primary" type="submit">Sign in</button>
|
||||
</form>
|
||||
<p id="loginError" class="error" role="alert"></p>
|
||||
</section>
|
||||
|
||||
<section id="appView" class="hidden">
|
||||
<header class="topbar">
|
||||
<div>
|
||||
<p class="eyebrow">External Services Gateway</p>
|
||||
<h1>Operations console</h1>
|
||||
</div>
|
||||
<div class="topbar-actions">
|
||||
<span id="profileLabel" class="pill"></span>
|
||||
<button id="logoutButton" class="ghost" type="button">Sign out</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div id="appError" class="error banner" role="alert"></div>
|
||||
|
||||
<section class="grid two">
|
||||
<article class="panel health-panel">
|
||||
<div class="panel-heading"><h2>System health</h2><button id="refreshHealth" class="icon-button" type="button" title="Refresh health">↻</button></div>
|
||||
<div id="healthStatus" class="health-status"><span class="status-dot"></span><span>Loading…</span></div>
|
||||
<pre id="healthOutput" class="code compact">Loading readiness details…</pre>
|
||||
</article>
|
||||
<article class="panel">
|
||||
<div class="panel-heading"><h2>Inquiry metrics</h2><button id="refreshMetrics" class="icon-button" type="button" title="Refresh metrics">↻</button></div>
|
||||
<div class="metric-grid">
|
||||
<div><span>Total requests</span><strong id="metricTotal">—</strong></div>
|
||||
<div><span>Evaluated</span><strong id="metricEvaluated">—</strong></div>
|
||||
<div><span>Success rate*</span><strong id="metricSuccess">—</strong></div>
|
||||
<div><span>Operational failures</span><strong id="metricFailure">—</strong></div>
|
||||
<div><span>No-match results</span><strong id="metricNoMatch">—</strong></div>
|
||||
<div><span>Avg duration</span><strong id="metricDuration">—</strong></div>
|
||||
</div>
|
||||
<p class="metric-note">* Success rate excludes valid provider responses with no matching policy or owner.</p>
|
||||
</article>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-heading"><div><p class="eyebrow">Manual request</p><h2>Run an inquiry</h2></div></div>
|
||||
<form id="inquiryForm" class="inquiry-form">
|
||||
<label>Inquiry type
|
||||
<select id="inquiryType">
|
||||
<option value="person">Person</option>
|
||||
<option value="realEstate">Real estate</option>
|
||||
<option value="sheba">Sheba</option>
|
||||
<option value="shahkar">Shahkar</option>
|
||||
<option value="postalCode">Postal code</option>
|
||||
<option value="legalPerson">Legal person</option>
|
||||
<option value="carByPlate">Car by plate</option>
|
||||
<option value="carByChassis">Car by chassis</option>
|
||||
<option value="thirdPartyCar">Third-party car</option>
|
||||
<option value="policyByChassis">Policy by chassis</option>
|
||||
<option value="policyByPlate">Policy by plate</option>
|
||||
<option value="policyByNationalCode">Policy by national code</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>Idempotency key <input id="idempotencyKey" /></label>
|
||||
<div class="request-toolbar wide">
|
||||
<span id="inquiryHint" class="muted"></span>
|
||||
<button id="toggleRawButton" class="ghost" type="button">Use JSON mode</button>
|
||||
</div>
|
||||
<div id="fieldMode" class="wide">
|
||||
<div id="inquiryFields" class="form-fields"></div>
|
||||
</div>
|
||||
<div id="rawMode" class="wide hidden">
|
||||
<label>JSON payload
|
||||
<textarea id="inquiryPayload" rows="9" spellcheck="false"></textarea>
|
||||
</label>
|
||||
<button id="applyJsonButton" class="ghost" type="button">Apply JSON to form fields</button>
|
||||
</div>
|
||||
<button class="primary" type="submit">Send inquiry</button>
|
||||
</form>
|
||||
<pre id="inquiryOutput" class="code response-box">The formatted response will appear here.</pre>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-heading"><div><p class="eyebrow">Batch input</p><h2>Test plate inquiries from JSON</h2></div></div>
|
||||
<p class="muted">Choose a JSON or TXT file, or paste a JSON array. For Parsian third-party plate inquiries, use <strong>Car by plate</strong>; the other routes remain available only for diagnostics.</p>
|
||||
<div class="batch-controls">
|
||||
<label>JSON/TXT file<input id="batchFile" type="file" accept=".json,.txt,application/json,text/plain" /></label>
|
||||
<label>Delay between requests (ms)<input id="batchDelay" type="number" min="0" max="10000" step="100" value="0" /></label>
|
||||
</div>
|
||||
<label class="wide">Input preview / paste JSON
|
||||
<textarea id="batchPayload" rows="8" spellcheck="false" placeholder='[{"nationalCode":"4311402422","plk1":"12","plk2":"ب","plk3":"345","plksrl":"67"}]'></textarea>
|
||||
</label>
|
||||
<div class="endpoint-list">
|
||||
<span class="muted">Endpoints</span>
|
||||
<label class="checkbox"><input type="checkbox" name="batchEndpoint" value="carByPlate" checked /> Car by plate</label>
|
||||
<label class="checkbox"><input type="checkbox" name="batchEndpoint" value="thirdPartyCar" /> Third-party car (diagnostic)</label>
|
||||
<label class="checkbox"><input type="checkbox" name="batchEndpoint" value="policyByPlate" /> Policy by plate (diagnostic)</label>
|
||||
</div>
|
||||
<div class="batch-actions">
|
||||
<button id="runBatchButton" class="primary" type="button">Run batch test</button>
|
||||
<button id="stopBatchButton" class="ghost hidden" type="button">Stop after current request</button>
|
||||
<span id="batchSummary" class="muted"></span>
|
||||
</div>
|
||||
<progress id="batchProgress" class="batch-progress hidden" max="1" value="0"></progress>
|
||||
<div class="table-wrap"><table><thead><tr><th>#</th><th>Input</th><th>Endpoint</th><th>Status</th><th>Tracking code</th><th>Message</th></tr></thead><tbody id="batchResultsBody"></tbody></table></div>
|
||||
<p id="batchOutput" class="table-hint" role="status">Click a request row to expand its full response.</p>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-heading"><div><p class="eyebrow">MongoDB audit trail</p><h2>Recent inquiry logs</h2></div><div class="panel-actions"><button id="refreshLogs" class="ghost" type="button">Refresh logs</button><button id="clearLogsButton" class="danger" type="button">Clear all logs</button></div></div>
|
||||
<div class="table-wrap"><table><thead><tr><th>Time</th><th>Type</th><th>Provider</th><th>Status</th><th>Duration</th><th>Tracking code</th></tr></thead><tbody id="logsBody"></tbody></table></div>
|
||||
<p id="logOutput" class="table-hint" role="status">Click a request row to expand its masked request and response.</p>
|
||||
</section>
|
||||
</section>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,116 @@
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--bg: #0b1020;
|
||||
--bg-soft: #121a2d;
|
||||
--panel: rgba(19, 29, 49, 0.84);
|
||||
--line: rgba(148, 163, 184, 0.2);
|
||||
--text: #e5edf8;
|
||||
--muted: #96a8c0;
|
||||
--accent: #65d8b2;
|
||||
--accent-strong: #20b486;
|
||||
--danger: #ff8f8f;
|
||||
--shadow: 0 24px 70px rgba(0, 0, 0, 0.28);
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; min-height: 100vh; background: radial-gradient(circle at top right, #1c3450 0, var(--bg) 48%); color: var(--text); font: 15px/1.5 Inter, ui-sans-serif, system-ui, -apple-system, sans-serif; }
|
||||
button, input, select, textarea { font: inherit; }
|
||||
button { cursor: pointer; }
|
||||
.shell { width: min(1240px, calc(100% - 32px)); margin: 0 auto; padding: 40px 0 72px; }
|
||||
.hidden { display: none !important; }
|
||||
.auth-card { width: min(440px, 100%); margin: 10vh auto 0; padding: 36px; background: var(--panel); border: 1px solid var(--line); border-radius: 24px; box-shadow: var(--shadow); backdrop-filter: blur(16px); }
|
||||
.brand-mark { width: 48px; height: 48px; display: grid; place-items: center; border-radius: 14px; background: linear-gradient(135deg, var(--accent), #67a7ff); color: #08131f; font-weight: 900; letter-spacing: .08em; }
|
||||
.eyebrow { margin: 0 0 4px; color: var(--accent); font-size: 11px; font-weight: 800; letter-spacing: .16em; text-transform: uppercase; }
|
||||
h1, h2, p { margin-top: 0; }
|
||||
h1 { margin-bottom: 8px; font-size: clamp(28px, 4vw, 44px); letter-spacing: -.04em; }
|
||||
h2 { margin-bottom: 0; font-size: 18px; }
|
||||
.muted { color: var(--muted); }
|
||||
.stack, .inquiry-form { display: grid; gap: 16px; }
|
||||
label { display: grid; gap: 7px; color: var(--muted); font-size: 13px; font-weight: 700; }
|
||||
input, select, textarea { width: 100%; border: 1px solid var(--line); border-radius: 10px; padding: 11px 12px; background: rgba(6, 12, 26, .66); color: var(--text); outline: none; }
|
||||
input:focus, select:focus, textarea:focus { border-color: var(--accent); box-shadow: 0 0 0 3px rgba(101, 216, 178, .14); }
|
||||
textarea { resize: vertical; font: 13px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; }
|
||||
button { border: 0; border-radius: 10px; padding: 10px 16px; color: var(--text); background: rgba(148, 163, 184, .14); }
|
||||
button:hover { filter: brightness(1.12); }
|
||||
.primary { background: linear-gradient(135deg, var(--accent-strong), #2d9ee8); color: #05131a; font-weight: 800; }
|
||||
.ghost, .icon-button { border: 1px solid var(--line); background: transparent; }
|
||||
.danger { border: 1px solid rgba(255, 143, 143, .45); background: rgba(255, 95, 95, .12); color: var(--danger); }
|
||||
.icon-button { padding: 5px 10px; font-size: 20px; }
|
||||
.topbar, .panel-heading { display: flex; align-items: center; justify-content: space-between; gap: 16px; }
|
||||
.panel-actions, .batch-actions, .endpoint-list { display: flex; align-items: center; flex-wrap: wrap; gap: 10px; }
|
||||
.topbar { margin-bottom: 24px; }
|
||||
.topbar h1 { margin-bottom: 0; }
|
||||
.topbar-actions { display: flex; align-items: center; gap: 10px; }
|
||||
.pill { border: 1px solid rgba(101, 216, 178, .35); border-radius: 999px; padding: 6px 10px; color: var(--accent); font-size: 12px; }
|
||||
.grid { display: grid; gap: 18px; margin-bottom: 18px; }
|
||||
.grid.two { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.panel { margin-bottom: 18px; padding: 22px; overflow: hidden; background: var(--panel); border: 1px solid var(--line); border-radius: 18px; box-shadow: 0 12px 38px rgba(0,0,0,.14); }
|
||||
.panel-content[hidden] { display: none; }
|
||||
.panel-collapse { flex: 0 0 auto; min-width: 34px; padding: 2px 9px; font-size: 20px; line-height: 1.2; }
|
||||
.panel-collapsed { padding-bottom: 14px; }
|
||||
.health-status { display: flex; align-items: center; gap: 8px; margin: 20px 0 12px; font-weight: 800; }
|
||||
.status-dot { width: 10px; height: 10px; border-radius: 50%; background: var(--muted); }
|
||||
.status-dot.ok { background: var(--accent); box-shadow: 0 0 14px var(--accent); }
|
||||
.status-dot.error { background: var(--danger); box-shadow: 0 0 14px var(--danger); }
|
||||
.code { margin: 16px 0 0; padding: 16px; overflow: auto; border: 1px solid var(--line); border-radius: 12px; background: #07101e; color: #b9d4ee; white-space: pre-wrap; word-break: break-word; }
|
||||
.compact { max-height: 260px; font-size: 12px; }
|
||||
.response-box { min-height: 160px; }
|
||||
.metric-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin-top: 20px; }
|
||||
.metric-grid div { padding: 16px; border: 1px solid var(--line); border-radius: 12px; background: rgba(6, 12, 26, .34); }
|
||||
.metric-grid span { display: block; color: var(--muted); font-size: 12px; }
|
||||
.metric-grid strong { display: block; margin-top: 4px; font-size: 24px; }
|
||||
.metric-note { margin: 14px 0 0; color: var(--muted); font-size: 11px; }
|
||||
.inquiry-form { grid-template-columns: repeat(2, minmax(0, 1fr)); margin-top: 20px; }
|
||||
.inquiry-form .wide, .inquiry-form button { grid-column: 1 / -1; }
|
||||
.request-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.form-fields { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; }
|
||||
.batch-controls { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; margin: 18px 0; }
|
||||
.endpoint-list { margin: 16px 0; }
|
||||
.checkbox { display: inline-flex; grid-template-columns: auto 1fr; align-items: center; gap: 7px; color: var(--text); font-weight: 600; }
|
||||
.checkbox input { width: auto; accent-color: var(--accent-strong); }
|
||||
.batch-actions { margin: 16px 0; }
|
||||
.batch-progress { width: 100%; height: 8px; margin: 4px 0 12px; accent-color: var(--accent-strong); }
|
||||
.field-hint { color: var(--muted); font-size: 11px; font-weight: 500; }
|
||||
#rawMode { display: grid; gap: 12px; }
|
||||
#rawMode button { justify-self: start; }
|
||||
.table-wrap { overflow-x: auto; margin-top: 18px; }
|
||||
table { width: 100%; border-collapse: collapse; min-width: 720px; }
|
||||
th, td { padding: 12px 10px; border-bottom: 1px solid var(--line); text-align: left; white-space: nowrap; }
|
||||
th { color: var(--muted); font-size: 11px; letter-spacing: .08em; text-transform: uppercase; }
|
||||
tbody tr.data-row { cursor: pointer; }
|
||||
tbody tr.data-row:hover { background: rgba(101, 216, 178, .07); }
|
||||
tbody tr.data-row:focus { outline: 2px solid var(--accent); outline-offset: -2px; }
|
||||
.row-toggle { display: inline-block; width: 1.1em; margin-right: 4px; color: var(--accent); transition: transform .16s ease; }
|
||||
.data-row[aria-expanded="true"] .row-toggle { transform: rotate(90deg); }
|
||||
.detail-row td { padding: 0 10px 14px; background: rgba(6, 12, 26, .28); }
|
||||
.detail-panel { margin: 0; padding: 14px; border: 1px solid var(--line); border-radius: 10px; background: #07101e; }
|
||||
.detail-panel pre { margin: 0; max-height: 420px; overflow: auto; color: #b9d4ee; white-space: pre-wrap; word-break: break-word; font: 12px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; }
|
||||
.detail-heading { margin: 0 0 10px; color: var(--accent); font-size: 12px; font-weight: 800; }
|
||||
.outbound-call { margin-top: 10px; padding: 12px; border: 1px solid var(--line); border-radius: 9px; background: rgba(19, 29, 49, .68); }
|
||||
.outbound-call-title { margin-bottom: 8px; overflow-wrap: anywhere; color: var(--text); font: 12px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; }
|
||||
.detail-label { display: block; margin-bottom: 5px; color: var(--muted); font-size: 11px; }
|
||||
.curl-row { display: flex; align-items: flex-start; gap: 8px; }
|
||||
.curl-row textarea { min-height: 84px; color: #b9d4ee; font-size: 11px; }
|
||||
.copy-curl { flex: 0 0 auto; white-space: nowrap; }
|
||||
.xml-viewer { margin-top: 10px; border: 1px solid var(--line); border-radius: 8px; background: rgba(6, 12, 26, .5); }
|
||||
.xml-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 10px; border-bottom: 1px solid var(--line); }
|
||||
.xml-toolbar .detail-label { margin: 0; color: var(--accent); font-weight: 800; }
|
||||
.xml-actions { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.xml-toolbar button { padding: 5px 9px; font-size: 12px; }
|
||||
.xml-search { display: flex; align-items: center; gap: 6px; padding: 8px 10px; border-bottom: 1px solid var(--line); }
|
||||
.xml-search input { min-width: 180px; padding: 6px 9px; font-size: 12px; }
|
||||
.xml-search button { min-width: 30px; padding: 5px 8px; font-size: 12px; }
|
||||
.xml-match-count { min-width: 64px; color: var(--muted); font-size: 11px; text-align: right; }
|
||||
.xml-output mark { border-radius: 3px; background: rgba(250, 204, 21, .35); color: inherit; }
|
||||
.xml-output mark.active-match { outline: 2px solid var(--accent); background: rgba(101, 216, 178, .35); }
|
||||
.xml-output { max-height: 360px !important; padding: 12px !important; }
|
||||
.outbound-response { margin-top: 10px !important; max-height: 180px !important; }
|
||||
.full-detail { margin-top: 12px; }
|
||||
.full-detail summary { cursor: pointer; color: var(--muted); font-size: 12px; }
|
||||
.table-hint { margin: 12px 0 0; color: var(--muted); font-size: 12px; }
|
||||
.status-success { color: var(--accent); }
|
||||
.status-neutral { color: #f6c85f; }
|
||||
.status-failure { color: var(--danger); }
|
||||
.error { min-height: 20px; color: var(--danger); }
|
||||
.banner { margin: 0 0 16px; }
|
||||
@media (max-width: 780px) { .shell { width: min(100% - 20px, 680px); padding-top: 20px; } .grid.two, .inquiry-form, .form-fields, .batch-controls, .metric-grid { grid-template-columns: 1fr; } .inquiry-form .wide, .inquiry-form button { grid-column: auto; } .request-toolbar { align-items: flex-start; flex-direction: column; } .topbar { align-items: flex-start; flex-direction: column; } .topbar-actions, .panel-actions { width: 100%; justify-content: space-between; } .panel { padding: 16px; } }
|
||||
@@ -18,6 +18,9 @@ import { UserRateLimitGuard } from './user-rate-limit.guard';
|
||||
{
|
||||
ttl: config.get<number>('throttle.ttl', 60) * 1000,
|
||||
limit: config.get<number>('throttle.limit', 100),
|
||||
// Keep the guard registered so route-level metadata remains intact,
|
||||
// but allow local batch tests to disable enforcement explicitly.
|
||||
skipIf: () => !config.get<boolean>('throttle.enabled', true),
|
||||
},
|
||||
],
|
||||
}),
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { Request } from 'express';
|
||||
import { AuthenticatedUser } from '../auth/interfaces/authenticated-user.interface';
|
||||
import { UsersService } from '../users/users.service';
|
||||
@@ -18,9 +19,14 @@ export class UserRateLimitGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly rateLimitService: UserRateLimitService,
|
||||
private readonly usersService: UsersService,
|
||||
private readonly configService: ConfigService,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
if (!this.configService.get<boolean>('throttle.enabled', true)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const request = context.switchToHttp().getRequest<Request & { user?: AuthenticatedUser }>();
|
||||
const user = request.user;
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { DistributedLockService } from '../../src/providers/services/distributed-lock.service';
|
||||
|
||||
describe('DistributedLockService', () => {
|
||||
it('runs the operation under an acquired lease and releases it', async () => {
|
||||
const service = new DistributedLockService({} as never);
|
||||
const lease = {
|
||||
lockKey: 'provider-token:TejaratNou',
|
||||
ownerId: 'owner-1',
|
||||
fencingToken: 1,
|
||||
};
|
||||
const acquire = jest.spyOn(service, 'acquire').mockResolvedValue(lease);
|
||||
const release = jest.spyOn(service, 'release').mockResolvedValue(undefined);
|
||||
|
||||
await expect(service.withLock(lease.lockKey, async () => 'ok')).resolves.toBe('ok');
|
||||
expect(acquire).toHaveBeenCalled();
|
||||
expect(release).toHaveBeenCalledWith(lease);
|
||||
});
|
||||
|
||||
it('fails after the configured wait when the lock is held elsewhere', async () => {
|
||||
const service = new DistributedLockService({} as never);
|
||||
jest.spyOn(service, 'acquire').mockResolvedValue(null);
|
||||
|
||||
await expect(service.withLock('busy', async () => 'never', { waitMs: 2 })).rejects.toMatchObject({
|
||||
code: 'ELOCKED',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
import { HealthService } from '../../src/health/health.service';
|
||||
|
||||
describe('HealthService', () => {
|
||||
it('provides safe defaults for memory and disk health checks', () => {
|
||||
const service = new HealthService();
|
||||
expect(service.heapThresholdBytes()).toBe(512 * 1024 * 1024);
|
||||
expect(service.diskThresholdPercent()).toBe(0.9);
|
||||
expect(service.diskPath()).toBe('/');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
import { IdempotencyService } from '../../src/idempotency/idempotency.service';
|
||||
import { IdempotencyRecordStatus } from '../../src/idempotency/schemas/idempotency-record.schema';
|
||||
|
||||
class FakeRecordModel {
|
||||
private readonly records = new Map<string, any>();
|
||||
|
||||
findOne(filter: { scopeHash: string }) {
|
||||
return { exec: async () => this.records.get(filter.scopeHash) ?? null };
|
||||
}
|
||||
|
||||
async create(record: any) {
|
||||
if (this.records.has(record.scopeHash)) {
|
||||
throw Object.assign(new Error('duplicate'), { code: 11000 });
|
||||
}
|
||||
const saved = { ...record, _id: record.scopeHash };
|
||||
this.records.set(record.scopeHash, saved);
|
||||
return saved;
|
||||
}
|
||||
|
||||
updateOne(filter: { scopeHash: string; status: IdempotencyRecordStatus }, update: any) {
|
||||
return {
|
||||
exec: async () => {
|
||||
const record = this.records.get(filter.scopeHash);
|
||||
if (record?.status === filter.status) Object.assign(record, update.$set);
|
||||
return { acknowledged: true };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
deleteOne(filter: { scopeHash: string; status: IdempotencyRecordStatus }) {
|
||||
return {
|
||||
exec: async () => {
|
||||
const record = this.records.get(filter.scopeHash);
|
||||
if (record?.status === filter.status) this.records.delete(filter.scopeHash);
|
||||
return { acknowledged: true };
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
describe('IdempotencyService', () => {
|
||||
it('replays completed responses and rejects body reuse', async () => {
|
||||
const service = new IdempotencyService(new FakeRecordModel() as never);
|
||||
const input = {
|
||||
key: 'request-1',
|
||||
callerId: 'user-1',
|
||||
method: 'POST',
|
||||
path: '/inquiry/person',
|
||||
body: { birthDate: '1370-01-01', nationalCode: '0012345678' },
|
||||
};
|
||||
|
||||
const reservation = await service.begin(input);
|
||||
const response = { success: true, trackingCode: 'INQ-1' };
|
||||
await service.complete(reservation.scopeHash, response, 201);
|
||||
|
||||
const replay = await service.begin(input);
|
||||
expect(replay.replay).toMatchObject({ responseStatus: 201, responseBody: response });
|
||||
|
||||
await expect(service.begin({ ...input, body: { different: true } })).rejects.toMatchObject({
|
||||
normalizedError: { code: 'IDEMPOTENCY_KEY_REUSED' },
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects a duplicate while the original request is in progress', async () => {
|
||||
const service = new IdempotencyService(new FakeRecordModel() as never);
|
||||
const input = {
|
||||
key: 'request-2',
|
||||
callerId: 'user-1',
|
||||
method: 'POST',
|
||||
path: '/inquiry/person',
|
||||
body: { nationalCode: '0012345678' },
|
||||
};
|
||||
|
||||
await service.begin(input);
|
||||
await expect(service.begin(input)).rejects.toMatchObject({
|
||||
normalizedError: { code: 'IDEMPOTENCY_REQUEST_IN_PROGRESS' },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import { InquiryType } from '../../src/common/enums/inquiry-type.enum';
|
||||
import { ParsianProvider } from '../../src/providers/implementations/parsian.provider';
|
||||
|
||||
describe('Parsian third-party plate routing', () => {
|
||||
it('uses the one-factor car-by-plate provider path without a national-code lookup', async () => {
|
||||
const inquireCarByPlate = jest.fn().mockResolvedValue({ raw: { policy: true } });
|
||||
const inquireThirdPartyCar = jest.fn();
|
||||
const provider = Object.create(ParsianProvider.prototype) as any;
|
||||
provider.config = {};
|
||||
provider.centInsurCarSupport = { inquireCarByPlate, inquireThirdPartyCar };
|
||||
|
||||
const result = await provider.callProvider(
|
||||
InquiryType.THIRD_PARTY_CAR,
|
||||
{ nationalCode: '1234567890', plk1: '16', plk2: 'ب', plk3: '498', plksrl: '60' },
|
||||
{ requestId: 'req-1', trackingCode: 'trk-1' },
|
||||
);
|
||||
|
||||
expect(result).toEqual({ raw: { policy: true } });
|
||||
expect(inquireCarByPlate).toHaveBeenCalledTimes(1);
|
||||
expect(inquireThirdPartyCar).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import { ProviderName } from '../../src/common/enums/provider-name.enum';
|
||||
import { ProviderIsolationService } from '../../src/providers/strategy/provider-isolation.service';
|
||||
|
||||
describe('ProviderIsolationService', () => {
|
||||
const provider = ProviderName.HAMTA;
|
||||
|
||||
beforeEach(() => {
|
||||
delete process.env.PROVIDER_CIRCUIT_FAILURE_THRESHOLD;
|
||||
delete process.env.PROVIDER_CIRCUIT_OPEN_MS;
|
||||
delete process.env.PROVIDER_BULKHEAD_LIMIT;
|
||||
});
|
||||
|
||||
it('opens after repeated normalized transport failures and allows a half-open probe', async () => {
|
||||
process.env.PROVIDER_CIRCUIT_FAILURE_THRESHOLD = '2';
|
||||
process.env.PROVIDER_CIRCUIT_OPEN_MS = '20';
|
||||
const isolation = new ProviderIsolationService();
|
||||
const failure = () => {
|
||||
const error = new Error('upstream timeout') as Error & {
|
||||
normalizedError: { code: string };
|
||||
};
|
||||
error.normalizedError = { code: 'PROVIDER_TIMEOUT' };
|
||||
return Promise.reject(error);
|
||||
};
|
||||
|
||||
await expect(isolation.execute(provider, failure)).rejects.toThrow('upstream timeout');
|
||||
await expect(isolation.execute(provider, failure)).rejects.toThrow('upstream timeout');
|
||||
await expect(isolation.execute(provider, async () => 'blocked')).rejects.toMatchObject({
|
||||
normalizedError: { code: 'PROVIDER_CIRCUIT_OPEN' },
|
||||
});
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 25));
|
||||
await expect(isolation.execute(provider, async () => 'recovered')).resolves.toBe('recovered');
|
||||
expect(isolation.snapshot(provider)).toMatchObject({
|
||||
consecutiveFailures: 0,
|
||||
openUntil: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects work when the provider bulkhead is full', async () => {
|
||||
process.env.PROVIDER_BULKHEAD_LIMIT = '1';
|
||||
const isolation = new ProviderIsolationService();
|
||||
let release!: () => void;
|
||||
const held = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
|
||||
const first = isolation.execute(provider, async () => {
|
||||
await held;
|
||||
return 'done';
|
||||
});
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
|
||||
await expect(isolation.execute(provider, async () => 'blocked')).rejects.toMatchObject({
|
||||
normalizedError: { code: 'PROVIDER_BULKHEAD_FULL' },
|
||||
});
|
||||
|
||||
release();
|
||||
await expect(first).resolves.toBe('done');
|
||||
});
|
||||
});
|
||||
@@ -14,6 +14,7 @@ describe('provider resilience helpers', () => {
|
||||
it('retries transport failures but not 429 or business rejects', () => {
|
||||
expect(isTransportRetryable({ code: 'ETIMEDOUT' })).toBe(true);
|
||||
expect(isTransportRetryable({ response: { status: 503 } })).toBe(true);
|
||||
expect(isTransportRetryable({ response: { status: 404 } })).toBe(true);
|
||||
expect(isTransportRetryable({ response: { status: 429 } })).toBe(false);
|
||||
expect(
|
||||
isTransportRetryable({
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import {
|
||||
getCarPolicyProviderError,
|
||||
parseFirstCarPolicy,
|
||||
} from '../../src/common/helpers/soap-car-policy.helper';
|
||||
|
||||
describe('Parsian car-policy SOAP responses', () => {
|
||||
it('extracts the Persian message from a nested KeyValue error and classifies no-policy', () => {
|
||||
const xml = `
|
||||
<CIIWSPolicyNationalIdResult>
|
||||
<b:Error>
|
||||
<b:KeyValueOfstringstring>
|
||||
<b:Key>2</b:Key>
|
||||
<b:Value> موردی یافت نشد .</b:Value>
|
||||
</b:KeyValueOfstringstring>
|
||||
</b:Error>
|
||||
</CIIWSPolicyNationalIdResult>`;
|
||||
|
||||
expect(getCarPolicyProviderError(xml, parseFirstCarPolicy(xml))).toEqual({
|
||||
message: 'موردی یافت نشد .',
|
||||
code: 'CAR_POLICY_NOT_FOUND',
|
||||
providerCode: '2',
|
||||
});
|
||||
});
|
||||
|
||||
it('does not classify an unrelated provider error as a no-policy result', () => {
|
||||
const xml = `
|
||||
<CIIWSPolicyNationalIdResult>
|
||||
<b:Error>
|
||||
<b:KeyValueOfstringstring>
|
||||
<b:Key>500</b:Key>
|
||||
<b:Value>خطای موقت سرویس</b:Value>
|
||||
</b:KeyValueOfstringstring>
|
||||
</b:Error>
|
||||
</CIIWSPolicyNationalIdResult>`;
|
||||
|
||||
expect(getCarPolicyProviderError(xml, parseFirstCarPolicy(xml))).toEqual({
|
||||
message: 'خطای موقت سرویس',
|
||||
code: 'PROVIDER_ERROR',
|
||||
providerCode: '500',
|
||||
});
|
||||
});
|
||||
|
||||
it('uses the car-policy catalog code when the response has no policy and no explicit error', () => {
|
||||
const xml = '<CIIWSPolicyNationalIdResult><b:Error i:nil="true" /></CIIWSPolicyNationalIdResult>';
|
||||
|
||||
expect(getCarPolicyProviderError(xml, {})).toEqual({
|
||||
message: 'No policy record found',
|
||||
code: 'CAR_POLICY_NOT_FOUND',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -42,6 +42,34 @@ describe('timeout / deadline resilience bugs', () => {
|
||||
expect(Date.now() - started).toBeLessThan(250);
|
||||
});
|
||||
|
||||
it('aborts the active operation when the attempt timeout wins', async () => {
|
||||
let aborted = false;
|
||||
|
||||
await expect(
|
||||
runWithProviderResilience(
|
||||
(signal) =>
|
||||
new Promise((resolve) => {
|
||||
signal?.addEventListener('abort', () => {
|
||||
aborted = true;
|
||||
resolve('cancelled');
|
||||
});
|
||||
}),
|
||||
{
|
||||
providerName: 'PARSIAN',
|
||||
maxAttempts: 1,
|
||||
timeoutMs: 150,
|
||||
context: {
|
||||
requestId: 'req',
|
||||
trackingCode: 'trk',
|
||||
},
|
||||
label: 'PARSIAN request',
|
||||
},
|
||||
),
|
||||
).rejects.toMatchObject({ code: 'ETIMEDOUT' });
|
||||
|
||||
expect(aborted).toBe(true);
|
||||
});
|
||||
|
||||
it('default inquiry deadline must exceed a single slow CentInsur SOAP (~30s)', () => {
|
||||
// thirdPartyCar may need two SOAP calls over a proxy; 20s was killing successful ~28s responses
|
||||
expect(INQUIRY_DEADLINE_MS).toBeGreaterThanOrEqual(60_000);
|
||||
|
||||
Reference in New Issue
Block a user