postgres

package
v0.0.0-...-cd790ac Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 18, 2026 License: AGPL-3.0 Imports: 35 Imported by: 2

Documentation

Overview

Package postgres provides PostgreSQL database connectivity with retry logic

Package postgres provides PostgreSQL database implementation for KiloCenter

Index

Constants

View Source
const (
	KeyMaterialSurfaceTLSKey             = "basestations.tls_key"
	KeyMaterialSurfacePendingMetadataKey = "bssci_pending_operations.metadata.encryptedKey"
	KeyMaterialSurfacePendingRecordKey   = "bssci_pending_operations.operation_data.nwkSnKey"
)

Key material surfaces that are not a whole BYTEA column.

View Source
const (
	// ChannelUplinkStored announces a stored uplink (a ulData row of messages).
	ChannelUplinkStored = "kc_uplink_stored"
	// ChannelEventStored announces a stored system event, or one moved forward in time.
	ChannelEventStored = "kc_event_stored"
)

Channels the triggers of migrations 000182 and 000183 notify, with an empty payload, when a row is stored.

Variables

View Source
var (
	ErrNilMigrationConfig = errors.New("migration runner: config is nil")
	ErrNilSchemaGate      = errors.New("migration runner: schema gate is nil")
)

Construction faults of a migration runner.

View Source
var (
	// ErrDownlinkAlreadyReserved indicates downlink was reserved by concurrent dispatcher
	// This occurs when FOR UPDATE SKIP LOCKED finds no available rows due to concurrent reservation
	ErrDownlinkAlreadyReserved = errors.New("downlink already reserved for dispatch")
)

Downlink dispatch errors

View Source
var ErrKeyMaterialNotEnvelope = errors.New("stored key material is not an authenticated envelope; run the rekey command")

ErrKeyMaterialNotEnvelope reports a stored key value that is not a valid authenticated envelope. Runtime reads never fall back to interpreting such bytes as cleartext: pre-envelope rows are converted once by the offline rekey command (KC-DB/cmd/rekey), which owns all format detection.

View Source
var ErrUnconvertedKeyMaterial = errors.New("stored key material is not converted to authenticated envelopes; run the rekey command (-mode=apply, then -mode=verify) before migrating further")

ErrUnconvertedKeyMaterial reports key material that is not yet an authenticated envelope when an upgrade would move the schema past 000143. The offline rekey command converts it; the upgrade then continues.

Functions

func IsUniqueViolation

func IsUniqueViolation(err error) bool

IsUniqueViolation checks if error is PostgreSQL unique constraint violation (SQLSTATE 23505) PostgreSQL error codes matched when translating driver errors.

func WrapDuplicateError

func WrapDuplicateError(err error, resource string) error

WrapDuplicateError wraps PostgreSQL unique violations as kcerrors.ErrDuplicate while preserving original error details for diagnostics **DOUBLE %w FORMAT**: ErrDuplicate FIRST so errors.Is() works, then pq.Error for errors.As()

Types

type APIKeyRepository

type APIKeyRepository struct {
	// contains filtered or unexported fields
}

APIKeyRepository implements the APIKeyRepository interface for PostgreSQL.

func NewAPIKeyRepository

func NewAPIKeyRepository(db *sqlx.DB, clk clock.Clock) *APIKeyRepository

NewAPIKeyRepository creates a new PostgreSQL API key repository

func (*APIKeyRepository) Count

func (r *APIKeyRepository) Count(ctx context.Context, tenantID int64, orgID uuid.UUID, userID *uuid.UUID) (int64, error)

Count returns total API key count for a tenant and organization with optional user filter

func (*APIKeyRepository) Create

func (r *APIKeyRepository) Create(ctx context.Context, key *models.APIKey) error

Create inserts a new API key

func (*APIKeyRepository) Delete

func (r *APIKeyRepository) Delete(ctx context.Context, id uuid.UUID) error

Delete removes an API key by ID

func (*APIKeyRepository) DeleteByIDAndOrg

func (r *APIKeyRepository) DeleteByIDAndOrg(ctx context.Context, id, orgID uuid.UUID) error

DeleteByIDAndOrg removes an API key by ID with organization ownership check.

func (*APIKeyRepository) GetByHash

func (r *APIKeyRepository) GetByHash(ctx context.Context, hash string) (*models.APIKey, error)

GetByHash retrieves an API key by its SHA-256 hash. The returned IsActive is false when the key is revoked or its owning user is deactivated; service account keys (user_id NULL) depend on the key flag alone.

func (*APIKeyRepository) GetByID

func (r *APIKeyRepository) GetByID(ctx context.Context, id uuid.UUID) (*models.APIKey, error)

GetByID retrieves an API key by UUID

func (*APIKeyRepository) GetByIDAndOrg

func (r *APIKeyRepository) GetByIDAndOrg(ctx context.Context, id, orgID uuid.UUID) (*models.APIKey, error)

GetByIDAndOrg retrieves an API key by UUID with organization ownership check.

func (*APIKeyRepository) List

func (r *APIKeyRepository) List(ctx context.Context, tenantID int64, orgID uuid.UUID, userID *uuid.UUID, limit, offset int) ([]*models.APIKey, error)

List returns API keys for a tenant and organization with optional user filter

func (*APIKeyRepository) UpdateLastUsed

func (r *APIKeyRepository) UpdateLastUsed(ctx context.Context, id uuid.UUID) error

UpdateLastUsed updates the last_used_at timestamp

type ArchivalConfig

type ArchivalConfig struct {
	// Message archival settings
	MessageRetentionDays int
	MessageArchivalHour  int // Hour of day to run (0-23)

	// General settings
	ArchivalEnabled bool
	CheckInterval   time.Duration // How often to check if archival should run
}

ArchivalConfig defines configuration for archival operations

func DefaultArchivalConfig

func DefaultArchivalConfig() ArchivalConfig

DefaultArchivalConfig returns default archival configuration Archival job names used for last-run bookkeeping.

type ArchivalScheduler

type ArchivalScheduler struct {
	// contains filtered or unexported fields
}

ArchivalScheduler manages scheduled archival operations. A single loop goroutine runs every archival itself, so runs never overlap and Stop, which cancels the loop and waits for it, returns only after the run in flight has ended.

func NewArchivalScheduler

func NewArchivalScheduler(archiver messageArchiver, logger logger.Logger, config ArchivalConfig, clk clock.Clock) *ArchivalScheduler

NewArchivalScheduler creates a new archival scheduler

func (*ArchivalScheduler) GetStatus

func (s *ArchivalScheduler) GetStatus() map[string]interface{}

GetStatus returns the current status of the archival scheduler

func (*ArchivalScheduler) Start

func (s *ArchivalScheduler) Start(ctx context.Context) error

Start begins the archival scheduler. ctx is the process lifecycle context; the running archival aborts when it or Stop cancels the loop.

func (*ArchivalScheduler) Stop

func (s *ArchivalScheduler) Stop() error

Stop cancels the scheduler loop and waits until it, and the archival it may be running, has ended.

type ArchivalService

type ArchivalService struct {
	// contains filtered or unexported fields
}

ArchivalService handles message archiving operations

func NewArchivalService

func NewArchivalService(db *sql.DB, logger logger.Logger, clk clock.Clock) *ArchivalService

NewArchivalService creates a new archival service pg_size_pretty style byte formatting: the 1024 unit step, the plain-bytes format, and the unit ladder.

func (*ArchivalService) ArchiveOldMessages

func (s *ArchivalService) ArchiveOldMessages(ctx context.Context, olderThan time.Duration) (int64, error)

ArchiveOldMessages archives messages older than the specified duration

func (*ArchivalService) CreateMonthlyPartitions

func (s *ArchivalService) CreateMonthlyPartitions(ctx context.Context, monthsAhead int) error

CreateMonthlyPartitions ensures partitions exist for the next N months

func (*ArchivalService) GetArchivalStats

func (s *ArchivalService) GetArchivalStats(ctx context.Context) (*ArchivalStats, error)

GetArchivalStats returns statistics about archived messages

func (*ArchivalService) PurgeArchivedMessages

func (s *ArchivalService) PurgeArchivedMessages(ctx context.Context, archivedBefore time.Time) (int64, error)

PurgeArchivedMessages removes messages from the main table that have been archived This should only be run after verifying the archive is complete and backed up

type ArchivalStats

type ArchivalStats struct {
	MainTableCount    int64
	MainTableArchived int64
	MainTableSize     string
	OldestMainMessage *time.Time
	NewestMainMessage *time.Time

	ArchiveTableCount     int64
	ArchiveTableSize      string
	CanonicalArchiveCount int64
	CanonicalArchiveSize  string
	LegacyArchiveCount    int64
	LegacyArchiveSize     string
	OldestArchiveMessage  *time.Time
	NewestArchiveMessage  *time.Time

	Partitions []PartitionInfo
}

ArchivalStats contains statistics about archived messages. The combined ArchiveTableCount/ArchiveTableSize cover the canonical archive plus the preserved pre-000139 legacy archive; the split fields expose each side.

type BaseStationMetricsRepository

type BaseStationMetricsRepository struct {
	// contains filtered or unexported fields
}

BaseStationMetricsRepository answers availability and throughput queries for one base station.

func NewBaseStationMetricsRepository

func NewBaseStationMetricsRepository(db *sqlx.DB) *BaseStationMetricsRepository

NewBaseStationMetricsRepository creates the metrics repository.

func (*BaseStationMetricsRepository) CountBaseStationMessagesByBucket

func (r *BaseStationMetricsRepository) CountBaseStationMessagesByBucket(ctx context.Context, tenantID int64, bsEui []byte,
	start, end time.Time, intervalSeconds int64) (counts map[int64]int64, err error)

CountBaseStationMessagesByBucket counts received uplink data messages ('ulData' only) per intervalSeconds bucket over [start, end), keyed by rx_time (BSSCI reception time, ns) / intervalSeconds. Absent buckets are zero-filled by the caller; secondary receivers (base_stations JSONB) are included. The base station must belong to the tenant; the receptions it counts belong to every tenant, so roaming traffic shows up as load without exposing whose it is.

func (*BaseStationMetricsRepository) GetBaseStationOnlineIntervals

func (r *BaseStationMetricsRepository) GetBaseStationOnlineIntervals(ctx context.Context, tenantID, baseStationID int64,
	start, end time.Time) (intervals []mioty.BaseStationOnlineInterval, err error)

GetBaseStationOnlineIntervals returns the connected intervals for a base station that overlap [start, end), derived from its BSSCI sessions. An interval with a nil End is still active. These intervals are the source for time-weighted availability; callers bucket them. Results are ordered by start time.

type BaseStationRepository

type BaseStationRepository struct {
	// contains filtered or unexported fields
}

BaseStationRepository implements the BaseStationRepository interface for PostgreSQL

func NewBaseStationRepository

func NewBaseStationRepository(db *sqlx.DB, clk clock.Clock, log logger.Logger) *BaseStationRepository

NewBaseStationRepository creates a new PostgreSQL Base Station repository updateFixedArgs counts the leading fixed parameters (tenant, id) of the dynamic update statement.

func (*BaseStationRepository) Create

Create creates a new Base Station

func (*BaseStationRepository) DeleteByEUI

func (r *BaseStationRepository) DeleteByEUI(ctx context.Context, tenantID int64, eui []byte) (*models.BaseStation, error)

DeleteByEUI removes a tenant's base station addressed by EUI in one statement and returns the row it removed.

func (*BaseStationRepository) GetByEUI

func (r *BaseStationRepository) GetByEUI(ctx context.Context, tenantID int64, eui []byte) (*models.BaseStation, error)

GetByEUI retrieves a Base Station by EUI

func (*BaseStationRepository) GetByEUIGlobal

func (r *BaseStationRepository) GetByEUIGlobal(ctx context.Context, eui []byte) (*models.BaseStation, error)

GetByEUIGlobal retrieves a Base Station by EUI across all tenants. Used during BSSCI connect handshake when tenant is not yet resolved.

func (*BaseStationRepository) GetByID

func (r *BaseStationRepository) GetByID(ctx context.Context, tenantID, id int64) (*models.BaseStation, error)

GetByID retrieves a Base Station by ID

func (*BaseStationRepository) GetDB

func (r *BaseStationRepository) GetDB() *sqlx.DB

GetDB returns the database connection for direct database operations This is used by the BSSCI server for session management operations

func (*BaseStationRepository) GetStatistics

func (r *BaseStationRepository) GetStatistics(ctx context.Context, tenantID int64) (*models.BaseStationStatistics, error)

GetStatistics retrieves statistics for Base Stations

func (*BaseStationRepository) List

List retrieves Base Stations based on filter criteria

func (*BaseStationRepository) ListAllLocations

func (r *BaseStationRepository) ListAllLocations(ctx context.Context) ([]*models.BaseStation, error)

ListAllLocations retrieves all base stations with non-null coordinates across all tenants.

func (*BaseStationRepository) ListWithStats

func (r *BaseStationRepository) ListWithStats(ctx context.Context, tenantID int64, limit, offset int) ([]*BaseStationWithStats, int64, error)

ListWithStats retrieves base stations with message statistics

func (*BaseStationRepository) TakeTLSKey

func (r *BaseStationRepository) TakeTLSKey(ctx context.Context, tenantID int64, eui []byte, open func(sealed string) error) (err error)

TakeTLSKey hands a tenant's base station's stored private key to open and removes it once open accepts it, all in one transaction: the key leaves the service center once, and a key open refuses (one that fails to decrypt, or does not match) stays stored. A station without a stored key, or of another tenant, is storage.ErrNotFound; a take while another holds the key fails at once.

func (*BaseStationRepository) Update

func (r *BaseStationRepository) Update(ctx context.Context, tenantID, id int64, updates map[string]interface{}) error

Update updates an existing Base Station

func (*BaseStationRepository) UpdateConnectionStatus

func (r *BaseStationRepository) UpdateConnectionStatus(ctx context.Context, tenantID, id int64, isOnline bool, lastError *string) error

UpdateConnectionStatus updates the connection status of a Base Station

func (*BaseStationRepository) UpdateEUI

func (r *BaseStationRepository) UpdateEUI(ctx context.Context, tenantID int64, oldEui, newEui []byte) (_ *models.BaseStation, err error)

UpdateEUI updates the Base Station EUI with transactional cascade to all dependent tables

func (*BaseStationRepository) UpdateProfile

func (r *BaseStationRepository) UpdateProfile(ctx context.Context, bs *models.BaseStation) error

UpdateProfile persists the operator-editable base station fields: name, description, location and tags.

func (*BaseStationRepository) UpdateTLSCertExpiryIfBlank

func (r *BaseStationRepository) UpdateTLSCertExpiryIfBlank(ctx context.Context, tenantID, id int64, expiresAt time.Time) (bool, error)

UpdateTLSCertExpiryIfBlank persists the certificate expiry only while the stored tls_cert_expires_at is still NULL, so an existing expiry is never overwritten; reports whether a row was updated.

func (*BaseStationRepository) UpdateTLSFingerprintIfBlank

func (r *BaseStationRepository) UpdateTLSFingerprintIfBlank(ctx context.Context, tenantID, id int64, fingerprint string) (bool, error)

