internal/node_uuid/node_uuid.go (46 lines of code) (raw):
package node_uuid //nolint:staticcheck
import (
"log/slog"
"os"
"path/filepath"
"github.com/google/uuid"
)
const FileName = "node.uuid"
type NodeUUID struct {
indexDir string
}
func NewNodeUUID(indexDir string) NodeUUID {
return NodeUUID{
indexDir: indexDir,
}
}
func (u *NodeUUID) Get() (string, error) {
uuid := u.loadFromDisk()
if uuid != "" {
slog.Info("loading existing node", "uuid", uuid)
return uuid, nil
}
newUUID := u.generateNew()
if err := u.saveToDisk(newUUID); err != nil {
return "", err
}
slog.Info("assigning new node", "uuid", newUUID)
return newUUID, nil
}
func (u *NodeUUID) loadFromDisk() string {
path := filepath.Join(u.indexDir, FileName)
f, err := os.ReadFile(filepath.Clean(path))
if err != nil {
return ""
}
return string(f)
}
func (u *NodeUUID) saveToDisk(uuid string) error {
path := filepath.Join(u.indexDir, FileName)
data := []byte(uuid)
return os.WriteFile(path, data, 0644) //nolint:gosec
}
func (u *NodeUUID) generateNew() string {
id := uuid.New()
return id.String()
}