Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
366 lines (334 loc) · 9.97 KB
/
Copy pathmain.go
File metadata and controls
366 lines (334 loc) · 9.97 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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/url"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"github.com/erpc/erpc/common"
"github.com/erpc/erpc/common/legacy"
"github.com/erpc/erpc/erpc"
"github.com/erpc/erpc/internal/policy"
"github.com/erpc/erpc/util"
"github.com/joho/godotenv"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/spf13/afero"
"github.com/urfave/cli/v3"
"google.golang.org/grpc/grpclog"
yaml "gopkg.in/yaml.v3"
)
func init() {
grpclog.SetLoggerV2(grpclog.NewLoggerV2(io.Discard, io.Discard, os.Stderr))
// Wire the legacy → modern config migration hook. Done here (init
// of cmd/erpc) rather than in common so that the common package
// itself stays free of the common/legacy dependency. Tests that
// exercise legacy YAML can mirror this assignment in TestMain.
common.LegacyTranslateFn = legacy.TranslateFromConfig
common.LegacyTranslateLogger = func(w string) {
log.Warn().Str("source", "config-migration").Msg(w)
}
// Load .env file if it exists
if err := godotenv.Load(); err != nil {
if !os.IsNotExist(err) {
log.Error().Err(err).Msg("failed to load .env file")
}
}
zerolog.TimeFieldFormat = zerolog.TimeFormatUnixMs
zerolog.ErrorMarshalFunc = func(err error) interface{} {
return err
}
if logWriter := os.Getenv("LOG_WRITER"); logWriter == "console" {
log.Logger = zerolog.New(zerolog.NewConsoleWriter(func(w *zerolog.ConsoleWriter) {
w.TimeFormat = "04:05.000ms"
})).With().Timestamp().Logger()
}
if logLevel := os.Getenv("LOG_LEVEL"); logLevel != "" {
level, err := zerolog.ParseLevel(logLevel)
if err != nil {
log.Warn().Msgf("invalid log level '%s', defaulting to 'debug': %s", logLevel, err)
} else {
zerolog.SetGlobalLevel(level)
}
}
}
func main() {
logger := log.With().Logger()
// Create a context that is cancelled on SIGINT/SIGTERM
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
// Define the flag for the config file
configFileFlag := &cli.StringFlag{
Name: "config",
Usage: "Config file to use (by default checking erpc.js, erpc.ts, erpc.yaml, erpc.yml)",
Required: false,
}
endpointFlag := &cli.StringSliceFlag{
Name: "endpoint",
Aliases: []string{"e"},
Usage: "Endpoint URL to use when no config file is provided (can be specified multiple times)",
}
// setFlag := &cli.StringSliceFlag{
// Name: "set",
// Aliases: []string{"s"},
// Usage: "Override a config value (can be specified multiple times)",
// }
requireConfigFlag := &cli.BoolFlag{
Name: "require-config",
Usage: "Enforce passing a config file instead of using a default project and public endpoints",
}
// Define the validate command
validateCmd := &cli.Command{
Name: "validate",
Usage: "Validate the eRPC configuration",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "format",
Usage: "Output format: json|md",
Value: "json",
},
},
Action: func(ctx context.Context, cmd *cli.Command) error {
// Suppress all logs
zerolog.SetGlobalLevel(zerolog.Disabled)
cfg, err := getConfig(logger, cmd)
if err != nil {
// Config load errors should be included as Errors in output, not printed
report := &erpc.ValidationReport{Errors: []string{fmt.Sprintf("config load error: %v", err)}}
format := cmd.String("format")
if format == "md" {
out := erpc.RenderValidationReportMarkdown(report)
fmt.Println(out)
} else {
out, _ := erpc.RenderValidationReportJSON(report, true)
fmt.Println(out)
}
util.OsExit(1)
return nil
}
report := erpc.GenerateValidationReport(ctx, cfg)
format := cmd.String("format")
if format == "md" {
out := erpc.RenderValidationReportMarkdown(report)
fmt.Println(out)
} else {
out, _ := erpc.RenderValidationReportJSON(report, true)
fmt.Println(out)
}
if len(report.Errors) > 0 {
util.OsExit(1)
}
return nil
},
}
// Define the dump command
dumpCmd := &cli.Command{
Name: "dump",
Usage: "Parse a config file (TS, JS, or YAML) and dump the exact configuration eRPC would run with — selectionPolicy filled with the effective policy per network, TS function sentinels resolved to source",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "format",
Usage: "Output format: yaml|json",
Value: "yaml",
},
},
Action: func(ctx context.Context, cmd *cli.Command) error {
zerolog.SetGlobalLevel(zerolog.Disabled)
cfg, err := getConfig(logger, cmd)
if err != nil {
fmt.Fprintf(os.Stderr, "error: failed to load config: %v\n", err)
util.OsExit(1)
return nil
}
// Make each network's effective selectionPolicy explicit — the
// rich default for nil, the upgrade for the trivial placeholder,
// and best-effort TS source resolution. Mirrors what the engine
// applies at register-time, so the dump matches what `erpc start`
// would actually run.
policy.ResolveEffectiveSelectionPolicies(cfg)
format := cmd.String("format")
switch format {
case "json":
out, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
fmt.Fprintf(os.Stderr, "error: failed to marshal config to JSON: %v\n", err)
util.OsExit(1)
return nil
}
fmt.Println(string(out))
case "yaml", "yml":
out, err := yaml.Marshal(cfg)
if err != nil {
fmt.Fprintf(os.Stderr, "error: failed to marshal config to YAML: %v\n", err)
util.OsExit(1)
return nil
}
fmt.Print(string(out))
default:
fmt.Fprintf(os.Stderr, "error: unsupported format %q (use yaml or json)\n", format)
util.OsExit(1)
return nil
}
return nil
},
}
// Define the start command
startCmd := &cli.Command{
Name: "start",
Usage: "Start the eRPC service",
Flags: []cli.Flag{
endpointFlag,
// setFlag,
requireConfigFlag,
},
Action: baseCliAction(logger, func(ctx context.Context, cfg *common.Config) error {
return erpc.Init(
ctx,
cfg,
logger,
)
}),
}
// Define the main command
cmd := &cli.Command{
Name: "erpc",
Usage: "eRPC service, if no command is provided, it will start the service",
ArgsUsage: "[config file]",
Version: common.ErpcVersion,
Flags: []cli.Flag{
configFileFlag,
endpointFlag,
// setFlag,
requireConfigFlag,
},
// Legacy action being the start one directly, to ensure we fetch the potential first arg as config file
Action: baseCliAction(logger, func(ctx context.Context, cfg *common.Config) error {
return erpc.Init(
ctx,
cfg,
logger,
)
}),
// sub command for start / validation / dump
Commands: []*cli.Command{
startCmd,
validateCmd,
dumpCmd,
},
}
if err := cmd.Run(ctx, os.Args); err != nil {
logger.Error().Msgf("failed to start erpc: %v", err)
util.OsExit(util.ExitCodeERPCStartFailed)
}
}
// Base cli action func with init log + config loading
func baseCliAction(
logger zerolog.Logger,
fn func(ctx context.Context, cfg *common.Config) error,
) cli.ActionFunc {
return func(ctx context.Context, cmd *cli.Command) error {
logger.Info().
Str("action", cmd.Name).
Str("version", common.ErpcVersion).
Str("commit", common.ErpcCommitSha).
Msg("executing command")
cfg, err := getConfig(logger, cmd)
if err != nil {
logger.Error().Err(err).Msg("failed to load configuration")
return err
}
return fn(ctx, cfg)
}
}
// Get the config object from the file system, validate it and return it
func getConfig(
logger zerolog.Logger,
cmd *cli.Command,
) (*common.Config, error) {
fs := afero.NewOsFs()
configPath := ""
possibleConfigs := []string{
"./erpc.yaml",
"./erpc.yml",
"./erpc.ts",
"./erpc.js",
"/erpc.yaml",
"/erpc.yml",
"/erpc.ts",
"/erpc.js",
"/root/erpc.yaml",
"/root/erpc.yml",
"/root/erpc.ts",
"/root/erpc.js",
}
requireConfig := cmd.Bool("require-config")
endpoints := cmd.StringSlice("endpoint")
// configOverrides := cmd.StringMap("set")
// Check for the config flag, if present, use that file
if configFile := cmd.String("config"); len(configFile) > 1 {
configPath = configFile
requireConfig = true // Since a config path is provided, we enforce it
} else if len(cmd.Args().Slice()) > 0 { // Check for positional arg, if present, use that file
configPath = cmd.Args().First()
requireConfig = true
} else { // Check for defaults config paths
currentDir, err := os.Getwd()
if err != nil {
return nil, fmt.Errorf("failed to get current directory: %v", err)
}
for _, path := range possibleConfigs {
fullPath := path
if !strings.HasPrefix(path, "/") {
fullPath = filepath.Join(currentDir, path)
}
logger.Info().Msgf("looking for config file: %s", fullPath)
if _, err := fs.Stat(fullPath); err == nil {
configPath = path
break
}
}
}
cfg := &common.Config{}
opts := &common.DefaultOptions{}
// If endpoints are provided via command line, use them
if len(endpoints) > 0 {
logger.Info().Msgf("using %d endpoints provided via command line", len(endpoints))
for _, ep := range endpoints {
if _, err := url.ParseRequestURI(ep); err != nil {
return nil, fmt.Errorf("invalid endpoint URL format: %s (%w)", ep, err)
}
}
opts.Endpoints = endpoints
}
if requireConfig || configPath != "" {
if configPath == "" {
return nil, fmt.Errorf("no valid configuration file found in %v", possibleConfigs)
}
logger.Info().Msgf("resolved configuration file to: %s", configPath)
var err error
cfg, err = common.LoadConfig(fs, configPath, opts)
if err != nil {
return nil, fmt.Errorf("failed to load configuration from %s: %v", configPath, err)
}
} else {
if err := cfg.SetDefaults(opts); err != nil {
return nil, fmt.Errorf("failed to set defaults for config: %v", err)
}
}
if lvl := os.Getenv("LOG_LEVEL"); lvl != "" {
// Allow overriding the log level from the environment variable
level, err := zerolog.ParseLevel(lvl)
if err != nil {
logger.Warn().Msgf("invalid log level '%s', defaulting to 'debug': %s", lvl, err)
} else {
cfg.LogLevel = level.String()
}
zerolog.SetGlobalLevel(level)
}
return cfg, nil
}