UpdateTLSFingerprintIfBlank persists the certificate fingerprint only while the stored tls_cert_fingerprint is still NULL or empty (see interface contract). The conditional WHERE makes the backfill race-safe: a concurrent writer wins and this call reports false so the caller reloads and compares.

type BaseStationSessionRepository

type BaseStationSessionRepository struct {
	// contains filtered or unexported fields
}

BaseStationSessionRepository implements the BaseStationSessionRepository interface for PostgreSQL

func NewBaseStationSessionRepository

func NewBaseStationSessionRepository(db *sqlx.DB, clk clock.Clock, log logger.Logger) *BaseStationSessionRepository

NewBaseStationSessionRepository creates a new PostgreSQL Base Station session repository setNullClauseFmt renders a column-to-NULL assignment in the update builder.

func (*BaseStationSessionRepository) ActivateSessionIfResumable

func (r *BaseStationSessionRepository) ActivateSessionIfResumable(ctx context.Context, tenantID, sessionID int64, req *models.BaseStationSessionUpdateRequest) (bool, error)

ActivateSessionIfResumable applies the resume activation only while the row is still disconnected and resumable. Two connections that both found the same row through FindResumableSession reach this update, and only the first one matches: the loser gets false and must abandon the resume.

func (*BaseStationSessionRepository) CheckSessionResumable

func (r *BaseStationSessionRepository) CheckSessionResumable(ctx context.Context, tenantID int64, snBsUUID [16]byte, bsOpId int64) (*models.SessionResumptionInfo, error)

CheckSessionResumable determines if a session can be resumed per MIOTY spec

func (*BaseStationSessionRepository) CreateSession

CreateSession creates a new Base Station session per MIOTY BSSCI 3.3

func (*BaseStationSessionRepository) DisconnectAbandonedSessions

func (r *BaseStationSessionRepository) DisconnectAbandonedSessions(ctx context.Context, scEUI models.EUI) ([]int64, error)

DisconnectAbandonedSessions hands the sessions a previous process of the service center scEUI left active back resumable, as a lost connection's teardown would have, and returns their ids. A row without an owner predates ownership tracking and is claimed for scEUI; rows of other service centers are not touched. The last write to a row is the closest known end time.

func (*BaseStationSessionRepository) FindResumableSession

func (r *BaseStationSessionRepository) FindResumableSession(ctx context.Context, tenantID int64, bsEUI []byte, snBsUUID [16]byte) (*models.BaseStationSession, error)

FindResumableSession finds the resumable session for a base station, scoped by tenant, base station EUI, and snBsUuid, requiring status=disconnected and can_resume=true (BSSCI §5.3.1)

func (*BaseStationSessionRepository) GetActiveSessionByBaseStation

func (r *BaseStationSessionRepository) GetActiveSessionByBaseStation(ctx context.Context, tenantID, baseStationID int64) (*models.BaseStationSession, error)

GetActiveSessionByBaseStation retrieves the active session for a Base Station

func (*BaseStationSessionRepository) GetSessionByID

func (r *BaseStationSessionRepository) GetSessionByID(ctx context.Context, tenantID, sessionID int64) (*models.BaseStationSession, error)

GetSessionByID retrieves a session by ID

func (*BaseStationSessionRepository) GetSessionByScUUID

func (r *BaseStationSessionRepository) GetSessionByScUUID(ctx context.Context, tenantID int64, snScUUID [16]byte) (*models.BaseStationSession, error)

GetSessionByScUUID retrieves a session by Service Center session UUID

func (*BaseStationSessionRepository) GetSessionStatistics

func (r *BaseStationSessionRepository) GetSessionStatistics(ctx context.Context, tenantID int64) (*models.SessionStatistics, error)

GetSessionStatistics retrieves session statistics

func (*BaseStationSessionRepository) ListSessions

ListSessions retrieves sessions based on filter criteria

func (*BaseStationSessionRepository) MarkDisconnected

func (r *BaseStationSessionRepository) MarkDisconnected(ctx context.Context, tenantID, sessionID int64, connectionID string, endedAt time.Time) error

MarkDisconnected marks an active session disconnected and resumable, guarded by the stored connection ID and by the active status: a reconnect that already replaced this connection, or a session already retired, matches zero rows and stays untouched (not an error).

func (*BaseStationSessionRepository) TerminateResumableSessions

func (r *BaseStationSessionRepository) TerminateResumableSessions(ctx context.Context, tenantID, baseStationID int64) ([]int64, error)

TerminateResumableSessions retires the leftover resumable sessions of a base station so a fresh session starts from discarded state (BSSCI §3), returning the retired session ids for pending-operation cleanup. Zero matches is not an error.

func (*BaseStationSessionRepository) TerminateSession

func (r *BaseStationSessionRepository) TerminateSession(ctx context.Context, tenantID, sessionID int64) error

TerminateSession marks a session as terminated

func (*BaseStationSessionRepository) UpdateEncoding

func (r *BaseStationSessionRepository) UpdateEncoding(ctx context.Context, tenantID, sessionID int64, encoding string) error

UpdateEncoding updates the message encoding for a session This is called when encoding is negotiated on first message per BSSCI Section 1

func (*BaseStationSessionRepository) UpdateOperationIDs

func (r *BaseStationSessionRepository) UpdateOperationIDs(ctx context.Context, tenantID, sessionID int64, bsOpId, scOpId int64) error

UpdateOperationIDs advances both Base Station and Service Center operation IDs atomically. Counters only move forward (BSSCI §3.2: base station IDs rise, service center IDs fall), so a snapshot written out of order never lowers what a later one stored.

func (*BaseStationSessionRepository) UpdateSession

func (r *BaseStationSessionRepository) UpdateSession(ctx context.Context, tenantID, sessionID int64, req *models.BaseStationSessionUpdateRequest) error

UpdateSession updates session fields (operation IDs, status, timing)

type BaseStationStatus

type BaseStationStatus struct {
	BsEUI           []byte          `db:"bs_eui"`
	Name            string          `db:"name"`
	IsOnline        bool            `db:"is_online"`
	LastSeenAt      *time.Time      `db:"last_seen_at"`
	Bidi            sql.NullBool    `db:"bidi"`
	Latitude        sql.NullFloat64 `db:"latitude"`
	Longitude       sql.NullFloat64 `db:"longitude"`
	Altitude        sql.NullFloat64 `db:"altitude"`
	RecentEvents    int             `db:"recent_events"`
	SnScUUID        sql.NullString  `db:"sn_sc_uuid"`       // Session SC UUID (NULL if no recent session)
	SnBsUUID        sql.NullString  `db:"sn_bs_uuid"`       // Session BS UUID (NULL if no recent session)
	SnBsOpId        sql.NullInt64   `db:"sn_bs_op_id"`      // Last BS operation ID (NULL if no recent session)
	SnScOpId        sql.NullInt64   `db:"sn_sc_op_id"`      // Last SC operation ID (NULL if no recent session)
	CanResume       sql.NullBool    `db:"can_resume"`       // Session resumable flag (NULL if no recent session)
	Encoding        sql.NullString  `db:"encoding"`         // Message encoding (NULL if no recent session)
	ProtocolVersion sql.NullString  `db:"protocol_version"` // BSSCI protocol version (NULL if no recent session)
	ConnectInfo     sql.NullString  `db:"connect_info"`     // Connect info JSON blob (NULL if no recent session)
	LastPingAt      sql.NullTime    `db:"last_ping_at"`     // Last ping timestamp (NULL if no ping received, BSSCI §5.4)
}

BaseStationStatus represents BSSCI connection status with event summary and session metadata BSSCI §5-5.3: Session fields support offline station troubleshooting via most recent session LEFT JOIN

type BaseStationStatusRepository

type BaseStationStatusRepository struct {
	// contains filtered or unexported fields
}

BaseStationStatusRepository implements base station status history storage operations Implements interfaces.MIOTYBaseStationStatusRepository

func NewBaseStationStatusRepository

func NewBaseStationStatusRepository(db *sqlx.DB, clk clock.Clock) *BaseStationStatusRepository

NewBaseStationStatusRepository creates a new base station status repository

func (*BaseStationStatusRepository) Create

Create stores a new base station status record per BSSCI §3.5.2

type BaseStationWithStats

type BaseStationWithStats struct {
	ID              int64          `db:"id"`
	BsEui           []byte         `db:"bs_eui"`
	Name            string         `db:"name"`
	Description     sql.NullString `db:"description"`
	IsOnline        bool           `db:"is_online"`
	LastSeenAt      sql.NullTime   `db:"last_seen_at"`
	CreatedAt       time.Time      `db:"created_at"`
	UpdatedAt       time.Time      `db:"updated_at"`
	MessageCount    int            `db:"message_count"`
	UniqueEndpoints int            `db:"unique_endpoints"`
	AvgRSSI         float64        `db:"avg_rssi"`
	AvgSNR          float64        `db:"avg_snr"`
}

BaseStationWithStats represents a base station with aggregated statistics

type BlueprintRepository

type BlueprintRepository struct {
	// contains filtered or unexported fields
}

BlueprintRepository implements the BlueprintRepository interface for PostgreSQL

func NewBlueprintRepository

func NewBlueprintRepository(db sqlx.ExtContext) *BlueprintRepository

NewBlueprintRepository creates a new PostgreSQL Blueprint repository

func (*BlueprintRepository) Count

func (r *BlueprintRepository) Count(ctx context.Context, tenantID int64, isSystem bool) (int64, error)

Count returns the total count of blueprints for a tenant

func (*BlueprintRepository) CountByDeviceModel

func (r *BlueprintRepository) CountByDeviceModel(ctx context.Context, tenantID int64, isSystem bool, deviceModelID uuid.UUID) (int64, error)

CountByDeviceModel returns the count of blueprints for a device model

func (*BlueprintRepository) Create

Create creates a new blueprint

func (*BlueprintRepository) Delete

func (r *BlueprintRepository) Delete(ctx context.Context, tenantID int64, isSystem bool, id uuid.UUID) error

Delete deletes a blueprint by ID within the isSystem-selected ownership scope

func (*BlueprintRepository) GetByID

func (r *BlueprintRepository) GetByID(ctx context.Context, tenantID int64, id uuid.UUID) (*models.Blueprint, error)

GetByID retrieves a blueprint by ID with tenant isolation

func (*BlueprintRepository) GetByTypeEUI

func (r *BlueprintRepository) GetByTypeEUI(ctx context.Context, tenantID int64, typeEUI []byte) (*models.Blueprint, error)

GetByTypeEUI retrieves a blueprint by Type EUI with tenant isolation

func (*BlueprintRepository) GetDefaultForModel

func (r *BlueprintRepository) GetDefaultForModel(ctx context.Context, tenantID int64, deviceModelID uuid.UUID) (*models.Blueprint, error)

GetDefaultForModel retrieves the default blueprint for a device model

func (*BlueprintRepository) List

List retrieves blueprints for a tenant with pagination and optional filters

func (*BlueprintRepository) SetDefault

func (r *BlueprintRepository) SetDefault(ctx context.Context, tenantID int64, isSystem bool, id uuid.UUID) error

SetDefault sets a blueprint as the default for its device model

func (*BlueprintRepository) Update

func (r *BlueprintRepository) Update(ctx context.Context, tenantID int64, isSystem bool, id uuid.UUID, params *models.BlueprintUpdateParams) error

Update updates an existing blueprint

func (*BlueprintRepository) UpdateRegistryInfo

func (r *BlueprintRepository) UpdateRegistryInfo(ctx context.Context, tenantID int64, isSystem bool, id uuid.UUID, repo, commitSHA, prURL string, verified bool) error

UpdateRegistryInfo updates the GitHub registry metadata for a blueprint

type CEInstallationRepository

type CEInstallationRepository struct {
	// contains filtered or unexported fields
}

CEInstallationRepository manages the singleton CE installation record using PostgreSQL.

func NewCEInstallationRepository

func NewCEInstallationRepository(db *sqlx.DB) *CEInstallationRepository

NewCEInstallationRepository creates a new CEInstallationRepository backed by sqlx.

func (*CEInstallationRepository) CompleteOnboarding

func (r *CEInstallationRepository) CompleteOnboarding(ctx context.Context, companyName string, at time.Time) (uuid.UUID, error)

CompleteOnboarding records companyName as completed at the given time and returns the installation's CE ID. It fails with storage.ErrInstallationOnboarded once onboarding has completed.

func (*CEInstallationRepository) Get

Get retrieves the singleton installation record, or storage.ErrNotFound before one exists.

func (*CEInstallationRepository) Update

func (r *CEInstallationRepository) Update(ctx context.Context, updates map[string]interface{}) error

Update applies partial updates using a field map. Only provided keys are changed.

type Config

type Config struct {
	Host            string
	Port            int
	Database        string
	Username        string
	Password        string
	SSLMode         string
	MaxOpenConns    int
	MaxIdleConns    int
	ConnMaxLifetime time.Duration
	ConnMaxIdleTime time.Duration
}

Config holds PostgreSQL connection configuration

func (*Config) GetDSN

func (c *Config) GetDSN() string

GetDSN returns the PostgreSQL connection string dsnFormat renders the PostgreSQL connection string.

type ConnectionManager

type ConnectionManager struct {
	// contains filtered or unexported fields
}

ConnectionManager manages database connections with retry logic

func NewConnectionManager

func NewConnectionManager(config *Config, logger logger.Logger) *ConnectionManager

NewConnectionManager creates a new connection manager

func (*ConnectionManager) Close

func (cm *ConnectionManager) Close() error

Close closes the database connection

func (*ConnectionManager) Connect

func (cm *ConnectionManager) Connect(ctx context.Context) error

Connect establishes a database connection with retry logic

func (*ConnectionManager) ExecuteWithRetry

func (cm *ConnectionManager) ExecuteWithRetry(ctx context.Context, fn func() error) error

ExecuteWithRetry executes a function with retry logic

func (*ConnectionManager) GetDB

func (cm *ConnectionManager) GetDB() *sql.DB

GetDB returns the database connection

func (*ConnectionManager) HealthCheck

func (cm *ConnectionManager) HealthCheck(ctx context.Context) error

HealthCheck performs a health check on the database connection

func (*ConnectionManager) Stats

func (cm *ConnectionManager) Stats() sql.DBStats

Stats returns database connection pool statistics

func (*ConnectionManager) WaitForConnection

func (cm *ConnectionManager) WaitForConnection(ctx context.Context, timeout time.Duration) error

WaitForConnection waits for the database to become available

type DB

type DB struct {
	// contains filtered or unexported fields
}

DB represents a PostgreSQL database connection

func New

func New(opts Options, cipher keycrypto.Cipher) (*DB, error)

New creates a new PostgreSQL database connection with retry logic. The cipher is mandatory: it encrypts all key material at rest, so a nil cipher is a configuration error rather than a silent plaintext fallback. componentPostgres labels this component in structured logs.

func (*DB) BeginTx

func (db *DB) BeginTx(ctx context.Context) (*Transaction, error)

