Mining/pkg/mining/xmrig_stats.go
Claude a97f93b919
Some checks are pending
Security Scan / security (push) Waiting to run
Test / test (push) Waiting to run
ax(mining): replace banned errors import with domain error constructors
xmrig_stats.go and ttminer_stats.go used errors.New() despite the
package providing ErrMinerNotRunning() and ErrInternal() for exactly
these cases. Removes banned errors import from both files.

Co-Authored-By: Charon <charon@lethean.io>
2026-04-02 14:00:08 +01:00

65 lines
1.7 KiB
Go

package mining
import (
"context"
"time"
)
// statsTimeout is the timeout for stats HTTP requests (shorter than general timeout)
const statsTimeout = 5 * time.Second
// GetStats retrieves the performance statistics from the running XMRig miner.
func (m *XMRigMiner) GetStats(ctx context.Context) (*PerformanceMetrics, error) {
// Read state under RLock, then release before HTTP call
m.mutex.RLock()
if !m.Running {
m.mutex.RUnlock()
return nil, ErrMinerNotRunning(m.Name)
}
if m.API == nil || m.API.ListenPort == 0 {
m.mutex.RUnlock()
return nil, ErrInternal("miner API not configured or port is zero")
}
config := HTTPStatsConfig{
Host: m.API.ListenHost,
Port: m.API.ListenPort,
Endpoint: "/2/summary",
}
m.mutex.RUnlock()
// Create request with context and timeout
reqCtx, cancel := context.WithTimeout(ctx, statsTimeout)
defer cancel()
// Use the common HTTP stats fetcher
var summary XMRigSummary
if err := FetchJSONStats(reqCtx, config, &summary); err != nil {
return nil, err
}
// Store the full summary in the miner struct (requires lock)
m.mutex.Lock()
m.FullStats = &summary
m.mutex.Unlock()
var hashrate int
if len(summary.Hashrate.Total) > 0 {
hashrate = int(summary.Hashrate.Total[0])
}
// Calculate average difficulty per accepted share
var avgDifficulty int
if summary.Results.SharesGood > 0 {
avgDifficulty = summary.Results.HashesTotal / summary.Results.SharesGood
}
return &PerformanceMetrics{
Hashrate: hashrate,
Shares: summary.Results.SharesGood,
Rejected: summary.Results.SharesTotal - summary.Results.SharesGood,
Uptime: summary.Uptime,
Algorithm: summary.Algo,
AvgDifficulty: avgDifficulty,
DiffCurrent: summary.Results.DiffCurrent,
}, nil
}