sync

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2026 License: MIT Imports: 39 Imported by: 1

Documentation

Overview

Package sync provides SQLite-based offline caching for Aha Studio.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultDBPath

func DefaultDBPath() string

DefaultDBPath returns the default database path.

Types

type DB

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

DB wraps a SQLite database connection for Aha data caching. The 13 core tables (features, initiatives, etc.) are managed by the generated Ent client; the FTS5 virtual tables/triggers stay hand-written SQL against the shared *sql.DB connection (Ent has no concept of SQLite virtual tables). See /Users/johnwang/.claude/plans/sprightly-waddling-platypus.md.

func Open

func Open(dbPath string) (*DB, error)

Open opens or creates a SQLite database at the given path.

func (*DB) Close

func (d *DB) Close() error

Close closes the database connection (and the Ent client sharing it).

func (*DB) CountIdeaEndorsements added in v0.12.0

func (d *DB) CountIdeaEndorsements(ctx context.Context, ideaID string) (int, error)

CountIdeaEndorsements returns the number of endorsement rows already cached for an idea.

func (*DB) CreateFilter

func (d *DB) CreateFilter(ctx context.Context, f *SavedFilter) error

CreateFilter creates a new saved filter.

func (*DB) DeleteFilter

func (d *DB) DeleteFilter(ctx context.Context, id string) error

DeleteFilter deletes a saved filter by ID.

func (*DB) FullTextSearch

func (d *DB) FullTextSearch(ctx context.Context, query string, entityTypes []string, limit int) ([]map[string]any, error)

FullTextSearch searches across all FTS5 tables.

func (*DB) GetFeatureIDs

func (d *DB) GetFeatureIDs(ctx context.Context, product string) ([]string, error)

GetFeatureIDs returns all feature IDs for a product.

func (*DB) GetFeaturesByReleaseDate added in v0.9.0

func (d *DB) GetFeaturesByReleaseDate(ctx context.Context, product, releaseDate string) ([]map[string]any, error)

GetFeaturesByReleaseDate returns all features for releases matching a specific date. The date should be in YYYY-MM-DD format.

func (*DB) GetFeaturesByReleaseDateRange added in v0.9.0

func (d *DB) GetFeaturesByReleaseDateRange(ctx context.Context, product, startDate, endDate string) ([]map[string]any, error)

GetFeaturesByReleaseDateRange returns all features for releases within a date range. Both dates should be in YYYY-MM-DD format. Either can be empty for open-ended range.

func (*DB) GetFeaturesByReleaseID added in v0.9.0

func (d *DB) GetFeaturesByReleaseID(ctx context.Context, product, releaseID string) ([]map[string]any, error)

GetFeaturesByReleaseID returns all features for a given release ID.

func (*DB) GetFeaturesByReleaseName added in v0.9.0

func (d *DB) GetFeaturesByReleaseName(ctx context.Context, product, releaseName string) ([]map[string]any, error)

GetFeaturesByReleaseName returns all features for a given release name.

func (*DB) GetFeaturesStatistics added in v0.12.0

func (d *DB) GetFeaturesStatistics(ctx context.Context, product string, limit int) (*FeatureStatistics, error)

GetFeaturesStatistics returns aggregated statistics for features in a product.

func (*DB) GetFilter

func (d *DB) GetFilter(ctx context.Context, id string) (*SavedFilter, error)

GetFilter returns a saved filter by ID.

func (*DB) GetFilterByName

func (d *DB) GetFilterByName(ctx context.Context, name string) (*SavedFilter, error)

GetFilterByName returns a saved filter by name.

func (*DB) GetIdeaEndorsementsByIdea added in v0.12.0

func (d *DB) GetIdeaEndorsementsByIdea(ctx context.Context, ideaID string) ([]map[string]any, error)

GetIdeaEndorsementsByIdea returns cached endorsements (votes) for an idea, including the voter's portal email.

func (*DB) GetIdeaOrganizationsByDomain added in v0.12.0

func (d *DB) GetIdeaOrganizationsByDomain(ctx context.Context) (map[string]IdeaOrganizationSummary, error)

GetIdeaOrganizationsByDomain returns a domain -> organization lookup built from every cached IdeaOrganization's (possibly comma-separated) email_domains field. Built once per omnisignalcache.Fetch() call rather than once per voter.

func (*DB) GetIdeaVoteCounts added in v0.12.0

func (d *DB) GetIdeaVoteCounts(ctx context.Context, product string) (map[string]int, error)

