summaryrefslogtreecommitdiff
path: root/internal/askcli/task_alias_cache.go
blob: 3ea5dff9d4526e64808766dc8a8bb3ee1b5cfe7b (plain)
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package askcli

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"slices"
	"time"

	"codeberg.org/snonux/hexai/internal/stats"
)

const taskAliasCacheTTL = 120 * 24 * time.Hour

var (
	nowTaskAliasCache  = time.Now
	taskAliasCacheRoot = stats.CacheDir
)

// taskAliasCache maps UUIDs to short human-readable aliases for display and
// completion. The Entries slice is persisted as JSON; the byUUID and byAlias
// maps are derived in-memory for O(1) lookups and are rebuilt after every load
// or mutation.
type taskAliasCache struct {
	NextID  uint64                `json:"next_id"`
	Entries []taskAliasCacheEntry `json:"entries"`

	// In-memory lookup maps — not serialized to JSON.
	byUUID  map[string]*taskAliasCacheEntry
	byAlias map[string]*taskAliasCacheEntry
}

type taskAliasCacheEntry struct {
	UUID           string    `json:"uuid"`
	Alias          string    `json:"alias"`
	CreatedAt      time.Time `json:"created_at"`
	LastAccessedAt time.Time `json:"last_accessed_at"`
}

func ensureTaskAliases(tasks []TaskExport) (map[string]string, error) {
	cache, path, err := loadTaskAliasCache()
	if err != nil {
		return nil, err
	}

	now := nowTaskAliasCache().UTC()
	changed := cache.prune(now)
	aliases := make(map[string]string, len(tasks))
	for _, task := range tasks {
		if task.UUID == "" {
			continue
		}
		alias, updated := cache.ensureAlias(task.UUID, now)
		aliases[task.UUID] = alias
		changed = changed || updated
	}

	if !changed {
		return aliases, nil
	}
	if err := cache.save(path); err != nil {
		return nil, err
	}
	return aliases, nil
}

func ensureTaskAliasesForUUIDs(uuids []string) (map[string]string, error) {
	tasks := make([]TaskExport, 0, len(uuids))
	for _, uuid := range uuids {
		if uuid == "" {
			continue
		}
		tasks = append(tasks, TaskExport{UUID: uuid})
	}
	return ensureTaskAliases(tasks)
}

func loadTaskAliasCache() (taskAliasCache, string, error) {
	path, err := taskAliasCachePath()
	if err != nil {
		return taskAliasCache{}, "", err
	}
	data, err := os.ReadFile(path)
	if os.IsNotExist(err) {
		return taskAliasCache{}, path, nil
	}
	if err != nil {
		return taskAliasCache{}, "", fmt.Errorf("read task alias cache: %w", err)
	}

	var cache taskAliasCache
	if err := json.Unmarshal(data, &cache); err != nil {
		return taskAliasCache{}, "", fmt.Errorf("parse task alias cache: %w", err)
	}
	if err := cache.validate(); err != nil {
		return taskAliasCache{}, "", fmt.Errorf("validate task alias cache: %w", err)
	}
	// Rebuild lookup maps from the deserialized entries so that all subsequent
	// operations use O(1) map access rather than a linear scan.
	cache.rebuildMaps()
	return cache, path, nil
}

func taskAliasCachePath() (string, error) {
	dir, err := taskAliasCacheRoot()
	if err != nil {
		return "", fmt.Errorf("resolve cache dir: %w", err)
	}
	return filepath.Join(dir, "ask", "task-aliases-v1.json"), nil
}

func (c *taskAliasCache) validate() error {
	seenUUIDs := make(map[string]struct{}, len(c.Entries))
	seenAliases := make(map[string]struct{}, len(c.Entries))
	var maxID uint64
	hasEntries := false
	for _, entry := range c.Entries {
		if entry.UUID == "" {
			return fmt.Errorf("entry missing uuid")
		}
		if entry.Alias == "" {
			return fmt.Errorf("entry %q missing alias", entry.UUID)
		}
		id, ok := decodeTaskAliasID(entry.Alias)
		if !ok {
			return fmt.Errorf("entry %q has invalid alias %q", entry.UUID, entry.Alias)
		}
		if _, ok := seenUUIDs[entry.UUID]; ok {
			return fmt.Errorf("duplicate uuid %q", entry.UUID)
		}
		if _, ok := seenAliases[entry.Alias]; ok {
			return fmt.Errorf("duplicate alias %q", entry.Alias)
		}
		seenUUIDs[entry.UUID] = struct{}{}
		seenAliases[entry.Alias] = struct{}{}
		if !hasEntries || id > maxID {
			maxID = id
			hasEntries = true
		}
	}
	if hasEntries && c.NextID <= maxID {
		return fmt.Errorf("next_id %d must be greater than max alias id %d", c.NextID, maxID)
	}
	return nil
}

// rebuildMaps repopulates byUUID and byAlias from the current Entries slice.
// This must be called after any operation that mutates Entries (load, prune,
// add). Pointer stability is guaranteed because entries are addressed by their
// slice index at the time the map is built; both maps are fully rebuilt each
// time rather than patched to avoid stale pointers after slice reallocation.
func (c *taskAliasCache) rebuildMaps() {
	c.byUUID = make(map[string]*taskAliasCacheEntry, len(c.Entries))
	c.byAlias = make(map[string]*taskAliasCacheEntry, len(c.Entries))
	for i := range c.Entries {
		c.byUUID[c.Entries[i].UUID] = &c.Entries[i]
		c.byAlias[c.Entries[i].Alias] = &c.Entries[i]
	}
}