BeginTx starts a new database transaction. It returns the concrete type: transactions are consumed by the storage adapters in this module, which pass a narrow, operation-specific view to their callers.

func (*DB) Close

func (db *DB) Close() error

Close closes the database connection

func (*DB) Exec

func (db *DB) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

Exec executes a query without returning any rows with retry logic

func (*DB) GetDB

func (db *DB) GetDB() *sql.DB

GetDB returns the underlying database connection This should be used sparingly and only for operations that need direct access

func (*DB) Ping

func (db *DB) Ping(ctx context.Context) error

Ping checks the database connection with context

func (*DB) Query

func (db *DB) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

Query executes a query that returns rows with retry logic

func (*DB) QueryRow

func (db *DB) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row

QueryRow executes a query that returns at most one row

func (*DB) Sqlx

func (db *DB) Sqlx() *sqlx.DB

Sqlx returns the facade's sqlx handle for repositories constructed by the composition roots.

func (*DB) WaitForConnection

func (db *DB) WaitForConnection(ctx context.Context, timeout time.Duration) error

WaitForConnection waits for the database to become available

type DLRXStatusRepository

type DLRXStatusRepository struct {
	// contains filtered or unexported fields
}

DLRXStatusRepository handles DL RX status persistence per BSSCI §3.15

func NewDLRXStatusRepository

func NewDLRXStatusRepository(db *sqlx.DB, logger logger.Logger) *DLRXStatusRepository

NewDLRXStatusRepository creates a new DL RX status repository DL RX status lifecycle values persisted in dl_rx_status.status.

func (*DLRXStatusRepository) CreateDLRXStatus

func (r *DLRXStatusRepository) CreateDLRXStatus(ctx context.Context, status *mioty.DLRXStatus) error

CreateDLRXStatus persists a new DL RX status report

func (*DLRXStatusRepository) CreateDLRXStatusQuery

func (r *DLRXStatusRepository) CreateDLRXStatusQuery(ctx context.Context, tenantID int64, orgUUID *uuid.UUID, epEui, bsEui []byte, opId int64) error

CreateDLRXStatusQuery tracks a dlRxStatQry request for correlation (BSSCI §5.15 audit trail)

func (*DLRXStatusRepository) ExpireDLRXStatusQuery

func (r *DLRXStatusRepository) ExpireDLRXStatusQuery(ctx context.Context, cutoff time.Time) (int64, error)

ExpireDLRXStatusQuery marks queries older than cutoff as 'timeout' Returns count of expired queries (used by cleanup job)

func (*DLRXStatusRepository) GetAverageDLRXMetrics

func (r *DLRXStatusRepository) GetAverageDLRXMetrics(ctx context.Context, tenantID int64, epEui []byte, startTime, endTime *time.Time) (avgSnr, avgRssi float64, count int, err error)

GetAverageDLRXMetrics calculates average SNR and RSSI for an endpoint over a time period

func (*DLRXStatusRepository) GetDLRXStatusByEndpoint

func (r *DLRXStatusRepository) GetDLRXStatusByEndpoint(ctx context.Context, tenantID int64, epEui []byte, limit, offset int, startTime, endTime *time.Time) ([]*mioty.DLRXStatus, int, error)

GetDLRXStatusByEndpoint retrieves DL RX status records for a specific endpoint

func (*DLRXStatusRepository) GetDLRXStatusQueryHistory

func (r *DLRXStatusRepository) GetDLRXStatusQueryHistory(ctx context.Context, tenantID int64, epEui []byte, limit, offset int, startTime, endTime *time.Time) ([]*mioty.DLRXStatusQuery, int, error)

GetDLRXStatusQueryHistory retrieves query tracking records for an endpoint (BSSCI §5.15 telemetry)

func (*DLRXStatusRepository) GetDLRXStatusQueryStats

func (r *DLRXStatusRepository) GetDLRXStatusQueryStats(ctx context.Context, tenantID int64, epEui []byte, startTime, endTime *time.Time) (pending, received, timeout int64, err error)

GetDLRXStatusQueryStats calculates query status distribution for an endpoint (BSSCI §5.15 telemetry)

func (*DLRXStatusRepository) GetDLRXStatusSinceLastHeard

func (r *DLRXStatusRepository) GetDLRXStatusSinceLastHeard(
	ctx context.Context,
	tenantID int64,
	epEui []byte,
	bsEuis [][]byte,
) ([]*mioty.DLRXStatus, error)

GetDLRXStatusSinceLastHeard returns, per base station, the latest DL RX status reported after the endpoint was last heard, so each report is attached to the first uplink after it (SCACI §3.8.1 "previous DL reception") in a single query.

func (*DLRXStatusRepository) MarkDLRXStatusReceived

func (r *DLRXStatusRepository) MarkDLRXStatusReceived(ctx context.Context, tenantID int64, epEui []byte, bsEui []byte, bsOpID int64) (bool, error)

MarkDLRXStatusReceived marks the OLDEST pending query for the tenant, endpoint, AND expected base station as received (BSSCI §5.15). Correlating on the expected bs_eui prevents a report from one base station satisfying a concurrent query issued for a different base station. The actual BS EUI/opId are recorded for audit. Returns true if a matching pending query was found and updated.

type DeviceModelRepository

type DeviceModelRepository struct {
	// contains filtered or unexported fields
}

DeviceModelRepository implements the DeviceModelRepository interface for PostgreSQL

func NewDeviceModelRepository

func NewDeviceModelRepository(db sqlx.ExtContext, log logger.Logger) *DeviceModelRepository

NewDeviceModelRepository creates a new PostgreSQL DeviceModel repository

func (*DeviceModelRepository) Count

func (r *DeviceModelRepository) Count(ctx context.Context, tenantID int64, isSystem bool) (int64, error)

Count returns the total count of device models for a tenant

func (*DeviceModelRepository) CountByManufacturer

func (r *DeviceModelRepository) CountByManufacturer(ctx context.Context, tenantID int64, isSystem bool, manufacturerID uuid.UUID) (int64, error)

CountByManufacturer returns the count of device models for a manufacturer

func (*DeviceModelRepository) Create

Create creates a new device model

func (*DeviceModelRepository) Delete

func (r *DeviceModelRepository) Delete(ctx context.Context, tenantID int64, isSystem bool, id uuid.UUID) error

Delete deletes a device model by ID within the isSystem-selected ownership scope

func (*DeviceModelRepository) GetByID

func (r *DeviceModelRepository) GetByID(ctx context.Context, tenantID int64, id uuid.UUID) (*models.DeviceModel, error)

GetByID retrieves a device model by ID with tenant isolation

func (*DeviceModelRepository) GetByTypeEUI

func (r *DeviceModelRepository) GetByTypeEUI(ctx context.Context, tenantID int64, typeEUI []byte) (*models.DeviceModel, error)

GetByTypeEUI retrieves a device model by Type EUI with tenant isolation

func (*DeviceModelRepository) List

List retrieves device models for a tenant with pagination and optional filters

func (*DeviceModelRepository) Update

func (r *DeviceModelRepository) Update(ctx context.Context, tenantID int64, isSystem bool, id uuid.UUID, params *models.DeviceModelUpdateParams) error

Update updates an existing device model

type DownlinkExpirySweep

type DownlinkExpirySweep struct {
	// contains filtered or unexported fields
}

DownlinkExpirySweep ends the wait of the downlinks whose lifetime elapsed.

func (*DownlinkExpirySweep) ExpireOverdueUnheld

func (r *DownlinkExpirySweep) ExpireOverdueUnheld(ctx context.Context, limit int) ([]*storage.DownlinkMessage, error)

ExpireOverdueUnheld ends expired up to limit downlinks of any tenant whose lifetime elapsed while no base station held them, and returns them for their originators: no station can transmit them any more.

func (*DownlinkExpirySweep) RevokeOverdueHeld

func (r *DownlinkExpirySweep) RevokeOverdueHeld(ctx context.Context, askedAt time.Time, limit int) ([]*storage.DownlinkMessage, error)

RevokeOverdueHeld moves to revoking up to limit downlinks of any tenant whose lifetime elapsed while a base station held them queued, keeping that station as their holder and recording askedAt, the start of the sweep that asks it, and returns them so it is asked to drop them (BSSCI §3.13); their outcome waits for its answer.

type DownlinkQueueLookup

type DownlinkQueueLookup struct {
	// contains filtered or unexported fields
}

DownlinkQueueLookup reads queue rows by endpoint, queue id and packet counter.

func (*DownlinkQueueLookup) GetDownlinkByQueueID

func (r *DownlinkQueueLookup) GetDownlinkByQueueID(ctx context.Context, queId uint64, tenantID string) (*storage.DownlinkMessage, error)

GetDownlinkByQueueID retrieves the tenant's downlink by its queue ID, with the user data of each packet counter it was queued for.

func (*DownlinkQueueLookup) GetDownlinkByRevocation

func (r *DownlinkQueueLookup) GetDownlinkByRevocation(ctx context.Context, revocation storage.DownlinkRevocation) (*storage.DownlinkMessage, error)

GetDownlinkByRevocation retrieves the downlink a revocation names, of the organization and endpoint when it names them; sql.ErrNoRows when no row of that owner carries the queue id.

func (*DownlinkQueueLookup) GetDownlinkQueue

func (r *DownlinkQueueLookup) GetDownlinkQueue(ctx context.Context, deviceEUI string, tenantID string) ([]*storage.DownlinkMessage, error)

GetDownlinkQueue retrieves pending downlink messages for a device Delegates to DownlinkQueueReader for DRY implementation

func (*DownlinkQueueLookup) GetDownlinksByPacketCnt

func (r *DownlinkQueueLookup) GetDownlinksByPacketCnt(ctx context.Context, tenantID string, epEui string, packetCnt uint32) ([]*storage.DownlinkMessage, error)

GetDownlinksByPacketCnt lists the tenant's in-flight counter-dependent downlinks of the endpoint scheduled for the packet counter (SCACI §3.11.1), newest first; empty when none is.

func (r *DownlinkQueueLookup) ListInFlightDownlinks(ctx context.Context, tenantID int64, filter storage.DownlinkQueueFilter) ([]*storage.DownlinkMessage, error)

ListInFlightDownlinks lists the tenant's in-flight downlinks the filter narrows, bounded like the tenant queue listing.

func (r *DownlinkQueueLookup) ListPacketCounterDownlinks(ctx context.Context, query storage.PacketCounterDownlinks) ([]*storage.DownlinkMessage, error)

ListPacketCounterDownlinks lists the in-flight counter-dependent downlinks the query names, newest first; empty when none is.

type DownlinkQueueReader

type DownlinkQueueReader struct {
	// contains filtered or unexported fields
}

DownlinkQueueReader implements read-only downlink queue operations Reuses storage.DownlinkMessage to avoid struct duplication

func NewDownlinkQueueReader

func NewDownlinkQueueReader(db *sqlx.DB, log logger.Logger) *DownlinkQueueReader

NewDownlinkQueueReader creates a new downlink queue reader

func (*DownlinkQueueReader) CountTenantQueue

func (r *DownlinkQueueReader) CountTenantQueue(ctx context.Context, tenantID int64, filter storage.DownlinkQueueFilter) (int64, error)

CountTenantQueue counts the downlinks ListTenantQueue lists for the filter.

func (*DownlinkQueueReader) GetTenantIDByQueueID

func (r *DownlinkQueueReader) GetTenantIDByQueueID(ctx context.Context, queueID uint64) (int64, error)

GetTenantIDByQueueID resolves the tenant that owns a specific downlink queue Used by TenantResolver for cold-path tenant lookup during result processing Implements interfaces.DownlinkQueueStore

func (*DownlinkQueueReader) ListTenantQueue

func (r *DownlinkQueueReader) ListTenantQueue(ctx context.Context, tenantID int64, filter storage.DownlinkQueueFilter, limit, offset int) ([]*storage.DownlinkMessage, error)

ListTenantQueue lists one page of a tenant's queued downlinks, highest priority first.

type DownlinkQueueWriter

type DownlinkQueueWriter struct {
	// contains filtered or unexported fields
}

DownlinkQueueWriter enqueues downlinks and changes them while no base station holds them yet.

func (*DownlinkQueueWriter) CommandQueued

func (r *DownlinkQueueWriter) CommandQueued(ctx context.Context, command storage.DownlinkCommandRef) (bool, error)

CommandQueued reports whether the organization already queued a downlink for the endpoint under the MQTT command's ref, in flight or finished.

func (r *DownlinkQueueWriter) EnqueueDownlink(ctx context.Context, downlink *storage.DownlinkMessage, lifetime time.Duration) (*storage.DownlinkMessage, error)

EnqueueDownlink adds a downlink to the queue; it waits for a downlink window for lifetime from now, or until the deadline of the MQTT command that queued it when that comes first, and then expires. A ref the organization already queued for the endpoint queues nothing: storage.ErrDownlinkRefTaken, whether or not the deadline passed since. A deadline that is not after the moment the downlink is queued: storage.ErrDownlinkDeadlineElapsed.

func (*DownlinkQueueWriter) UpdateDownlinkStatus

func (r *DownlinkQueueWriter) UpdateDownlinkStatus(ctx context.Context, id string, status mioty.DLQueueStatus, orgID *uuid.UUID) error

UpdateDownlinkStatus updates the status of a downlink message named by its queue id or, at or below queueIDThreshold, its row id. orgID filters by organization with strict equality (a NULL organization row never matches); nil means no filter.

func (r *DownlinkQueueWriter) UpdatePendingDownlink(ctx context.Context, tenantID int64, orgID *uuid.UUID, epEUI []byte, queID int64, patch storage.DownlinkPatch) (*storage.DownlinkMessage, error)

UpdatePendingDownlink replaces the SCACI §3.10.1 fields of a pending downlink in one statement scoped to the owning tenant and endpoint, so a dispatcher that reserves the row first wins and a foreign endpoint's queue id never touches another endpoint's row.

type DownlinkReservations

type DownlinkReservations struct {
	// contains filtered or unexported fields
}

DownlinkReservations moves pending downlinks to the base station that transmits them and back when the station lets them go.

func (r *DownlinkReservations) ListPendingDownlinks(ctx context.Context) (pending []storage.PendingDownlink, err error)

ListPendingDownlinks returns the unexpired pending downlinks of every tenant, grouped by endpoint in the order a downlink window takes them.

func (*DownlinkReservations) MarkReservedAsQueued

func (r *DownlinkReservations) MarkReservedAsQueued(ctx context.Context, queID uint64, tenantID int64, bsEUI uint64, txTime int64, packetCnt *uint32, orgID *uuid.UUID) error

MarkReservedAsQueued confirms a row the base station holds reserved as queued after the wire send; a station the row is not reserved for confirms nothing.

func (*DownlinkReservations) ReleaseEndpointAtStation

func (r *DownlinkReservations) ReleaseEndpointAtStation(ctx context.Context, tenantID int64, epEUI, bsEUI uint64, sentBy time.Time) ([]storage.PendingDownlink, error)

ReleaseEndpointAtStation returns to pending the tenant's downlinks for the endpoint that are queued at the base station and were sent to it no later than sentBy, clearing the station as their holder, and returns the rows it released. A queued row without a recorded send time predates it.

