-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.go
More file actions
198 lines (177 loc) · 5.32 KB
/
Copy pathmain.go
File metadata and controls
198 lines (177 loc) · 5.32 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
// main.go
// Пакет main реализует утилиту для фильтрации прокси-подписок.
// Поддерживает два режима работы:
// - HTTP-сервер для динамической фильтрации (/filter?id=1&c=AD)
// - CLI-режим для однократной обработки всех подписок (--cli)
package main
import (
"flag"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"sub-filter/pkg/config"
"sub-filter/pkg/logger"
"sub-filter/pkg/service"
)
func main() {
// Инициализируем логгер
logLevel := logger.ParseLevel(os.Getenv("LOG_LEVEL"))
if logLevel == 0 {
logLevel = logger.ParseLevel("info")
}
log := logger.NewDefault(logLevel)
var (
cliMode = flag.Bool("cli", false, "Run in CLI mode")
stdout = flag.Bool("stdout", false, "Print results to stdout (CLI only)")
configPath = flag.String("config", "", "Path to config file (YAML/JSON/TOML). Defaults to ./config/config.yaml or env SUBFILTER_CONFIG if not specified.")
countryCodesCLI = flag.String("country", "", "Filter by country codes (comma-separated, max 20), e.g. --country=AR,AE")
debugMode = flag.Bool("debug", false, "Enable debug mode: verbose startup info and request logging")
)
flag.Parse()
defaultConfigPath := os.Getenv("SUBFILTER_CONFIG")
if defaultConfigPath == "" {
defaultConfigPath = "./config/config.yaml"
}
if *configPath == "" {
*configPath = defaultConfigPath
}
if *cliMode {
cfg, err := config.Load(*configPath)
if err != nil {
log.Error("Failed to load configuration",
"error", err,
"configPath", *configPath,
)
os.Exit(1)
}
// Парсим коды стран
var parsedCountryCodes []string
if *countryCodesCLI != "" {
parsedCountryCodes = strings.Split(*countryCodesCLI, ",")
for i, code := range parsedCountryCodes {
parsedCountryCodes[i] = strings.TrimSpace(code)
}
}
// Подготавливаем опции сервиса
opts := &service.ServiceOptions{
Sources: cfg.SourcesMap,
Rules: cfg.Rules,
BadWordRules: cfg.BadWordRules,
Countries: cfg.Countries,
MaxCountryCodes: cfg.Validation.MaxCountries,
MaxMergeIDs: cfg.Validation.MaxMergeIDs,
MergeBuckets: cfg.Cache.MergeBuckets,
}
// Create service options debug flag
opts.Debug = *debugMode
// Создаем сервис
svc, err := service.NewService(cfg, log, opts)
if err != nil {
log.Error("Failed to create service", "error", err)
os.Exit(1)
}
defer func() {
if err := svc.Stop(); err != nil {
log.Error("Failed to stop service", "error", err)
}
}()
// Получаем ИД источников
var ids []string
if flag.NArg() > 0 {
ids = flag.Args()
} else {
ids = make([]string, 0, len(cfg.SourcesMap))
for id := range cfg.SourcesMap {
ids = append(ids, id)
}
}
// Обрабатываем CLI
if err := svc.ProcessCLI(ids, parsedCountryCodes, *stdout); err != nil {
log.Error("CLI processing failed", "error", err)
os.Exit(1)
}
return
}
// Нормальный режим работы
portStr := ""
if flag.NArg() > 0 {
portStr = flag.Arg(0)
} else {
portStr = "8000"
}
cfg, err := config.Load(*configPath)
if err != nil {
log.Error("Failed to load configuration",
"error", err,
"configPath", *configPath,
)
os.Exit(1)
}
// Если включён debug, выводим статистику конфигурации в консоль
if *debugMode {
// Количество правил в rules.yaml
rulesCount := len(cfg.Rules)
countriesCount := len(cfg.Countries)
// Количество badword правил по типам
stripCount := 0
deleteCount := 0
replaceCount := 0
for _, br := range cfg.BadWordRules {
a := strings.ToLower(strings.TrimSpace(br.Action))
if a == "strip" {
stripCount++
} else if a == "replace" {
replaceCount++
} else {
deleteCount++
}
}
log.Info("Debug mode enabled: config summary",
"rules_count", rulesCount,
"badword_strip", stripCount,
"badword_replace", replaceCount,
"badword_delete", deleteCount,
"sources_count", len(cfg.SourcesMap),
"countries_count", countriesCount,
)
}
if p, err := strconv.Atoi(portStr); err == nil && p > 0 && p < 65536 {
cfg.Server.Port = uint16(p)
} else {
cfg.Server.Port = 8000
}
// Prepare service options
opts := &service.ServiceOptions{
Sources: cfg.SourcesMap,
Rules: cfg.Rules,
BadWordRules: cfg.BadWordRules,
Countries: cfg.Countries,
MaxCountryCodes: cfg.Validation.MaxCountries,
MaxMergeIDs: cfg.Validation.MaxMergeIDs,
MergeBuckets: cfg.Cache.MergeBuckets,
Debug: *debugMode,
}
// Create service
svc, err := service.NewService(cfg, log, opts)
if err != nil {
log.Error("Failed to start server", "error", err)
os.Exit(1)
}
// Setup graceful shutdown handler
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGTERM, syscall.SIGINT)
go func() {
sig := <-sigChan
log.Info("Received signal, initiating graceful shutdown", "signal", sig)
if err := svc.Stop(); err != nil {
log.Error("Error stopping service", "error", err)
}
os.Exit(0)
}()
if err := svc.Start(); err != nil {
log.Error("Failed to start server", "error", err)
os.Exit(1)
}
}