summaryrefslogtreecommitdiff
path: root/internal/askcli/task_alias_cache_test.go
blob: 7cfa2a7241dd313f36b46b8aad6b3ad2a4a92276 (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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
package askcli

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"sync"
	"testing"
	"time"
)

func TestEncodeTaskAliasID(t *testing.T) {
	t.Parallel()

	// Aliases are stored in reversed form so that the first character varies
	// quickly across consecutive IDs, improving shell tab-completion.
	tests := []struct {
		id   uint64
		want string
	}{
		{id: 0, want: "0"},
		{id: 9, want: "9"},
		{id: 10, want: "a"},
		{id: 35, want: "z"},
		{id: 36, want: "00"},
		{id: 37, want: "10"},
		{id: 71, want: "z0"},
		{id: 72, want: "01"},
		{id: 1331, want: "zz"},
		{id: 1332, want: "000"},
		{id: 1333, want: "100"},
	}

	for _, tc := range tests {
		if got := encodeTaskAliasID(tc.id); got != tc.want {
			t.Fatalf("encodeTaskAliasID(%d) = %q, want %q", tc.id, got, tc.want)
		}
	}
}

func TestDecodeTaskAliasID(t *testing.T) {
	t.Parallel()

	// Aliases are in reversed form (matching encodeTaskAliasID output), so
	// decodeTaskAliasID must reverse them back before decoding.
	tests := []struct {
		alias string
		want  uint64
		ok    bool
	}{
		{alias: "0", want: 0, ok: true},
		{alias: "z", want: 35, ok: true},
		{alias: "00", want: 36, ok: true},
		{alias: "10", want: 37, ok: true},
		{alias: "zz", want: 1331, ok: true},
		{alias: "000", want: 1332, ok: true},
		{alias: "", ok: false},
		{alias: "A", ok: false},
		{alias: "-", ok: false},
	}

	for _, tc := range tests {
		got, ok := decodeTaskAliasID(tc.alias)
		if ok != tc.ok {
			t.Fatalf("decodeTaskAliasID(%q) ok = %v, want %v", tc.alias, ok, tc.ok)
		}
		if ok && got != tc.want {
			t.Fatalf("decodeTaskAliasID(%q) = %d, want %d", tc.alias, got, tc.want)
		}
	}
}

func TestEnsureTaskAliases_PersistsAliasesAndTracksAccess(t *testing.T) {
	dir := t.TempDir()
	t.Setenv("XDG_CACHE_HOME", dir)

	oldNow := nowTaskAliasCache
	oldRoot := taskAliasCacheRoot
	nowTaskAliasCache = func() time.Time { return time.Date(2026, 3, 26, 12, 0, 0, 0, time.UTC) }
	taskAliasCacheRoot = func() (string, error) { return filepath.Join(dir, "hexai"), nil }
	defer func() {
		nowTaskAliasCache = oldNow
		taskAliasCacheRoot = oldRoot
	}()

	tasks := []TaskExport{{UUID: "uuid-1"}, {UUID: "uuid-2"}}
	aliases, err := ensureTaskAliases(tasks)
	if err != nil {
		t.Fatalf("ensureTaskAliases returned error: %v", err)
	}
	if aliases["uuid-1"] != "0" || aliases["uuid-2"] != "1" {
		t.Fatalf("aliases = %#v, want sequential aliases", aliases)
	}

	path, err := taskAliasCachePath()
	if err != nil {
		t.Fatalf("taskAliasCachePath: %v", err)
	}
	cache := readTaskAliasCacheForTest(t, path)
	if cache.NextID != 2 {
		t.Fatalf("NextID = %d, want 2", cache.NextID)
	}
	if len(cache.Entries) != 2 {
		t.Fatalf("len(Entries) = %d, want 2", len(cache.Entries))
	}

	nowTaskAliasCache = func() time.Time { return time.Date(2026, 3, 27, 12, 0, 0, 0, time.UTC) }
	aliases, err = ensureTaskAliases([]TaskExport{{UUID: "uuid-2"}, {UUID: "uuid-3"}})
	if err != nil {
		t.Fatalf("ensureTaskAliases second call returned error: %v", err)
	}
	if aliases["uuid-2"] != "1" || aliases["uuid-3"] != "2" {
		t.Fatalf("second aliases = %#v, want existing+new aliases", aliases)
	}

	cache = readTaskAliasCacheForTest(t, path)
	if cache.NextID != 3 {
		t.Fatalf("NextID after second call = %d, want 3", cache.NextID)
	}
	entry := findTaskAliasEntry(t, cache, "uuid-2")
	if got := entry.LastAccessedAt; !got.Equal(nowTaskAliasCache()) {
		t.Fatalf("LastAccessedAt = %s, want %s", got, nowTaskAliasCache())
	}
}