func (*DownlinkReservations) ReleaseStationQueue

func (r *DownlinkReservations) ReleaseStationQueue(ctx context.Context, bsEUI uint64) ([]storage.PendingDownlink, error)

ReleaseStationQueue returns to pending every downlink queued at the base station, whichever tenant owns it, clearing the station as its holder, and returns the rows it released.

func (*DownlinkReservations) ReleaseStationReservations

func (r *DownlinkReservations) ReleaseStationReservations(ctx context.Context, bsEUI uint64, keepQueIDs []int64) ([]storage.PendingDownlink, error)

ReleaseStationReservations returns to pending every downlink the base station holds reserved, except the rows whose service center queue ids are kept, clearing the station as their holder, and returns the rows it released. que_id is unique across the installation, so the kept ids identify rows of every tenant the station carried.

func (r *DownlinkReservations) ReserveNextPendingDownlink(
	ctx context.Context,
	tenantID int64,
	epEUI []byte,
	bsEUI uint64,
) (*storage.DownlinkMessage, error)

ReserveNextPendingDownlink atomically selects+reserves highest-priority pending downlink Uses FOR UPDATE SKIP LOCKED to avoid blocking concurrent dispatchers Returns storage.ErrNotFound if no pending downlinks available Returns ErrDownlinkAlreadyReserved ONLY when UPDATE affects 0 rows due to race The selected row's organization_id is authoritative for the dispatch: the caller reads it from the returned message rather than filtering by one.

func (*DownlinkReservations) ReservePendingDownlinkByQueueID

func (r *DownlinkReservations) ReservePendingDownlinkByQueueID(ctx context.Context, tenantID int64, organizationID uuid.UUID, queueID uint64, epEUI []byte, bsEUI uint64) (*storage.DownlinkMessage, error)

ReservePendingDownlinkByQueueID reserves one exact pending row scoped to the enqueuing organization.

type DownlinkResultsReader

type DownlinkResultsReader struct {
	// contains filtered or unexported fields
}

DownlinkResultsReader lists the downlinks that reached a final state.

func (*DownlinkResultsReader) GetDownlinkResults

func (r *DownlinkResultsReader) GetDownlinkResults(ctx context.Context, tenantID int64, orgID *uuid.UUID, filter storage.DownlinkResultFilter, limit, offset int) ([]*storage.DownlinkMessage, int, error)

GetDownlinkResults lists one page of a tenant's terminal downlink rows, newest transmission first, narrowed by the filter.

type DownlinkRevocations

type DownlinkRevocations struct {
	// contains filtered or unexported fields
}

DownlinkRevocations ends downlinks revoked where they wait: in the service center's queue, or at the base station that answered a dlDataRev.

func (r *DownlinkRevocations) RevokeDownlink(ctx context.Context, revocation storage.DownlinkRevocation) (bool, error)

RevokeDownlink ends the tenant's downlink revoked and reports whether it did. A revoke in the queue ends only a pending downlink, which no base station holds yet, so a dispatcher that reserved it first wins. A base station's answer ends only the in-flight downlink that station holds, including one whose dlDataQue it had not confirmed yet; a downlink another station holds since, one it was asked to drop when its lifetime ended (DownlinkRevoking ends that one) and one that already finished keep their state. The result column holds the dlDataRes outcome and is left alone.

type DownlinkRevoking

type DownlinkRevoking struct {
	// contains filtered or unexported fields
}

DownlinkRevoking ends the downlinks a base station was asked to drop when their lifetime ended while it held them: each stays revoking, with its holder, until the station answers or starts a session that discarded it.

func (*DownlinkRevoking) ClaimUnansweredRevocations

func (r *DownlinkRevoking) ClaimUnansweredRevocations(ctx context.Context, connected []uint64, askedAt time.Time, unansweredFor time.Duration, limit int) (claimed []*storage.DownlinkMessage, err error)

ClaimUnansweredRevocations returns up to limit downlinks of any tenant that stay revoking at one of the connected stations although that station was last asked to drop them at least unansweredFor before askedAt, oldest ask first, and records askedAt as their ask. askedAt is the start of the sweep that asks, so the sweep one interval later finds them due again. Rows another sweep holds locked are skipped.

func (r *DownlinkRevoking) ExpireRevokedDownlink(ctx context.Context, revocation storage.DownlinkRevocation) (*storage.DownlinkMessage, bool, error)

ExpireRevokedDownlink ends expired the revoking downlink the answering station holds, the one a revocation names, once that station confirmed the revoke or answered it does not hold it (BSSCI §3.13, §3.17), and returns it for its originators; false when no such downlink is revoking, such as one a dlDataRes ended first or another station's.

func (*DownlinkRevoking) ExpireStationRevocations

func (r *DownlinkRevoking) ExpireStationRevocations(ctx context.Context, bsEUI uint64) (expired []*storage.DownlinkMessage, err error)

ExpireStationRevocations ends expired every downlink the base station was asked to drop, of every tenant, and returns them for their originators: its new session is not resumed, so it discarded them with the previous one (BSSCI §1) and will never transmit them.

func (*DownlinkRevoking) ListStationRevocations

func (r *DownlinkRevoking) ListStationRevocations(ctx context.Context, bsEUI uint64) (revoking []*storage.DownlinkMessage, err error)

ListStationRevocations lists the downlinks the base station is asked to drop, of every tenant, so a session that resumed is asked again.

type DownlinkStationOutcomes

type DownlinkStationOutcomes struct {
	// contains filtered or unexported fields
}

DownlinkStationOutcomes records what a base station holding a downlink answered: its holder, its result, its refusal, and the endpoint's acknowledgement of a transmitted one, which it also reads back for delivery.

func (r *DownlinkStationOutcomes) FailQueuedDownlink(ctx context.Context, queID int64, tenantID int64, bsEUI uint64, reason string) (*storage.DownlinkMessage, error)

FailQueuedDownlink fails the tenant's downlink the base station holds (reserved, queued or asked to drop) and answered with error, recording the station's error as the failure reason, and returns the row for its originators; storage.ErrDownlinkNotFound when no such row matched, another station's downlink included.

func (r *DownlinkStationOutcomes) GetAcknowledgedDownlink(ctx context.Context, tenantID, downlinkID int64) (*storage.DownlinkMessage, error)

GetAcknowledgedDownlink reads the tenant's downlink its endpoint acknowledged, with the window it was transmitted in, for the organization its acknowledgement is published to; storage.ErrNotFound when the tenant has no such acknowledged downlink.

func (*DownlinkStationOutcomes) MarkEndpointAcknowledged

MarkEndpointAcknowledged records that the endpoint acknowledged the downlink the tenant transmitted in the window of ack.WindowPacketCnt (BSSCI §3.10.1 dlAck) and, in the same statement, queues the acknowledgement on ack.Channels. It returns the row it marked for the downlink's originators; false when no unacknowledged one matched, and then nothing is queued.

func (*DownlinkStationOutcomes) UpdateDownlinkBaseStation

func (r *DownlinkStationOutcomes) UpdateDownlinkBaseStation(ctx context.Context, queID uint64, tenantID int64, bsEUI uint64) error

UpdateDownlinkBaseStation records the base station's acceptance of the tenant's downlink (dlDataQueRsp, BSSCI §3.12) while that station still holds it, reserved, queued or asked to drop; a late answer from a station that no longer holds the row, like one arriving after a reconnect released it, matches nothing. storage.ErrDownlinkNotFound covers that, an unknown queue id and another tenant's downlink alike.

func (*DownlinkStationOutcomes) UpdateDownlinkResult

func (r *DownlinkStationOutcomes) UpdateDownlinkResult(ctx context.Context, tenantID int64, bsEUI uint64, result *mioty.DLDataResult) (*storage.DownlinkMessage, error)

UpdateDownlinkResult records the result a base station reported for the tenant's downlink it holds, reserved, queued or asked to drop (BSSCI §3.14): only a result proves what became of a downlink being revoked, so a "sent" it reports first is its outcome. It returns the row for its originators. The endpoint, the tenant and the holding station are part of the match, so a station cannot finish another endpoint's, another tenant's or another station's downlink, nor one back in the queue: storage.ErrDownlinkNotFound for each, as for an unknown queue id. A downlink that already finished, expired or revoked included, keeps its outcome: storage.ErrDownlinkFinished, or storage.ErrDownlinkSentAfterExpiry for the first "sent" its holder reports after it ended expired.

type DownlinkStationRemoval

type DownlinkStationRemoval struct {
	// contains filtered or unexported fields
}

DownlinkStationRemoval ends the downlinks a base station held once the station no longer exists: it never gets a session again, so it cannot report them, and a station still powered may transmit what it held, so none is returned to the queue where an endpoint could receive it twice.

func (*DownlinkStationRemoval) ExpireHeldAtRemovedStations

func (r *DownlinkStationRemoval) ExpireHeldAtRemovedStations(ctx context.Context, limit int) (expired []*storage.DownlinkMessage, err error)

ExpireHeldAtRemovedStations ends expired up to limit downlinks of any tenant held by a base station no registration names any more, one whose deletion could not settle them, and returns each with that station. Rows another statement holds locked are skipped.

func (r *DownlinkStationRemoval) ExpireRemovedStationDownlinks(ctx context.Context, bsEUI uint64) (expired []*storage.DownlinkMessage, err error)

ExpireRemovedStationDownlinks ends expired every downlink of every tenant the deleted base station held, reserved, queued or asked to drop, and returns them for their originators.

type EndPointRepository

type EndPointRepository struct {
	// contains filtered or unexported fields
}

EndPointRepository implements interfaces.EndpointRepository for PostgreSQL

func NewEndPointRepository

func NewEndPointRepository(db *sqlx.DB, cipher keycrypto.Cipher, clk clock.Clock, log logger.Logger) *EndPointRepository

NewEndPointRepository creates a new endpoints table repository. The cipher encrypts nwk_key / app_key on write and decrypts them on read.

func (*EndPointRepository) CheckEUIUnique

func (r *EndPointRepository) CheckEUIUnique(ctx context.Context, eui []byte) error

CheckEUIUnique verifies no endpoint with the given EUI exists (global uniqueness)

func (*EndPointRepository) CountByTenant

func (r *EndPointRepository) CountByTenant(ctx context.Context, tenantID int64) (int64, error)

CountByTenant returns the total count of endpoints for a tenant

func (*EndPointRepository) Create

func (r *EndPointRepository) Create(ctx context.Context, endpoint *models.EndPoint) error

Create creates a new endpoint

func (*EndPointRepository) CreateWithStatus

func (r *EndPointRepository) CreateWithStatus(ctx context.Context, endpoint *models.EndPoint, status string) (err error)

CreateWithStatus creates the endpoint and records its attachment status, and the time of that decision, in one transaction.

func (*EndPointRepository) DeleteByTenant

func (r *EndPointRepository) DeleteByTenant(ctx context.Context, tenantID int64, eui []byte) (int64, error)

DeleteByTenant deletes the tenant's endpoint with the EUI and returns its id; storage.ErrNotFound when the tenant has no such endpoint.

func (*EndPointRepository) EndpointAttachSessionUpdate

func (r *EndPointRepository) EndpointAttachSessionUpdate(ctx context.Context, tenantID int64, endpointID int64, p models.EndpointAttachSessionParams) error

EndpointAttachSessionUpdate writes the attach-propagate radio parameters.

func (*EndPointRepository) EndpointAttachmentStateUpdate

func (r *EndPointRepository) EndpointAttachmentStateUpdate(ctx context.Context, tenantID int64, endpointID int64, p models.EndpointAttachmentStateParams) error

EndpointAttachmentStateUpdate writes the attach and attach-propagate completion field set for the BSSCI server.

func (*EndPointRepository) EndpointDetachStateUpdate

func (r *EndPointRepository) EndpointDetachStateUpdate(ctx context.Context, tenantID int64, endpointID int64, p models.EndpointDetachStateParams) error

EndpointDetachStateUpdate writes the detach field set for all detach paths.

func (*EndPointRepository) EndpointRegistrationUpdate

func (r *EndPointRepository) EndpointRegistrationUpdate(ctx context.Context, tenantID int64, endpointID int64, p models.EndpointRegistrationParams) error

EndpointRegistrationUpdate writes the SCACI Register field set (§3.6.1), encrypting the network key at rest before the row is written.

func (*EndPointRepository) Get

Get retrieves an endpoint by EUI

func (*EndPointRepository) GetByAttachmentChangedSince

func (r *EndPointRepository) GetByAttachmentChangedSince(ctx context.Context, tenantID int64, status string, since *time.Time) ([]*models.EndPoint, error)

GetByAttachmentChangedSince returns the tenant's endpoints whose status was changed to, or restated as, status after since, or every recorded one when since is nil.

func (*EndPointRepository) GetByEUI

func (r *EndPointRepository) GetByEUI(ctx context.Context, tenantID int64, eui []byte) (*models.EndPoint, error)

GetByEUI retrieves an endpoint by EUI for a specific tenant

func (*EndPointRepository) GetByID

func (r *EndPointRepository) GetByID(ctx context.Context, id int64, tenantID int64) (*models.EndPoint, error)

GetByID retrieves an endpoint by ID with tenant isolation

func (*EndPointRepository) GetByTenant

func (r *EndPointRepository) GetByTenant(ctx context.Context, tenantID int64) ([]*models.EndPoint, error)

GetByTenant retrieves all endpoints for a tenant Returns full BSSCI §3.8.1/§5.8.1 attach propagate fields for reconciliation

func (*EndPointRepository) GetPreferredBsEui

func (r *EndPointRepository) GetPreferredBsEui(ctx context.Context, tenantID int64, epEui []byte) (*uint64, bool, error)

GetPreferredBsEui returns the last_attached_bs_eui for an endpoint. Used by UL Data Transmit (SCACI §3.9.1) for "Service Center preferred BS" selection. Returns (nil, false, nil) if endpoint not found or column is NULL.

func (*EndPointRepository) GetRoamingEndpoints

func (r *EndPointRepository) GetRoamingEndpoints(ctx context.Context, tenantID int64) ([]*models.EndPoint, error)

GetRoamingEndpoints retrieves endpoints that are roaming (owner_tenant_id != tenant_id)

func (*EndPointRepository) ListAllEUIs

func (r *EndPointRepository) ListAllEUIs(ctx context.Context) ([]models.EUI, error)

ListAllEUIs returns every endpoint EUI across all tenants. Used to pre-warm the ingress disposition index at startup.

func (*EndPointRepository) ListByModelWithSnapshot

func (r *EndPointRepository) ListByModelWithSnapshot(ctx context.Context, tenantID int64, deviceModelID uuid.UUID) ([]*models.EndPoint, error)

ListByModelWithSnapshot returns a tenant's snapshot-bearing endpoints for a device model.

func (*EndPointRepository) ListByTenantPaginated

func (r *EndPointRepository) ListByTenantPaginated(ctx context.Context, tenantID int64, limit, offset int) ([]*models.EndPoint, error)

ListByTenantPaginated retrieves paginated endpoints for a tenant with LIMIT/OFFSET

func (*EndPointRepository) ListUnpinnedByOwner

