[PR #7005] feat(clients): expose derived depletion time and reason via API #6573

Open
opened 2026-11-02 04:09:45 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/MHSanaei/3x-ui/pull/7005
Author: @HamedSanaei
Created: 10/28/2026
Status: 🔄 Open

Base: main ← Head: feat/derived-client-depletion-6883


📝 Commits (1)

  • 582f766 feat(clients): derive depletion metadata on demand

📊 Changes

13 files changed (+1526 additions, -37 deletions)

View changed files

📝 docs/content/docs/en/reference/api/clients.mdx (+38 -5)
📝 docs/public/openapi.json (+303 -3)
📝 frontend/public/openapi.json (+303 -3)
📝 frontend/src/generated/examples.ts (+85 -0)
📝 frontend/src/generated/schemas.ts (+265 -0)
📝 frontend/src/generated/types.ts (+55 -0)
📝 frontend/src/generated/zod.ts (+59 -0)
📝 frontend/src/pages/api-docs/endpoints.ts (+8 -4)
📝 internal/web/controller/client.go (+37 -21)
➕ internal/web/controller/client_depletion.go (+57 -0)
➕ internal/web/controller/client_depletion_test.go (+271 -0)
➕ internal/web/controller/client_depletion_unit_test.go (+43 -0)
📝 tools/openapigen/main.go (+2 -1)

📄 Description

Problem

Single-client APIs do not expose convenient metadata for current quota exhaustion or expiration.

Previous approach

PR #6954 was closed without merge. It persisted depletion timestamps and changed database migrations, lifecycle processing, synchronization and subscription responses. This proposal implements derived estimates instead of persisted event history.

New approach and scope

Add read-only depletedAt and depletedReason only to:

  • GET /panel/api/clients/get/:email: top-level fields beside usedTraffic.
  • GET /panel/api/clients/traffic/:email: fields beside the existing traffic fields inside obj.

Reuse GetClientTrafficByEmail() and its existing fresh-global per-direction overlay. The detail handler reuses the traffic already loaded for usedTraffic; derivation adds no queries or writes. Overflow-safe addition saturates the single-email detail's usedTraffic at int64 limits rather than wrapping.

The calculation is O(1):

Current conditions depletedReason depletedAt (Unix ms)
Neither limit exceeded "" 0
Quota exhausted traffic lastOnline, including 0 when unknown
Absolute expiry reached expiry exact expiryTime
Both limits exceeded both earlier of positive lastOnline and expiryTime; otherwise expiryTime

A nonpositive quota is unlimited; nonpositive expiry is not an absolute deadline. Enable state does not determine the reason. Manually disabled clients below both limits receive zero/empty metadata; still-enabled clients over a limit already receive the corresponding reason. Resets, renewals and limit edits affect subsequent reads without metadata cleanup.

Compatibility and limits

No database columns, tables, indexes, migrations, stored metadata, jobs, cache, new dependencies or changes to enforcement/enable/disable processing. xray.ClientTraffic, model/service code, node-sync payloads, list APIs, subscriptions and UI behavior are unchanged. The shared base payload keeps subId/tgId responses free of the new fields, and absent/orphan traffic retains existing null/error behavior.

Traffic exhaustion time is deliberately an approximation from the existing lastOnline. Global reports supply no authoritative quota-exhaustion timestamp. These values describe current conditions, not historical audit events; they cannot reconstruct earlier depletion periods.

Runtime changes are limited to the client controller and a 57-line DTO/calculation file. API schemas/examples come from those Go response types. The remaining changes are tests, generator registration, generated artifacts and API documentation. Existing OpenAPI component schemas were compared with main and remain identical; four response/support schemas were added. The subId documentation now describes its unchanged base payload accurately.

Testing

All checks used disposable local SQLite/PostgreSQL data and an isolated Linux source copy (Go 1.27.3, Node 26.12.1, npm 11.20.0); no production deployment or database was used.

  • make verify — PASS: generation freshness, Go/frontend lint, formatting, typecheck, all Go packages, 2,022 frontend/Chromium Storybook tests across 215 files, panel and Go builds, Storybook build and matching published OpenAPI copies.
  • go test -race ./internal/web/controller/... -count=1 — PASS.
  • go test -race ./internal/web/controller -run '^Test(ClientDerivedDepletionHTTP|DeriveClientDepletion|ClientGetBySubID)' -count=1 — PASS on SQLite, including existing lookup contracts.
  • XUI_TEST_PG_DSN=<disposable PostgreSQL 16 DSN> go test -race ./internal/web/controller -run '^TestClientDerivedDepletionPostgres$' -count=1 -v — PASS; the same 18 API scenarios actually ran on PostgreSQL. This integration is opt-in and skips without that environment variable.
  • cd frontend && npm run gen; copy panel OpenAPI to docs; cd docs && npm run gen:api — PASS, outputs regenerated rather than edited manually.
  • make gen-check lint format-check, staged diff checks and comparison of the tested source with staged Git content — PASS after final formatting.

The initial HTTP regression failed because both endpoints omitted the fields, then passed after implementation. Pure calculation cases cover quota/expiry boundaries, both timestamp orderings and equality, zero/negative legacy values, unknown lastOnline, unlimited quota, one-millisecond expiry boundaries, repeatability and int64 overflow. API cases cover fresh/stale/no global data, directional maxima, overlapping masters without summation, global depletion followed by expiry, reset/quota increase/extended expiry while disabled, nullable SQL values and missing/orphan rows. Database write callbacks reject any write during reads, and query counters verify a single traffic lookup for each normal per-email request. Legacy traffic fields/envelopes and the absence of metadata on list/paged/subId/tgId responses are checked explicitly.

Closes #6883 with the documented change from persisted historical timestamps to read-only derived estimates.


🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/MHSanaei/3x-ui/pull/7005 **Author:** [@HamedSanaei](https://github.com/HamedSanaei) **Created:** 10/28/2026 **Status:** 🔄 Open **Base:** `main` ← **Head:** `feat/derived-client-depletion-6883` --- ### 📝 Commits (1) - [`582f766`](https://github.com/MHSanaei/3x-ui/commit/582f76657ff94241d4fd615140ae9619b3cd2207) feat(clients): derive depletion metadata on demand ### 📊 Changes **13 files changed** (+1526 additions, -37 deletions) <details> <summary>View changed files</summary> 📝 `docs/content/docs/en/reference/api/clients.mdx` (+38 -5) 📝 `docs/public/openapi.json` (+303 -3) 📝 `frontend/public/openapi.json` (+303 -3) 📝 `frontend/src/generated/examples.ts` (+85 -0) 📝 `frontend/src/generated/schemas.ts` (+265 -0) 📝 `frontend/src/generated/types.ts` (+55 -0) 📝 `frontend/src/generated/zod.ts` (+59 -0) 📝 `frontend/src/pages/api-docs/endpoints.ts` (+8 -4) 📝 `internal/web/controller/client.go` (+37 -21) ➕ `internal/web/controller/client_depletion.go` (+57 -0) ➕ `internal/web/controller/client_depletion_test.go` (+271 -0) ➕ `internal/web/controller/client_depletion_unit_test.go` (+43 -0) 📝 `tools/openapigen/main.go` (+2 -1) </details> ### 📄 Description ## Problem Single-client APIs do not expose convenient metadata for current quota exhaustion or expiration. ## Previous approach [PR #6954](https://github.com/MHSanaei/3x-ui/pull/6954) was closed without merge. It persisted depletion timestamps and changed database migrations, lifecycle processing, synchronization and subscription responses. This proposal implements derived estimates instead of persisted event history. ## New approach and scope Add read-only `depletedAt` and `depletedReason` only to: - `GET /panel/api/clients/get/:email`: top-level fields beside `usedTraffic`. - `GET /panel/api/clients/traffic/:email`: fields beside the existing traffic fields inside `obj`. Reuse `GetClientTrafficByEmail()` and its existing fresh-global per-direction overlay. The detail handler reuses the traffic already loaded for `usedTraffic`; derivation adds no queries or writes. Overflow-safe addition saturates the single-email detail's `usedTraffic` at int64 limits rather than wrapping. The calculation is O(1): | Current conditions | depletedReason | depletedAt (Unix ms) | | --- | --- | --- | | Neither limit exceeded | `""` | `0` | | Quota exhausted | `traffic` | `lastOnline`, including `0` when unknown | | Absolute expiry reached | `expiry` | exact `expiryTime` | | Both limits exceeded | `both` | earlier of positive `lastOnline` and `expiryTime`; otherwise `expiryTime` | A nonpositive quota is unlimited; nonpositive expiry is not an absolute deadline. Enable state does not determine the reason. Manually disabled clients below both limits receive zero/empty metadata; still-enabled clients over a limit already receive the corresponding reason. Resets, renewals and limit edits affect subsequent reads without metadata cleanup. ## Compatibility and limits No database columns, tables, indexes, migrations, stored metadata, jobs, cache, new dependencies or changes to enforcement/enable/disable processing. `xray.ClientTraffic`, model/service code, node-sync payloads, list APIs, subscriptions and UI behavior are unchanged. The shared base payload keeps subId/tgId responses free of the new fields, and absent/orphan traffic retains existing null/error behavior. Traffic exhaustion time is deliberately an approximation from the existing `lastOnline`. Global reports supply no authoritative quota-exhaustion timestamp. These values describe current conditions, not historical audit events; they cannot reconstruct earlier depletion periods. Runtime changes are limited to the client controller and a 57-line DTO/calculation file. API schemas/examples come from those Go response types. The remaining changes are tests, generator registration, generated artifacts and API documentation. Existing OpenAPI component schemas were compared with main and remain identical; four response/support schemas were added. The subId documentation now describes its unchanged base payload accurately. ## Testing All checks used disposable local SQLite/PostgreSQL data and an isolated Linux source copy (Go 1.27.3, Node 26.12.1, npm 11.20.0); no production deployment or database was used. - `make verify` — PASS: generation freshness, Go/frontend lint, formatting, typecheck, all Go packages, **2,022 frontend/Chromium Storybook tests across 215 files**, panel and Go builds, Storybook build and matching published OpenAPI copies. - `go test -race ./internal/web/controller/... -count=1` — PASS. - `go test -race ./internal/web/controller -run '^Test(ClientDerivedDepletionHTTP|DeriveClientDepletion|ClientGetBySubID)' -count=1` — PASS on SQLite, including existing lookup contracts. - `XUI_TEST_PG_DSN=<disposable PostgreSQL 16 DSN> go test -race ./internal/web/controller -run '^TestClientDerivedDepletionPostgres$' -count=1 -v` — PASS; the same 18 API scenarios actually ran on PostgreSQL. This integration is opt-in and skips without that environment variable. - `cd frontend && npm run gen`; copy panel OpenAPI to docs; `cd docs && npm run gen:api` — PASS, outputs regenerated rather than edited manually. - `make gen-check lint format-check`, staged diff checks and comparison of the tested source with staged Git content — PASS after final formatting. The initial HTTP regression failed because both endpoints omitted the fields, then passed after implementation. Pure calculation cases cover quota/expiry boundaries, both timestamp orderings and equality, zero/negative legacy values, unknown lastOnline, unlimited quota, one-millisecond expiry boundaries, repeatability and int64 overflow. API cases cover fresh/stale/no global data, directional maxima, overlapping masters without summation, global depletion followed by expiry, reset/quota increase/extended expiry while disabled, nullable SQL values and missing/orphan rows. Database write callbacks reject any write during reads, and query counters verify a single traffic lookup for each normal per-email request. Legacy traffic fields/envelopes and the absence of metadata on list/paged/subId/tgId responses are checked explicitly. ## Related issue Closes #6883 with the documented change from persisted historical timestamps to read-only derived estimates. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
MHSanaei/3x-ui#6573
No description provided.