fix: resolve CodeRabbit findings — init ordering, crash safety, lock order

- log.go: remove atomic.Pointer — defaultLog init was nil (var runs before init())
- error.go: Reports(n) validates n<=0, appendReport creates parent dir
- contract.go: WithServiceLock is order-independent (LockApply after all opts)

Co-Authored-By: Virgil <virgil@lethean.io>
This commit is contained in:
Snider 2026-03-18 13:20:30 +00:00
parent 2406e81c20
commit ead9ea00e5
3 changed files with 9 additions and 14 deletions

View file

@ -106,6 +106,7 @@ func New(opts ...Option) (*Core, error) {
}
}
c.LockApply()
return c, nil
}
@ -188,10 +189,10 @@ func WithAssets(efs embed.FS) Option {
// WithServiceLock prevents service registration after initialisation.
// Order-independent — lock is applied after all options are processed.
func WithServiceLock() Option {
return func(c *Core) error {
c.LockEnable()
c.LockApply()
return nil
}
}

View file

@ -13,6 +13,7 @@ import (
"iter"
"maps"
"os"
"path/filepath"
"runtime"
"runtime/debug"
"strings"
@ -385,7 +386,7 @@ func (h *ErrPan) Reports(n int) ([]CrashReport, error) {
if err := json.Unmarshal(data, &reports); err != nil {
return nil, err
}
if len(reports) <= n {
if n <= 0 || len(reports) <= n {
return reports, nil
}
return reports[len(reports)-n:], nil
@ -406,6 +407,7 @@ func (h *ErrPan) appendReport(report CrashReport) {
reports = append(reports, report)
if data, err := json.MarshalIndent(reports, "", " "); err == nil {
_ = os.MkdirAll(filepath.Dir(h.filePath), 0755)
_ = os.WriteFile(h.filePath, data, 0600)
}
}

View file

@ -12,7 +12,6 @@ import (
"os/user"
"slices"
"sync"
"sync/atomic"
"time"
)
@ -298,23 +297,16 @@ func Username() string {
// --- Default logger ---
var defaultLogPtr atomic.Pointer[Log]
func init() {
l := NewLog(LogOpts{Level: LevelInfo})
defaultLogPtr.Store(l)
}
var defaultLog = defaultLogPtr.Load()
var defaultLog = NewLog(LogOpts{Level: LevelInfo})
// Default returns the default logger.
func Default() *Log {
return defaultLogPtr.Load()
return defaultLog
}
// SetDefault sets the default logger (thread-safe).
// SetDefault sets the default logger.
func SetDefault(l *Log) {
defaultLogPtr.Store(l)
defaultLog = l
}
// SetLevel sets the default logger's level.