feat(clients): add calendar weekly renewal and schedule previews (#6524)

* feat(clients): add calendar weekly renewal and schedule previews

Expose fixed-day, calendar-weekly, calendar-monthly, and disabled renewal
through one shared selector in individual and bulk client forms. Store the
weekly weekday separately (Monday 1 through Sunday 7) and use panel-local
calendar dates rather than a fixed 168-hour duration. Resolve skipped or
repeated midnights to the first valid instant of the selected date, and skip
an entirely nonexistent calendar date rather than changing the weekday.

Reuse the existing renewal writer and share its boundary alignment and
per-period catch-up calculation with an authenticated, read-only preview.
Keep monthly precedence for legacy records, fixed-day interval semantics,
maximum renewal allowances, first-use durations, and operator-disabled
settings unchanged. Selecting a mode does not rewrite an existing cutoff;
an unset calendar cutoff requires an explicit action to choose the first.
The last-valid-second preview uses the stored exclusive expiry, even when
the billing calculation aligns a legacy last-second cutoff up to midnight.

Carry weekly schedules through client persistence, paging, enable toggles,
inbound settings, and node traffic reconciliation. Migrate missing or nullable
weekday columns to disabled by default without altering existing limits, and
include the new isolated-schema PostgreSQL regression in the live CI gate.

Regenerate API contracts and reference documentation, add lifecycle and form
regressions, and document timezone, quota-reset, and upgrade considerations.
All participating nodes must be upgraded before weekly mode is enabled;
older binaries ignore the new field. Independent periodic traffic resets and
the optional month-end subscription-header display are not changed.

* fix(clients): validate renewal schedules across inbound write paths

Reject conflicting weekly/interval/monthly schedules and out-of-range
weekdays on inbound creation and edits, legacy one-client apply paths,
record/link synchronization, and traffic metadata writes. Validate imported
traffic snapshots as well, before any inbound or client is persisted, so
an inbound API cannot create a client that the clients page cannot toggle.

Merge a weekly-related schedule as one timestamp-selected tuple rather
than filling its zero fields from another renewal mode. Preserve empty
migration snapshots and the existing non-weekly monthly/interval merge
semantics. Renewal caps, counters, credentials, and deadlines are unchanged.

Add regressions for nine write paths, unchanged records and runtime calls
after rejection, valid inbound clients remaining editable, and duplicate
record merges between individually valid renewal modes.

* docs(clients): clarify depleted-client deletion risks on downgrade

Explain in English and Chinese that older versions not only stop weekly
renewal: their depleted-client cleanup can delete a weekly-only client once
its expiry or quota is exhausted. This is conditional on cleanup, not an
automatic deletion caused by downgrade itself.

Recommend backing up and converting weekly schedules to a mode supported
by every participating version before rollback, and avoiding cleanup while
mixed versions or unconverted clients remain. Merely disabling weekly
renewal does not restore the old binary's missing purge protection.

* fix(clients): bound weekly renewal date searches

Limit the search for a valid weekly calendar date to eight candidates so
an unusual timezone cannot monopolize the single traffic writer. Exhaustion
returns the original instant, allowing the existing catch-up forward-progress
guard to stop without advancing expiry, consuming an allowance, resetting
traffic, or falling back to a fixed-duration schedule that can drift.

Reject a non-future calendar suggestion in the read-only preview instead of
offering an immediately expired initial cutoff. Also report failed weekly
catch-up as a search error when allowances remain, not as cap exhaustion.
Existing preview errors use the form's current warning; no API schema or
locale changes are needed.

Exercise exhaustion with a synthetic valid TZif containing twelve skipped
Sundays. This fault-injection case was red without the bound; it is not a
claim that a production IANA timezone was observed hanging. Keep the Havana
and Apia regressions for real skipped/repeated midnights and absent dates.

* fix(tests): isolate weekly renewal preview timezone

Stop the weekly search regression from replacing process-global time.Local.
CI caught that assignment and its cleanup racing with background timer reads
through time.Now, even though the top-level tests do not use t.Parallel.

Pass the timezone and current instant into the unchanged preview calculation.
The public service still validates the request and resolves the panel timezone;
API responses, renewal accounting, and persisted client data are unchanged.

Use fixed dates for both suggestion and catch-up exhaustion, removing the
test's dependency on today's date and its unnecessary database setup. Keep a
bounded-lifetime background clock reader to expose future global-timezone
mutations under the existing race gate rather than disabling that check.

* ci: retrigger PR checks

Create an empty commit to request a fresh pull-request CI run after release dependency downloads failed with network errors.

No source, dependency, or workflow changes are included. Retry the existing checks without bypassing them.

* ci: retry PR checks and record deferred download hardening

Request another CI run after the amd64 release job compiled successfully but failed during dependency fetching with exit code 4 (network failure).

Record possible follow-up improvements for the Linux release fetch helper:
- Print each download URL and destination, and preserve error details.
- Reuse the existing curl configuration with up to five retries; add connection and per-attempt timeouts and a bounded retry window.
- Download to a temporary file and promote it to the final filename only after a successful, non-empty transfer. Keep the job failing if downloads ultimately fail.
- Validate successful downloads, recovery after a temporary failure, and correct failure after persistent errors before shipping such a change.

These improvements are intentionally deferred, not implemented or tested by this commit. This commit is empty: renewal logic, dependencies, workflow configuration, check requirements, and TLS verification remain unchanged.

---------

Co-authored-by: JacktheRanger <219502738+JacktheRanger@users.noreply.github.com>
This commit is contained in:
Jack
2026-09-27 04:59:23 +08:00
committed by GitHub
parent 5e15120cec
commit 9672249edb
58 changed files with 2712 additions and 197 deletions
+96 -1
View File
@@ -1,6 +1,10 @@
package service
import "time"
import (
"time"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
// nextCalendarRenewal returns the next renewal strictly after from, at midnight
// in loc; a missing day clamps to the month's last, so the 31st comes back (#6106).
@@ -40,3 +44,94 @@ func calendarDay(year int, month time.Month, day int, loc *time.Location) time.T
func daysInMonth(year int, month time.Month) int {
return time.Date(year, month+1, 0, 0, 0, 0, 0, time.UTC).Day()
}
// Advance by calendar dates, not 168 hours; a repeated midnight must not spend
// another weekly allowance on the same local date.
func nextWeeklyRenewal(from time.Time, weekday int, loc *time.Location) time.Time {
if loc == nil {
loc = time.UTC
}
local := from.In(loc)
days := (min(7, max(1, weekday))%7 - int(local.Weekday()) + 7) % 7
if days == 0 {
days = 7
}
date := time.Date(local.Year(), local.Month(), local.Day()+days, 0, 0, 0, 0, time.UTC)
// A corrupt or unusual zone must not stall the single traffic writer.
// Returning from lets the catch-up forward-progress guard fail closed.
for range 8 {
candidate, exists := localCalendarDateStart(date, loc)
if exists && candidate.After(local) {
return candidate
}
date = date.AddDate(0, 0, 7)
}
return from
}
// Find the first valid instant of a local date: Date can pick a repeated
// midnight or normalize a nonexistent midnight into the preceding day.
func localCalendarDateStart(date time.Time, loc *time.Location) (time.Time, bool) {
localDate := func(at time.Time) time.Time {
local := at.In(loc)
return time.Date(local.Year(), local.Month(), local.Day(), 0, 0, 0, 0, time.UTC)
}
candidate := time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, loc)
if localDate(candidate).Equal(date) && localDate(candidate.Add(-time.Second)).Before(date) {
return candidate, true
}
low, high := candidate.Unix()-86400, candidate.Unix()+86400
for low < high {
mid := low + (high-low)/2
if localDate(time.Unix(mid, 0)).Before(date) {
low = mid + 1
} else {
high = mid
}
}
start := time.Unix(low, 0).In(loc)
return start, localDate(start).Equal(date)
}
func nextClientRenewal(expiry int64, reset, day, weekday int, loc *time.Location) int64 {
if day > 0 {
return nextCalendarRenewal(time.UnixMilli(expiry), day, loc).UnixMilli()
}
if weekday > 0 {
return nextWeeklyRenewal(time.UnixMilli(expiry), weekday, loc).UnixMilli()
}
return expiry + int64(reset)*86400000
}
func canonicalRenewalExpiry(expiry int64, reset, day, weekday int, loc *time.Location) int64 {
if day > 0 || weekday > 0 {
boundary := nextClientRenewal(expiry, reset, day, weekday, loc)
if expiry >= boundary-1000 && expiry < boundary {
return boundary
}
}
return expiry
}
func catchUpClientRenewal(traffic *xray.ClientTraffic, now int64, loc *time.Location) (int64, int) {
if traffic.ResetDay <= 0 && traffic.ResetWeekday <= 0 && traffic.Reset <= 0 {
return traffic.ExpiryTime, 0
}
expiry := canonicalRenewalExpiry(traffic.ExpiryTime, traffic.Reset, traffic.ResetDay, traffic.ResetWeekday, loc)
renewals := 0
for expiry < now {
if traffic.ResetMax > 0 && traffic.ResetCount+renewals >= traffic.ResetMax {
break
}
next := nextClientRenewal(expiry, traffic.Reset, traffic.ResetDay, traffic.ResetWeekday, loc)
if next <= expiry {
return traffic.ExpiryTime, 0
}
expiry = next
renewals++
}
if renewals == 0 {
return traffic.ExpiryTime, 0
}
return expiry, renewals
}
@@ -0,0 +1,78 @@
package service
import (
"encoding/binary"
"testing"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
func TestWeeklyRenewalSearchFailsClosed(t *testing.T) {
// Keep a background clock reader so -race catches global timezone writes.
started, stop, done := make(chan struct{}), make(chan struct{}), make(chan struct{})
go func() {
defer close(done)
_ = time.Now()
close(started)
for {
select {
case <-stop:
return
default:
_ = time.Now()
}
}
}()
<-started
t.Cleanup(func() { close(stop); <-done })
// Fault injection: a valid TZif with twelve absent Sundays, not a claim
// about real IANA zones. Each following Monday repeats, so no Sunday returns.
const transitions = 24
data := make([]byte, 44+transitions*5+2*6+2)
copy(data, "TZif")
binary.BigEndian.PutUint32(data[32:36], transitions)
binary.BigEndian.PutUint32(data[36:40], 2)
binary.BigEndian.PutUint32(data[40:44], 2)
from := time.Date(2026, time.March, 1, 0, 0, 0, 0, time.UTC)
for week := range 12 {
at := from.AddDate(0, 0, (week+1)*7).Unix()
for day := range 2 {
index := week*2 + day
binary.BigEndian.PutUint32(data[44+index*4:48+index*4], uint32(at+int64(day)*86400))
data[44+transitions*4+index] = byte(1 - day)
}
}
binary.BigEndian.PutUint32(data[44+transitions*5+6:48+transitions*5+6], 86400)
data[len(data)-2] = 'X'
loc, err := time.LoadLocationFromTZData("Test/SkippedSundays", data)
if err != nil {
t.Fatal(err)
}
if got := nextWeeklyRenewal(from, 7, loc); !got.Equal(from) {
t.Fatalf("exhausted weekly search advanced to %s, want unchanged %s", got.Format(time.RFC3339), from.Format(time.RFC3339))
}
traffic := &xray.ClientTraffic{ExpiryTime: from.UnixMilli(), ResetWeekday: 7, ResetMax: 4, ResetCount: 2, Enable: false, Up: 111, Down: 222}
before := *traffic
expiry, renewals := catchUpClientRenewal(traffic, from.AddDate(0, 0, 28).UnixMilli(), loc)
if expiry != before.ExpiryTime || renewals != 0 || *traffic != before {
t.Fatalf("exhausted search changed billing/traffic: expiry=%d renewals=%d traffic=%+v", expiry, renewals, traffic)
}
for _, tt := range []struct {
name string
now int64
}{
{"initial suggestion exhausted", from.UnixMilli()},
{"catch-up exhausted with allowances left", from.AddDate(0, 3, 0).UnixMilli()},
} {
t.Run(tt.name, func(t *testing.T) {
preview, err := previewClientRenewal(ClientRenewalPreviewRequest{
ExpiryTime: before.ExpiryTime, ResetWeekday: 7, ResetMax: 4, ResetCount: 2,
}, tt.now, loc)
if err == nil || err.Error() != "calendar renewal could not find a future expiry\n" || preview != nil {
t.Fatalf("failed search preview/error = %+v/%v, want nil/calendar search error", preview, err)
}
})
}
}
@@ -0,0 +1,52 @@
package service
import (
"testing"
"time"
)
func TestNextWeeklyRenewal_RepeatedMidnight(t *testing.T) {
loc, err := time.LoadLocation("America/Havana")
if err != nil {
t.Fatal(err)
}
for _, tt := range []struct{ expiry, want string }{
{"2026-10-25T00:00:00-04:00", "2026-11-01T00:00:00-04:00"},
{"2026-11-01T00:00:00-04:00", "2026-11-08T00:00:00-05:00"},
{"2026-11-01T00:00:00-05:00", "2026-11-08T00:00:00-05:00"},
} {
from, err := time.Parse(time.RFC3339, tt.expiry)
if err != nil {
t.Fatal(err)
}
got := nextWeeklyRenewal(from, 7, loc).Format(time.RFC3339)
if got != tt.want {
t.Fatalf("next Sunday after %s = %s, want %s", tt.expiry, got, tt.want)
}
}
}
func TestNextWeeklyRenewal_SkippedDates(t *testing.T) {
for _, tt := range []struct {
zone, from, want string
weekday int
}{
{"America/Havana", "2026-03-01T00:00:00-05:00", "2026-03-08T01:00:00-04:00", 7},
{"Pacific/Apia", "2011-12-23T00:00:00-10:00", "2012-01-06T00:00:00+14:00", 5},
} {
t.Run(tt.zone, func(t *testing.T) {
loc, err := time.LoadLocation(tt.zone)
if err != nil {
t.Fatal(err)
}
from, err := time.Parse(time.RFC3339, tt.from)
if err != nil {
t.Fatal(err)
}
got := nextWeeklyRenewal(from, tt.weekday, loc).Format(time.RFC3339)
if got != tt.want {
t.Fatalf("next weekly cutoff = %s, want %s", got, tt.want)
}
})
}
}
+1 -1
View File
@@ -1303,7 +1303,7 @@ func (s *ClientService) BulkCreate(inboundSvc *InboundService, payloads []Client
skip(email, verr.Error())
continue
}
if verr := validateClientResetDay(client.ResetDay); verr != nil {
if verr := validateClientRenewal(client); verr != nil {
skip(email, verr.Error())
continue
}
+25 -2
View File
@@ -81,6 +81,28 @@ func validateClientResetMax(resetMax int) error {
return nil
}
func validateClientRenewal(client model.Client) error {
if err := validateClientResetDay(client.ResetDay); err != nil {
return err
}
if client.ResetWeekday < 0 || client.ResetWeekday > 7 {
return common.NewError("client resetWeekday must be between 0 and 7, got:", client.ResetWeekday)
}
if client.ResetWeekday > 0 && (client.Reset > 0 || client.ResetDay > 0) {
return common.NewError("client weekly renewal cannot be combined with reset or resetDay")
}
return nil
}
func validateClientsRenewal(clients []model.Client) error {
for _, client := range clients {
if err := validateClientRenewal(client); err != nil {
return err
}
}
return nil
}
// normalizeClientTrafficReset stores what the inbound path would store, so the
// day never reaches the DB as a 0 that three layers downstream each clamp to 1.
func normalizeClientTrafficReset(c *model.Client) {
@@ -137,7 +159,7 @@ func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreate
if err := validateClientSubID(client.SubID); err != nil {
return false, err
}
if err := validateClientResetDay(client.ResetDay); err != nil {
if err := validateClientRenewal(client); err != nil {
return false, err
}
if err := validateClientResetMax(client.ResetMax); err != nil {
@@ -591,7 +613,7 @@ func (s *ClientService) Update(inboundSvc *InboundService, id int, updated model
if err := validateClientSubID(updated.SubID); err != nil {
return false, err
}
if err := validateClientResetDay(updated.ResetDay); err != nil {
if err := validateClientRenewal(updated); err != nil {
return false, err
}
if err := validateClientResetMax(updated.ResetMax); err != nil {
@@ -756,6 +778,7 @@ func (s *ClientService) Update(inboundSvc *InboundService, id int, updated model
"comment": merged.Comment,
"reset": merged.Reset,
"reset_day": merged.ResetDay,
"reset_weekday": merged.ResetWeekday,
"reset_max": merged.ResetMax,
"traffic_reset": merged.TrafficReset,
"traffic_reset_day": merged.TrafficResetDay,
@@ -329,6 +329,9 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model
if err != nil {
return false, err
}
if err := validateClientsRenewal(clients); err != nil {
return false, err
}
var settings map[string]any
err = json.Unmarshal([]byte(data.Settings), &settings)
@@ -659,6 +662,9 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
if err != nil {
return false, err
}
if err := validateClientsRenewal(clients); err != nil {
return false, err
}
var settings map[string]any
err = json.Unmarshal([]byte(data.Settings), &settings)
+4
View File
@@ -65,6 +65,7 @@ func applyClientRecordMerge(row *model.ClientRecord, incoming *model.ClientRecor
row.Comment = incoming.Comment
row.Reset = incoming.Reset
row.ResetDay = incoming.ResetDay
row.ResetWeekday = incoming.ResetWeekday
row.ResetMax = incoming.ResetMax
// Guarded like Group and AdTag: a node snapshot rebuilt from settings that
// predate the cycle would otherwise silently erase it.
@@ -94,6 +95,9 @@ func (s *ClientService) ApplyInboundClientDelta(tx *gorm.DB, inboundId int, chan
}
func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients []model.Client, detachEmails []string, prune bool) error {
if err := validateClientsRenewal(clients); err != nil {
return err
}
if tx == nil {
tx = database.GetDB()
}
+36 -34
View File
@@ -18,22 +18,23 @@ import (
// so the list payload stays compact even when the panel manages thousands
// of clients. Modals that need the full record still call /get/:email.
type ClientSlim struct {
Email string `json:"email" example:"alice@example.com"`
SubID string `json:"subId" example:"abcd1234"`
Enable bool `json:"enable" example:"true"`
TotalGB int64 `json:"totalGB" example:"53687091200"`
ExpiryTime int64 `json:"expiryTime" example:"1735689600000"`
LimitIP int `json:"limitIp" example:"0"`
LimitHwid int `json:"limitHwid" example:"0"`
Reset int `json:"reset" example:"0"`
ResetDay int `json:"resetDay" example:"0"`
ResetMax int `json:"resetMax" example:"0"`
Group string `json:"group,omitempty" example:"staff"`
Comment string `json:"comment,omitempty" example:"Primary device"`
InboundIds []int `json:"inboundIds" example:"[3,5]"`
Traffic *xray.ClientTraffic `json:"traffic,omitempty"`
CreatedAt int64 `json:"createdAt" example:"1735000000000"`
UpdatedAt int64 `json:"updatedAt" example:"1735100000000"`
Email string `json:"email" example:"alice@example.com"`
SubID string `json:"subId" example:"abcd1234"`
Enable bool `json:"enable" example:"true"`
TotalGB int64 `json:"totalGB" example:"53687091200"`
ExpiryTime int64 `json:"expiryTime" example:"1735689600000"`
LimitIP int `json:"limitIp" example:"0"`
LimitHwid int `json:"limitHwid" example:"0"`
Reset int `json:"reset" example:"0"`
ResetDay int `json:"resetDay" example:"0"`
ResetWeekday int `json:"resetWeekday" example:"0"`
ResetMax int `json:"resetMax" example:"0"`
Group string `json:"group,omitempty" example:"staff"`
Comment string `json:"comment,omitempty" example:"Primary device"`
InboundIds []int `json:"inboundIds" example:"[3,5]"`
Traffic *xray.ClientTraffic `json:"traffic,omitempty"`
CreatedAt int64 `json:"createdAt" example:"1735000000000"`
UpdatedAt int64 `json:"updatedAt" example:"1735100000000"`
}
// ClientPageParams are the query params accepted by /panel/api/clients/list/paged.
@@ -246,9 +247,9 @@ func (q clientQuery) applyParams(tx *gorm.DB, params ClientPageParams, onlines [
}
switch strings.ToLower(strings.TrimSpace(params.AutoRenew)) {
case "on":
where("(COALESCE(c.reset, 0) > 0 OR COALESCE(c.reset_day, 0) > 0)")
where("(COALESCE(c.reset, 0) > 0 OR COALESCE(c.reset_day, 0) > 0 OR COALESCE(c.reset_weekday, 0) > 0)")
case "off":
where("(COALESCE(c.reset, 0) <= 0 AND COALESCE(c.reset_day, 0) <= 0)")
where("(COALESCE(c.reset, 0) <= 0 AND COALESCE(c.reset_day, 0) <= 0 AND COALESCE(c.reset_weekday, 0) <= 0)")
}
switch strings.ToLower(strings.TrimSpace(params.HasTgID)) {
case "yes":
@@ -598,22 +599,23 @@ func sqlInt(v int64) string {
func toClientSlim(c ClientWithAttachments) ClientSlim {
return ClientSlim{
Email: c.Email,
SubID: c.SubID,
Enable: c.Enable,
TotalGB: c.TotalGB,
ExpiryTime: c.ExpiryTime,
LimitIP: c.LimitIP,
LimitHwid: c.LimitHwid,
Reset: c.Reset,
ResetDay: c.ResetDay,
ResetMax: c.ResetMax,
Group: c.Group,
Comment: c.Comment,
InboundIds: c.InboundIds,
Traffic: c.Traffic,
CreatedAt: c.CreatedAt,
UpdatedAt: c.UpdatedAt,
Email: c.Email,
SubID: c.SubID,
Enable: c.Enable,
TotalGB: c.TotalGB,
ExpiryTime: c.ExpiryTime,
LimitIP: c.LimitIP,
LimitHwid: c.LimitHwid,
Reset: c.Reset,
ResetDay: c.ResetDay,
ResetWeekday: c.ResetWeekday,
ResetMax: c.ResetMax,
Group: c.Group,
Comment: c.Comment,
InboundIds: c.InboundIds,
Traffic: c.Traffic,
CreatedAt: c.CreatedAt,
UpdatedAt: c.UpdatedAt,
}
}
+1 -1
View File
@@ -115,7 +115,7 @@ func (s *ClientService) ImportClients(inboundSvc *InboundService, items []Client
skip(email, verr.Error())
continue
}
if verr := validateClientResetDay(client.ResetDay); verr != nil {
if verr := validateClientRenewal(client); verr != nil {
skip(email, verr.Error())
continue
}
@@ -0,0 +1,81 @@
package service
import (
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
type ClientRenewalPreviewRequest struct {
ExpiryTime int64 `json:"expiryTime" example:"1893456000000"`
Reset int `json:"reset" example:"0"`
ResetDay int `json:"resetDay" example:"1"`
ResetWeekday int `json:"resetWeekday" example:"0"`
ResetMax int `json:"resetMax" example:"0"`
ResetCount int `json:"resetCount" example:"0"`
}
type ClientRenewalPreview struct {
TimeZone string `json:"timeZone" example:"UTC"`
RenewAt string `json:"renewAt" example:"2030-01-01T00:00:00Z"`
ValidThrough string `json:"validThrough" example:"2029-12-31T23:59:59Z"`
NextExpiry string `json:"nextExpiry" example:"2030-02-01T00:00:00Z"`
SuggestedExpiryTime int64 `json:"suggestedExpiryTime" example:"1893456000000"`
SuggestedExpiry string `json:"suggestedExpiry" example:"2030-01-01T00:00:00Z"`
Renewals int `json:"renewals" example:"1"`
CanRenew bool `json:"canRenew" example:"true"`
DelayedStart bool `json:"delayedStart" example:"false"`
}
func (s *ClientService) PreviewRenewal(request ClientRenewalPreviewRequest, settings *SettingService) (*ClientRenewalPreview, error) {
client := model.Client{Reset: request.Reset, ResetDay: request.ResetDay, ResetWeekday: request.ResetWeekday}
if err := validateClientRenewal(client); err != nil {
return nil, err
}
if err := validateClientResetMax(request.ResetMax); err != nil {
return nil, err
}
if request.ResetCount < 0 || request.Reset < 0 {
return nil, common.NewError("renewal preview reset and resetCount must not be negative")
}
loc, err := settings.GetTimeLocation()
if err != nil {
return nil, err
}
return previewClientRenewal(request, time.Now().UnixMilli(), loc)
}
func previewClientRenewal(request ClientRenewalPreviewRequest, now int64, loc *time.Location) (*ClientRenewalPreview, error) {
preview := &ClientRenewalPreview{TimeZone: loc.String(), DelayedStart: request.ExpiryTime < 0}
if request.ResetDay > 0 || request.ResetWeekday > 0 {
preview.SuggestedExpiryTime = nextClientRenewal(now, request.Reset, request.ResetDay, request.ResetWeekday, loc)
if preview.SuggestedExpiryTime <= now {
return nil, common.NewError("calendar renewal could not find a future expiry")
}
preview.SuggestedExpiry = time.UnixMilli(preview.SuggestedExpiryTime).In(loc).Format(time.RFC3339)
}
if request.ExpiryTime <= 0 || (request.Reset <= 0 && request.ResetDay <= 0 && request.ResetWeekday <= 0) {
return preview, nil
}
at := canonicalRenewalExpiry(request.ExpiryTime, request.Reset, request.ResetDay, request.ResetWeekday, loc)
preview.RenewAt = time.UnixMilli(at).In(loc).Format(time.RFC3339Nano)
// Billing alignment does not rewrite the stored exclusive deadline; the
// preview must not promise an extra second before the first renewal.
preview.ValidThrough = time.UnixMilli(request.ExpiryTime - 1).In(loc).Format(time.RFC3339)
traffic := &xray.ClientTraffic{
ExpiryTime: request.ExpiryTime, Reset: request.Reset, ResetDay: request.ResetDay,
ResetWeekday: request.ResetWeekday, ResetMax: request.ResetMax, ResetCount: request.ResetCount,
}
expiry, renewals := catchUpClientRenewal(traffic, max(now, at+1), loc)
if renewals == 0 && request.ResetWeekday > 0 && (request.ResetMax == 0 || request.ResetCount < request.ResetMax) {
return nil, common.NewError("calendar renewal could not find a future expiry")
}
preview.Renewals = renewals
preview.CanRenew = renewals > 0 && expiry > max(now, at)
if renewals > 0 {
preview.NextExpiry = time.UnixMilli(expiry).In(loc).Format(time.RFC3339Nano)
}
return preview, nil
}
@@ -0,0 +1,131 @@
package service
import (
"testing"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
func TestClientRenewalWriteValidation(t *testing.T) {
for _, operation := range []string{"add inbound", "update inbound", "add inbound client", "update inbound client", "sync inbound", "client delta", "add stat", "update stat", "import stat"} {
for _, schedule := range []struct {
name string
reset, day, weekday int
errorMessage string
}{
{"weekly and interval", 7, 0, 3, "client weekly renewal cannot be combined with reset or resetDay"},
{"weekly and monthly", 0, 1, 3, "client weekly renewal cannot be combined with reset or resetDay"},
{"invalid weekday", 0, 0, 8, "client resetWeekday must be between 0 and 7, got: 8"},
} {
t.Run(operation+"/"+schedule.name, func(t *testing.T) {
setupConflictDB(t)
nodeID, fake := setupNodeRuntime(t)
svc, inboundSvc := &ClientService{}, &InboundService{}
client := model.Client{Email: "renewal-boundary", ID: "11111111-1111-1111-1111-111111111111", SubID: "renewal-boundary-sub", Enable: true, ResetWeekday: 3, ResetMax: 4, ExpiryTime: time.Now().Add(time.Hour).UnixMilli()}
inbound := nodeInbound(t, nodeID, 41759, []model.Client{client})
if err := inboundSvc.AddClientStat(database.GetDB(), inbound.Id, &client); err != nil {
t.Fatal(err)
}
record, err := svc.GetRecordByEmail(nil, client.Email)
if err != nil {
t.Fatal(err)
}
beforeRecord := *record
beforeTraffic := readTraffic(t, database.GetDB(), client.Email)
beforeSettings := inbound.Settings
client.Reset, client.ResetDay, client.ResetWeekday = schedule.reset, schedule.day, schedule.weekday
update := *inbound
update.Settings = clientsSettings(t, []model.Client{client})
switch operation {
case "add inbound", "import stat":
update.Id, update.Port, update.Tag = 0, 41760, "renewal-boundary-new"
if operation == "import stat" {
update.Settings = beforeSettings
update.ClientStats = []xray.ClientTraffic{{Email: "invalid-import-stat", Reset: schedule.reset, ResetDay: schedule.day, ResetWeekday: schedule.weekday}}
}
_, _, err = inboundSvc.AddInbound(&update)
case "update inbound":
_, _, err = inboundSvc.UpdateInbound(&update)
case "add inbound client":
client.Email = "invalid-new-client"
update.Settings = clientsSettings(t, []model.Client{client})
_, err = svc.AddInboundClient(inboundSvc, &update)
case "update inbound client":
_, err = svc.UpdateInboundClient(inboundSvc, &update, client.Email)
case "sync inbound":
err = svc.SyncInbound(nil, inbound.Id, []model.Client{client})
case "client delta":
err = svc.ApplyInboundClientDelta(nil, inbound.Id, []model.Client{client}, nil)
case "add stat":
err = inboundSvc.AddClientStat(database.GetDB(), inbound.Id, &client)
case "update stat":
err = inboundSvc.UpdateClientStat(database.GetDB(), client.Email, &client)
}
if err == nil || err.Error() != schedule.errorMessage+"\n" {
t.Fatalf("write error = %v, want %q", err, schedule.errorMessage)
}
var persisted model.Inbound
if err := database.GetDB().First(&persisted, inbound.Id).Error; err != nil {
t.Fatal(err)
}
if persisted.Settings != beforeSettings {
t.Fatal("rejected write changed inbound settings")
}
record, err = svc.GetRecordByEmail(nil, beforeRecord.Email)
if err != nil || *record != beforeRecord || readTraffic(t, database.GetDB(), beforeRecord.Email) != beforeTraffic {
t.Fatalf("rejected write changed client/traffic: record=%+v error=%v", record, err)
}
for _, table := range []string{"inbounds", "clients", "client_traffics"} {
var count int64
if err := database.GetDB().Table(table).Count(&count).Error; err != nil || count != 1 {
t.Fatalf("%s count/error = %d/%v, want 1/nil", table, count, err)
}
}
if fake.addInbound.Load() != 0 || fake.updateInbound.Load() != 0 || fake.delInbound.Load() != 0 || fake.addClient.Load() != 0 || fake.updateUser.Load() != 0 {
t.Fatal("rejected write dispatched to the runtime")
}
})
}
}
}
func TestInboundRenewalModesRemainEditable(t *testing.T) {
for _, weekly := range []bool{false, true} {
name := "legacy monthly with interval"
if weekly {
name = "weekly"
}
t.Run(name, func(t *testing.T) {
setupConflictDB(t)
nodeID, _ := setupNodeRuntime(t)
svc, inboundSvc := &ClientService{}, &InboundService{}
client := model.Client{Email: "renewal-editable", ID: "11111111-1111-1111-1111-111111111111", Enable: true, Reset: 7, ResetDay: 1, ResetMax: 4, ExpiryTime: time.Now().Add(time.Hour).UnixMilli()}
if weekly {
client.Reset, client.ResetDay, client.ResetWeekday = 0, 0, 3
}
inbound := &model.Inbound{Tag: "renewal-editable", NodeID: &nodeID, Port: 41761, Protocol: model.VLESS, Enable: true, Settings: clientsSettings(t, []model.Client{client})}
if _, _, err := inboundSvc.AddInbound(inbound); err != nil {
t.Fatal(err)
}
if _, _, err := inboundSvc.UpdateInbound(inbound); err != nil {
t.Fatal(err)
}
record, err := svc.GetRecordByEmail(nil, client.Email)
if err != nil {
t.Fatal(err)
}
toggle := *record.ToClient()
toggle.Enable = false
if _, err := svc.Update(inboundSvc, record.Id, toggle, 0); err != nil {
t.Fatalf("valid inbound client could not be toggled: %v", err)
}
record, err = svc.GetRecordByEmail(nil, client.Email)
if err != nil || record.Enable || record.Reset != client.Reset || record.ResetDay != client.ResetDay || record.ResetWeekday != client.ResetWeekday || record.ResetMax != 4 {
t.Fatalf("valid schedule/toggle not preserved: %+v/%v", record, err)
}
})
}
}
@@ -0,0 +1,71 @@
package service
import (
"testing"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
func TestClientWeeklyRenewCRUD(t *testing.T) {
setupBulkDB(t)
svc, inboundSvc := &ClientService{}, &InboundService{}
first := mkInbound(t, 41701, model.VLESS, `{"clients":[]}`)
second := mkInbound(t, 41702, model.VLESS, `{"clients":[]}`)
client := model.Client{
Email: "weekly-crud", ID: "11111111-1111-1111-1111-111111111111", Enable: true,
ResetWeekday: 7, ResetMax: 3, ExpiryTime: time.Now().Add(-time.Hour).UnixMilli(),
}
if _, err := svc.Create(inboundSvc, &ClientCreatePayload{Client: client, InboundIds: []int{first.Id, second.Id}}); err != nil {
t.Fatal(err)
}
record, err := svc.GetRecordByEmail(nil, client.Email)
if err != nil {
t.Fatal(err)
}
assertSchedule := func(want int) {
t.Helper()
got, err := svc.GetRecordByEmail(nil, client.Email)
if err != nil || got.ResetWeekday != want || got.ToClient().ResetWeekday != want {
t.Fatalf("record schedule/error = %+v/%v, want %d", got, err, want)
}
traffic := readTraffic(t, database.GetDB(), client.Email)
if traffic.ResetWeekday != want || traffic.ResetMax != 3 {
t.Fatalf("traffic policy = %+v, want weekday %d and cap 3", traffic, want)
}
for _, id := range []int{first.Id, second.Id} {
var inbound model.Inbound
if err := database.GetDB().First(&inbound, id).Error; err != nil {
t.Fatal(err)
}
clients, err := inboundSvc.GetClients(&inbound)
if err != nil || len(clients) != 1 || clients[0].ResetWeekday != want {
t.Fatalf("inbound %d schedule/error = %+v/%v, want %d", id, clients, err, want)
}
}
filter := "on"
if want == 0 {
filter = "off"
}
page, err := svc.ListPaged(inboundSvc, nil, ClientPageParams{AutoRenew: filter})
if err != nil || len(page.Items) != 1 || page.Items[0].ResetWeekday != want {
t.Fatalf("renewal filter/projection = %+v/%v, want weekday %d", page, err, want)
}
}
assertSchedule(7)
if deleted, _, err := svc.DelDepleted(inboundSvc); err != nil || deleted != 0 {
t.Fatalf("expired weekly client was purged: deleted/error = %d/%v", deleted, err)
}
for _, weekday := range []int{2, 0} {
updated := *record.ToClient()
updated.ResetWeekday = weekday
if _, err := svc.Update(inboundSvc, record.Id, updated, 0); err != nil {
t.Fatal(err)
}
assertSchedule(weekday)
}
if deleted, _, err := svc.DelDepleted(inboundSvc); err != nil || deleted != 1 {
t.Fatalf("non-renewing expired client was not purged: deleted/error = %d/%v", deleted, err)
}
}
+11
View File
@@ -1133,6 +1133,14 @@ func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, boo
if err != nil {
return inbound, false, err
}
if err := validateClientsRenewal(clients); err != nil {
return inbound, false, err
}
for _, traffic := range inbound.ClientStats {
if err := validateClientRenewal(model.Client{Reset: traffic.Reset, ResetDay: traffic.ResetDay, ResetWeekday: traffic.ResetWeekday}); err != nil {
return inbound, false, err
}
}
existEmail, err := s.clientService.checkEmailsExistForClients(s, clients)
if err != nil {
return inbound, false, err
@@ -1702,6 +1710,9 @@ func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound,
if err != nil {
return inbound, false, err
}
if err := validateClientsRenewal(clients); err != nil {
return inbound, false, err
}
if inbound.Protocol == model.Hysteria {
for _, client := range clients {
if client.Auth == "" {
@@ -0,0 +1,95 @@
package service
import (
"testing"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
func TestAutoRenewClients_WeeklyMode(t *testing.T) {
for _, tt := range []struct {
name, zone string
weekday, max, count int
inclusive, manual bool
}{
{name: "UTC Monday catch-up across shared inbounds", zone: "UTC", weekday: 1},
{name: "New York Sunday across daylight saving", zone: "America/New_York", weekday: 7},
{name: "capped catch-up stays expired", zone: "UTC", weekday: 3, max: 3, count: 2},
{name: "inclusive last second spends one allowance", zone: "Asia/Taipei", weekday: 1, max: 1, inclusive: true},
{name: "operator-disabled settings stay disabled", zone: "UTC", weekday: 5, manual: true},
} {
t.Run(tt.name, func(t *testing.T) {
setupBulkDB(t)
db := database.GetDB()
zone := pinPanelZone(t, tt.zone)
now := time.Now().In(zone)
boundary := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, zone)
for int(boundary.Weekday()+6)%7+1 != tt.weekday || !boundary.Before(now) {
boundary = boundary.AddDate(0, 0, -1)
}
past := boundary.AddDate(0, 0, -21)
if tt.zone == "America/New_York" {
past = time.Date(2026, time.March, 1, 0, 0, 0, 0, zone)
}
if tt.inclusive {
past = boundary.Add(-time.Second)
}
client := model.Client{
Email: "weekly@x", ID: "11111111-1111-1111-1111-111111111111",
ResetWeekday: tt.weekday, ResetMax: tt.max, ExpiryTime: past.UnixMilli(),
}
svc := &InboundService{}
for _, port := range []int{30241, 30242} {
ib := mkInbound(t, port, model.VLESS, clientsSettings(t, []model.Client{client}))
if err := svc.clientService.SyncInbound(nil, ib.Id, []model.Client{client}); err != nil {
t.Fatal(err)
}
}
traffic := xray.ClientTraffic{
Email: client.Email, ResetWeekday: tt.weekday, ResetMax: tt.max, ResetCount: tt.count,
ExpiryTime: past.UnixMilli(), Up: 111, Down: 222, Enable: tt.manual,
}
if err := db.Create(&traffic).Error; err != nil {
t.Fatal(err)
}
want, steps := past, 0
if tt.inclusive {
want = boundary
}
for !want.After(now) && (tt.max == 0 || tt.count+steps < tt.max) {
want = want.AddDate(0, 0, 7)
steps++
}
if _, _, err := svc.autoRenewClients(db, newTrafficMutationBatch()); err != nil {
t.Fatal(err)
}
var got xray.ClientTraffic
if err := db.Where("email = ?", client.Email).First(&got).Error; err != nil {
t.Fatal(err)
}
if got.ExpiryTime != want.UnixMilli() || got.ResetCount != tt.count+steps || got.ResetWeekday != tt.weekday {
t.Fatalf("expiry/count/weekday = %d/%d/%d, want %d/%d/%d", got.ExpiryTime, got.ResetCount, got.ResetWeekday, want.UnixMilli(), tt.count+steps, tt.weekday)
}
if want.After(now) {
if !got.Enable || got.Up != 0 || got.Down != 0 {
t.Fatalf("renewed enable/up/down = %v/%d/%d, want true/0/0", got.Enable, got.Up, got.Down)
}
} else if got.Enable || got.Up != 111 || got.Down != 222 {
t.Fatalf("capped enable/up/down = %v/%d/%d, want false/111/222", got.Enable, got.Up, got.Down)
}
var record model.ClientRecord
if err := db.Where("email = ?", client.Email).First(&record).Error; err != nil {
t.Fatal(err)
}
if record.ResetWeekday != tt.weekday || record.ExpiryTime != got.ExpiryTime || record.Enable != (want.After(now) && !tt.manual) {
t.Fatalf("client record lost weekly schedule or operator enable state: %+v", record)
}
if _, count, err := svc.autoRenewClients(db, newTrafficMutationBatch()); err != nil || count != 0 {
t.Fatalf("repeat tick count/error = %d/%v, want 0/nil", count, err)
}
})
}
}
+21 -16
View File
@@ -290,7 +290,7 @@ func applyMasterClientLifecycle(c *model.Client, master *xray.ClientTraffic, cs
// nodeClientRenewed reports a node-side auto-renew: an absolute deadline moved
// forward, evidenced by a renewal-count bump or a drop below the stored baseline.
func nodeClientRenewed(existing *xray.ClientTraffic, cs xray.ClientTraffic, canon, base nodeTrafficCounter) bool {
if (cs.Reset <= 0 && cs.ResetDay <= 0) || cs.ExpiryTime <= 0 || existing.ExpiryTime <= 0 {
if (cs.Reset <= 0 && cs.ResetDay <= 0 && cs.ResetWeekday <= 0) || cs.ExpiryTime <= 0 || existing.ExpiryTime <= 0 {
return false
}
if cs.ExpiryTime <= existing.ExpiryTime {
@@ -952,16 +952,19 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi
seedUp, seedDown = canon.Up, canon.Down
}
row := &xray.ClientTraffic{
InboundId: c.Id,
Email: cs.Email,
Enable: cs.Enable,
Total: cs.Total,
ExpiryTime: cs.ExpiryTime,
Reset: cs.Reset,
ResetDay: cs.ResetDay,
Up: seedUp,
Down: seedDown,
LastOnline: cs.LastOnline,
InboundId: c.Id,
Email: cs.Email,
Enable: cs.Enable,
Total: cs.Total,
ExpiryTime: cs.ExpiryTime,
Reset: cs.Reset,
ResetDay: cs.ResetDay,
ResetWeekday: cs.ResetWeekday,
ResetMax: cs.ResetMax,
ResetCount: cs.ResetCount,
Up: seedUp,
Down: seedDown,
LastOnline: cs.LastOnline,
}
if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "email"}}, DoNothing: true}).
Create(row).Error; err != nil {
@@ -985,7 +988,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi
// re-enables from the node.
enableChanged := !lifecycleFrozen && existing.Enable && !cs.Enable &&
!nodeDisableIsStale(existing, cs, now, deltaUp, deltaDown)
metaChanged := !lifecycleFrozen && (existing.Total != cs.Total || existing.Reset != cs.Reset)
metaChanged := !lifecycleFrozen && (existing.Total != cs.Total || existing.Reset != cs.Reset || existing.ResetWeekday != cs.ResetWeekday)
if enableChanged || metaChanged || expiryChanged {
structuralChange = true
}
@@ -1009,12 +1012,12 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi
fmt.Sprintf(
`UPDATE client_traffics
SET up = ?, down = ?, enable = ?, total = ?,
expiry_time = ?, reset = ?, reset_day = ?, reset_count = ?, last_online = %s
expiry_time = ?, reset = ?, reset_day = ?, reset_weekday = ?, reset_count = ?, last_online = %s
WHERE email = ?`,
database.GreatestExpr("last_online", "?"),
),
canon.Up, canon.Down, cs.Enable, cs.Total,
cs.ExpiryTime, cs.Reset, cs.ResetDay, cs.ResetCount,
cs.ExpiryTime, cs.Reset, cs.ResetDay, cs.ResetWeekday, cs.ResetCount,
cs.LastOnline, cs.Email,
).Error; err != nil {
return false, err
@@ -1028,6 +1031,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi
existing.Total = cs.Total
existing.ExpiryTime = cs.ExpiryTime
existing.Reset = cs.Reset
existing.ResetWeekday = cs.ResetWeekday
existing.ResetCount = cs.ResetCount
structuralChange = true
} else if lifecycleFrozen {
@@ -1058,7 +1062,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi
`UPDATE client_traffics
SET up = %s, down = %s, enable = %s, total = ?,
expiry_time = %s,
reset = ?, reset_day = ?, last_online = %s
reset = ?, reset_day = ?, reset_weekday = ?, last_online = %s
WHERE email = ?`,
database.ClampedAddExpr("up"),
database.ClampedAddExpr("down"),
@@ -1069,7 +1073,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi
deltaUp, deltaDown,
cs.Enable, cs.ExpiryTime, cs.Total, now, deltaUp, deltaDown,
cs.Total,
cs.ExpiryTime, cs.Reset, cs.ResetDay,
cs.ExpiryTime, cs.Reset, cs.ResetDay, cs.ResetWeekday,
cs.LastOnline, cs.Email,
).Error; err != nil {
return false, err
@@ -1084,6 +1088,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi
existing.Down = clampTrafficCounter(existing.Down + deltaDown)
existing.Total = cs.Total
existing.Reset = cs.Reset
existing.ResetWeekday = cs.ResetWeekday
}
}
// A dip plus a lagging longer expiry mimics nodeClientRenewed and would
+27 -49
View File
@@ -23,7 +23,7 @@ import (
// A client with a renewal day set auto-renews too, so it must not read as
// depleted — otherwise the operator's purge deletes it between cycles (#6239).
const depletedClientsClause = "reset = 0 and reset_day = 0 and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))"
const depletedClientsClause = "reset = 0 and reset_day = 0 and reset_weekday = 0 and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))"
func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (needRestart bool, clientsDisabled bool, err error) {
var disabledNodeIDs []int
@@ -345,7 +345,7 @@ func (s *InboundService) autoRenewClients(tx *gorm.DB, mutationBatch *trafficMut
// attached to, so it could be a node inbound even when the client also has
// local inbounds. The email-based join through client_inbounds is authoritative.
err = tx.Model(xray.ClientTraffic{}).
Where("(reset > 0 or reset_day > 0) and expiry_time > 0 and expiry_time <= ?", now).
Where("(reset > 0 or reset_day > 0 or reset_weekday > 0) and expiry_time > 0 and expiry_time <= ?", now).
// A prepaid plan stops itself: once as many renewals have fired as the
// operator allowed, the client is left to expire like any other.
Where("reset_max <= 0 or reset_count < reset_max").
@@ -447,37 +447,7 @@ func (s *InboundService) autoRenewClients(tx *gorm.DB, mutationBatch *trafficMut
}
// One allowance per period, not per tick: a client away for three
// cycles must not catch up three of them against a prepaid cap.
newExpiryTime := traffic.ExpiryTime
if traffic.ResetDay <= 0 && traffic.Reset <= 0 {
// Unreachable while the selection filter holds: a zero step below
// would spin forever on the single traffic writer and hang the panel.
continue
}
at := time.UnixMilli(newExpiryTime)
// Inclusive end-of-day expiries share the next billing midnight; snap without
// spending an allowance so the first charged step is a full month (#6300).
if traffic.ResetDay > 0 {
boundary := nextCalendarRenewal(at, traffic.ResetDay, renewLocation)
if !at.Before(boundary.Add(-time.Second)) && at.Before(boundary) {
at = boundary
newExpiryTime = at.UnixMilli()
}
}
renewals := 0
for newExpiryTime < now {
if traffic.ResetMax > 0 && traffic.ResetCount+renewals >= traffic.ResetMax {
break
}
if traffic.ResetDay > 0 {
// Calendar mode: step whole months in the panel's zone, so the
// renewal date does not drift the way a fixed 30-day step does.
at = nextCalendarRenewal(at, traffic.ResetDay, renewLocation)
newExpiryTime = at.UnixMilli()
} else {
newExpiryTime += (int64(traffic.Reset) * 86400000)
}
renewals++
}
newExpiryTime, renewals := catchUpClientRenewal(traffic, now, renewLocation)
if renewals > 0 {
traffic.ExpiryTime = newExpiryTime
traffic.ResetCount += renewals
@@ -580,33 +550,41 @@ func (s *InboundService) autoRenewClients(tx *gorm.DB, mutationBatch *trafficMut
// happens to reuse an orphaned email still inherits that row's leftover
// up/down, since nothing at this call site can tell the two cases apart.
func (s *InboundService) AddClientStat(tx *gorm.DB, inboundId int, client *model.Client) error {
if err := validateClientRenewal(*client); err != nil {
return err
}
clientTraffic := xray.ClientTraffic{
InboundId: inboundId,
Email: client.Email,
Total: client.TotalGB,
ExpiryTime: client.ExpiryTime,
Enable: client.Enable,
Reset: client.Reset,
ResetDay: client.ResetDay,
ResetMax: client.ResetMax,
InboundId: inboundId,
Email: client.Email,
Total: client.TotalGB,
ExpiryTime: client.ExpiryTime,
Enable: client.Enable,
Reset: client.Reset,
ResetDay: client.ResetDay,
ResetWeekday: client.ResetWeekday,
ResetMax: client.ResetMax,
}
return tx.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "email"}},
DoUpdates: clause.AssignmentColumns([]string{"inbound_id", "total", "expiry_time", "enable", "reset", "reset_day", "reset_max"}),
DoUpdates: clause.AssignmentColumns([]string{"inbound_id", "total", "expiry_time", "enable", "reset", "reset_day", "reset_weekday", "reset_max"}),
}).Create(&clientTraffic).Error
}
func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *model.Client) error {
if err := validateClientRenewal(*client); err != nil {
return err
}
result := tx.Model(xray.ClientTraffic{}).
Where("email = ?", email).
Updates(map[string]any{
"enable": client.Enable,
"email": client.Email,
"total": client.TotalGB,
"expiry_time": client.ExpiryTime,
"reset": client.Reset,
"reset_day": client.ResetDay,
"reset_max": client.ResetMax,
"enable": client.Enable,
"email": client.Email,
"total": client.TotalGB,
"expiry_time": client.ExpiryTime,
"reset": client.Reset,
"reset_day": client.ResetDay,
"reset_weekday": client.ResetWeekday,
"reset_max": client.ResetMax,
})
err := result.Error
return err
@@ -0,0 +1,53 @@
package service
import (
"testing"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
func TestNodeWeeklyRenew_AdoptsNewPeriod(t *testing.T) {
db := initTrafficTestDB(t)
createNodeInbound(t, db, 1, "n1-weekly", 41011)
svc := &InboundService{}
first := time.Date(2030, time.January, 7, 0, 0, 0, 0, time.UTC).UnixMilli()
second := first + 7*86400000
client := model.Client{Email: "node-weekly", ID: "11111111-1111-1111-1111-111111111111", Enable: true, ResetWeekday: 1, ResetMax: 4, ExpiryTime: first}
stats := xray.ClientTraffic{Email: client.Email, Enable: true, ResetWeekday: 1, ResetMax: 4, ResetCount: 2, ExpiryTime: first}
syncNodeWithSettings(t, svc, 1, "n1-weekly", clientsSettings(t, []model.Client{client}), stats)
seeded := readTraffic(t, db, client.Email)
if seeded.ResetMax != 4 || seeded.ResetCount != 2 || seeded.ResetWeekday != 1 {
t.Fatalf("node adoption lost renewal policy: %+v", seeded)
}
stats.Up, stats.Down = 500, 100
syncNodeWithSettings(t, svc, 1, "n1-weekly", clientsSettings(t, []model.Client{client}), stats)
if err := db.Model(&xray.ClientTraffic{}).Where("email = ?", client.Email).Update("enable", false).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&model.ClientGlobalTraffic{MasterGuid: "other", Email: client.Email, Up: 90}).Error; err != nil {
t.Fatal(err)
}
client.ExpiryTime, stats.ExpiryTime = second, second
stats.Up, stats.Down, stats.ResetCount = 0, 0, 3
syncNodeWithSettings(t, svc, 1, "n1-weekly", clientsSettings(t, []model.Client{client}), stats)
got := readTraffic(t, db, client.Email)
if got.ExpiryTime != second || got.ResetCount != 3 || got.ResetMax != 4 || got.ResetWeekday != 1 || !got.Enable || got.Up != 0 || got.Down != 0 {
t.Fatalf("node weekly renewal was not adopted: %+v", got)
}
var count int64
if err := db.Model(&model.ClientGlobalTraffic{}).Where("email = ?", client.Email).Count(&count).Error; err != nil || count != 0 {
t.Fatalf("stale global traffic count/error = %d/%v, want 0/nil", count, err)
}
var record model.ClientRecord
if err := db.Where("email = ?", client.Email).First(&record).Error; err != nil {
t.Fatal(err)
}
if record.ResetWeekday != 1 || record.ExpiryTime != second {
t.Fatalf("node weekly client record lost schedule: %+v", record)
}
stats.Up, stats.Down = 20, 8
syncNodeWithSettings(t, svc, 1, "n1-weekly", clientsSettings(t, []model.Client{client}), stats)
assertUpDown(t, readTraffic(t, db, client.Email), 20, 8, "new weekly period")
}