| package instance |
|
|
| import ( |
| "fmt" |
| "sync" |
|
|
| "github.com/pinchtab/pinchtab/internal/bridge" |
| ) |
|
|
| |
| |
| type Repository struct { |
| mu sync.RWMutex |
| instances map[string]*bridge.Instance |
| launcher InstanceLauncher |
| } |
|
|
| |
| func NewRepository(launcher InstanceLauncher) *Repository { |
| return &Repository{ |
| instances: make(map[string]*bridge.Instance), |
| launcher: launcher, |
| } |
| } |
|
|
| |
| func (r *Repository) Launch(name, port string, headless bool) (*bridge.Instance, error) { |
| inst, err := r.launcher.Launch(name, port, headless) |
| if err != nil { |
| return nil, fmt.Errorf("launch instance: %w", err) |
| } |
| r.mu.Lock() |
| r.instances[inst.ID] = inst |
| r.mu.Unlock() |
| return inst, nil |
| } |
|
|
| |
| func (r *Repository) Stop(id string) error { |
| if err := r.launcher.Stop(id); err != nil { |
| return fmt.Errorf("stop instance %q: %w", id, err) |
| } |
| r.mu.Lock() |
| delete(r.instances, id) |
| r.mu.Unlock() |
| return nil |
| } |
|
|
| |
| func (r *Repository) List() []bridge.Instance { |
| r.mu.RLock() |
| defer r.mu.RUnlock() |
| out := make([]bridge.Instance, 0, len(r.instances)) |
| for _, inst := range r.instances { |
| out = append(out, *inst) |
| } |
| return out |
| } |
|
|
| |
| func (r *Repository) Running() []bridge.Instance { |
| r.mu.RLock() |
| defer r.mu.RUnlock() |
| out := make([]bridge.Instance, 0, len(r.instances)) |
| for _, inst := range r.instances { |
| if inst.Status == "running" { |
| out = append(out, *inst) |
| } |
| } |
| return out |
| } |
|
|
| |
| func (r *Repository) Get(id string) (*bridge.Instance, bool) { |
| r.mu.RLock() |
| defer r.mu.RUnlock() |
| inst, ok := r.instances[id] |
| if !ok { |
| return nil, false |
| } |
| copy := *inst |
| return ©, true |
| } |
|
|
| |
| func (r *Repository) Add(inst *bridge.Instance) { |
| r.mu.Lock() |
| r.instances[inst.ID] = inst |
| r.mu.Unlock() |
| } |
|
|
| |
| func (r *Repository) Remove(id string) { |
| r.mu.Lock() |
| delete(r.instances, id) |
| r.mu.Unlock() |
| } |
|
|
| |
| func (r *Repository) Count() int { |
| r.mu.RLock() |
| defer r.mu.RUnlock() |
| return len(r.instances) |
| } |
|
|