51 lines
1.7 KiB
Go
51 lines
1.7 KiB
Go
package store
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"git.ipao.vip/rogee/go-sip/internal/tenant"
|
|
)
|
|
|
|
var ErrDispatcherIdentityMismatch = errors.New("database belongs to another dispatcher")
|
|
|
|
// DispatcherID returns the already-bound database identity, never a new identity.
|
|
func (s *Store) DispatcherID() (string, error) {
|
|
var id string
|
|
if err := s.db.QueryRow(`SELECT dispatcher_id FROM dispatcher_identity WHERE singleton=1`).Scan(&id); err != nil {
|
|
return "", fmt.Errorf("read dispatcher identity: %w", err)
|
|
}
|
|
return id, tenant.ValidateDispatcherID(id)
|
|
}
|
|
|
|
// BindDispatcherID permanently associates this database with a logical owner.
|
|
// Changing a lease epoch or restarting never changes this identity.
|
|
func (s *Store) BindDispatcherID(id string) error {
|
|
if err := tenant.ValidateDispatcherID(id); err != nil {
|
|
return err
|
|
}
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
tx, err := s.db.Begin()
|
|
if err != nil {
|
|
return fmt.Errorf("begin dispatcher identity binding: %w", err)
|
|
}
|
|
defer tx.Rollback()
|
|
if _, err := tx.Exec(`INSERT INTO dispatcher_identity(singleton, dispatcher_id, created_at)
|
|
VALUES(1, ?, ?) ON CONFLICT(singleton) DO NOTHING`, id, s.now().UTC().Format(time.RFC3339Nano)); err != nil {
|
|
return fmt.Errorf("persist dispatcher identity: %w", err)
|
|
}
|
|
var stored string
|
|
if err := tx.QueryRow(`SELECT dispatcher_id FROM dispatcher_identity WHERE singleton=1`).Scan(&stored); err != nil {
|
|
return fmt.Errorf("read dispatcher identity: %w", err)
|
|
}
|
|
if stored != id {
|
|
return fmt.Errorf("%w: stored=%s requested=%s", ErrDispatcherIdentityMismatch, stored, id)
|
|
}
|
|
if err := tx.Commit(); err != nil {
|
|
return fmt.Errorf("commit dispatcher identity: %w", err)
|
|
}
|
|
return nil
|
|
}
|