func (r *EndPointRepository) ListUnpinnedByOwner(ctx context.Context, ownerTenantID, afterID int64, limit int) ([]*models.EndPoint, error)

ListUnpinnedByOwner selects by owner_tenant_id, so roaming endpoints are the owner's.

func (*EndPointRepository) LockAttachCounter

func (r *EndPointRepository) LockAttachCounter(ctx context.Context, tenantID int64, endpointID int64) (*uint32, error)

LockAttachCounter returns the attach counter the endpoint's next over-the-air attach must advance, nil when none binds it, and holds the endpoint row until the transaction ends.

func (*EndPointRepository) PinSnapshotIfUnpinned

func (r *EndPointRepository) PinSnapshotIfUnpinned(ctx context.Context, ownerTenantID, endpointID int64, snapshot json.RawMessage) (bool, error)

PinSnapshotIfUnpinned never replaces a snapshot written meanwhile; false when nothing was written.

func (*EndPointRepository) RegisteredAt

func (r *EndPointRepository) RegisteredAt(ctx context.Context, tenantID int64, eui []byte) (time.Time, error)

RegisteredAt is when the tenant registered the endpoint an EUI names, read without its session keys; storage.ErrNotFound when it has not.

func (*EndPointRepository) RestartPacketCounter

func (r *EndPointRepository) RestartPacketCounter(ctx context.Context, tenantID int64, endpointID int64) error

RestartPacketCounter records the counter restart of an over-the-air attach (radio protocol §3.6.5.3).

func (*EndPointRepository) RestateEndpointStatus

func (r *EndPointRepository) RestateEndpointStatus(ctx context.Context, tenantID int64, endpointID int64, status string) (bool, error)

RestateEndpointStatus sets the endpoint's ep_status and records the time even when the status stays, for a decision that restates what the base stations hold; it reports whether this call changed the status.

func (*EndPointRepository) TransitionEndpointStatus

func (r *EndPointRepository) TransitionEndpointStatus(ctx context.Context, tenantID int64, endpointID int64, status string) (bool, error)

TransitionEndpointStatus sets the endpoint's ep_status and reports whether this call changed it.

func (*EndPointRepository) Update

func (r *EndPointRepository) Update(ctx context.Context, endpoint *models.EndPoint) error

Update updates an endpoint with tenant isolation

func (*EndPointRepository) UpdateLastSeen

func (r *EndPointRepository) UpdateLastSeen(ctx context.Context, tenantID int64, eui models.EUI, frameCount uint32) error

UpdateLastSeen updates the last seen timestamp and frame count with tenant isolation

func (*EndPointRepository) UpdateRadioMetricsSelective

func (r *EndPointRepository) UpdateRadioMetricsSelective(ctx context.Context, tenantID int64, eui models.EUI, update models.RadioMetricsUpdate) error

UpdateRadioMetricsSelective updates radio metrics with optional field support. Nil pointers in the update struct preserve existing database values.

func (*EndPointRepository) UpdateWithEUI

func (r *EndPointRepository) UpdateWithEUI(ctx context.Context, tenantID int64, oldEui []byte, endpoint *models.EndPoint) (_ *models.EndPoint, err error)

UpdateWithEUI atomically cascades an EUI change across all dependent tables and updates endpoint fields

type EndPointSessionRepository

type EndPointSessionRepository struct {
	// contains filtered or unexported fields
}

EndPointSessionRepository implements interfaces.EndPointSessionRepository

func NewEndPointSessionRepository

func NewEndPointSessionRepository(
	db sqlx.ExtContext,
	cipher keycrypto.Cipher,
	log logger.Logger,
) *EndPointSessionRepository

NewEndPointSessionRepository creates a new endpoint session repository. The cipher encrypts session_key on write and decrypts it on read.

func (*EndPointSessionRepository) Create

Create creates a new endpoint session

func (*EndPointSessionRepository) GetActive

func (r *EndPointSessionRepository) GetActive(ctx context.Context, endpointID string) (*models.EndPointSession, error)

GetActive retrieves the active session for an endpoint

func (*EndPointSessionRepository) GetByID

GetByID retrieves a session by ID

func (*EndPointSessionRepository) Update

Update updates an endpoint session

type EndpointLocations

type EndpointLocations struct {
	// contains filtered or unexported fields
}

EndpointLocations reads where a tenant's endpoint was last heard or attached.

func (*EndpointLocations) GetEndpointLocation

func (r *EndpointLocations) GetEndpointLocation(ctx context.Context, tenantID int64, epEUI uint64) (storage.EndpointLocation, error)

GetEndpointLocation reads where the tenant's endpoint was last heard and attached; roaming stations of any tenant count. An uplink stored without its reception list names its first receiver alone. storage.ErrNotFound when the tenant has no such endpoint; a known endpoint neither heard nor attached has an empty location.

type FederationOutboxRepository

type FederationOutboxRepository struct {
	// contains filtered or unexported fields
}

FederationOutboxRepository manages CE-side outbox records using PostgreSQL.

func NewFederationOutboxRepository

func NewFederationOutboxRepository(db *sqlx.DB, clk clock.Clock) *FederationOutboxRepository

NewFederationOutboxRepository creates a new FederationOutboxRepository.

func (*FederationOutboxRepository) Insert

Insert adds a new pending outbox record.

func (*FederationOutboxRepository) ListPending

ListPending returns pending and sent records for relay or replay on reconnect.

func (*FederationOutboxRepository) ListPendingOnly

func (r *FederationOutboxRepository) ListPendingOnly(ctx context.Context, limit int) ([]*models.FederationOutboxRecord, error)

ListPendingOnly returns only records with status 'pending', excluding already-sent records.

func (*FederationOutboxRepository) MarkAcked

func (r *FederationOutboxRepository) MarkAcked(ctx context.Context, relayID uuid.UUID) error

MarkAcked transitions a record to acked status.

func (*FederationOutboxRepository) MarkRejected

func (r *FederationOutboxRepository) MarkRejected(ctx context.Context, relayID uuid.UUID, errMsg string) error

MarkRejected marks a record as permanently rejected.

func (*FederationOutboxRepository) MarkSent

func (r *FederationOutboxRepository) MarkSent(ctx context.Context, relayID uuid.UUID) error

MarkSent transitions a record to sent status.

type IntegrationRepository

type IntegrationRepository struct {
	// contains filtered or unexported fields
}

IntegrationRepository implements the IntegrationRepository interface for PostgreSQL (CRUD for API parity)

func NewIntegrationRepository

func NewIntegrationRepository(db *sqlx.DB, clk clock.Clock) *IntegrationRepository

NewIntegrationRepository creates a new PostgreSQL integration repository

func (*IntegrationRepository) Create

func (r *IntegrationRepository) Create(ctx context.Context, integration *models.Integration) (err error)

Create inserts a new integration

func (*IntegrationRepository) Delete

func (r *IntegrationRepository) Delete(ctx context.Context, id int64, tenantID int64) error

Delete deletes an integration by ID with tenant isolation

func (*IntegrationRepository) GetByID

func (r *IntegrationRepository) GetByID(ctx context.Context, id int64, tenantID int64) (*models.Integration, error)

GetByID retrieves an integration by ID with tenant isolation

func (*IntegrationRepository) ListByTenant

func (r *IntegrationRepository) ListByTenant(ctx context.Context, tenantID int64, limit, offset int) ([]*models.Integration, int64, error)

ListByTenant retrieves paginated integrations for a tenant

func (*IntegrationRepository) Update

func (r *IntegrationRepository) Update(ctx context.Context, integration *models.Integration) error

Update updates an existing integration

type KeyMaterialColumn

type KeyMaterialColumn struct {
	Table      string
	Column     string
	PrimaryKey string
}

KeyMaterialColumn names a BYTEA column that stores key material as a binary keycrypto envelope.

func KeyMaterialColumns

func KeyMaterialColumns() []KeyMaterialColumn

KeyMaterialColumns returns every BYTEA column that stores key material.

type KeyMaterialField

type KeyMaterialField struct {
	Surface string
	// contains filtered or unexported fields
}

KeyMaterialField is a stored key location that is not a whole BYTEA column. unconverted is the read-only probe keyMaterialGate runs for it.

func KeyMaterialFields

func KeyMaterialFields() []KeyMaterialField

KeyMaterialFields returns every key location that is not a whole BYTEA column.

type MIOTYDownlinkRepository

MIOTYDownlinkRepository is the downlink queue, one type per port it serves; each consumer depends on the narrow port it uses.

func NewMIOTYDownlinkRepository

func NewMIOTYDownlinkRepository(db *sqlx.DB, queueReader *DownlinkQueueReader, clk clock.Clock, log logger.Logger) *MIOTYDownlinkRepository

NewMIOTYDownlinkRepository creates the downlink queue repository. Every statement takes its time from the clock, never from the database.

type ManufacturerRepository

type ManufacturerRepository struct {
	// contains filtered or unexported fields
}

ManufacturerRepository implements the ManufacturerRepository interface for PostgreSQL

func NewManufacturerRepository

func NewManufacturerRepository(db *sqlx.DB, log logger.Logger) *ManufacturerRepository

NewManufacturerRepository creates a new PostgreSQL Manufacturer repository

func (*ManufacturerRepository) Count

func (r *ManufacturerRepository) Count(ctx context.Context, tenantID int64, isSystem bool) (int64, error)

Count returns the total count of manufacturers for a tenant

func (*ManufacturerRepository) Create

Create creates a new manufacturer

func (*ManufacturerRepository) Delete

func (r *ManufacturerRepository) Delete(ctx context.Context, tenantID int64, isSystem bool, id uuid.UUID) error

Delete deletes a manufacturer by ID within the isSystem-selected ownership scope

func (*ManufacturerRepository) GetByID

func (r *ManufacturerRepository) GetByID(ctx context.Context, tenantID int64, id uuid.UUID) (*models.Manufacturer, error)

GetByID retrieves a manufacturer by ID with tenant isolation

func (*ManufacturerRepository) List

List retrieves manufacturers for a tenant with pagination and optional search

func (*ManufacturerRepository) Update

func (r *ManufacturerRepository) Update(ctx context.Context, tenantID int64, isSystem bool, id uuid.UUID, params *models.ManufacturerUpdateParams) error

Update updates an existing manufacturer

type MessageAnalyticsRepository

type MessageAnalyticsRepository struct {
	// contains filtered or unexported fields
}

MessageAnalyticsRepository aggregates tenant-wide message activity.

func NewMessageAnalyticsRepository

func NewMessageAnalyticsRepository(db *sqlx.DB) *MessageAnalyticsRepository

NewMessageAnalyticsRepository creates the analytics repository on the given connection.

func (*MessageAnalyticsRepository) GetAnalyticsOverview

func (r *MessageAnalyticsRepository) GetAnalyticsOverview(ctx context.Context, tenantID int64, startTime, endTime time.Time) (*mioty.AnalyticsOverviewStats, error)

GetAnalyticsOverview returns overview analytics within a time range

func (*MessageAnalyticsRepository) GetDailyActivity

func (r *MessageAnalyticsRepository) GetDailyActivity(ctx context.Context, tenantID int64, startTime, endTime time.Time) ([]mioty.DailyActivity, error)

GetDailyActivity returns daily activity statistics within a time range

func (*MessageAnalyticsRepository) GetHourlyActivity

func (r *MessageAnalyticsRepository) GetHourlyActivity(ctx context.Context, tenantID int64, startTime, endTime time.Time) ([]mioty.HourlyActivity, error)

GetHourlyActivity returns hourly message counts within a time range

func (*MessageAnalyticsRepository) GetMessageCountsByBaseStation

func (r *MessageAnalyticsRepository) GetMessageCountsByBaseStation(ctx context.Context, tenantID int64, startTime, endTime time.Time) (counts map[string]int64, err error)

GetMessageCountsByBaseStation returns uncapped message counts grouped by base station EUI.

func (*MessageAnalyticsRepository) GetMessageCountsByEndpoint

func (r *MessageAnalyticsRepository) GetMessageCountsByEndpoint(ctx context.Context, tenantID int64, startTime, endTime time.Time) (counts map[string]int64, err error)

GetMessageCountsByEndpoint returns uncapped message counts grouped by endpoint EUI.

func (*MessageAnalyticsRepository) GetMessageStatsByEndpoint

func (r *MessageAnalyticsRepository) GetMessageStatsByEndpoint(ctx context.Context, epEui uint64, tenantID int64) (*mioty.MessageStats, error)

GetMessageStatsByEndpoint returns the statistics of every stored uplink of the endpoint.

func (*MessageAnalyticsRepository) GetMessageStatsByEndpointSince

func (r *MessageAnalyticsRepository) GetMessageStatsByEndpointSince(ctx context.Context, epEui uint64, tenantID int64, since time.Time) (*mioty.MessageStats, error)

GetMessageStatsByEndpointSince returns the statistics of the endpoint's uplinks received at or after since.

func (*MessageAnalyticsRepository) GetMonthlyActivity

func (r *MessageAnalyticsRepository) GetMonthlyActivity(ctx context.Context, tenantID int64, startTime, endTime time.Time) ([]mioty.MonthlyActivity, error)

GetMonthlyActivity returns message counts grouped by month.

func (*MessageAnalyticsRepository) GetOverallStats

func (r *MessageAnalyticsRepository) GetOverallStats(ctx context.Context, tenantID int64) (*mioty.MessageStats, error)

GetOverallStats returns overall message statistics

func (*MessageAnalyticsRepository) GetSignalQualityByBaseStation

func (r *MessageAnalyticsRepository) GetSignalQualityByBaseStation(ctx context.Context, tenantID int64, startTime, endTime time.Time) (stations []mioty.BaseStationSignalQuality, err error)

GetSignalQualityByBaseStation returns the signal quality of the tenant's uplinks per receiving base station, busiest station first.

func (*MessageAnalyticsRepository) GetSignalQualityStats

func (r *MessageAnalyticsRepository) GetSignalQualityStats(ctx context.Context, tenantID int64, startTime, endTime time.Time) (*mioty.SignalQualityStats, error)

GetSignalQualityStats returns signal quality statistics within a time range

func (*MessageAnalyticsRepository) GetTopEndpointsByActivity

func (r *MessageAnalyticsRepository) GetTopEndpointsByActivity(ctx context.Context, tenantID int64, startTime, endTime time.Time, limit int) (endpoints []mioty.EndpointActivity, err error)

GetTopEndpointsByActivity returns the most active endpoints within a time range

func (*MessageAnalyticsRepository) GetWeeklyActivity

func (r *MessageAnalyticsRepository) GetWeeklyActivity(ctx context.Context, tenantID int64, startTime, endTime time.Time) ([]mioty.WeeklyActivity, error)

GetWeeklyActivity returns message counts grouped by ISO week.

type MessageDeliveryOutboxRepository

type MessageDeliveryOutboxRepository struct {
	// contains filtered or unexported fields
}

MessageDeliveryOutboxRepository hands due outbox rows to the delivery worker and records the result of each attempt; every time it writes or compares comes from its clock.

func NewMessageDeliveryOutboxRepository

