[PR #6954] [CLOSED] feat(clients): persist depletion timestamp and derive current reasons #6539

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

📋 Pull Request Information

Original PR: https://github.com/MHSanaei/3x-ui/pull/6954
Author: @HamedSanaei
Created: 10/26/2026
Status: ❌ Closed

Base: main ← Head: codex/persist-client-depletion


📝 Commits (1)

  • b6ec3bd feat(clients): persist depletion timestamp and derive current reasons

📊 Changes

45 files changed (+3341 additions, -296 deletions)

View changed files

📝 .github/workflows/ci.yml (+13 -3)
📝 docs/content/docs/en/reference/api/clients.mdx (+17 -6)
📝 docs/custom-subscription-templates.md (+56 -0)
📝 docs/public/openapi.json (+307 -31)
📝 frontend/public/openapi.json (+307 -31)
📝 frontend/src/env.d.ts (+2 -0)
📝 frontend/src/generated/examples.ts (+68 -0)
📝 frontend/src/generated/schemas.ts (+122 -0)
📝 frontend/src/generated/types.ts (+27 -0)
📝 frontend/src/generated/zod.ts (+29 -0)
📝 frontend/src/pages/api-docs/endpoints.ts (+9 -19)
📝 frontend/src/schemas/client.ts (+4 -0)
➕ frontend/src/test/client-depletion-schema.test.ts (+35 -0)
➕ internal/database/client_depletion_migration_test.go (+172 -0)
📝 internal/database/db.go (+35 -0)
📝 internal/database/dump_sqlite_test.go (+2 -2)
📝 internal/database/migrate_data.go (+6 -1)
➕ internal/nodee2e/client_depletion_test.go (+61 -0)
📝 internal/sub/controller.go (+25 -23)
➕ internal/sub/depletion_test.go (+133 -0)

...and 25 more files

📄 Description

Summary

Persist the start of a client's current automatic-depletion period in one database column and derive its current reasons when existing responses are read. Expose the read-only fields through client details, traffic/inbound responses, subscription info JSON, and custom subscription templates.

Why

Closes #6883.

A timestamp should survive restarts and partial recovery, while a reason must follow current quota and expiry conditions rather than retain a stale cause. Existing routes, authentication, request handling, response envelopes, portable export/import, and renewal eligibility remain unchanged.

Database and lifecycle

  • Add only depleted_at BIGINT NOT NULL DEFAULT 0; no new table or index. The explicit SQLite/PostgreSQL migration is idempotent, normalizes nullable timestamps, preserves existing values, and enforces the default and nullability. Historical event times remain unknown.
  • depletedReason is a read-only SQL projection: "", "traffic", "expiry", or "both". A legacy depleted_reason column is retained in place but is neither created nor maintained by this implementation. Database copying excludes virtual fields and retains the timestamp.
  • Record the first timestamp atomically with automatic disablement. Preserve it through partial recovery and manual toggles. Expiry uses its exact boundary; traffic uses detection time, normally within the five-second traffic-job interval. Unknown timestamps stay 0 even when the current reason is known.
  • Reuse the enforcement predicates for the authoritative shared traffic accumulator and fresh, independent cross-panel aggregates. Display-only per-direction maxima never determine depletion. Quota arithmetic avoids PostgreSQL overflow when valid individual counters have an oversized sum.
  • Clear obsolete timestamps in the existing mutation transactions, in bounded email batches. Reads mask obsolete timestamps without writing. Remove periodic full-table metadata cleanup; empty node-mutation scopes are no-ops. Active clients without a timestamp retain the original counter UPDATE.
  • Preserve accepted node timestamps and the existing stale-report, pending-reset, frozen-lifecycle, and renewal safeguards. Restore upstream's unattached-client renewal behavior. No new cross-node reset policy or runtime dispatch is introduced.

API and subscription semantics

Existing client-detail objects gain depletedAt and depletedReason beside usedTraffic; existing traffic objects gain the same fields. A typed response DTO drives generated schemas and examples without adding these columns to the client record. Frontend parsers continue accepting older responses without the fields.

During traffic -> both -> expiry -> recovered, a known timestamp remains unchanged until full recovery, then becomes 0. Crossing an expiry boundary changes the current reason on a read without an UPDATE. For example, this metadata fragment can change from "traffic" to "both" while retaining its timestamp:

{"depletedAt": 1700000000000, "depletedReason": "both"}

For a shared subscription ID, every distinct member must currently be depleted, including members without emitted links. Otherwise the result is 0/"". When all members are depleted, reasons are the union of their causes: mixed traffic-only and expiry-only members produce "both", without claiming that every member has both causes. Return the latest member timestamp only when every timestamp is known; otherwise return 0 with the current aggregate reason. Reuse the batched traffic load rather than issue a second metadata lookup.

Accounting boundary

Existing legacy adoption behavior can start a missing master traffic row at zero on a known node inbound. The master then undercounts usage from before adoption. Metadata follows its authoritative shared accumulator and fresh cross-panel totals; node baselines have no quota-period identifier and cannot safely reconstruct the missing period. This limitation is documented and covered by regression tests. Other nodes' counters and independent renewal periods are preserved.

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Documentation
  • Tests only
  • Build / CI / tooling
  • Other

Areas affected

  • Frontend (UI / panel pages)
  • Backend (API endpoints, login, settings)
  • Xray config generation
  • Subscription (share links / Clash / JSON)
  • Statistics / traffic counters
  • Database / migrations
  • Install / upgrade script
  • Docker image
  • Multi-node (sub-nodes)
  • Telegram bot

Frontend changes are response schemas and API documentation only; there is no new UI or translation key.

How was this tested?

TDD reproductions cover stale reasons after expiry, continuous and recovered periods, cross-panel freshness gaps, independent master totals, read-only legacy columns, nullable migrations, PostgreSQL counter overflow, and idle node synchronization accidentally sweeping unrelated metadata. Regression coverage also includes manual toggles, resets/corrections/limit edits, renewal, imports, rollback, concurrency, 400-client chunk boundaries, node snapshots, subscription aggregation, template rendering, and older frontend responses. Additional red-to-green cases cover extending an already-expired deadline while stale global evidence exists, nullable legacy limits, server-derived metadata in inbound mutation responses, and rejecting foreign-client metadata in those responses.

Local verification used Linux/amd64 under WSL, Go 1.27.3, Node 26.3.0, SQLite, and a disposable PostgreSQL 16 database:

  • make verify passed on the final commit, including generated artifacts, Go/frontend checks, frontend/Go builds, Storybook, and matching published OpenAPI specifications.
  • After the final lifecycle and mutation-response corrections, GOFLAGS=-p=2 make gen-check lint-go test-go and GOFLAGS=-p=2 make race passed on the final tree.
  • PostgreSQL migration, depletion lifecycle, durable-first, heartbeat, node/IP, subscription, and database-copy tests passed. Optional scale tests were excluded from that CI-equivalent selection. An exploratory broader run reached its cumulative ten-minute timeout; the interrupted 20,000-client bulk-operations case passed separately in 65.5 seconds.
  • The node contract suite and make node-e2e passed; the latter ran real disposable panels, including depletion/recovery, restart, and chained global-traffic synchronization.
  • Link-parser and TLS-pin fuzz targets each passed 30 seconds with two workers.
  • Docs typecheck, lint, formatting, tests, API regeneration, and the actual pre-commit hook passed. The committed Git tree matches the validated Linux tree.

Remote CI: all 12 checks passed on b6ec3bdc7d428dcdd84a4280e9539e79df87f66c, including PostgreSQL migrations/lifecycle, race, frontend, parser fuzzing, and node end-to-end tests. Verified on 2026-10-26.

Database performance

Identical benchmark harness against old PR HEAD 31ceee68c35360e6cc776cec5ee36052474dafdb and this implementation, on the same i7-1185G7 Linux host. Ten measured iterations per case; setup excluded. These are point estimates, not statistical performance guarantees. The idle measurement covers the depletion phase, not the entire traffic job. Reads use the existing full traffic loader; active-counter measurements update every listed client in one transaction.

Without cross-panel/node reports, before -> after in milliseconds:

Clients Idle depletion phase Active counter batch Traffic read
1,000 0.209 -> 0.118 22.097 -> 28.504 4.073 -> 4.887
5,000 0.583 -> 0.339 88.536 -> 98.510 20.422 -> 30.624
20,000 2.071 -> 1.218 366.352 -> 308.736 77.532 -> 110.093

With one fresh master report and one node baseline per client, before -> after in milliseconds:

Clients Idle depletion phase Active counter batch Traffic read
1,000 1.184 -> 0.594 23.006 -> 20.352 10.042 -> 8.658
5,000 3.196 -> 2.930 87.352 -> 79.614 36.324 -> 40.539
20,000 12.273 -> 11.631 382.375 -> 316.358 153.518 -> 158.203

Statement budgets:

  • Idle depletion: two reads before and after; one metadata UPDATE becomes zero at every size.
  • Active counters: one read and exactly N existing counter UPDATEs before and after; no additional per-client statement.
  • A 401-member shared subscription with a duplicate identity uses three queries, down from four; the two metadata batches are reused for counters and aggregation.
  • Traffic reads: two reads without reports; 5/15/52 reads at 1k/5k/20k with reports, unchanged from the existing 400-email overlay batching. No UPDATEs.

Deriving current reasons adds read-side CPU, and the overflow-safe comparisons also have a measured cost with fresh reports. This trades some computation for correct current state and removal of repeated metadata writes; timings do not show a universal speedup.

Reproduce with go test ./internal/web/service -run '^$' -bench '^BenchmarkClientDepletion' -benchtime=10x -count=1, using the same harness on both revisions.

Breaking changes

None. Responses gain read-only fields, older responses remain accepted, and the timestamp column is added automatically. Historical depletion times cannot be reconstructed. Older binaries do not maintain this metadata, so history continuity through a downgrade is not guaranteed. Portable client exports still omit depletion history; database backups retain the timestamp.

Checklist

  • I tested the change locally and confirmed the described behavior.
  • I added or updated tests for the new behavior (when applicable).
  • go build ./... and the test suite pass locally.
  • For frontend changes: npm run lint, npm run typecheck, and npm run build pass.
  • I updated the Wiki / README / API docs if user-facing behavior changed.
  • My commits follow the project's existing message style.
  • I have no unrelated changes mixed into this PR.

🔄 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/6954 **Author:** [@HamedSanaei](https://github.com/HamedSanaei) **Created:** 10/26/2026 **Status:** ❌ Closed **Base:** `main` ← **Head:** `codex/persist-client-depletion` --- ### 📝 Commits (1) - [`b6ec3bd`](https://github.com/MHSanaei/3x-ui/commit/b6ec3bdc7d428dcdd84a4280e9539e79df87f66c) feat(clients): persist depletion timestamp and derive current reasons ### 📊 Changes **45 files changed** (+3341 additions, -296 deletions) <details> <summary>View changed files</summary> 📝 `.github/workflows/ci.yml` (+13 -3) 📝 `docs/content/docs/en/reference/api/clients.mdx` (+17 -6) 📝 `docs/custom-subscription-templates.md` (+56 -0) 📝 `docs/public/openapi.json` (+307 -31) 📝 `frontend/public/openapi.json` (+307 -31) 📝 `frontend/src/env.d.ts` (+2 -0) 📝 `frontend/src/generated/examples.ts` (+68 -0) 📝 `frontend/src/generated/schemas.ts` (+122 -0) 📝 `frontend/src/generated/types.ts` (+27 -0) 📝 `frontend/src/generated/zod.ts` (+29 -0) 📝 `frontend/src/pages/api-docs/endpoints.ts` (+9 -19) 📝 `frontend/src/schemas/client.ts` (+4 -0) ➕ `frontend/src/test/client-depletion-schema.test.ts` (+35 -0) ➕ `internal/database/client_depletion_migration_test.go` (+172 -0) 📝 `internal/database/db.go` (+35 -0) 📝 `internal/database/dump_sqlite_test.go` (+2 -2) 📝 `internal/database/migrate_data.go` (+6 -1) ➕ `internal/nodee2e/client_depletion_test.go` (+61 -0) 📝 `internal/sub/controller.go` (+25 -23) ➕ `internal/sub/depletion_test.go` (+133 -0) _...and 25 more files_ </details> ### 📄 Description ## Summary Persist the start of a client's current automatic-depletion period in one database column and derive its current reasons when existing responses are read. Expose the read-only fields through client details, traffic/inbound responses, subscription info JSON, and custom subscription templates. ## Why Closes #6883. A timestamp should survive restarts and partial recovery, while a reason must follow current quota and expiry conditions rather than retain a stale cause. Existing routes, authentication, request handling, response envelopes, portable export/import, and renewal eligibility remain unchanged. ### Database and lifecycle - Add only `depleted_at BIGINT NOT NULL DEFAULT 0`; no new table or index. The explicit SQLite/PostgreSQL migration is idempotent, normalizes nullable timestamps, preserves existing values, and enforces the default and nullability. Historical event times remain unknown. - `depletedReason` is a read-only SQL projection: `""`, `"traffic"`, `"expiry"`, or `"both"`. A legacy `depleted_reason` column is retained in place but is neither created nor maintained by this implementation. Database copying excludes virtual fields and retains the timestamp. - Record the first timestamp atomically with automatic disablement. Preserve it through partial recovery and manual toggles. Expiry uses its exact boundary; traffic uses detection time, normally within the five-second traffic-job interval. Unknown timestamps stay `0` even when the current reason is known. - Reuse the enforcement predicates for the authoritative shared traffic accumulator and fresh, independent cross-panel aggregates. Display-only per-direction maxima never determine depletion. Quota arithmetic avoids PostgreSQL overflow when valid individual counters have an oversized sum. - Clear obsolete timestamps in the existing mutation transactions, in bounded email batches. Reads mask obsolete timestamps without writing. Remove periodic full-table metadata cleanup; empty node-mutation scopes are no-ops. Active clients without a timestamp retain the original counter UPDATE. - Preserve accepted node timestamps and the existing stale-report, pending-reset, frozen-lifecycle, and renewal safeguards. Restore upstream's unattached-client renewal behavior. No new cross-node reset policy or runtime dispatch is introduced. ### API and subscription semantics Existing client-detail objects gain `depletedAt` and `depletedReason` beside `usedTraffic`; existing traffic objects gain the same fields. A typed response DTO drives generated schemas and examples without adding these columns to the client record. Frontend parsers continue accepting older responses without the fields. During `traffic -> both -> expiry -> recovered`, a known timestamp remains unchanged until full recovery, then becomes `0`. Crossing an expiry boundary changes the current reason on a read without an UPDATE. For example, this metadata fragment can change from `"traffic"` to `"both"` while retaining its timestamp: ```json {"depletedAt": 1700000000000, "depletedReason": "both"} ``` For a shared subscription ID, every distinct member must currently be depleted, including members without emitted links. Otherwise the result is `0`/`""`. When all members are depleted, reasons are the union of their causes: mixed traffic-only and expiry-only members produce `"both"`, without claiming that every member has both causes. Return the latest member timestamp only when every timestamp is known; otherwise return `0` with the current aggregate reason. Reuse the batched traffic load rather than issue a second metadata lookup. ### Accounting boundary Existing legacy adoption behavior can start a missing master traffic row at zero on a known node inbound. The master then undercounts usage from before adoption. Metadata follows its authoritative shared accumulator and fresh cross-panel totals; node baselines have no quota-period identifier and cannot safely reconstruct the missing period. This limitation is documented and covered by regression tests. Other nodes' counters and independent renewal periods are preserved. ## Type of change - [ ] Bug fix - [x] New feature - [ ] Refactoring (no behavior change) - [x] Documentation - [ ] Tests only - [ ] Build / CI / tooling - [ ] Other ## Areas affected - [x] Frontend (UI / panel pages) - [x] Backend (API endpoints, login, settings) - [ ] Xray config generation - [x] Subscription (share links / Clash / JSON) - [x] Statistics / traffic counters - [x] Database / migrations - [ ] Install / upgrade script - [ ] Docker image - [x] Multi-node (sub-nodes) - [ ] Telegram bot Frontend changes are response schemas and API documentation only; there is no new UI or translation key. ## How was this tested? TDD reproductions cover stale reasons after expiry, continuous and recovered periods, cross-panel freshness gaps, independent master totals, read-only legacy columns, nullable migrations, PostgreSQL counter overflow, and idle node synchronization accidentally sweeping unrelated metadata. Regression coverage also includes manual toggles, resets/corrections/limit edits, renewal, imports, rollback, concurrency, 400-client chunk boundaries, node snapshots, subscription aggregation, template rendering, and older frontend responses. Additional red-to-green cases cover extending an already-expired deadline while stale global evidence exists, nullable legacy limits, server-derived metadata in inbound mutation responses, and rejecting foreign-client metadata in those responses. Local verification used Linux/amd64 under WSL, Go 1.27.3, Node 26.3.0, SQLite, and a disposable PostgreSQL 16 database: - `make verify` passed on the final commit, including generated artifacts, Go/frontend checks, frontend/Go builds, Storybook, and matching published OpenAPI specifications. - After the final lifecycle and mutation-response corrections, `GOFLAGS=-p=2 make gen-check lint-go test-go` and `GOFLAGS=-p=2 make race` passed on the final tree. - PostgreSQL migration, depletion lifecycle, durable-first, heartbeat, node/IP, subscription, and database-copy tests passed. Optional scale tests were excluded from that CI-equivalent selection. An exploratory broader run reached its cumulative ten-minute timeout; the interrupted 20,000-client bulk-operations case passed separately in 65.5 seconds. - The node contract suite and `make node-e2e` passed; the latter ran real disposable panels, including depletion/recovery, restart, and chained global-traffic synchronization. - Link-parser and TLS-pin fuzz targets each passed 30 seconds with two workers. - Docs typecheck, lint, formatting, tests, API regeneration, and the actual pre-commit hook passed. The committed Git tree matches the validated Linux tree. Remote CI: all 12 checks passed on `b6ec3bdc7d428dcdd84a4280e9539e79df87f66c`, including PostgreSQL migrations/lifecycle, race, frontend, parser fuzzing, and node end-to-end tests. Verified on 2026-10-26. ### Database performance Identical benchmark harness against old PR HEAD `31ceee68c35360e6cc776cec5ee36052474dafdb` and this implementation, on the same i7-1185G7 Linux host. Ten measured iterations per case; setup excluded. These are point estimates, not statistical performance guarantees. The idle measurement covers the depletion phase, not the entire traffic job. Reads use the existing full traffic loader; active-counter measurements update every listed client in one transaction. Without cross-panel/node reports, before -> after in milliseconds: | Clients | Idle depletion phase | Active counter batch | Traffic read | | --- | --- | --- | --- | | 1,000 | 0.209 -> 0.118 | 22.097 -> 28.504 | 4.073 -> 4.887 | | 5,000 | 0.583 -> 0.339 | 88.536 -> 98.510 | 20.422 -> 30.624 | | 20,000 | 2.071 -> 1.218 | 366.352 -> 308.736 | 77.532 -> 110.093 | With one fresh master report and one node baseline per client, before -> after in milliseconds: | Clients | Idle depletion phase | Active counter batch | Traffic read | | --- | --- | --- | --- | | 1,000 | 1.184 -> 0.594 | 23.006 -> 20.352 | 10.042 -> 8.658 | | 5,000 | 3.196 -> 2.930 | 87.352 -> 79.614 | 36.324 -> 40.539 | | 20,000 | 12.273 -> 11.631 | 382.375 -> 316.358 | 153.518 -> 158.203 | Statement budgets: - Idle depletion: two reads before and after; one metadata UPDATE becomes zero at every size. - Active counters: one read and exactly N existing counter UPDATEs before and after; no additional per-client statement. - A 401-member shared subscription with a duplicate identity uses three queries, down from four; the two metadata batches are reused for counters and aggregation. - Traffic reads: two reads without reports; 5/15/52 reads at 1k/5k/20k with reports, unchanged from the existing 400-email overlay batching. No UPDATEs. Deriving current reasons adds read-side CPU, and the overflow-safe comparisons also have a measured cost with fresh reports. This trades some computation for correct current state and removal of repeated metadata writes; timings do not show a universal speedup. Reproduce with `go test ./internal/web/service -run '^$' -bench '^BenchmarkClientDepletion' -benchtime=10x -count=1`, using the same harness on both revisions. ## Breaking changes None. Responses gain read-only fields, older responses remain accepted, and the timestamp column is added automatically. Historical depletion times cannot be reconstructed. Older binaries do not maintain this metadata, so history continuity through a downgrade is not guaranteed. Portable client exports still omit depletion history; database backups retain the timestamp. ## Checklist - [x] I tested the change locally and confirmed the described behavior. - [x] I added or updated tests for the new behavior (when applicable). - [x] `go build ./...` and the test suite pass locally. - [x] For frontend changes: `npm run lint`, `npm run typecheck`, and `npm run build` pass. - [x] I updated the Wiki / README / API docs if user-facing behavior changed. - [x] My commits follow the project's existing message style. - [x] I have no unrelated changes mixed into this PR. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-11-02 04:09:29 +07:00
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#6539
No description provided.