GetIdeaVoteCounts returns each cached idea's current vote count, keyed by idea ID, for a product. Used by syncIdeaEndorsements to decide which ideas' endorsements actually need re-fetching.

func (*DB) GetIdeas added in v0.12.0

func (d *DB) GetIdeas(ctx context.Context, product string, since time.Time) ([]map[string]any, error)

GetIdeas returns cached ideas for a product, optionally filtered to those created at or after since. Used by the omnisignalcache provider, which builds signals from the cache rather than live API calls.

func (*DB) GetIdeasStatistics added in v0.12.0

func (d *DB) GetIdeasStatistics(ctx context.Context, product string, limit int) (*IdeaStatistics, error)

GetIdeasStatistics returns aggregated statistics for ideas in a product.

func (*DB) GetLastSync

func (d *DB) GetLastSync(ctx context.Context, entity, product string) (time.Time, error)

GetLastSync returns the last sync time for an entity/product combination.

func (*DB) GetRecord added in v0.12.0

func (d *DB) GetRecord(ctx context.Context, entityType, id string) (map[string]any, error)

GetRecord returns one cached record by entity type and ID (or reference number), in the same flattened shape as ListRecords. Returns sql.ErrNoRows when no record matches.

func (*DB) GetRelationships

func (d *DB) GetRelationships(ctx context.Context, entityType, entityID string) ([]map[string]any, error)

GetRelationships returns relationships for an entity.

func (*DB) GetReleaseByDate added in v0.9.0

func (d *DB) GetReleaseByDate(ctx context.Context, product, releaseDate string) (*map[string]any, error)

GetReleaseByDate returns a release matching a specific date.

func (*DB) GetReleaseByName added in v0.9.0

func (d *DB) GetReleaseByName(ctx context.Context, product, releaseName string) (*map[string]any, error)

GetReleaseByName returns a release matching a specific name.

func (*DB) GetSyncStatus

func (d *DB) GetSyncStatus(ctx context.Context, product string) (map[string]SyncStatus, error)

GetSyncStatus returns the sync status for all entities.

func (*DB) GetVoterEmailDomainStatistics added in v0.12.0

func (d *DB) GetVoterEmailDomainStatistics(ctx context.Context, product, ideaID string, limit int) (*VoterDomainStatistics, error)

GetVoterEmailDomainStatistics returns a histogram of idea voters grouped by email domain (the part of portal_user_email after "@"). If ideaID is empty, the histogram covers every idea in the product; otherwise it's scoped to that one idea. AQL's executor has no string/computed-expression functions (no SUBSTR equivalent), so this can't be a generic AQL GROUP BY -- it needs the same hand-written-SQL approach as GetIdeasStatistics.

func (*DB) ListFilters

func (d *DB) ListFilters(ctx context.Context) ([]SavedFilter, error)

ListFilters returns all saved filters.

func (*DB) ListRecords added in v0.12.0

func (d *DB) ListRecords(ctx context.Context, entityType, product string) ([]map[string]any, error)

ListRecords returns all cached records of an entity type ("features"|"initiatives"|"epics"|"releases"), optionally filtered by product (empty product = all products). Records are returned in the flattened shape QueryOffline uses: real columns plus the data JSON column's keys merged in (column values win), so custom_fields — when the record was detail-synced — surfaces as a []any of {key,name,value,type} maps.

func (*DB) QueryOffline

func (d *DB) QueryOffline(ctx context.Context, plan *planner.Plan) (*result.Result, error)

QueryOffline executes a query against the local SQLite database.

func (*DB) SetLastSync

func (d *DB) SetLastSync(ctx context.Context, entity, product string, t time.Time, count int) error

SetLastSync updates the last sync time for an entity/product combination.

func (*DB) SetProduct

func (d *DB) SetProduct(product string)

SetProduct sets the current product context.

func (*DB) UpdateFilter

func (d *DB) UpdateFilter(ctx context.Context, f *SavedFilter) error

UpdateFilter updates an existing saved filter.

func (*DB) UpsertComment

func (d *DB) UpsertComment(ctx context.Context, product string, data map[string]any) error

UpsertComment inserts or updates a comment record.

func (*DB) UpsertEpic

func (d *DB) UpsertEpic(ctx context.Context, product string, data map[string]any) error

UpsertEpic inserts or updates an epic record.

func (*DB) UpsertFeature

func (d *DB) UpsertFeature(ctx context.Context, product string, data map[string]any) error

UpsertFeature inserts or updates a feature record.

func (*DB) UpsertGoal

func (d *DB) UpsertGoal(ctx context.Context, product string, data map[string]any) error