func NewMessageDeliveryOutboxRepository(db *sqlx.DB, clk clock.Clock) *MessageDeliveryOutboxRepository

NewMessageDeliveryOutboxRepository creates the outbox repository.

func (*MessageDeliveryOutboxRepository) ClaimDue

ClaimDue locks due pending rows, counts the attempt and hides each row from other workers for the lease.

func (*MessageDeliveryOutboxRepository) MarkDelivered

func (r *MessageDeliveryOutboxRepository) MarkDelivered(ctx context.Context, messageID uuid.UUID, channel models.DeliveryChannel) error

MarkDelivered closes the row after a successful delivery.

func (*MessageDeliveryOutboxRepository) Park

func (r *MessageDeliveryOutboxRepository) Park(ctx context.Context, messageID uuid.UUID, channel models.DeliveryChannel, reason string) error

Park takes the row out of the retry loop and keeps the last failure.

func (*MessageDeliveryOutboxRepository) Reschedule

func (r *MessageDeliveryOutboxRepository) Reschedule(ctx context.Context, messageID uuid.UUID, channel models.DeliveryChannel,
	delay time.Duration, reason string,
) error

Reschedule keeps a pending row for another attempt after delay and records the failure.

type MessageRepository

type MessageRepository struct {
	// contains filtered or unexported fields
}

MessageRepository implements interfaces.MIOTYMessageRepository: the stored uplinks and propagate messages of the messages table.

func NewMessageRepository

func NewMessageRepository(db *sqlx.DB, clk clock.Clock, log logger.Logger) *MessageRepository

NewMessageRepository creates a new message repository

func (*MessageRepository) ClaimDownlinkWindow

func (r *MessageRepository) ClaimDownlinkWindow(ctx context.Context, ownerTenantID int64, messageID string) (bool, error)

ClaimDownlinkWindow claims the downlink window of the owner's telegram for one dispatch and reports whether this caller got it (radio §3.6.1).

func (*MessageRepository) CreateAttachPropagateMessage

func (r *MessageRepository) CreateAttachPropagateMessage(ctx context.Context, msg *mioty.AttachPropagateMessage) error

CreateAttachPropagateMessage stores an attach propagate operation (BSSCI §5.8) with the endpoint parameters it propagated (§5.8.1).

func (*MessageRepository) CreateDetachMessage

func (r *MessageRepository) CreateDetachMessage(ctx context.Context, msg *mioty.DetachMessage, structuredMsg map[string]interface{}) error

CreateDetachMessage stores a detach operation (BSSCI §5.7) with its structured message.

func (*MessageRepository) CreateDetachPropagateMessage

func (r *MessageRepository) CreateDetachPropagateMessage(ctx context.Context, msg *mioty.DetachPropagateMessage) error

CreateDetachPropagateMessage stores a detach propagate operation (BSSCI §5.9).

func (*MessageRepository) GetBaseStationEndpointCounts

func (r *MessageRepository) GetBaseStationEndpointCounts(ctx context.Context, tenantID int64, bsEui []byte,
	startTime, endTime *time.Time,
) (map[string]int64, error)

GetBaseStationEndpointCounts counts per endpoint the uplinks the base station received within the window, as the primary receiver or as one of the receptions; a nil bound leaves the window open.

func (*MessageRepository) GetBaseStationLastSeen

func (r *MessageRepository) GetBaseStationLastSeen(ctx context.Context, tenantID int64, bsEui []byte) (*time.Time, error)

GetBaseStationLastSeen is when the base station last received an uplink, as the primary receiver or as one of the receptions; without any, when its last session started.

func (*MessageRepository) GetBaseStationMessageStats

func (r *MessageRepository) GetBaseStationMessageStats(ctx context.Context, tenantID int64, bsEui []byte,
	startTime, endTime *time.Time,
) (*mioty.BaseStationMessageStats, error)

GetBaseStationMessageStats aggregates the uplinks the base station received, as the primary receiver or as one of the receptions, within the window; a nil bound leaves it open. Today, this week and this month ignore the window.

func (*MessageRepository) GetULDataMessage

func (r *MessageRepository) GetULDataMessage(ctx context.Context, id string, tenantID int64) (*mioty.ULDataMessage, error)

GetULDataMessage retrieves a single UL Data message by ID

func (*MessageRepository) ListStoredULData

func (r *MessageRepository) ListStoredULData(ctx context.Context, filter mioty.ULDataMessageFilter) ([]*mioty.ULDataMessage, error)

ListStoredULData lists one page of stored ulData in the order the database stored it, newest first, without a total; the live stream reads it.

func (*MessageRepository) ListULDataMessages

func (r *MessageRepository) ListULDataMessages(ctx context.Context, filter mioty.ULDataMessageFilter) ([]*mioty.ULDataMessage, int64, error)

ListULDataMessages lists one page of stored ulData, newest first; the propagate messages sharing the table are not uplinks and never listed.

func (*MessageRepository) ReleaseDownlinkWindow

func (r *MessageRepository) ReleaseDownlinkWindow(ctx context.Context, ownerTenantID int64, messageID string) error

ReleaseDownlinkWindow gives back the claim of a telegram whose dispatch sent nothing.

type MigrationRunner

type MigrationRunner struct {
	// contains filtered or unexported fields
}

MigrationRunner handles database migrations using dedicated short-lived connections. This design ensures that m.Close() can be safely called without affecting the main storage pool used by the application.

func NewMigrationRunner

func NewMigrationRunner(config *Config, gates []SchemaGate) (*MigrationRunner, error)

NewMigrationRunner creates a migration runner that holds every upgrade at each of gates until the gate's check passes.

func (*MigrationRunner) Down

func (mr *MigrationRunner) Down(ctx context.Context) error

Down rolls back all migrations

func (*MigrationRunner) Force

func (mr *MigrationRunner) Force(ctx context.Context, version int) error

Force sets the migration version without running actual migrations. Useful for recovering from a dirty state.

func (*MigrationRunner) Run

func (mr *MigrationRunner) Run(ctx context.Context) (uint, error)

Run executes all pending migrations and returns the final version. Uses a dedicated short-lived DB connection to avoid closing the main pool.

func (*MigrationRunner) RunTo

func (mr *MigrationRunner) RunTo(ctx context.Context, target uint) (uint, error)

RunTo applies pending migrations up to and including target and returns the resulting version. It never migrates down: a database already at or past target is left untouched, so a repeated upgrade step is harmless.

func (*MigrationRunner) Steps

func (mr *MigrationRunner) Steps(ctx context.Context, n int) error

Steps runs n migration steps (positive = up, negative = down)

func (*MigrationRunner) Version

func (mr *MigrationRunner) Version(ctx context.Context) (uint, bool, error)

Version returns the current migration version

type NotificationListener

type NotificationListener struct {
	// contains filtered or unexported fields
}

NotificationListener relays the notifications of its channels to their handlers. Its connection reconnects on its own with a doubling backoff; after a reconnect every handler runs once, since the notifications sent while it was down are lost.

func NewNotificationListener

func NewNotificationListener(dsn string, handlers map[string]func(), log logger.Logger) *NotificationListener

NewNotificationListener returns a listener on the database dsn names that runs handlers[channel] for every notification on channel.

func (*NotificationListener) Run

Run relays notifications until ctx ends; it fails only when the server refuses to listen on a channel.

type OperationStatusRepository

type OperationStatusRepository struct {
	// contains filtered or unexported fields
}

OperationStatusRepository measures lookback windows from the clock that stamps events, never NOW().

func NewOperationStatusRepository

func NewOperationStatusRepository(db *sqlx.DB, clk clock.Clock) *OperationStatusRepository

NewOperationStatusRepository creates a new operation status repository.

func (*OperationStatusRepository) GetBSSCIStatusSummary

func (r *OperationStatusRepository) GetBSSCIStatusSummary(
	ctx context.Context,
	tenantID int64,
	categories []string,
	eventWindow time.Duration,
) ([]BaseStationStatus, error)

GetBSSCIStatusSummary retrieves base station status with recent event counts Parameters:

  • tenantID: Tenant ID for filtering
  • categories: Event categories to include
  • eventWindow: Event count lookback (e.g., 24 hours)

func (*OperationStatusRepository) GetEndpointOperationsByID

func (r *OperationStatusRepository) GetEndpointOperationsByID(
	ctx context.Context,
	endpointID int64,
	tenantID int64,
	categories []string,
	since time.Duration,
	limit int,
	offset int,
) ([]models.SystemEvent, error)

GetEndpointOperationsByID retrieves recent operations for an endpoint Searches across event data, title, and description fields Parameters:

  • endpointID: The endpoint database ID
  • tenantID: Tenant scope for security isolation
  • categories: Event categories to include
  • since: Lookback window
  • limit: Maximum number of results
  • offset: Pagination offset

func (*OperationStatusRepository) GetEventSummary

func (r *OperationStatusRepository) GetEventSummary(
	ctx context.Context,
	categories []string,
	since time.Duration,
) (summary map[string]int, err error)

GetEventSummary retrieves event type counts within time window Parameters:

  • categories: Event categories to include
  • since: Lookback window (e.g., 5 minutes)

func (*OperationStatusRepository) GetOperationEventsByID

func (r *OperationStatusRepository) GetOperationEventsByID(
	ctx context.Context,
	operationID string,
	categories []string,
	since time.Duration,
	operationType string,
	limit int,
) ([]models.SystemEvent, error)

GetOperationEventsByID retrieves events for a specific operation ID Parameters:

  • operationID: The operation identifier to search for
  • categories: Event categories to include (e.g., ["bssci", "scaci"])
  • since: Lookback window (e.g., 24 hours)
  • operationType: Optional filter - "attach", "detach", or "" for all
  • limit: Maximum number of results

type Options

type Options struct {
	// Clock stamps rows; nil means the system clock.
	Clock           clock.Clock
	Host            string
	Port            int
	Database        string
	Username        string
	Password        string
	SSLMode         string
	MaxOpenConns    int
	MaxIdleConns    int
	ConnMaxLifetime time.Duration
	ConnMaxIdleTime time.Duration
}

Options carries the database connection settings New needs to open a pool. Callers translate their application configuration into Options at the call site so the persistence layer stays independent of any app config package.

func (Options) DSN

func (o Options) DSN() string

DSN is the connection string of the database the options name.

type OrganizationRepository

type OrganizationRepository struct {
	// contains filtered or unexported fields
}

OrganizationRepository implements the OrganizationRepository interface for PostgreSQL

func NewOrganizationRepository

func NewOrganizationRepository(db *sqlx.DB, log logger.Logger) *OrganizationRepository

NewOrganizationRepository creates a new PostgreSQL Organization repository orgUpdateFixedArgs counts the leading fixed parameters (org id, tenant) of the dynamic update statement.

func (*OrganizationRepository) AddMember

AddMember adds a user to an organization with specified role

func (*OrganizationRepository) CountOrgMembersByRole

func (r *OrganizationRepository) CountOrgMembersByRole(ctx context.Context, orgID uuid.UUID, role string) (int64, error)

CountOrgMembersByRole returns the count of active members with the given role.

func (*OrganizationRepository) Create

Create creates a new organization with its description and tags; no tags store the column's empty default.

func (*OrganizationRepository) Delete

func (r *OrganizationRepository) Delete(ctx context.Context, orgID uuid.UUID, tenantID int64) (err error)

Delete hard-deletes an organization and its members, scoped to a tenant for defense-in-depth. Also deletes the associated tenant if orphaned.

func (*OrganizationRepository) GetByID

func (r *OrganizationRepository) GetByID(ctx context.Context, orgID uuid.UUID, tenantID int64) (*models.Organization, error)

GetByID retrieves an organization by UUID, scoped to a tenant for defense-in-depth.

func (*OrganizationRepository) GetByIDUnscoped

func (r *OrganizationRepository) GetByIDUnscoped(ctx context.Context, orgID uuid.UUID) (*models.Organization, error)

GetByIDUnscoped retrieves an organization by UUID without tenant scoping.

func (*OrganizationRepository) GetOrgByExternalID

func (r *OrganizationRepository) GetOrgByExternalID(ctx context.Context, externalID string) (*models.Organization, error)

GetOrgByExternalID retrieves an organization by external IdP identifier. Used for OIDC external_org_claim resolution.

func (*OrganizationRepository) GetOrgByTenantID

func (r *OrganizationRepository) GetOrgByTenantID(ctx context.Context, tenantID int64) (*models.Organization, error)

GetOrgByTenantID returns the default organization for a tenant Used for fallback when no org header provided (community mode)

func (*OrganizationRepository) GetOrgMemberWithEmail

func (r *OrganizationRepository) GetOrgMemberWithEmail(ctx context.Context, orgID, userID uuid.UUID) (*models.OrganizationMemberWithEmail, error)

GetOrgMemberWithEmail returns a single member with email. Used for organization user detail view in admin UI.

func (*OrganizationRepository) GetTenantByOrgID

func (r *OrganizationRepository) GetTenantByOrgID(ctx context.Context, orgID uuid.UUID) (int64, error)

GetTenantByOrgID resolves organization UUID to numeric tenant ID Hot path for org.Resolver.LookupTenant - optimized with unique index

func (*OrganizationRepository) ListOrgMembersWithEmail

func (r *OrganizationRepository) ListOrgMembersWithEmail(ctx context.Context, orgID uuid.UUID, status string, limit, offset int) ([]*models.OrganizationMemberWithEmail, int64, error)

ListOrgMembersWithEmail returns members with email from users table (JOIN query). Returns paginated results and total count matching the status filter. The status parameter uses three modes:

  • "" (empty) — no status filter (all statuses)
  • models.OrganizationMemberStatusFilterInactive ("inactive") — status != 'active'
  • Any other value ("active", "invited", "removed") — exact match

func (*OrganizationRepository) ListOrganizations

func (r *OrganizationRepository) ListOrganizations(ctx context.Context, tenantID *int64, limit, offset int) ([]*models.Organization, int64, error)

ListOrganizations retrieves organizations with optional tenant filter and pagination. Returns organizations slice and total count for pagination.

func (*OrganizationRepository) ListUserMemberships

func (r *OrganizationRepository) ListUserMemberships(ctx context.Context, userID uuid.UUID) ([]*models.OrganizationMembershipWithOrg, error)

ListUserMemberships retrieves all organizations a user belongs to with org details. Used for profile endpoint to show user's org memberships.

func (*OrganizationRepository) ListUserMembershipsByTenant

func (r *OrganizationRepository) ListUserMembershipsByTenant(ctx context.Context, userID uuid.UUID, tenantID int64) ([]*models.OrganizationMembershipWithOrg, error)

ListUserMembershipsByTenant retrieves organizations a user belongs to within a specific tenant. Adds tenant_id filter to prevent cross-tenant data leak.

func (*OrganizationRepository) RemoveMember

func (r *OrganizationRepository) RemoveMember(ctx context.Context, orgID uuid.UUID, userID uuid.UUID) error

RemoveMember soft-removes a user from an organization (sets status = 'removed')

func (*OrganizationRepository) Update

func (r *OrganizationRepository) Update(ctx context.Context, orgID uuid.UUID, tenantID int64, updates map[string]interface{}) error

