package ai import ( "context" "sync" ) type operationKey struct{ owner, id string } type reportOperation struct { cancel context.CancelFunc report string } type reportGate struct { mu sync.Mutex refs int } type ReportManager struct { mu sync.Mutex cancels map[operationKey]reportOperation gates map[operationKey]*reportGate } func NewReportManager() *ReportManager { return &ReportManager{cancels: map[operationKey]reportOperation{}, gates: map[operationKey]*reportGate{}} } // WithReport serializes existence checks/registration with confirmed deletion. func (m *ReportManager) WithReport(owner, report string, fn func() error) error { key := operationKey{owner, report} m.mu.Lock() g := m.gates[key] if g == nil { g = &reportGate{} m.gates[key] = g } g.refs++ m.mu.Unlock() g.mu.Lock() defer func() { g.mu.Unlock() m.mu.Lock() g.refs-- if g.refs == 0 { delete(m.gates, key) } m.mu.Unlock() }() return fn() } func (m *ReportManager) Register(owner, operation string, cancel context.CancelFunc) { m.register(owner, operation, operation, cancel) } func (m *ReportManager) register(owner, report, operation string, cancel context.CancelFunc) { m.mu.Lock() old, exists := m.cancels[operationKey{owner, operation}] m.cancels[operationKey{owner, operation}] = reportOperation{cancel, report} m.mu.Unlock() if exists { old.cancel() } } func (m *ReportManager) RegisterForReport(owner, report, operation string, cancel context.CancelFunc, exists func() (bool, error)) error { err := m.WithReport(owner, report, func() error { ok, err := exists() if err != nil { return err } if !ok { return context.Canceled } m.register(owner, report, operation, cancel) return nil }) if err != nil { cancel() } return err } func (m *ReportManager) Cancel(owner, operation string) { m.mu.Lock() work, ok := m.cancels[operationKey{owner, operation}] delete(m.cancels, operationKey{owner, operation}) m.mu.Unlock() if ok { work.cancel() } } func (m *ReportManager) CancelReport(owner, report string) { callbacks := []context.CancelFunc{} m.mu.Lock() for key, work := range m.cancels { if key.owner == owner && work.report == report { callbacks = append(callbacks, work.cancel) delete(m.cancels, key) } } m.mu.Unlock() for _, cancel := range callbacks { cancel() } } func (m *ReportManager) Remove(owner, operation string) { m.mu.Lock() delete(m.cancels, operationKey{owner, operation}) m.mu.Unlock() }