Files
x0gp/server/internal/catalog/store_memory.go
T

106 lines
2.3 KiB
Go

package catalog
import (
"context"
"sync"
)
// memoryStore is an in-process implementation of Store for tests and
// for early PoC runs without a database. It is goroutine-safe.
type memoryStore struct {
mu sync.Mutex
tracks map[TrackID]TrackMeta
cars map[CarID]CarMeta
calendar []TrackCalendarEntry
nextID int
}
func newMemoryStore() *memoryStore {
return &memoryStore{
tracks: make(map[TrackID]TrackMeta),
cars: make(map[CarID]CarMeta),
nextID: 1,
}
}
func (m *memoryStore) Load(_ context.Context) ([]TrackMeta, []CarMeta, error) {
m.mu.Lock()
defer m.mu.Unlock()
tracks := make([]TrackMeta, 0, len(m.tracks))
for _, t := range m.tracks {
tracks = append(tracks, t)
}
cars := make([]CarMeta, 0, len(m.cars))
for _, c := range m.cars {
cars = append(cars, c)
}
return tracks, cars, nil
}
func (m *memoryStore) UpsertTrack(_ context.Context, t TrackMeta) error {
m.mu.Lock()
defer m.mu.Unlock()
m.tracks[t.ID] = t
return nil
}
func (m *memoryStore) DeleteTrack(_ context.Context, id string) error {
m.mu.Lock()
defer m.mu.Unlock()
delete(m.tracks, id)
return nil
}
func (m *memoryStore) UpsertCar(_ context.Context, c CarMeta) error {
m.mu.Lock()
defer m.mu.Unlock()
m.cars[c.ID] = c
return nil
}
func (m *memoryStore) DeleteCar(_ context.Context, id string) error {
m.mu.Lock()
defer m.mu.Unlock()
delete(m.cars, id)
return nil
}
func (m *memoryStore) UpdateCarStats(_ context.Context, id string, fn func(*CarMeta)) error {
m.mu.Lock()
defer m.mu.Unlock()
c, ok := m.cars[id]
if !ok {
return ErrNotFound
}
fn(&c)
m.cars[id] = c
return nil
}
func (m *memoryStore) GetTrackCalendar(_ context.Context) ([]TrackCalendarEntry, error) {
m.mu.Lock()
defer m.mu.Unlock()
out := append([]TrackCalendarEntry(nil), m.calendar...)
return out, nil
}
func (m *memoryStore) CreateTrackCalendar(_ context.Context, entry TrackCalendarEntry) (TrackCalendarEntry, error) {
m.mu.Lock()
defer m.mu.Unlock()
entry.ID = m.nextID
m.nextID++
m.calendar = append(m.calendar, entry)
return entry, nil
}
func (m *memoryStore) DeleteTrackCalendar(_ context.Context, id int) error {
m.mu.Lock()
defer m.mu.Unlock()
for i, entry := range m.calendar {
if entry.ID == id {
m.calendar = append(m.calendar[:i], m.calendar[i+1:]...)
return nil
}
}
return ErrNotFound
}