func TestEnsureTaskAliases_PrunesExpiredEntriesWithoutReusingIDs(t *testing.T) {
	dir := t.TempDir()

	oldNow := nowTaskAliasCache
	oldRoot := taskAliasCacheRoot
	nowTaskAliasCache = func() time.Time { return time.Date(2026, 3, 26, 12, 0, 0, 0, time.UTC) }
	taskAliasCacheRoot = func() (string, error) { return filepath.Join(dir, "hexai"), nil }
	defer func() {
		nowTaskAliasCache = oldNow
		taskAliasCacheRoot = oldRoot
	}()

	path, err := taskAliasCachePath()
	if err != nil {
		t.Fatalf("taskAliasCachePath: %v", err)
	}

	cache := taskAliasCache{
		NextID: 37,
		Entries: []taskAliasCacheEntry{
			{
				UUID:           "expired",
				Alias:          "z",
				CreatedAt:      time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC),
				LastAccessedAt: time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC),
			},
			{
				UUID:           "fresh",
				Alias:          "00",
				CreatedAt:      time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC),
				LastAccessedAt: time.Date(2026, 3, 20, 0, 0, 0, 0, time.UTC),
			},
		},
	}
	if err := cache.save(path); err != nil {
		t.Fatalf("save seed cache: %v", err)
	}

	aliases, err := ensureTaskAliases([]TaskExport{{UUID: "fresh"}, {UUID: "new-task"}})
	if err != nil {
		t.Fatalf("ensureTaskAliases returned error: %v", err)
	}
	if aliases["fresh"] != "00" {
		t.Fatalf("fresh alias = %q, want 00", aliases["fresh"])
	}
	if aliases["new-task"] != "10" {
		t.Fatalf("new-task alias = %q, want 10", aliases["new-task"])
	}

	cache = readTaskAliasCacheForTest(t, path)
	if cache.NextID != 38 {
		t.Fatalf("NextID = %d, want 38", cache.NextID)
	}
	if len(cache.Entries) != 2 {
		t.Fatalf("len(Entries) = %d, want 2 after prune", len(cache.Entries))
	}
	if hasTaskAliasEntry(cache, "expired") {
		t.Fatalf("expired entry should have been pruned")
	}
}

func TestEnsureTaskAliases_DoesNotPruneEntriesAt120DayBoundary(t *testing.T) {
	dir := t.TempDir()

	oldNow := nowTaskAliasCache
	oldRoot := taskAliasCacheRoot
	nowTaskAliasCache = func() time.Time { return time.Date(2026, 3, 26, 12, 0, 0, 0, time.UTC) }
	taskAliasCacheRoot = func() (string, error) { return filepath.Join(dir, "hexai"), nil }
	defer func() {
		nowTaskAliasCache = oldNow
		taskAliasCacheRoot = oldRoot
	}()

	path, err := taskAliasCachePath()
	if err != nil {
		t.Fatalf("taskAliasCachePath: %v", err)
	}

	boundary := nowTaskAliasCache().Add(-taskAliasCacheTTL)
	cache := taskAliasCache{
		NextID: 37,
		Entries: []taskAliasCacheEntry{
			{
				UUID:           "boundary",
				Alias:          "z",
				CreatedAt:      boundary,
				LastAccessedAt: boundary,
			},
		},
	}
	if err := cache.save(path); err != nil {
		t.Fatalf("save seed cache: %v", err)
	}

	aliases, err := ensureTaskAliases([]TaskExport{{UUID: "boundary"}})
	if err != nil {
		t.Fatalf("ensureTaskAliases returned error: %v", err)
	}
	if aliases["boundary"] != "z" {
		t.Fatalf("boundary alias = %q, want z", aliases["boundary"])
	}

	cache = readTaskAliasCacheForTest(t, path)
	if !hasTaskAliasEntry(cache, "boundary") {
		t.Fatal("boundary entry should not have been pruned")
	}
}

func TestEnsureTaskAliases_CorruptedCacheIsResetGracefully(t *testing.T) {
	dir := t.TempDir()

	oldRoot := taskAliasCacheRoot
	taskAliasCacheRoot = func() (string, error) { return filepath.Join(dir, "hexai"), nil }
	defer func() { taskAliasCacheRoot = oldRoot }()

	path, err := taskAliasCachePath()
	if err != nil {
		t.Fatalf("taskAliasCachePath: %v", err)
	}
	if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
		t.Fatalf("MkdirAll: %v", err)
	}
	// Write a corrupted cache (e.g. two JSON objects concatenated due to a
	// concurrent write race). The function must recover gracefully by resetting
	// the cache instead of returning an error.
	if err := os.WriteFile(path, []byte("{not-json"), 0o600); err != nil {
		t.Fatalf("WriteFile: %v", err)
	}

	aliases, err := ensureTaskAliases([]TaskExport{{UUID: "uuid-1"}})
	if err != nil {
		t.Fatalf("expected graceful recovery from corrupted cache, got error: %v", err)
	}
	// A fresh alias should have been assigned after the corrupt file was discarded.
	if aliases["uuid-1"] == "" {
		t.Fatal("expected alias to be assigned after cache reset")
	}
	// The corrupt file should have been removed and replaced with a valid one.
	if _, statErr := os.Stat(path); os.IsNotExist(statErr) {
		t.Fatal("expected a new cache file to be written after reset")
	}
}

