File size: 9,895 Bytes
6a7089a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package instance_test

import (
	"fmt"
	"testing"

	"github.com/pinchtab/pinchtab/internal/allocation"
	bridgepkg "github.com/pinchtab/pinchtab/internal/bridge"
	"github.com/pinchtab/pinchtab/internal/instance"
)

// --- Test doubles ---

type mockLauncher struct {
	instances map[string]*bridgepkg.Instance
	nextID    int
	stopErr   error
}

func newMockLauncher() *mockLauncher {
	return &mockLauncher{instances: make(map[string]*bridgepkg.Instance)}
}

func (m *mockLauncher) Launch(name, port string, headless bool) (*bridgepkg.Instance, error) {
	m.nextID++
	inst := &bridgepkg.Instance{
		ID:          fmt.Sprintf("inst_%d", m.nextID),
		ProfileName: name,
		Port:        port,
		URL:         "http://localhost:" + port,
		Headless:    headless,
		Status:      "running",
	}
	m.instances[inst.ID] = inst
	return inst, nil
}

func (m *mockLauncher) Stop(id string) error {
	if m.stopErr != nil {
		return m.stopErr
	}
	delete(m.instances, id)
	return nil
}

type mockFetcher struct {
	// tabsByURL maps instance URL β†’ tabs
	tabsByURL map[string][]bridgepkg.InstanceTab
}

func newMockFetcher() *mockFetcher {
	return &mockFetcher{tabsByURL: make(map[string][]bridgepkg.InstanceTab)}
}

func (f *mockFetcher) FetchTabs(instanceURL string) ([]bridgepkg.InstanceTab, error) {
	tabs, ok := f.tabsByURL[instanceURL]
	if !ok {
		return nil, fmt.Errorf("instance %s not reachable", instanceURL)
	}
	return tabs, nil
}

func (f *mockFetcher) AddTab(instancePort, tabID, url string) {
	key := "http://localhost:" + instancePort
	f.AddTabForURL(key, tabID, url)
}

func (f *mockFetcher) AddTabForURL(instanceURL, tabID, url string) {
	key := instanceURL
	f.tabsByURL[key] = append(f.tabsByURL[key], bridgepkg.InstanceTab{
		ID:  tabID,
		URL: url,
	})
}

// --- Repository tests ---

func TestRepository_LaunchAndGet(t *testing.T) {
	launcher := newMockLauncher()
	repo := instance.NewRepository(launcher)

	inst, err := repo.Launch("default", "9868", true)
	if err != nil {
		t.Fatal(err)
	}

	got, ok := repo.Get(inst.ID)
	if !ok {
		t.Fatal("instance not found after launch")
	}
	if got.ProfileName != "default" {
		t.Errorf("expected profile default, got %s", got.ProfileName)
	}
	if repo.Count() != 1 {
		t.Errorf("expected count 1, got %d", repo.Count())
	}
}

func TestRepository_StopRemovesInstance(t *testing.T) {
	launcher := newMockLauncher()
	repo := instance.NewRepository(launcher)

	inst, _ := repo.Launch("default", "9868", true)
	if err := repo.Stop(inst.ID); err != nil {
		t.Fatal(err)
	}
	if _, ok := repo.Get(inst.ID); ok {
		t.Error("instance should be gone after stop")
	}
	if repo.Count() != 0 {
		t.Errorf("expected count 0, got %d", repo.Count())
	}
}

func TestRepository_Running_FiltersNonRunning(t *testing.T) {
	launcher := newMockLauncher()
	repo := instance.NewRepository(launcher)

	inst1, _ := repo.Launch("prof1", "9868", true)
	_, _ = repo.Launch("prof2", "9869", true)

	// Manually mark inst1 as stopped via Add.
	stopped := *inst1
	stopped.Status = "stopped"
	repo.Add(&stopped)

	running := repo.Running()
	if len(running) != 1 {
		t.Errorf("expected 1 running, got %d", len(running))
	}
}

// --- Locator tests ---