Update updates an existing organization, scoped to a tenant for defense-in-depth.

func (*OrganizationRepository) UpdateMemberPermissions

func (r *OrganizationRepository) UpdateMemberPermissions(ctx context.Context, orgID, userID uuid.UUID, isOrgAdmin, isBaseStationAdmin, isEndpointAdmin bool) error

UpdateMemberPermissions updates member permission flags (explicit booleans). Permissions are independent of role - role is only for ownership semantics.

func (*OrganizationRepository) UpdateMemberRole

func (r *OrganizationRepository) UpdateMemberRole(ctx context.Context, orgID uuid.UUID, userID uuid.UUID, role string) error

UpdateMemberRole changes a member's role

type PartitionInfo

type PartitionInfo struct {
	Name string
	Size string
}

PartitionInfo contains information about a message partition

type PendingOperationRepository

type PendingOperationRepository struct {
	// contains filtered or unexported fields
}

PendingOperationRepository persists BSSCI pending operations.

func NewPendingOperationRepository

func NewPendingOperationRepository(db *sqlx.DB, log logger.Logger) *PendingOperationRepository

NewPendingOperationRepository creates a new pending operation repository

func (*PendingOperationRepository) Create

Create inserts or updates a pending operation (UPSERT pattern)

func (*PendingOperationRepository) CreateBatch

CreateBatch inserts or updates several pending operations in one local transaction so a multi-frame sequence is recorded all-or-nothing. Requests are inserted in slice order so the id column preserves reissue order.

func (*PendingOperationRepository) DeleteBySession

func (r *PendingOperationRepository) DeleteBySession(ctx context.Context, sessionID int64) (int64, error)

DeleteBySession removes all pending operations for a session Used during session termination per BSSCI §3 "discarding state" requirement

func (*PendingOperationRepository) DeleteBySessionAndOperation

func (r *PendingOperationRepository) DeleteBySessionAndOperation(ctx context.Context, sessionID int64, operationID int64) error

DeleteBySessionAndOperation removes by compound key

func (*PendingOperationRepository) GetBySession

func (r *PendingOperationRepository) GetBySession(ctx context.Context, sessionID int64) ([]*models.PendingOperation, error)

GetBySession retrieves all pending operations for a session

func (*PendingOperationRepository) UpdateMetadata

func (r *PendingOperationRepository) UpdateMetadata(ctx context.Context, sessionID int64, operationID int64, metadata json.RawMessage) error

UpdateMetadata updates only the metadata field

type RefreshTokenRepository

type RefreshTokenRepository struct {
	// contains filtered or unexported fields
}

RefreshTokenRepository implements the RefreshTokenRepository interface for PostgreSQL Supports refresh token rotation with reuse detection

func NewRefreshTokenRepository

func NewRefreshTokenRepository(db *sqlx.DB, clk clock.Clock) *RefreshTokenRepository

NewRefreshTokenRepository creates a new PostgreSQL RefreshToken repository

func (*RefreshTokenRepository) CreateForPassword

func (r *RefreshTokenRepository) CreateForPassword(ctx context.Context, token *models.RefreshToken, passwordHash string) (err error)

CreateForPassword opens a session: it stores token only while its owner is active and still has passwordHash, the hash the caller verified or set. It fails with storage.ErrUserInactive or storage.ErrUserCredentialsChanged and stores nothing otherwise.

func (*RefreshTokenRepository) GetByHash

func (r *RefreshTokenRepository) GetByHash(ctx context.Context, tokenHash string) (*models.RefreshToken, error)

GetByHash retrieves a refresh token by its hash

func (*RefreshTokenRepository) RevokeByUserID

func (r *RefreshTokenRepository) RevokeByUserID(ctx context.Context, userID uuid.UUID) (err error)

RevokeByUserID revokes all tokens for a user (family revocation)

func (*RefreshTokenRepository) Rotate

func (r *RefreshTokenRepository) Rotate(ctx context.Context, oldTokenID uuid.UUID, newToken *models.RefreshToken) (err error)

Rotate atomically stores newToken and marks oldTokenID as replaced by it. It fails with storage.ErrUserInactive when the owner of newToken is missing or deactivated, and with storage.ErrRefreshTokenNotClaimable when the old token belongs to another user or is already replaced, revoked or expired; nothing is stored in either case.

type RegistrationRepository

type RegistrationRepository struct {
	// contains filtered or unexported fields
}

RegistrationRepository handles atomic self-service account registration.

func NewRegistrationRepository

func NewRegistrationRepository(db *sqlx.DB, clk clock.Clock) *RegistrationRepository

NewRegistrationRepository creates a new registration repository.

func (*RegistrationRepository) RegisterAccount

RegisterAccount atomically creates a user, tenant, organization, and membership. All operations run within a single transaction — partial state is impossible.

func (*RegistrationRepository) RegisterCEAccount

func (r *RegistrationRepository) RegisterCEAccount(ctx context.Context, params *models.CERegistrationParams) (_ *models.RegistrationResult, err error)

RegisterCEAccount atomically creates a user and adds them to the existing CE default org. No new tenant or organization is created.

type Repositories

type Repositories struct {
	BaseStations        *BaseStationRepository
	BaseStationSessions *BaseStationSessionRepository
	BaseStationStatus   *BaseStationStatusRepository
	BaseStationMetrics  *BaseStationMetricsRepository
	Endpoints           *EndPointRepository
	EndpointSessions    *EndPointSessionRepository
	Organizations       *OrganizationRepository
	Tenants             *TenantRepository
	Users               *UserRepository
	RefreshTokens       *RefreshTokenRepository
	Registrations       *RegistrationRepository
	APIKeys             *APIKeyRepository
	Integrations        *IntegrationRepository
	OperationStatus     *OperationStatusRepository
	Manufacturers       *ManufacturerRepository
	DeviceModels        *DeviceModelRepository
	Blueprints          *BlueprintRepository
	SystemEvents        *SystemEventStore
	SCACIEvents         *SCACIEventStore
	Messages            *MessageRepository
	MessageAnalytics    *MessageAnalyticsRepository
	UplinkStore         *UplinkStore
	DeliveryOutbox      *MessageDeliveryOutboxRepository
	DLRXStatus          *DLRXStatusRepository
	PendingOperations   *PendingOperationRepository
	SCACISessions       *SCACISessionRepository
	SCACIOperations     *SCACIOperationRepository
	Downlinks           *MIOTYDownlinkRepository
	DownlinkQueueReader *DownlinkQueueReader
	Roaming             *RoamingRepository
	FederationOutbox    *FederationOutboxRepository
	CEInstallations     *CEInstallationRepository
}

Repositories is the eager set of every repository built over one connection. Composition roots hand out its fields; nothing is constructed lazily and nothing is looked up by name.

func NewRepositories

func NewRepositories(db *DB) *Repositories

NewRepositories builds every repository over the connection's handles, cipher and clock.

type RoamingRepository

type RoamingRepository struct {
	// contains filtered or unexported fields
}

RoamingRepository implements roaming-specific database operations

func NewRoamingRepository

func NewRoamingRepository(db *sqlx.DB) *RoamingRepository

NewRoamingRepository creates a new roaming repository

func (*RoamingRepository) AddRoamingEndpointToSession

func (r *RoamingRepository) AddRoamingEndpointToSession(ctx context.Context, sessionID int64, epEui string, ownerTenantID int64) error

AddRoamingEndpointToSession adds an endpoint to a session's roaming list Appends to the JSONB array and increments the roaming_endpoint_count

func (*RoamingRepository) AreTenantsPartners

func (r *RoamingRepository) AreTenantsPartners(ctx context.Context, tenant1, tenant2 int64) (bool, error)

AreTenantsPartners checks if two tenants have a roaming partnership Uses LEAST/GREATEST to handle bidirectional partnerships stored as (smaller_id, larger_id)

func (*RoamingRepository) GetEndpointOwner

func (r *RoamingRepository) GetEndpointOwner(ctx context.Context, epEui []byte) (int64, error)

GetEndpointOwner retrieves the owner tenant ID for an endpoint Returns storage.ErrNotFound if the endpoint does not exist.

func (*RoamingRepository) IsRoamingEnabled

func (r *RoamingRepository) IsRoamingEnabled(ctx context.Context, tenantID int64) (bool, error)

IsRoamingEnabled checks if roaming is enabled for a tenant

func (*RoamingRepository) RecordRoamingEvent

func (r *RoamingRepository) RecordRoamingEvent(ctx context.Context, event *models.RoamingEvent) error

RecordRoamingEvent inserts a roaming event into the audit trail

func (*RoamingRepository) RemoveRoamingEndpointFromSession

func (r *RoamingRepository) RemoveRoamingEndpointFromSession(ctx context.Context, sessionID int64, epEuiHex string) error

RemoveRoamingEndpointFromSession removes an endpoint from a session's roaming list Filters the JSONB array and decrements the roaming_endpoint_count only if element was present

type SCACIEventStore

type SCACIEventStore struct {
	// contains filtered or unexported fields
}

SCACIEventStore records and reads SCACI protocol events in the system event log.

func NewSCACIEventStore

func NewSCACIEventStore(db *sql.DB, events *SystemEventStore, clk clock.Clock, log logger.Logger) *SCACIEventStore

NewSCACIEventStore creates a SCACI event store that writes through the system event store.

func (*SCACIEventStore) CountSCACIEventsByFilter

func (s *SCACIEventStore) CountSCACIEventsByFilter(ctx context.Context, tenantID int64, sessionID *int64, eventType string) (int64, error)

CountSCACIEventsByFilter counts SCACI events matching ListSCACIEvents filters. Used for accurate pagination metadata.

func (*SCACIEventStore) ListSCACIEvents

func (s *SCACIEventStore) ListSCACIEvents(ctx context.Context, tenantID int64, sessionID *int64, eventType string, limit, offset int) ([]*models.SystemEvent, error)

ListSCACIEvents retrieves SCACI-category events with optional filters. sessionID filtering uses bigint cast for index-friendly queries.

func (*SCACIEventStore) RecordSCACIError

func (s *SCACIEventStore) RecordSCACIError(ctx context.Context, tenantID int64, sessionID int64, command string, opId int64, errorCode int, errorMsg string) error

RecordSCACIError records a SCACI protocol error event

func (*SCACIEventStore) RecordSessionEvent

func (s *SCACIEventStore) RecordSessionEvent(ctx context.Context, event *models.SCACISessionEvent) error

RecordSessionEvent files a step in the lifecycle of an application center session (SCACI §1, §3.3) under the event's tenant and category.

type SCACIOperationRepository

type SCACIOperationRepository struct {
	// contains filtered or unexported fields
}

SCACIOperationRepository implements the SCACIOperationRepository interface for PostgreSQL

func NewSCACIOperationRepository

func NewSCACIOperationRepository(db *sqlx.DB, log logger.Logger, clk clock.Clock) *SCACIOperationRepository

NewSCACIOperationRepository creates a new PostgreSQL SCACI operation repository

func (*SCACIOperationRepository) CompleteFailedOperation

func (r *SCACIOperationRepository) CompleteFailedOperation(ctx context.Context, sessionID int64, opId int64, responseData map[string]interface{}) error

CompleteFailedOperation sets completed_at on a failed operation without changing state. This is used by error handshake completion (errorAck) to mark the operation as "done" while preserving error evidence (state remains 'failed', error_code/error_token preserved).

func (*SCACIOperationRepository) CountOperationsBySession

func (r *SCACIOperationRepository) CountOperationsBySession(ctx context.Context, tenantID int64, sessionIDs []int64) (map[int64]int64, error)

CountOperationsBySession returns how many operations each of the given sessions logged; sessions without operations are absent from the map.

func (*SCACIOperationRepository) CountPendingSCOperations

func (r *SCACIOperationRepository) CountPendingSCOperations(ctx context.Context, sessionID int64) (int, error)

CountPendingSCOperations counts the operations the service center initiated for a session (SCACI §3.2 negative opIds) that still await completion.

func (*SCACIOperationRepository) EnsureUplinkOperation

func (r *SCACIOperationRepository) EnsureUplinkOperation(ctx context.Context, req *models.SCACIOperationRequest, sourceMessageID string) (*models.SCACIOperation, bool, error)

EnsureUplinkOperation records, under req.OpId, the outbound ulData operation that delivers the stored uplink sourceMessageID to the session of req, unless the session has one already: an operation keeps its opId and state however often the delivery is retried (SCACI §3.2). It returns the session's operation for the uplink and whether it recorded it now.

func (*SCACIOperationRepository) GetLatestOperation

func (r *SCACIOperationRepository) GetLatestOperation(ctx context.Context, tenantID int64, command string) (*models.SCACIOperation, error)

GetLatestOperation returns the tenant's most recent operation for a command, or nil when none was logged.

func (*SCACIOperationRepository) GetOperationByOpID

func (r *SCACIOperationRepository) GetOperationByOpID(ctx context.Context, sessionID int64, opId int64) (*models.SCACIOperation, error)

GetOperationByOpID retrieves an operation by session ID and operation ID

func (*SCACIOperationRepository) GetPendingOperations

func (r *SCACIOperationRepository) GetPendingOperations(ctx context.Context, sessionID int64) ([]*models.SCACIOperation, error)

GetPendingOperations retrieves all pending operations for a session

func (*SCACIOperationRepository) GetPingSummary

func (r *SCACIOperationRepository) GetPingSummary(ctx context.Context, tenantID int64, command string, from, to time.Time, staleAfter time.Duration) (*models.SCACIPingSummary, error)

GetPingSummary reports the latest completed ping and counts the pings in [from, to] that failed or have been pending longer than staleAfter.

func (*SCACIOperationRepository) GetTenantOperationSummaryBetween

func (r *SCACIOperationRepository) GetTenantOperationSummaryBetween(ctx context.Context, tenantID int64, from, to time.Time) (*models.SCACIOperationSummary, error)

GetTenantOperationSummaryBetween aggregates the operations a tenant initiated inside [from, to].

func (*SCACIOperationRepository) ListFailedOperationGroups

func (r *SCACIOperationRepository) ListFailedOperationGroups(ctx context.Context, tenantID int64, from, to time.Time, limit, offset int) ([]*models.SCACIOperationErrorGroup, int64, error)

ListFailedOperationGroups buckets the failed operations initiated inside [from, to] by command, error code and token, newest bucket first.

func (*SCACIOperationRepository) RecordOperation

RecordOperation records a new SCACI operation

func (*SCACIOperationRepository) UpdateOperationState

func (r *SCACIOperationRepository) UpdateOperationState(ctx context.Context, sessionID int64, opId int64, state models.OperationState, responseData map[string]interface{}) error

UpdateOperationState updates operation state

func (*SCACIOperationRepository) UpdateOperationStateWithError

func (r *SCACIOperationRepository) UpdateOperationStateWithError(ctx context.Context, sessionID int64, opId int64,
	state models.OperationState, errorCode int, errorToken string, errorMessage string,
	responseData map[string]interface{},
) error

UpdateOperationStateWithError updates state with explicit error columns per SCACI §3.14 Used when failing an operation with structured error metadata per SCACI §3.14