func TestEnsureTaskAliases_RejectsNextIDReuse(t *testing.T) {
	dir := t.TempDir()

	oldRoot := taskAliasCacheRoot
	taskAliasCacheRoot = func() (string, error) { return filepath.Join(dir, "hexai"), nil }
	defer func() { taskAliasCacheRoot = oldRoot }()

	path, err := taskAliasCachePath()
	if err != nil {
		t.Fatalf("taskAliasCachePath: %v", err)
	}

	cache := taskAliasCache{
		NextID: 36,
		Entries: []taskAliasCacheEntry{
			{UUID: "uuid-1", Alias: "00", CreatedAt: time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC)},
		},
	}
	if err := cache.save(path); err != nil {
		t.Fatalf("save seed cache: %v", err)
	}

	if _, err := ensureTaskAliases([]TaskExport{{UUID: "uuid-2"}}); err == nil {
		t.Fatal("expected error when next_id would reuse an alias")
	}
}

func TestEnsureTaskAliases_ConcurrentCallsDoNotRaceOnTempFile(t *testing.T) {
	dir := t.TempDir()

	oldNow := nowTaskAliasCache
	oldRoot := taskAliasCacheRoot
	nowTaskAliasCache = func() time.Time { return time.Date(2026, 5, 1, 12, 0, 0, 0, time.UTC) }
	taskAliasCacheRoot = func() (string, error) { return filepath.Join(dir, "hexai"), nil }
	defer func() {
		nowTaskAliasCache = oldNow
		taskAliasCacheRoot = oldRoot
	}()

	const goroutines = 16
	uuids := make([]string, goroutines)
	for i := range uuids {
		uuids[i] = fmt.Sprintf("uuid-%02d", i)
	}

	// Release all goroutines simultaneously to maximise the chance of a race
	// before the fix (shared .tmp filename + concurrent rename) and to prove
	// the fix's locking serialises load/modify/save correctly.
	var start sync.WaitGroup
	start.Add(1)
	var done sync.WaitGroup
	errs := make([]error, goroutines)
	for i := 0; i < goroutines; i++ {
		done.Add(1)
		go func(idx int) {
			defer done.Done()
			start.Wait()
			_, err := ensureTaskAliases([]TaskExport{{UUID: uuids[idx]}})
			errs[idx] = err
		}(i)
	}
	start.Done()
	done.Wait()

	for i, err := range errs {
		if err != nil {
			t.Fatalf("goroutine %d: ensureTaskAliases returned error: %v", i, err)
		}
	}

	path, err := taskAliasCachePath()
	if err != nil {
		t.Fatalf("taskAliasCachePath: %v", err)
	}
	cache := readTaskAliasCacheForTest(t, path)
	if got, want := len(cache.Entries), goroutines; got != want {
		t.Fatalf("len(Entries) = %d, want %d (cache lost updates under concurrency)", got, want)
	}
	if got, want := cache.NextID, uint64(goroutines); got != want {
		t.Fatalf("NextID = %d, want %d", got, want)
	}
	for _, uuid := range uuids {
		if !hasTaskAliasEntry(cache, uuid) {
			t.Fatalf("expected entry for %s after concurrent writes", uuid)
		}
	}
	// Aliases must be unique — if save() is racy, two UUIDs could share an
	// alias because both processes saw the same NextID.
	seen := make(map[string]string, len(cache.Entries))
	for _, entry := range cache.Entries {
		if existing, ok := seen[entry.Alias]; ok {
			t.Fatalf("alias %q assigned to both %s and %s", entry.Alias, existing, entry.UUID)
		}
		seen[entry.Alias] = entry.UUID
	}

	// No leftover .tmp files should remain in the cache directory.
	entries, err := os.ReadDir(filepath.Dir(path))
	if err != nil {
		t.Fatalf("ReadDir: %v", err)
	}
	for _, e := range entries {
		if filepath.Ext(e.Name()) == ".tmp" {
			t.Fatalf("leftover temp file: %s", e.Name())
		}
	}
}

func readTaskAliasCacheForTest(t *testing.T, path string) taskAliasCache {
	t.Helper()

	data, err := os.ReadFile(path)
	if err != nil {
		t.Fatalf("ReadFile(%s): %v", path, err)
	}
	var cache taskAliasCache
	if err := json.Unmarshal(data, &cache); err != nil {
		t.Fatalf("Unmarshal(%s): %v", path, err)
	}
	return cache
}

func findTaskAliasEntry(t *testing.T, cache taskAliasCache, uuid string) taskAliasCacheEntry {
	t.Helper()

	for _, entry := range cache.Entries {
		if entry.UUID == uuid {
			return entry
		}
	}
	t.Fatalf("missing alias entry for %q", uuid)
	return taskAliasCacheEntry{}
}

func hasTaskAliasEntry(cache taskAliasCache, uuid string) bool {
	for _, entry := range cache.Entries {
		if entry.UUID == uuid {
			return true
		}
	}
	return false
}