"research/neural_gpu/neural_gpu.py" did not exist on "90d6e3b97b6eaa62ddc5f0e8e8173b644de03396"
store.go 2.08 KB
Newer Older
mashun1's avatar
v1  
mashun1 committed
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
package store

import (
	"encoding/json"
	"errors"
	"fmt"
	"log/slog"
	"os"
	"path/filepath"
	"sync"

	"github.com/google/uuid"
)

type Store struct {
	ID           string `json:"id"`
	FirstTimeRun bool   `json:"first-time-run"`
}

var (
	lock  sync.Mutex
	store Store
)

func GetID() string {
	lock.Lock()
	defer lock.Unlock()
	if store.ID == "" {
		initStore()
	}
	return store.ID
}

func GetFirstTimeRun() bool {
	lock.Lock()
	defer lock.Unlock()
	if store.ID == "" {
		initStore()
	}
	return store.FirstTimeRun
}

func SetFirstTimeRun(val bool) {
	lock.Lock()
	defer lock.Unlock()
	if store.FirstTimeRun == val {
		return
	}
	store.FirstTimeRun = val
	writeStore(getStorePath())
}

// lock must be held
func initStore() {
	storeFile, err := os.Open(getStorePath())
	if err == nil {
		defer storeFile.Close()
		err = json.NewDecoder(storeFile).Decode(&store)
		if err == nil {
			slog.Debug(fmt.Sprintf("loaded existing store %s - ID: %s", getStorePath(), store.ID))
			return
		}
	} else if !errors.Is(err, os.ErrNotExist) {
		slog.Debug(fmt.Sprintf("unexpected error searching for store: %s", err))
	}
	slog.Debug("initializing new store")
	store.ID = uuid.New().String()
	writeStore(getStorePath())
}

func writeStore(storeFilename string) {
	ollamaDir := filepath.Dir(storeFilename)
	_, err := os.Stat(ollamaDir)
	if errors.Is(err, os.ErrNotExist) {
		if err := os.MkdirAll(ollamaDir, 0o755); err != nil {
			slog.Error(fmt.Sprintf("create ollama dir %s: %v", ollamaDir, err))
			return
		}
	}
	payload, err := json.Marshal(store)
	if err != nil {
		slog.Error(fmt.Sprintf("failed to marshal store: %s", err))
		return
	}
	fp, err := os.OpenFile(storeFilename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o755)
	if err != nil {
		slog.Error(fmt.Sprintf("write store payload %s: %v", storeFilename, err))
		return
	}
	defer fp.Close()
	if n, err := fp.Write(payload); err != nil || n != len(payload) {
		slog.Error(fmt.Sprintf("write store payload %s: %d vs %d -- %v", storeFilename, n, len(payload), err))
		return
	}
	slog.Debug("Store contents: " + string(payload))
	slog.Info(fmt.Sprintf("wrote store: %s", storeFilename))
}