func (c *taskAliasCache) prune(now time.Time) bool {
	if len(c.Entries) == 0 {
		return false
	}

	kept := c.Entries[:0]
	changed := false
	for _, entry := range c.Entries {
		if now.Sub(entry.lastTouchedAt()) > taskAliasCacheTTL {
			changed = true
			continue
		}
		kept = append(kept, entry)
	}
	c.Entries = kept
	if changed {
		c.sortEntries()
		// Rebuild maps after pruning so removed entries are no longer reachable.
		c.rebuildMaps()
	}
	return changed
}

// ensureAlias returns the alias for uuid, creating one if necessary. It uses
// the byUUID map for O(1) lookup instead of a linear slice scan.
func (c *taskAliasCache) ensureAlias(uuid string, now time.Time) (string, bool) {
	if entry, ok := c.byUUID[uuid]; ok {
		if entry.LastAccessedAt.Equal(now) {
			return entry.Alias, false
		}
		entry.LastAccessedAt = now
		return entry.Alias, true
	}

	alias := encodeTaskAliasID(c.NextID)
	c.NextID++
	c.Entries = append(c.Entries, taskAliasCacheEntry{
		UUID:           uuid,
		Alias:          alias,
		CreatedAt:      now,
		LastAccessedAt: now,
	})
	c.sortEntries()
	// Rebuild maps after append because sortEntries may reorder the slice and
	// the previous pointer stored in byUUID for other entries may now be stale.
	c.rebuildMaps()
	return alias, true
}

// lookupUUIDByAlias returns the UUID for the given alias using an O(1) map
// lookup. Returns (uuid, found, changed) where changed is true when
// LastAccessedAt was updated.
func (c *taskAliasCache) lookupUUIDByAlias(alias string, now time.Time) (string, bool, bool) {
	entry, ok := c.byAlias[alias]
	if !ok {
		return "", false, false
	}
	changed := !entry.LastAccessedAt.Equal(now)
	entry.LastAccessedAt = now
	return entry.UUID, true, changed
}

// lookupAliasByUUID returns the alias for the given UUID using an O(1) map
// lookup. Returns (alias, found, changed) where changed is true when
// LastAccessedAt was updated.
func (c *taskAliasCache) lookupAliasByUUID(uuid string, now time.Time) (string, bool, bool) {
	entry, ok := c.byUUID[uuid]
	if !ok {
		return "", false, false
	}
	changed := !entry.LastAccessedAt.Equal(now)
	entry.LastAccessedAt = now
	return entry.Alias, true, changed
}

func (c *taskAliasCache) save(path string) error {
	if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
		return fmt.Errorf("create task alias cache dir: %w", err)
	}
	data, err := json.MarshalIndent(c, "", "  ")
	if err != nil {
		return fmt.Errorf("marshal task alias cache: %w", err)
	}

	tempPath := path + ".tmp"
	if err := os.WriteFile(tempPath, data, 0o600); err != nil {
		return fmt.Errorf("write task alias cache: %w", err)
	}
	if err := os.Rename(tempPath, path); err != nil {
		return fmt.Errorf("replace task alias cache: %w", err)
	}
	return nil
}

func (c *taskAliasCache) sortEntries() {
	slices.SortFunc(c.Entries, func(a, b taskAliasCacheEntry) int {
		switch {
		case a.UUID < b.UUID:
			return -1
		case a.UUID > b.UUID:
			return 1
		default:
			return 0
		}
	})
}

func (e taskAliasCacheEntry) lastTouchedAt() time.Time {
	if !e.LastAccessedAt.IsZero() {
		return e.LastAccessedAt
	}
	return e.CreatedAt
}

func encodeTaskAliasID(id uint64) string {
	const alphabet = "0123456789abcdefghijklmnopqrstuvwxyz"

	width := 1
	blockSize := uint64(len(alphabet))
	remaining := id
	for remaining >= blockSize {
		remaining -= blockSize
		width++
		blockSize *= uint64(len(alphabet))
	}

	buf := make([]byte, width)
	for i := width - 1; i >= 0; i-- {
		buf[i] = alphabet[remaining%uint64(len(alphabet))]
		remaining /= uint64(len(alphabet))
	}
	return string(buf)
}

func decodeTaskAliasID(alias string) (uint64, bool) {
	const alphabet = "0123456789abcdefghijklmnopqrstuvwxyz"

	if alias == "" {
		return 0, false
	}

	width := len(alias)
	var id uint64
	blockSize := uint64(len(alphabet))
	for i := 1; i < width; i++ {
		id += blockSize
		blockSize *= uint64(len(alphabet))
	}

	var value uint64
	for _, r := range alias {
		index := int64(-1)
		for i, candidate := range alphabet {
			if r == candidate {
				index = int64(i)
				break
			}
		}
		if index < 0 {
			return 0, false
		}
		value = value*uint64(len(alphabet)) + uint64(index)
	}
	return id + value, true
}