-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathparental_bg.go
More file actions
205 lines (183 loc) · 6.76 KB
/
parental_bg.go
File metadata and controls
205 lines (183 loc) · 6.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
/*
File: parental_bg.go
Version: 1.9.0
Updated: 11-May-2026 08:37 CEST
Description:
Background sync and timer goroutines for the sdproxy parental subsystem.
Extracted from parental.go to isolate cron-like behavior from the hot-path.
Changes:
1.9.0 - [LOGGING] Managed progress updates, cache refreshes, and midnight
resets cleanly via the new `logParental` toggle.
1.8.0 - [FEAT] Integrated explicit progress-logging into the `runDebitTicker` loop.
Session-active telemetry is now emitted dynamically every 5 minutes
for ongoing categorical and total budgets natively.
1.7.0 - [FEAT] Upgraded `runDebitTicker` to isolate budget deductions to strictly
non-bypassed (`deductible`) traffic. Protects categorical allocations
from being drained when the user activates an explicit `FREE` or `LOG` override.
*/
package main
import (
"log"
"net/netip"
"strings"
"time"
)
// ---------------------------------------------------------------------------
// Background debit ticker
// ---------------------------------------------------------------------------
// runDebitTicker fires every ticker_interval seconds and:
// 1. Identifies which categories are still within their idle_pause window.
// 2. Logs "timer paused" for categories that just went idle.
// 3. Decrements remaining limits (including "total") for non-bypassed categories natively.
// 4. Generates live progress telemetry logs every 5 minutes organically.
// 5. Saves a snapshot to disk safely.
func runDebitTicker() {
interval := cfg.Parental.TickerInterval
if interval <= 0 {
interval = 10
}
tick := time.NewTicker(time.Duration(interval) * time.Second)
defer tick.Stop()
for now := range tick.C {
parentalStateMu.RLock()
sks := make([]string, 0, len(groupStates))
for sk := range groupStates {
sks = append(sks, sk)
}
parentalStateMu.RUnlock()
for _, sk := range sks {
parentalStateMu.RLock()
gs, ok := groupStates[sk]
groupName := stateToGroup[sk]
parentalStateMu.RUnlock()
if !ok {
continue
}
grpCfg, ok := cfg.Groups[groupName]
if !ok {
continue
}
gs.mu.Lock()
var activeScratch [8]string
active := activeScratch[:0]
var deductScratch [8]string
deductible := deductScratch[:0]
for cat, ls := range gs.lastSeen {
if now.Sub(ls) < effectiveIdlePause(grpCfg, cat) {
active = append(active, cat)
// Verify if the active flow is eligible for budget deduction natively
if lds, ok := gs.lastDeductibleSeen[cat]; ok && now.Sub(lds) < effectiveIdlePause(grpCfg, cat) {
deductible = append(deductible, cat)
}
} else if gs.sessionActive[cat] {
if logParental {
addr, _ := netip.ParseAddr(gs.lastClientIP)
log.Printf("[PARENTAL] [%s] Session %q timer paused | client: %s | remaining: %s",
sk, cat, buildClientID(gs.lastClientIP, gs.lastClientName, addr.Unmap()), remainingStr(gs, cat))
}
gs.sessionActive[cat] = false
}
}
if len(active) > 0 {
// Atomically deduct the time interval exclusively from categories registering DEDUCTIBLE activity
for _, cat := range deductible {
if rem, ok := gs.remaining[cat]; ok {
gs.remaining[cat] = rem - int64(interval)
}
}
for _, cat := range active {
// Emit structural progress logs cleanly every 5 minutes organically
if now.Sub(gs.lastProgressLog[cat]) >= 5*time.Minute {
gs.lastProgressLog[cat] = now
if logParental {
addr, _ := netip.ParseAddr(gs.lastClientIP)
log.Printf("[PARENTAL] [%s] Session %q progress | client: %s | remaining: %s",
sk, cat, buildClientID(gs.lastClientIP, gs.lastClientName, addr.Unmap()), remainingStr(gs, cat))
}
}
}
gs.mu.Unlock()
saveSnapshot(sk, gs)
} else {
gs.mu.Unlock()
}
}
}
}
// ---------------------------------------------------------------------------
// Background goroutines
// ---------------------------------------------------------------------------
// runWeeklyListRefresh re-fetches all category lists every Sunday at 03:00.
func runWeeklyListRefresh() {
for {
// [FEAT] Apply time offset to calculate the week boundary natively alongside schedules
now := time.Now().Local().Add(time.Duration(cfg.Parental.TimeOffsetHours) * time.Hour)
daysUntilSunday := (7 - int(now.Weekday())) % 7
if daysUntilSunday == 0 && now.Hour() >= 3 {
daysUntilSunday = 7
}
next := time.Date(now.Year(), now.Month(), now.Day()+daysUntilSunday, 3, 0, 0, 0, now.Location())
// Because `now` and `next` are both offset, their difference precisely yields
// the exact real-time duration until the target occurrence dynamically.
time.Sleep(next.Sub(now))
if logParental {
log.Printf("[PARENTAL] Weekly category list refresh starting")
}
loadAllCategoryLists(false) // Weekly background updates utilize standard cache metadata
}
}
// runMidnightReset fires just after midnight every day, reseeds all budget
// counters from the current config, and clears per-session tracking state.
// hardBlocked and hardAllowed are NOT reset — they are permanent config rules.
func runMidnightReset() {
for {
// [SECURITY/FIX] Enforce `.Local()` to accurately respect OS boundaries dynamically
// [FEAT] Apply time offset to midnight calculation to align with schedules natively.
now := time.Now().Local().Add(time.Duration(cfg.Parental.TimeOffsetHours) * time.Hour)
next := time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 1, 0, now.Location())
// `next` (offset midnight) minus `now` (offset time) evaluates directly
// to the literal physical time duration required to reach the target boundary.
time.Sleep(next.Sub(now))
if logParental {
log.Printf("[PARENTAL] Midnight reset — resetting all budgets")
}
parentalStateMu.RLock()
sks := make([]string, 0, len(groupStates))
for sk := range groupStates {
sks = append(sks, sk)
}
parentalStateMu.RUnlock()
for _, sk := range sks {
parentalStateMu.RLock()
gs, ok := groupStates[sk]
groupName := stateToGroup[sk]
parentalStateMu.RUnlock()
if !ok {
continue
}
grpCfg, ok := cfg.Groups[groupName]
if !ok {
continue
}
gs.mu.Lock()
for key, val := range grpCfg.Budget {
switch strings.ToLower(val) {
case "allow", "block", "free", "log", "unlimited":
delete(gs.remaining, key) // permanent rules carry no counter
default:
d, err := time.ParseDuration(val)
if err != nil {
continue
}
gs.remaining[key] = int64(d.Seconds())
}
}
gs.warnedThresholds = make(map[string]bool)
gs.lastSeen = make(map[string]time.Time)
gs.lastDeductibleSeen = make(map[string]time.Time)
gs.sessionActive = make(map[string]bool)
gs.lastProgressLog = make(map[string]time.Time)
gs.mu.Unlock()
}
}
}