UpsertGoal inserts or updates a goal record.

func (*DB) UpsertIdea

func (d *DB) UpsertIdea(ctx context.Context, product string, data map[string]any) error

UpsertIdea inserts or updates an idea record.

func (*DB) UpsertIdeaEndorsement added in v0.12.0

func (d *DB) UpsertIdeaEndorsement(ctx context.Context, product string, data map[string]any) error

UpsertIdeaEndorsement inserts or updates an idea endorsement (vote) record.

func (*DB) UpsertIdeaOrganization added in v0.12.0

func (d *DB) UpsertIdeaOrganization(ctx context.Context, data map[string]any) error

UpsertIdeaOrganization inserts or updates an idea organization (customer/account) record.

func (*DB) UpsertIdeaUser added in v0.12.0

func (d *DB) UpsertIdeaUser(ctx context.Context, data map[string]any) error

UpsertIdeaUser inserts or updates an idea user (voter identity) record.

func (*DB) UpsertInitiative

func (d *DB) UpsertInitiative(ctx context.Context, product string, data map[string]any) error

UpsertInitiative inserts or updates an initiative record.

func (*DB) UpsertProduct

func (d *DB) UpsertProduct(ctx context.Context, data map[string]any) error

UpsertProduct inserts or updates a product record.

func (*DB) UpsertRelationship

func (d *DB) UpsertRelationship(ctx context.Context, fromType, fromID, relType, toType, toID, product string) error

UpsertRelationship inserts or updates a relationship record.

func (*DB) UpsertRelease

func (d *DB) UpsertRelease(ctx context.Context, product string, data map[string]any) error

UpsertRelease inserts or updates a release record.

func (*DB) UpsertRequirement

func (d *DB) UpsertRequirement(ctx context.Context, product string, data map[string]any) error

UpsertRequirement inserts or updates a requirement record.

func (*DB) UpsertUser

func (d *DB) UpsertUser(ctx context.Context, data map[string]any) error

UpsertUser inserts or updates a user record.

type DomainCount added in v0.12.0

type DomainCount struct {
	Domain string `json:"domain"`
	Count  int    `json:"count"`
}

DomainCount is the voter count for a single email domain.

type FeatureStatistics added in v0.12.0

type FeatureStatistics struct {
	TotalCount       int              `json:"total_count"`
	ByStatus         map[string]int   `json:"by_status"`
	ByRelease        map[string]int   `json:"by_release"`
	WithRelease      int              `json:"with_release"`
	WithoutRelease   int              `json:"without_release"`
	RecentCount      int              `json:"recent_count"`   // features in last 30 days
	UpdatedRecent    int              `json:"updated_recent"` // updated in last 7 days
	UpcomingReleases []ReleaseSummary `json:"upcoming_releases"`
}

FeatureStatistics holds aggregated statistics for features.

type IdeaOrganizationSummary added in v0.12.0

type IdeaOrganizationSummary struct {
	ID           string
	Name         string
	ReferenceNum string
}

IdeaOrganizationSummary is the subset of a cached IdeaOrganization needed to resolve a voter's email domain to a customer reference.

type IdeaStatistics added in v0.12.0

type IdeaStatistics struct {
	TotalCount    int            `json:"total_count"`
	ByStatus      map[string]int `json:"by_status"`
	TotalVotes    int            `json:"total_votes"`
	AvgVotes      float64        `json:"avg_votes"`
	MaxVotes      int            `json:"max_votes"`
	TopIdeas      []IdeaSummary  `json:"top_ideas"`
	RecentCount   int            `json:"recent_count"`   // ideas in last 30 days
	UpdatedRecent int            `json:"updated_recent"` // updated in last 7 days
}

IdeaStatistics holds aggregated statistics for ideas.

type IdeaSummary added in v0.12.0

type IdeaSummary struct {
	ID           string `json:"id"`
	ReferenceNum string `json:"reference_num"`
	Name         string `json:"name"`
	Status       string `json:"status"`
	Votes        int    `json:"votes"`
}

IdeaSummary is a brief summary of an idea for statistics.

type ProgressFunc added in v0.9.0

type ProgressFunc func(current, total int, message string)

ProgressFunc is called during sync to report progress. current is the current record count, total is the estimated total (0 if unknown), and message describes the current operation.

type ReleaseSummary added in v0.12.0

type ReleaseSummary struct {
	ID           string `json:"id"`
	ReferenceNum string `json:"reference_num"`
	Name         string `json:"name"`
	ReleaseDate  string `json:"release_date"`
	FeatureCount int    `json:"feature_count"`
}

