From 895f9da069951ac0e5e83b529672b895b97c021d Mon Sep 17 00:00:00 2001 From: Virgil Date: Sat, 4 Apr 2026 08:15:43 +0000 Subject: [PATCH] docs: align mining code with AX naming --- cmd/mining/cmd/remote.go | 34 ++++++++++++++++---------------- cmd/mining/cmd/serve.go | 40 +++++++++++++++++++------------------- cmd/mining/cmd/simulate.go | 40 +++++++++++++++++++------------------- cmd/mining/cmd/start.go | 12 ++++++------ pkg/mining/mining.go | 30 ++++++++++++++-------------- pkg/mining/service.go | 27 ++++++++++++------------- 6 files changed, 90 insertions(+), 93 deletions(-) diff --git a/cmd/mining/cmd/remote.go b/cmd/mining/cmd/remote.go index 5a622b5..dd20aa4 100644 --- a/cmd/mining/cmd/remote.go +++ b/cmd/mining/cmd/remote.go @@ -17,14 +17,14 @@ var ( cachedRemoteControllerErr error ) -// remote status peer-19f3, remote start peer-19f3 --type xmrig, and remote ping peer-19f3 --count 4 live under this command group. +// Example: remote status peer-19f3, remote start peer-19f3 --type xmrig, and remote ping peer-19f3 --count 4 live under this command group. var remoteCmd = &cobra.Command{ Use: "remote", Short: "Control remote mining nodes", Long: `Send commands to remote worker nodes and retrieve their status.`, } -// remote status peer-19f3 prints stats for one peer, while `remote status` prints the whole fleet. +// Example: remote status peer-19f3 prints stats for one peer, while `remote status` prints the whole fleet. var remoteStatusCmd = &cobra.Command{ Use: "status [peer-id]", Short: "Get mining status from remote peers", @@ -36,7 +36,7 @@ var remoteStatusCmd = &cobra.Command{ } if len(arguments) > 0 { - // remote status peer-19f3 shows that peer's stats. + // Example: remote status peer-19f3 shows that peer's stats. peerID := arguments[0] selectedPeer := findPeerByPartialID(peerID) if selectedPeer == nil { @@ -50,7 +50,7 @@ var remoteStatusCmd = &cobra.Command{ printPeerStats(selectedPeer, stats) } else { - // remote status peer-19f3 shows one peer, while `remote status` shows the fleet. + // Example: remote status peer-19f3 shows one peer, while `remote status` shows the fleet. allStats := remoteController.GetAllStats() if len(allStats) == 0 { fmt.Println("No connected peers.") @@ -78,7 +78,7 @@ var remoteStatusCmd = &cobra.Command{ }, } -// remote start peer-19f3 --type xmrig --profile default starts a miner on the selected peer. +// Example: remote start peer-19f3 --type xmrig --profile default starts a miner on the selected peer. var remoteStartCmd = &cobra.Command{ Use: "start ", Short: "Start miner on remote peer", @@ -112,7 +112,7 @@ var remoteStartCmd = &cobra.Command{ }, } -// remote stop peer-19f3 xmrig-main stops a named miner on the selected peer. +// Example: remote stop peer-19f3 xmrig-main stops a named miner on the selected peer. var remoteStopCmd = &cobra.Command{ Use: "stop [miner-name]", Short: "Stop miner on remote peer", @@ -151,7 +151,7 @@ var remoteStopCmd = &cobra.Command{ }, } -// remote logs peer-19f3 xmrig-main prints the first 100 log lines for the remote miner. +// Example: remote logs peer-19f3 xmrig-main prints the first 100 log lines for the remote miner. var remoteLogsCmd = &cobra.Command{ Use: "logs ", Short: "Get console logs from remote miner", @@ -187,7 +187,7 @@ var remoteLogsCmd = &cobra.Command{ }, } -// remote connect peer-19f3 opens a WebSocket connection to the peer. +// Example: remote connect peer-19f3 opens a WebSocket connection to the peer. var remoteConnectCmd = &cobra.Command{ Use: "connect ", Short: "Connect to a remote peer", @@ -215,7 +215,7 @@ var remoteConnectCmd = &cobra.Command{ }, } -// remote disconnect peer-19f3 closes the active peer connection. +// Example: remote disconnect peer-19f3 closes the active peer connection. var remoteDisconnectCmd = &cobra.Command{ Use: "disconnect ", Short: "Disconnect from a remote peer", @@ -243,7 +243,7 @@ var remoteDisconnectCmd = &cobra.Command{ }, } -// remote ping peer-19f3 --count 4 averages four ping samples. +// Example: remote ping peer-19f3 --count 4 averages four ping samples. var remotePingCmd = &cobra.Command{ Use: "ping ", Short: "Ping a remote peer", @@ -296,29 +296,29 @@ var remotePingCmd = &cobra.Command{ func init() { rootCmd.AddCommand(remoteCmd) - // remote status peer-19f3 prints one peer, while `remote status` prints the fleet. + // Example: remote status peer-19f3 prints one peer, while `remote status` prints the fleet. remoteCmd.AddCommand(remoteStatusCmd) - // remote start peer-19f3 --type xmrig --profile default launches a miner. + // Example: remote start peer-19f3 --type xmrig --profile default launches a miner. remoteCmd.AddCommand(remoteStartCmd) remoteStartCmd.Flags().StringP("profile", "p", "", "Profile ID to start, for example default or office-rig") remoteStartCmd.Flags().StringP("type", "t", "", "Miner type to start, for example xmrig or tt-miner") - // remote stop peer-19f3 xmrig-main stops the selected miner. + // Example: remote stop peer-19f3 xmrig-main stops the selected miner. remoteCmd.AddCommand(remoteStopCmd) remoteStopCmd.Flags().StringP("miner", "m", "", "Miner name to stop, for example xmrig-main") - // remote logs peer-19f3 xmrig-main prints miner logs. + // Example: remote logs peer-19f3 xmrig-main prints miner logs. remoteCmd.AddCommand(remoteLogsCmd) remoteLogsCmd.Flags().IntP("lines", "n", 100, "Number of log lines to retrieve, for example 100") - // remote connect peer-19f3 opens the peer connection. + // Example: remote connect peer-19f3 opens the peer connection. remoteCmd.AddCommand(remoteConnectCmd) - // remote disconnect peer-19f3 closes the peer connection. + // Example: remote disconnect peer-19f3 closes the peer connection. remoteCmd.AddCommand(remoteDisconnectCmd) - // remote ping peer-19f3 --count 4 measures latency. + // Example: remote ping peer-19f3 --count 4 measures latency. remoteCmd.AddCommand(remotePingCmd) remotePingCmd.Flags().IntP("count", "c", 4, "Number of ping samples to send, for example 4") } diff --git a/cmd/mining/cmd/serve.go b/cmd/mining/cmd/serve.go index e56bc49..4e613ac 100644 --- a/cmd/mining/cmd/serve.go +++ b/cmd/mining/cmd/serve.go @@ -22,13 +22,13 @@ var ( apiBasePath string ) -// mining serve starts the HTTP API and interactive shell. +// Example: mining serve --host 0.0.0.0 --port 9090 exposes GET /api/v1/mining/status and keeps the shell open. var serveCmd = &cobra.Command{ Use: "serve", Short: "Start the mining service and interactive shell", Long: `Start the mining service, which provides a RESTful API for managing miners, and an interactive shell for CLI commands.`, RunE: func(_ *cobra.Command, arguments []string) error { - serviceContext, cancel := context.WithCancel(context.Background()) + runContext, cancel := context.WithCancel(context.Background()) defer cancel() displayHost := serveHost @@ -42,27 +42,27 @@ var serveCmd = &cobra.Command{ displayAddress := fmt.Sprintf("%s:%d", displayHost, servePort) listenAddress := fmt.Sprintf("%s:%d", serveHost, servePort) - // manager := getSharedManager() shares miner lifecycle state across `mining start`, `mining stop`, and `mining serve`. - manager := getSharedManager() + // Example: sharedManager := getSharedManager() keeps `mining start`, `mining stop`, and `mining serve` pointed at the same miner state. + sharedManager := getSharedManager() - service, err := mining.NewService(manager, listenAddress, displayAddress, apiBasePath) + service, err := mining.NewService(sharedManager, listenAddress, displayAddress, apiBasePath) if err != nil { return fmt.Errorf("failed to create new service: %w", err) } - // service.ServiceStartup(ctx) starts the HTTP server while the shell keeps reading stdin. + // Example: service.ServiceStartup(runContext) serves GET /api/v1/mining/status while stdin stays open. go func() { - if err := service.ServiceStartup(serviceContext); err != nil { + if err := service.ServiceStartup(runContext); err != nil { fmt.Fprintf(os.Stderr, "Failed to start service: %v\n", err) cancel() } }() - // shutdownSignal := make(chan os.Signal, 1) // captures Ctrl+C and SIGTERM for graceful shutdown. + // Example: shutdownSignal := make(chan os.Signal, 1) captures Ctrl+C and SIGTERM for graceful shutdown. shutdownSignal := make(chan os.Signal, 1) signal.Notify(shutdownSignal, syscall.SIGINT, syscall.SIGTERM) - // go func() { fmt.Print(">> ") } // keeps the interactive shell responsive while the API serves requests. + // Example: the prompt loop below keeps `>>` visible while the API serves requests. go func() { fmt.Printf("Mining service started on http://%s:%d\n", displayHost, servePort) fmt.Printf("Swagger documentation is available at http://%s:%d%s/index.html\n", displayHost, servePort, service.SwaggerUIPath) @@ -101,7 +101,7 @@ var serveCmd = &cobra.Command{ poolURL := commandArgs[1] walletAddress := commandArgs[2] - // poolURL := "stratum+tcp://pool.example.com:3333" keeps the miner configuration valid. + // Example: poolURL := "stratum+tcp://pool.example.com:3333" passes Config.Validate(). if !strings.HasPrefix(poolURL, "stratum+tcp://") && !strings.HasPrefix(poolURL, "stratum+ssl://") && !strings.HasPrefix(poolURL, "stratum://") { @@ -115,7 +115,7 @@ var serveCmd = &cobra.Command{ continue } - // walletAddress := "44Affq5kSiGBoZ..." keeps the wallet field within the 256-character limit. + // Example: walletAddress := "44Affq5kSiGBoZ..." keeps the wallet under the 256-character limit. if len(walletAddress) > 256 { fmt.Fprintf(os.Stderr, "Error: Wallet address too long (max 256 chars)\n") fmt.Print(">> ") @@ -128,14 +128,14 @@ var serveCmd = &cobra.Command{ LogOutput: true, } - // minerConfig.Validate() rejects malformed pool and wallet values before the miner starts. + // Example: minerConfig.Validate() rejects malformed pool and wallet values before the miner starts. if err := minerConfig.Validate(); err != nil { fmt.Fprintf(os.Stderr, "Error: Invalid configuration: %v\n", err) fmt.Print(">> ") continue } - miner, err := manager.StartMiner(context.Background(), minerType, minerConfig) + miner, err := sharedManager.StartMiner(context.Background(), minerType, minerConfig) if err != nil { fmt.Fprintf(os.Stderr, "Error starting miner: %v\n", err) } else { @@ -147,7 +147,7 @@ var serveCmd = &cobra.Command{ fmt.Println("Error: status command requires miner name, for example `status xmrig`") } else { minerName := commandArgs[0] - miner, err := manager.GetMiner(minerName) + miner, err := sharedManager.GetMiner(minerName) if err != nil { fmt.Fprintf(os.Stderr, "Error getting miner status: %v\n", err) } else { @@ -169,7 +169,7 @@ var serveCmd = &cobra.Command{ fmt.Println("Error: stop command requires miner name, for example `stop xmrig`") } else { minerName := commandArgs[0] - err := manager.StopMiner(context.Background(), minerName) + err := sharedManager.StopMiner(context.Background(), minerName) if err != nil { fmt.Fprintf(os.Stderr, "Error stopping miner: %v\n", err) } else { @@ -177,7 +177,7 @@ var serveCmd = &cobra.Command{ } } case "list": - miners := manager.ListMiners() + miners := sharedManager.ListMiners() if len(miners) == 0 { fmt.Println("No miners currently running.") } else { @@ -193,7 +193,7 @@ var serveCmd = &cobra.Command{ fmt.Print(">> ") } - // scanner.Err() reports stdin failures such as a closed terminal. + // Example: scanner.Err() reports a closed stdin pipe when the terminal exits. if err := scanner.Err(); err != nil { fmt.Fprintf(os.Stderr, "Error reading input: %v\n", err) } @@ -203,11 +203,11 @@ var serveCmd = &cobra.Command{ case <-shutdownSignal: fmt.Println("\nReceived shutdown signal, stopping service...") cancel() - case <-serviceContext.Done(): + case <-runContext.Done(): } - // manager.Stop() stops miner goroutines and closes the shared service state before exit. - manager.Stop() + // Example: sharedManager.Stop() stops miner goroutines and closes the shared service state before exit. + sharedManager.Stop() fmt.Println("Mining service stopped.") return nil diff --git a/cmd/mining/cmd/simulate.go b/cmd/mining/cmd/simulate.go index fe84dee..4ef856b 100644 --- a/cmd/mining/cmd/simulate.go +++ b/cmd/mining/cmd/simulate.go @@ -21,7 +21,7 @@ var ( simulationAlgorithm string ) -// mining simulate --count 3 --preset cpu-medium starts the API with fake miners. +// Example: mining simulate --count 3 --preset cpu-medium starts the API with fake miners. var simulateCmd = &cobra.Command{ Use: "simulate", Short: "Start the service with simulated miners for UI testing", @@ -46,7 +46,7 @@ Available presets: gpu-ethash - GPU mining ETH (30 MH/s, ethash) gpu-kawpow - GPU mining RVN (15 MH/s, kawpow)`, RunE: func(_ *cobra.Command, arguments []string) error { - serviceContext, cancel := context.WithCancel(context.Background()) + runContext, cancel := context.WithCancel(context.Background()) defer cancel() displayHost := serveHost @@ -60,21 +60,21 @@ Available presets: displayAddress := fmt.Sprintf("%s:%d", displayHost, servePort) listenAddress := fmt.Sprintf("%s:%d", serveHost, servePort) - // manager := mining.NewManagerForSimulation() keeps simulated miners isolated from the real autostart state. - manager := mining.NewManagerForSimulation() + // Example: simulatedManager := mining.NewManagerForSimulation() keeps fake miners isolated from the real autostart state. + simulatedManager := mining.NewManagerForSimulation() - // getSimulatedConfig(0) // returns a config such as sim-cpu-medium-001. + // Example: getSimulatedConfig(0) returns a config such as sim-cpu-medium-001. for i := 0; i < simulatedMinerCount; i++ { simulatedConfig := getSimulatedConfig(i) simulatedMiner := mining.NewSimulatedMiner(simulatedConfig) - // simulatedMiner.Start(&mining.Config{}) // starts the fake miner lifecycle without launching a real binary. + // Example: simulatedMiner.Start(&mining.Config{}) starts the fake miner lifecycle without launching a real binary. if err := simulatedMiner.Start(&mining.Config{}); err != nil { return fmt.Errorf("failed to start simulated miner %d: %w", i, err) } - // manager.RegisterMiner(simulatedMiner) makes the simulated miner visible to `mining serve`. - if err := manager.RegisterMiner(simulatedMiner); err != nil { + // Example: simulatedManager.RegisterMiner(simulatedMiner) makes the simulated miner visible to `mining serve`. + if err := simulatedManager.RegisterMiner(simulatedMiner); err != nil { return fmt.Errorf("failed to register simulated miner %d: %w", i, err) } @@ -82,15 +82,15 @@ Available presets: simulatedConfig.Name, simulatedConfig.Algorithm, simulatedConfig.BaseHashrate) } - // service, err := mining.NewService(manager, listenAddress, displayAddress, apiBasePath) serves the simulator on http://127.0.0.1:9090. - service, err := mining.NewService(manager, listenAddress, displayAddress, apiBasePath) + // Example: service, err := mining.NewService(simulatedManager, listenAddress, displayAddress, apiBasePath) serves the simulator on http://127.0.0.1:9090. + service, err := mining.NewService(simulatedManager, listenAddress, displayAddress, apiBasePath) if err != nil { return fmt.Errorf("failed to create new service: %w", err) } - // service.ServiceStartup(ctx) starts the API server while the simulation loop keeps running. + // Example: service.ServiceStartup(runContext) starts the API server while the simulation loop keeps running. go func() { - if err := service.ServiceStartup(serviceContext); err != nil { + if err := service.ServiceStartup(runContext); err != nil { fmt.Fprintf(os.Stderr, "Failed to start service: %v\n", err) cancel() } @@ -102,7 +102,7 @@ Available presets: fmt.Printf("\nSimulating %d miner(s). Press Ctrl+C to stop.\n", simulatedMinerCount) fmt.Printf("Note: All data is simulated - no actual mining is occurring.\n\n") - // shutdownSignal := make(chan os.Signal, 1) // captures Ctrl+C and SIGTERM for graceful shutdown. + // Example: shutdownSignal := make(chan os.Signal, 1) captures Ctrl+C and SIGTERM for graceful shutdown. shutdownSignal := make(chan os.Signal, 1) signal.Notify(shutdownSignal, syscall.SIGINT, syscall.SIGTERM) @@ -110,12 +110,12 @@ Available presets: case <-shutdownSignal: fmt.Println("\nReceived shutdown signal, stopping simulation...") cancel() - case <-serviceContext.Done(): + case <-runContext.Done(): } - // for _, miner := range manager.ListMiners() { manager.StopMiner(context.Background(), miner.GetName()) } stops every simulated miner before exit. - for _, miner := range manager.ListMiners() { - manager.StopMiner(context.Background(), miner.GetName()) + // Example: for _, miner := range simulatedManager.ListMiners() { simulatedManager.StopMiner(context.Background(), miner.GetName()) } stops every simulated miner before exit. + for _, miner := range simulatedManager.ListMiners() { + simulatedManager.StopMiner(context.Background(), miner.GetName()) } fmt.Println("Simulation stopped.") @@ -125,7 +125,7 @@ Available presets: // getSimulatedConfig(0) returns a simulated miner such as `sim-cpu-medium-001` with preset-driven hashrate and algorithm defaults. func getSimulatedConfig(index int) mining.SimulatedMinerConfig { - // name := fmt.Sprintf("sim-cpu-medium-001", index+1) // keeps the simulated miner names predictable. + // Example: name := fmt.Sprintf("sim-cpu-medium-001", index+1) keeps simulated miner names predictable. name := fmt.Sprintf("sim-%s-%03d", simulationPreset, index+1) var simulatedConfig mining.SimulatedMinerConfig @@ -137,11 +137,11 @@ func getSimulatedConfig(index int) mining.SimulatedMinerConfig { simulatedConfig.Name = name - // simulationHashrate = 8000 // overrides the preset with a custom 8 kH/s baseline. + // Example: simulationHashrate = 8000 overrides the preset with a custom 8 kH/s baseline. if simulationHashrate > 0 { simulatedConfig.BaseHashrate = simulationHashrate } - // simulationAlgorithm = "rx/0" // swaps the preset algorithm before the miner starts. + // Example: simulationAlgorithm = "rx/0" swaps the preset algorithm before the miner starts. if simulationAlgorithm != "" { simulatedConfig.Algorithm = simulationAlgorithm } diff --git a/cmd/mining/cmd/start.go b/cmd/mining/cmd/start.go index 95f982f..c54dc81 100644 --- a/cmd/mining/cmd/start.go +++ b/cmd/mining/cmd/start.go @@ -9,11 +9,11 @@ import ( ) var ( - poolAddress string + poolURL string walletAddress string ) -// mining start xmrig --pool stratum+tcp://pool.example.com:3333 --wallet 44Affq5kSiGBoZ... starts a miner with explicit pool and wallet values. +// Example: mining start xmrig --pool stratum+tcp://pool.example.com:3333 --wallet 44Affq5kSiGBoZ... starts a miner with explicit pool and wallet values. var startCmd = &cobra.Command{ Use: "start ", Short: "Start a new miner", @@ -21,12 +21,12 @@ var startCmd = &cobra.Command{ Args: cobra.ExactArgs(1), RunE: func(_ *cobra.Command, args []string) error { minerType := args[0] - minerConfig := &mining.Config{ - Pool: poolAddress, + startConfig := &mining.Config{ + Pool: poolURL, Wallet: walletAddress, } - miner, err := getSharedManager().StartMiner(context.Background(), minerType, minerConfig) + miner, err := getSharedManager().StartMiner(context.Background(), minerType, startConfig) if err != nil { return fmt.Errorf("failed to start miner: %w", err) } @@ -39,7 +39,7 @@ var startCmd = &cobra.Command{ func init() { rootCmd.AddCommand(startCmd) - startCmd.Flags().StringVarP(&poolAddress, "pool", "p", "", "Mining pool URL, for example stratum+tcp://pool.example.com:3333") + startCmd.Flags().StringVarP(&poolURL, "pool", "p", "", "Mining pool URL, for example stratum+tcp://pool.example.com:3333") startCmd.Flags().StringVarP(&walletAddress, "wallet", "w", "", "Wallet address, for example 44Affq5kSiGBoZ...") _ = startCmd.MarkFlagRequired("pool") _ = startCmd.MarkFlagRequired("wallet") diff --git a/pkg/mining/mining.go b/pkg/mining/mining.go index affedbd..fcf433e 100644 --- a/pkg/mining/mining.go +++ b/pkg/mining/mining.go @@ -52,7 +52,7 @@ type InstallationDetails struct { Version string `json:"version"` Path string `json:"path"` MinerBinary string `json:"miner_binary"` - ConfigPath string `json:"config_path,omitempty"` // Add path to the miner-specific config + ConfigPath string `json:"config_path,omitempty"` // Example: "/home/alice/.config/xmrig/xmrig.json" stores the miner-specific config path. } // info := SystemInfo{OS: "linux", Architecture: "amd64", AvailableCPUCores: 8} @@ -131,22 +131,22 @@ type Config struct { Seed string `json:"seed,omitempty"` Hash string `json:"hash,omitempty"` NoDMI bool `json:"noDMI,omitempty"` - // Config{GPUEnabled: true, GPUPool: "stratum+ssl://gpu.pool.example.com:4444", GPUWallet: "44Affq5kSiGBoZ..."} enables the GPU mining fields. - GPUEnabled bool `json:"gpuEnabled,omitempty"` // Enable GPU mining - GPUPool string `json:"gpuPool,omitempty"` // Separate pool for GPU (can differ from CPU) - GPUWallet string `json:"gpuWallet,omitempty"` // Wallet for GPU pool (defaults to main Wallet) - GPUAlgo string `json:"gpuAlgo,omitempty"` // GPU algorithm such as `kawpow` or `ethash`. - GPUPassword string `json:"gpuPassword,omitempty"` // Password for GPU pool - GPUIntensity int `json:"gpuIntensity,omitempty"` // GPU mining intensity (0-100) - GPUThreads int `json:"gpuThreads,omitempty"` // GPU threads per card - Devices string `json:"devices,omitempty"` // GPU device selection such as `0,1,2`. - OpenCL bool `json:"opencl,omitempty"` // Enable OpenCL (AMD/Intel GPUs) - CUDA bool `json:"cuda,omitempty"` // Enable CUDA (NVIDIA GPUs) - Intensity int `json:"intensity,omitempty"` // Mining intensity for GPU miners - CLIArgs string `json:"cliArgs,omitempty"` // Additional CLI arguments + // Example: Config{GPUEnabled: true, GPUPool: "stratum+ssl://gpu.pool.example.com:4444", GPUWallet: "44Affq5kSiGBoZ..."} enables the GPU mining fields. + GPUEnabled bool `json:"gpuEnabled,omitempty"` // Example: true enables GPU mining. + GPUPool string `json:"gpuPool,omitempty"` // Example: "stratum+ssl://gpu.pool.example.com:4444" sends GPU shares to a separate pool. + GPUWallet string `json:"gpuWallet,omitempty"` // Example: "44Affq5kSiGBoZ..." overrides the CPU wallet for GPU shares. + GPUAlgo string `json:"gpuAlgo,omitempty"` // Example: "kawpow" or "ethash" selects the GPU algorithm. + GPUPassword string `json:"gpuPassword,omitempty"` // Example: "worker-1" sets the GPU pool password. + GPUIntensity int `json:"gpuIntensity,omitempty"` // Example: 75 sets GPU mining intensity on a 0-100 scale. + GPUThreads int `json:"gpuThreads,omitempty"` // Example: 2 assigns two GPU threads per card. + Devices string `json:"devices,omitempty"` // Example: "0,1,2" targets the first three GPU devices. + OpenCL bool `json:"opencl,omitempty"` // Example: true enables OpenCL on AMD and Intel GPUs. + CUDA bool `json:"cuda,omitempty"` // Example: true enables CUDA on NVIDIA GPUs. + Intensity int `json:"intensity,omitempty"` // Example: 80 sets the overall GPU mining intensity. + CLIArgs string `json:"cliArgs,omitempty"` // Example: "--api 127.0.0.1:4048" appends extra CLI arguments. } -// if err := config.Validate(); err != nil { return err } +// Example: if err := config.Validate(); err != nil { return err } func (config *Config) Validate() error { // Pool URL validation if config.Pool != "" { diff --git a/pkg/mining/service.go b/pkg/mining/service.go index d1cf13a..3436661 100644 --- a/pkg/mining/service.go +++ b/pkg/mining/service.go @@ -32,9 +32,8 @@ import ( ginSwagger "github.com/swaggo/gin-swagger" ) -// service, err := mining.NewService(manager, "127.0.0.1:9090", "localhost:9090", "/api/v1/mining") -// if err != nil { return err } -// service.ServiceStartup(context.Background()) starts the REST API on 127.0.0.1:9090. +// Example: service, err := mining.NewService(manager, "127.0.0.1:9090", "localhost:9090", "/api/v1/mining") +// Example: service.ServiceStartup(context.Background()) starts the REST API on 127.0.0.1:9090. type Service struct { Manager ManagerInterface ProfileManager *ProfileManager @@ -187,7 +186,7 @@ func requestIDMiddleware() gin.HandlerFunc { } } -// requestID := generateRequestID() // example: 1712070000123-a1b2c3d4e5f6a7b8 +// Example: requestID := generateRequestID() // "1712070000123-a1b2c3d4e5f6a7b8" func generateRequestID() string { randomBytes := make([]byte, 8) if _, err := rand.Read(randomBytes); err != nil { @@ -462,8 +461,7 @@ func NewService(manager ManagerInterface, listenAddress string, displayAddress s }, nil } -// service.InitRouter() -// http.Handle("/", service.Router) // embeds GET /api/v1/mining/status under a parent HTTP server in Wails +// Example: service.InitRouter(); http.Handle("/", service.Router) // mounts GET /api/v1/mining/status under a parent HTTP server in Wails. func (service *Service) InitRouter() { service.Router = gin.Default() @@ -525,7 +523,7 @@ func (service *Service) InitRouter() { service.SetupRoutes() } -// service.Stop() // stops rate limiting, auth, event hub, and node transport during shutdown +// Example: service.Stop() stops rate limiting, auth, event hub, and node transport during shutdown. func (service *Service) Stop() { if service.rateLimiter != nil { service.rateLimiter.Stop() @@ -543,12 +541,12 @@ func (service *Service) Stop() { } } -// service.ServiceStartup(ctx) // starts the HTTP server and stops it when ctx.Done() fires -func (service *Service) ServiceStartup(ctx context.Context) error { +// Example: service.ServiceStartup(runContext) starts the HTTP server and stops it when runContext.Done() fires. +func (service *Service) ServiceStartup(runContext context.Context) error { service.InitRouter() service.Server.Handler = service.Router - // serverErrors captures ListenAndServe failures without blocking startup. + // Example: serverErrors := make(chan error, 1) lets ServiceStartup return if 127.0.0.1:9090 cannot bind. serverErrors := make(chan error, 1) go func() { @@ -560,8 +558,8 @@ func (service *Service) ServiceStartup(ctx context.Context) error { }() go func() { - <-ctx.Done() - service.Stop() // service.Stop() shuts down auth, the event hub, and node transport after `context.WithCancel(...)`. + <-runContext.Done() + service.Stop() // Example: service.Stop() shuts down auth, the event hub, and node transport after `context.WithCancel(...)`. service.Manager.Stop() shutdownContext, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() @@ -593,8 +591,7 @@ func (service *Service) ServiceStartup(ctx context.Context) error { return ErrInternal("server failed to start listening on " + service.Server.Addr + " within timeout") } -// service.InitRouter() -// service.SetupRoutes() // re-call after adding middleware manually +// Example: service.InitRouter(); service.SetupRoutes() // re-call after adding middleware manually. func (service *Service) SetupRoutes() { apiRoutes := service.Router.Group(service.APIBasePath) @@ -676,7 +673,7 @@ func (service *Service) SetupRoutes() { logging.Info("MCP server enabled", logging.Fields{"endpoint": service.APIBasePath + "/mcp"}) } -// requestContext.JSON(http.StatusOK, HealthResponse{Status: "healthy", Components: map[string]string{"database": "ok"}}) +// Example: requestContext.JSON(http.StatusOK, HealthResponse{Status: "healthy", Components: map[string]string{"database": "ok"}}) type HealthResponse struct { Status string `json:"status"` Components map[string]string `json:"components,omitempty"`