type SCACISessionRepository

type SCACISessionRepository struct {
	// contains filtered or unexported fields
}

SCACISessionRepository implements the SCACISessionRepository interface for PostgreSQL, over the database or over one transaction (Transaction.SCACISessions). Its writes take their time from the injected clock, except updated_at, which the table's update trigger stamps.

func NewSCACISessionRepository

func NewSCACISessionRepository(db *sqlx.DB, clk clock.Clock, log logger.Logger) *SCACISessionRepository

NewSCACISessionRepository creates a new PostgreSQL SCACI session repository.

func (*SCACISessionRepository) CheckSessionResumable

CheckSessionResumable reports whether the application center's latest session of snAcUUID can still be resumed (SCACI §1) and returns the operation ID counters and the negotiated version (§§2.1-2.3) it stored. Whether the application center's view of the counters agrees with them is the SCACI rule's to decide (scaci.ResumeOpIDConflict, §3.3.1).

func (*SCACISessionRepository) CreateSession

CreateSession inserts a new SCACI session. It retires nothing: the earlier sessions of the application center are retired by RetirePriorSessions, in the transaction that creates the new one.

func (*SCACISessionRepository) DisconnectAbandonedSessions

func (r *SCACISessionRepository) DisconnectAbandonedSessions(ctx context.Context, scEUI models.EUI) ([]int64, error)

DisconnectAbandonedSessions hands the sessions a previous process of the service center scEUI left live back to the resumable disconnected state, as the loss of their connections would have (SCACI §1), and returns their ids. A row without an owner predates ownership tracking and is claimed for scEUI; rows of other service centers are not touched. The last write to a row is the closest known end time.

func (*SCACISessionRepository) GetSessionByAcUUID

func (r *SCACISessionRepository) GetSessionByAcUUID(ctx context.Context, ac models.SCACIApplicationCenter, snAcUUID [16]byte) (*models.SCACISession, error)

GetSessionByAcUUID retrieves the application center's latest session of its session UUID snAcUUID.

func (*SCACISessionRepository) GetSessionByID

func (r *SCACISessionRepository) GetSessionByID(ctx context.Context, tenantID, sessionID int64) (*models.SCACISession, error)

GetSessionByID retrieves a session by ID

func (*SCACISessionRepository) GetSessionByScUUID

func (r *SCACISessionRepository) GetSessionByScUUID(ctx context.Context, tenantID int64, snScUUID [16]byte) (*models.SCACISession, error)

GetSessionByScUUID retrieves a session by Service Center session UUID

func (*SCACISessionRepository) GetSessionStatistics

func (r *SCACISessionRepository) GetSessionStatistics(ctx context.Context, tenantID int64) (*models.SCACISessionStatistics, error)

GetSessionStatistics retrieves aggregated session statistics

func (*SCACISessionRepository) ListResumableSessions

func (r *SCACISessionRepository) ListResumableSessions(ctx context.Context) ([]*models.SCACISession, error)

ListResumableSessions returns the sessions of every tenant an Application Center may still resume (SCACI §1), under the conditions CheckSessionResumable applies.

func (*SCACISessionRepository) ListSessions

ListSessions retrieves sessions based on filter criteria

func (*SCACISessionRepository) MarkSessionDisconnected

func (r *SCACISessionRepository) MarkSessionDisconnected(ctx context.Context, tenantID, sessionID int64) error

MarkSessionDisconnected records the loss of a session's connection. The session stays resumable (SCACI §1); a session a newer one already replaced stays terminated.

func (*SCACISessionRepository) ResumeSession

func (r *SCACISessionRepository) ResumeSession(ctx context.Context, tenantID, sessionID int64, req *models.SCACISessionResume) error

ResumeSession records the connection a resume moved the session to (SCACI §1): active again and owned by the resuming service center, with its heartbeat, TLS evidence and metadata. A session that is no longer resumable is left as it is and reported as storage.ErrNotFound.

func (*SCACISessionRepository) RetirePriorSessions

func (r *SCACISessionRepository) RetirePriorSessions(ctx context.Context, ac models.SCACIApplicationCenter) error

RetirePriorSessions terminates every session of the application center, so the session created next in the same transaction starts from discarded state (SCACI §1: a new session discards the state of the previous one, also of a connection that was never torn down). Another organization's sessions of the same acEui are left alone. It holds the application center's lock until the transaction ends.

func (*SCACISessionRepository) TerminateSession

func (r *SCACISessionRepository) TerminateSession(ctx context.Context, tenantID, sessionID int64) error

TerminateSession marks a session as terminated

func (*SCACISessionRepository) UpdateHeartbeat

func (r *SCACISessionRepository) UpdateHeartbeat(ctx context.Context, tenantID, sessionID int64) error

UpdateHeartbeat updates the last heartbeat timestamp

func (*SCACISessionRepository) UpdateOperationIDs

func (r *SCACISessionRepository) UpdateOperationIDs(ctx context.Context, tenantID, sessionID int64, acOpId, scOpId int64) error

UpdateOperationIDs advances both operation ID counters atomically. Writers race, so a stale pair never moves a counter back: the AC counter only grows and the SC counter only shrinks (SCACI §3.2).

type SchemaGate

type SchemaGate interface {
	Version() uint
	Check(ctx context.Context, db *sql.DB) error
}

SchemaGate holds an upgrade at a schema version until data that later migrations depend on is in place. Check only reads, so a refusal leaves the schema clean at Version.

func UpgradeGates

func UpgradeGates() []SchemaGate

UpgradeGates returns the gates every upgrade of this schema must pass; a composition root hands them to NewMigrationRunner.

type SystemEventStore

type SystemEventStore struct {
	// contains filtered or unexported fields
}

SystemEventStore provides system event storage operations per MIOTY requirements

func NewSystemEventStore

func NewSystemEventStore(db *sql.DB, clk clock.Clock, log logger.Logger) *SystemEventStore

NewSystemEventStore creates a new system event store

func (*SystemEventStore) CountActiveAlerts

func (s *SystemEventStore) CountActiveAlerts(ctx context.Context, filter models.AlertFilter) (int64, error)

CountActiveAlerts counts the alerts GetActiveAlerts pages through.

func (*SystemEventStore) CountAlertsBySeverity

func (s *SystemEventStore) CountAlertsBySeverity(ctx context.Context, filter models.AlertFilter) (map[string]int64, error)

CountAlertsBySeverity counts, per severity, the alerts CountActiveAlerts counts. A severity without alerts is absent from the map.

func (*SystemEventStore) CountEvents

func (s *SystemEventStore) CountEvents(ctx context.Context, filter models.SystemEventFilter) (int64, error)

CountEvents returns total count matching filter (for pagination)

func (*SystemEventStore) CreateEvent

func (s *SystemEventStore) CreateEvent(ctx context.Context, event *models.SystemEvent) error

CreateEvent creates a new system event per MIOTY requirements. Delegates to the unified insertEvent helper.

func (*SystemEventStore) GetActiveAlerts

func (s *SystemEventStore) GetActiveAlerts(ctx context.Context, filter models.AlertFilter) ([]*models.SystemEvent, error)

GetActiveAlerts retrieves the tenant's alert-level events in the filter's statuses, unresolved ones by default.

func (*SystemEventStore) GetEventStats

func (s *SystemEventStore) GetEventStats(ctx context.Context, tenantID string, since time.Time) (*models.SystemEventStats, error)

GetEventStats retrieves event statistics grouped by severity for a tenant.

func (*SystemEventStore) GetEvents

GetEvents retrieves events with filters

func (*SystemEventStore) ListErrorGroups

func (s *SystemEventStore) ListErrorGroups(ctx context.Context, filter models.ErrorGroupFilter) ([]*models.EventErrorGroup, int64, error)

ListErrorGroups groups the failures of the filter by event type, code and subject; SCACI operation failures join the result under their command.

type TenantRepository

type TenantRepository struct {
	// contains filtered or unexported fields
}

TenantRepository provides internal postgres-specific tenant operations. This is an internal implementation not exposed outside the postgres package.

func NewTenantRepository

func NewTenantRepository(db *sqlx.DB) *TenantRepository

NewTenantRepository creates a new internal tenant repository

func (*TenantRepository) CreateTenant

func (r *TenantRepository) CreateTenant(ctx context.Context, name string, description *string) (*models.Tenant, error)

CreateTenant creates a new tenant with the provided details

func (*TenantRepository) DeleteTenant

func (r *TenantRepository) DeleteTenant(ctx context.Context, id int64) error

DeleteTenant removes a tenant by ID - used for org creation rollback

func (*TenantRepository) GetSnapshotOnlyDecoding

func (r *TenantRepository) GetSnapshotOnlyDecoding(ctx context.Context, tenantID int64) (bool, error)

GetSnapshotOnlyDecoding returns storage.ErrNotFound for a missing tenant.

func (*TenantRepository) GetTenantByID

func (r *TenantRepository) GetTenantByID(ctx context.Context, id int64) (*models.Tenant, error)

GetTenantByID retrieves a tenant by ID

func (*TenantRepository) ListTenants

func (r *TenantRepository) ListTenants(ctx context.Context, statusFilter string) ([]models.Tenant, error)

ListTenants retrieves all tenants with optional status filtering

func (*TenantRepository) SetSnapshotOnlyDecoding

func (r *TenantRepository) SetSnapshotOnlyDecoding(ctx context.Context, tenantID int64, enabled bool) error

SetSnapshotOnlyDecoding returns storage.ErrNotFound for a missing tenant.

func (*TenantRepository) SetStatus

func (r *TenantRepository) SetStatus(ctx context.Context, id int64, active bool) error

SetStatus updates the status field (for soft delete/activation)

func (*TenantRepository) UpdateTenant

func (r *TenantRepository) UpdateTenant(ctx context.Context, id int64, updates map[string]interface{}) (*models.Tenant, error)

UpdateTenant updates tenant fields dynamically using a map of field updates

type Transaction

type Transaction struct {
	// contains filtered or unexported fields
}

Transaction represents a database transaction. It exposes only the repositories that participate in transactional operations: endpoint attach (endpoints + endpoint sessions), blueprint creation (device models + blueprints), downlink reservation (mioty downlinks) and SCACI session creation (SCACI sessions).

func (*Transaction) Blueprints

func (t *Transaction) Blueprints() interfaces.BlueprintRepository

Blueprints returns blueprint repository for this transaction

func (*Transaction) Commit

func (t *Transaction) Commit() error

Commit commits the transaction

func (*Transaction) DeviceModels

func (t *Transaction) DeviceModels() interfaces.DeviceModelRepository

DeviceModels returns device model repository for this transaction

func (*Transaction) EndPointSessions

func (t *Transaction) EndPointSessions() interfaces.EndPointSessionRepository

EndPointSessions returns the endpoint session repository for this transaction

func (*Transaction) EndPoints

func (t *Transaction) EndPoints() interfaces.EndpointRepository

EndPoints returns the endpoint repository for this transaction

func (t *Transaction) MIOTYDownlinks() interfaces.MIOTYDownlinkTxRepository

MIOTYDownlinks returns the transactional downlink repository, the only path to the FOR UPDATE SKIP LOCKED reservation queries.

func (*Transaction) Rollback

func (t *Transaction) Rollback() error

Rollback rolls back the transaction

func (*Transaction) SCACISessions

func (t *Transaction) SCACISessions() interfaces.SCACISessionRepository

SCACISessions returns the SCACI session repository for this transaction.

func (*Transaction) UplinkClassifier

func (t *Transaction) UplinkClassifier() interfaces.UplinkClassifierReset

UplinkClassifier returns the uplink classifier reset for this transaction.

func (*Transaction) WithSavepoint

func (t *Transaction) WithSavepoint(ctx context.Context, fn func() error) error

WithSavepoint runs fn inside a private savepoint. When fn fails, the transaction is rolled back to the savepoint - recovering it from an aborted statement (for example a unique violation) so the caller can retry inside the same transaction - and fn's error is returned. On success the savepoint is released.

type UplinkClassifierReset

type UplinkClassifierReset struct {
	// contains filtered or unexported fields
}

UplinkClassifierReset forgets the uplink store's duplicate-classifier rows of one endpoint inside the caller's transaction.

func (*UplinkClassifierReset) ForgetEndpoint

func (r *UplinkClassifierReset) ForgetEndpoint(ctx context.Context, tenantID int64, endpointID int64) error

ForgetEndpoint deletes the endpoint's classifier rows, so the packet counters an over-the-air attach restarted read as new data (radio protocol §3.6.5.3).

type UplinkStore

type UplinkStore struct {
	// contains filtered or unexported fields
}

UplinkStore is the PostgreSQL uplink classifier and writer. One transaction claims the (owner tenant, endpoint, packet counter) row, then either stores a new message with its outbox rows or merges the reception into the first message of the window; no in-memory state takes part. The request's tenant is the endpoint owner and keys every row written.

func NewUplinkStore

func NewUplinkStore(db *sqlx.DB, clk clock.Clock, log logger.Logger) *UplinkStore

NewUplinkStore creates the uplink store over the shared connection pool.

func (*UplinkStore) Persist

Persist classifies the reception in req and stores it accordingly.

type UserRepository

type UserRepository struct {
	// contains filtered or unexported fields
}

UserRepository implements the UserRepository interface for PostgreSQL

func NewUserRepository

func NewUserRepository(db *sqlx.DB, clk clock.Clock) *UserRepository

NewUserRepository creates a new PostgreSQL User repository

func (*UserRepository) Count

func (r *UserRepository) Count(ctx context.Context) (int64, error)

Count returns total user count

func (*UserRepository) Create

func (r *UserRepository) Create(ctx context.Context, user *models.User) error

Create inserts a new user

func (*UserRepository) Delete

func (r *UserRepository) Delete(ctx context.Context, id uuid.UUID) error

Delete removes a user by ID

func (*UserRepository) GetByEmail

func (r *UserRepository) GetByEmail(ctx context.Context, email string) (*models.User, error)

GetByEmail retrieves a user by email address

func (*UserRepository) GetByExternalID

func (r *UserRepository) GetByExternalID(ctx context.Context, externalID string) (*models.User, error)

GetByExternalID retrieves a user by external provider ID (OIDC)

func (*UserRepository) GetByID

func (r *UserRepository) GetByID(ctx context.Context, id uuid.UUID) (*models.User, error)

GetByID retrieves a user by UUID

func (*UserRepository) LinkExternalID

func (r *UserRepository) LinkExternalID(ctx context.Context, id uuid.UUID, externalID string) error

LinkExternalID records the external identity of an active user and touches no other column, so it cannot undo a concurrent change such as a deactivation. It fails with storage.ErrUserInactive when the user is missing or deactivated.

func (*UserRepository) List

func (r *UserRepository) List(ctx context.Context, limit, offset int) ([]*models.User, error)

List returns users with pagination

func (*UserRepository) SetPasswordHash

func (r *UserRepository) SetPasswordHash(ctx context.Context, id uuid.UUID, hash string) error

SetPasswordHash updates only the password hash field

func (*UserRepository) Update

func (r *UserRepository) Update(ctx context.Context, user *models.User) error

Update modifies an existing user

Source Files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址