ReleaseSummary is a brief summary of a release for statistics.

type SavedFilter

type SavedFilter struct {
	ID          string    `json:"id"`
	Name        string    `json:"name"`
	AQL         string    `json:"aql"`
	Product     string    `json:"product,omitempty"`
	Description string    `json:"description,omitempty"`
	IsFavorite  bool      `json:"is_favorite"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

SavedFilter represents a saved AQL query.

type Scheduler

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

Scheduler manages background sync operations.

func NewScheduler

func NewScheduler(syncer *Syncer, cfg SchedulerConfig) *Scheduler

NewScheduler creates a new sync scheduler.

func (*Scheduler) IsRunning

func (s *Scheduler) IsRunning() bool

IsRunning returns true if the scheduler is running.

func (*Scheduler) LastError

func (s *Scheduler) LastError() error

LastError returns the last sync error, if any.

func (*Scheduler) LastSync

func (s *Scheduler) LastSync() time.Time

LastSync returns the time of the last successful sync.

func (*Scheduler) Start

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

Start begins background sync. Non-blocking.

func (*Scheduler) Status

func (s *Scheduler) Status() SchedulerStatus

Status returns the current scheduler status.

func (*Scheduler) Stop

func (s *Scheduler) Stop()

Stop stops the background sync gracefully.

func (*Scheduler) SyncNow

func (s *Scheduler) SyncNow(ctx context.Context) ([]SyncResult, error)

SyncNow triggers an immediate sync, regardless of schedule.

type SchedulerConfig

type SchedulerConfig struct {
	// Interval between sync runs. Default: 15 minutes.
	Interval time.Duration

	// Product ID to sync.
	Product string

	// Logger for sync events. Default: slog.Default().
	Logger *slog.Logger

	// Entities to sync. Default: all entities.
	Entities []string
}

SchedulerConfig configures the sync scheduler.

func DefaultSchedulerConfig

func DefaultSchedulerConfig() SchedulerConfig

DefaultSchedulerConfig returns default scheduler configuration.

type SchedulerStatus

type SchedulerStatus struct {
	Running  bool
	Interval time.Duration
	Product  string
	LastSync time.Time
	LastErr  error
}

SchedulerStatus contains scheduler status information.

type SyncOptions

type SyncOptions struct {
	Product     string    // Product ID to sync
	Incremental bool      // Only sync changes since last sync
	Since       time.Time // Custom since time (overrides incremental lookup)
	Entities    []string  // Specific entities to sync (nil = all)

	// Detailed, when true, fetches full per-record data (including custom
	// fields) for features and initiatives via an additional per-record API
	// call after the initial list fetch. Has no effect on other entities.
	// This multiplies API calls roughly N+1 for the affected entities, so
	// use a rate-limited client (see aha.WithRequestsPerSecond) for large
	// products.
	Detailed bool
}

SyncOptions configures a sync operation.

type SyncResult

type SyncResult struct {
	Entity      string
	RecordCount int
	Duration    time.Duration
	Error       error
}

SyncResult contains the result of a sync operation.

type SyncStatus

type SyncStatus struct {
	LastSync    string
	RecordCount int
}

SyncStatus contains sync status for an entity.

type Syncer

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

Syncer synchronizes Aha data to a local SQLite database.

func NewSyncer

func NewSyncer(db *DB, client *aha.Client) *Syncer

NewSyncer creates a new Syncer with the given database and Aha client.

func NewSyncerWithGraphQL added in v0.9.0

func NewSyncerWithGraphQL(db *DB, client *aha.Client, subdomain, apiKey string) *Syncer

NewSyncerWithGraphQL creates a new Syncer with GraphQL support for enhanced feature sync. The subdomain and apiKey are used to create a GraphQL client for fetching features with release info.

func (*Syncer) SyncAll

func (s *Syncer) SyncAll(ctx context.Context, opts SyncOptions) ([]SyncResult, error)

SyncAll syncs all entities for a product.

func (*Syncer) WithProgress added in v0.9.0

func (s *Syncer) WithProgress(fn ProgressFunc) *Syncer

WithProgress sets a progress callback for the syncer.

type VoterDomainStatistics added in v0.12.0

type VoterDomainStatistics struct {
	TotalVoters   int           `json:"total_voters"`
	UniqueDomains int           `json:"unique_domains"`
	ByDomain      []DomainCount `json:"by_domain"`
}

VoterDomainStatistics holds an email-domain histogram of idea voters.

Jump to

Keyboard shortcuts

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