func TestLocator_CacheHit(t *testing.T) {
	launcher := newMockLauncher()
	fetcher := newMockFetcher()
	repo := instance.NewRepository(launcher)
	locator := instance.NewLocator(repo, fetcher)

	inst, _ := repo.Launch("default", "9868", true)

	// Pre-register in cache.
	locator.Register("tab_abc", inst.ID)

	found, err := locator.FindInstanceByTabID("tab_abc")
	if err != nil {
		t.Fatal(err)
	}
	if found.ID != inst.ID {
		t.Errorf("expected %s, got %s", inst.ID, found.ID)
	}
}

func TestLocator_CacheMiss_QueriesBridges(t *testing.T) {
	launcher := newMockLauncher()
	fetcher := newMockFetcher()
	repo := instance.NewRepository(launcher)
	locator := instance.NewLocator(repo, fetcher)

	inst, _ := repo.Launch("default", "9868", true)

	// Set up fetcher to return tabs for this instance.
	fetcher.AddTab("9868", "tab_xyz", "https://pinchtab.com")

	found, err := locator.FindInstanceByTabID("tab_xyz")
	if err != nil {
		t.Fatal(err)
	}
	if found.ID != inst.ID {
		t.Errorf("expected %s, got %s", inst.ID, found.ID)
	}

	// Should now be cached.
	if locator.CacheSize() != 1 {
		t.Errorf("expected cache size 1, got %d", locator.CacheSize())
	}
}

func TestLocator_TabNotFound(t *testing.T) {
	launcher := newMockLauncher()
	fetcher := newMockFetcher()
	repo := instance.NewRepository(launcher)
	locator := instance.NewLocator(repo, fetcher)

	_, _ = repo.Launch("default", "9868", true)
	fetcher.AddTab("9868", "tab_abc", "https://pinchtab.com")

	_, err := locator.FindInstanceByTabID("nonexistent")
	if err == nil {
		t.Error("expected error for nonexistent tab")
	}
}

func TestLocator_UsesInstanceURLWhenPresent(t *testing.T) {
	launcher := newMockLauncher()
	fetcher := newMockFetcher()
	repo := instance.NewRepository(launcher)
	locator := instance.NewLocator(repo, fetcher)

	inst, _ := repo.Launch("remote", "9868", true)
	inst.URL = "https://bridge.example.com:9868"
	repo.Add(inst)
	fetcher.AddTabForURL("https://bridge.example.com:9868", "tab_remote", "https://pinchtab.com")

	found, err := locator.FindInstanceByTabID("tab_remote")
	if err != nil {
		t.Fatal(err)
	}
	if found.ID != inst.ID {
		t.Fatalf("expected %s, got %s", inst.ID, found.ID)
	}
}

func TestLocator_InvalidateRemovesCacheEntry(t *testing.T) {
	launcher := newMockLauncher()
	fetcher := newMockFetcher()
	repo := instance.NewRepository(launcher)
	locator := instance.NewLocator(repo, fetcher)

	inst, _ := repo.Launch("default", "9868", true)
	locator.Register("tab_abc", inst.ID)

	if locator.CacheSize() != 1 {
		t.Fatal("expected cache size 1")
	}

	locator.Invalidate("tab_abc")
	if locator.CacheSize() != 0 {
		t.Error("expected cache size 0 after invalidate")
	}
}

func TestLocator_InvalidateInstance_RemovesAllTabs(t *testing.T) {
	launcher := newMockLauncher()
	fetcher := newMockFetcher()
	repo := instance.NewRepository(launcher)
	locator := instance.NewLocator(repo, fetcher)

	inst, _ := repo.Launch("default", "9868", true)
	locator.Register("tab_1", inst.ID)
	locator.Register("tab_2", inst.ID)
	locator.Register("tab_3", inst.ID)

	locator.InvalidateInstance(inst.ID)
	if locator.CacheSize() != 0 {
		t.Errorf("expected cache size 0, got %d", locator.CacheSize())
	}
}

func TestLocator_StaleCache_InstanceGone(t *testing.T) {
	launcher := newMockLauncher()
	fetcher := newMockFetcher()
	repo := instance.NewRepository(launcher)
	locator := instance.NewLocator(repo, fetcher)

	inst, _ := repo.Launch("default", "9868", true)
	locator.Register("tab_abc", inst.ID)

	// Remove instance from repo (simulates crash/stop).
	repo.Remove(inst.ID)

	// Cache hit returns stale entry, but instance is gone β†’ should fallback.
	_, err := locator.FindInstanceByTabID("tab_abc")
	if err == nil {
		t.Error("expected error when instance is gone")
	}
}

// --- Allocator tests ---

func TestAllocator_FCFS(t *testing.T) {
	launcher := newMockLauncher()
	repo := instance.NewRepository(launcher)
	policy := &allocation.FCFS{}
	alloc := instance.NewAllocator(repo, policy)

	_, _ = repo.Launch("prof1", "9868", true)

	got, err := alloc.Allocate()
	if err != nil {
		t.Fatal(err)
	}
	if got.ProfileName != "prof1" {
		t.Errorf("expected prof1, got %s", got.ProfileName)
	}
}

func TestAllocator_RoundRobin(t *testing.T) {
	launcher := newMockLauncher()
	repo := instance.NewRepository(launcher)
	policy := allocation.NewRoundRobin()
	alloc := instance.NewAllocator(repo, policy)

	_, _ = repo.Launch("prof1", "9868", true)
	_, _ = repo.Launch("prof2", "9869", true)

	// RoundRobin should cycle. Exact order depends on map iteration,
	// but each allocation should succeed.
	for range 4 {
		_, err := alloc.Allocate()
		if err != nil {
			t.Fatal(err)
		}
	}
}

func TestAllocator_NoRunningInstances(t *testing.T) {
	launcher := newMockLauncher()
	repo := instance.NewRepository(launcher)
	alloc := instance.NewAllocator(repo, &allocation.FCFS{})

	_, err := alloc.Allocate()
	if err == nil {
		t.Error("expected error with no running instances")
	}
}

// --- Manager facade tests ---

func TestManager_DelegatesToComponents(t *testing.T) {
	launcher := newMockLauncher()
	fetcher := newMockFetcher()
	mgr := instance.NewManager(launcher, fetcher, &allocation.FCFS{})

	// Launch via manager β†’ delegates to repo.
	inst, err := mgr.Launch("default", "9868", true)
	if err != nil {
		t.Fatal(err)
	}

	// Get via manager β†’ delegates to repo.
	got, ok := mgr.Get(inst.ID)
	if !ok || got.ID != inst.ID {
		t.Error("Get should delegate to repo")
	}

	// List via manager β†’ delegates to repo.
	list := mgr.List()
	if len(list) != 1 {
		t.Errorf("expected 1 instance, got %d", len(list))
	}

	// RegisterTab + FindInstanceByTabID β†’ delegates to locator.
	mgr.RegisterTab("tab_abc", inst.ID)
	found, err := mgr.FindInstanceByTabID("tab_abc")
	if err != nil {
		t.Fatal(err)
	}
	if found.ID != inst.ID {
		t.Error("FindInstanceByTabID should delegate to locator")
	}

	// Allocate β†’ delegates to allocator.
	alloc, err := mgr.Allocate()
	if err != nil {
		t.Fatal(err)
	}
	if alloc.ProfileName != "default" {
		t.Error("Allocate should delegate to allocator")
	}

	// Stop β†’ delegates to repo + invalidates cache.
	if err := mgr.Stop(inst.ID); err != nil {
		t.Fatal(err)
	}
	if _, ok := mgr.Get(inst.ID); ok {
		t.Error("instance should be gone after stop")
	}
}

func TestManager_StopInvalidatesTabCache(t *testing.T) {
	launcher := newMockLauncher()
	fetcher := newMockFetcher()
	mgr := instance.NewManager(launcher, fetcher, nil)

	inst, _ := mgr.Launch("default", "9868", true)
	mgr.RegisterTab("tab_1", inst.ID)
	mgr.RegisterTab("tab_2", inst.ID)

	_ = mgr.Stop(inst.ID)

	// Tabs should be invalidated.
	_, err := mgr.FindInstanceByTabID("tab_1")
	if err == nil {
		t.Error("expected error: tab cache should be invalidated after stop")
	}
}