Documentation
¶
Overview ¶
Package pluginitems owns the storage, keyset browse, full-text search, sync engine, Title projection, matching and resolution cache for plugin content kinds (spec §2.2-2.5, §3.1-3.6, §4.4, §6.3, §7).
Plugin items never enter catalog_titles; every query is scoped by library_id first, and item identity is the namespaced core.ItemRef ("pk:<pluginID>:<kindKey>:<externalID>") paired with a stored, never-reused RatingKey sequence number (core.PluginKey).
Index ¶
- Constants
- Variables
- func EffectiveCard(cardShape string, decl plugins.KindLibraryDecl) string
- func FoldFieldText(value string) string
- func FoldSortTitle(s string) string
- func Project(item core.KindItem, decl plugins.MediaKindMeta, present core.Presentations, ...) core.Title
- func ProjectWithText(item core.KindItem, decl plugins.MediaKindMeta, present core.Presentations, ...) core.Title
- func ResolveMediaClassAndRole(level string, decl plugins.MediaKindMeta, present core.Presentations) (core.MediaClass, core.MediaRole)
- func RuleFields(decl plugins.MediaKindMeta) map[string]string
- func SeriesFacetField(decl plugins.MediaKindMeta) string
- func SortTitle(s string) string
- type BrowsePage
- type BrowseQuery
- type Caller
- type DeleteGuardError
- type FacetBucket
- type FacetCollection
- type FacetCollectionsPage
- type FacetCollectionsQuery
- type FacetCount
- type FacetExpansion
- type FacetPage
- type FacetPeoplePage
- type FacetPeopleQuery
- type FacetPerson
- type HealthReporter
- type IndexedFieldValue
- type KeyedItem
- type KindRecord
- type MatchRecord
- type Options
- type PersonFacetMatch
- type PersonMatch
- type SearchQuery
- type Service
- func (s *Service) BestMatch(ctx context.Context, itemRef core.ItemRef, threshold float64) (MatchRecord, bool, error)
- func (s *Service) Browse(ctx context.Context, q BrowseQuery) (BrowsePage, error)
- func (s *Service) BumpGeneration() uint64
- func (s *Service) CancelKindSync(pluginID, kindKey string)
- func (s *Service) Children(ctx context.Context, parentRef core.ItemRef, cursor string, limit int) (BrowsePage, error)
- func (s *Service) ChildrenCountAndFreshness(ctx context.Context, libraryID core.LibraryID, parentRef core.ItemRef) (int, time.Time, error)
- func (s *Service) ChildrenFreshness(ctx context.Context, libraryID core.LibraryID, parentRef core.ItemRef) (bool, time.Time, error)
- func (s *Service) ClearManualMatch(ctx context.Context, itemRef core.ItemRef) error
- func (s *Service) Close()
- func (s *Service) CompilePolicy(ctx context.Context, lib core.LibraryID, specs []core.LibraryExclusion, ...) (*libraryfilter.Filter, error)
- func (s *Service) CountKindItems(ctx context.Context, pluginID, kindKey string) (int, error)
- func (s *Service) CountPartsMany(ctx context.Context, refs []core.ItemRef) (map[core.ItemRef]int, error)
- func (s *Service) DeleteItems(ctx context.Context, pluginID, kindKey string, externalIDs []string) error
- func (s *Service) EnsurePartsFromHints(ctx context.Context, item core.KindItem) ([]StoredPart, error)
- func (s *Service) FacetBuckets(ctx context.Context, libraryID core.LibraryID, level string, ...) ([]FacetBucket, error)
- func (s *Service) FacetCollections(ctx context.Context, q FacetCollectionsQuery) (FacetCollectionsPage, error)
- func (s *Service) FacetPeople(ctx context.Context, q FacetPeopleQuery) (FacetPeoplePage, error)
- func (s *Service) Facets(ctx context.Context, libraryID core.LibraryID, level, fieldKey string, ...) (FacetPage, error)
- func (s *Service) FilterVisibleIDs(ctx context.Context, pluginID, kindKey string, lib core.Library, ...) ([]string, error)
- func (s *Service) FilterVisibleRefs(ctx context.Context, lib core.Library, refs []core.ItemRef) (map[core.ItemRef]bool, error)
- func (s *Service) FindPersonID(ctx context.Context, libraryID core.LibraryID, policy *libraryfilter.Filter, ...) (int64, bool, error)
- func (s *Service) FinishFacetExpansion(ctx context.Context, pluginID, kindKey string, libraryID core.LibraryID, ...) error
- func (s *Service) Generation() uint64
- func (s *Service) GetByExternal(ctx context.Context, pluginID, kindKey, externalID string) (core.KindItem, core.LibraryID, error)
- func (s *Service) GetByKey(ctx context.Context, key core.RatingKey) (core.KindItem, core.LibraryID, error)
- func (s *Service) GetByKeys(ctx context.Context, keys []core.RatingKey) (map[core.RatingKey]KeyedItem, error)
- func (s *Service) GetByRef(ctx context.Context, ref core.ItemRef) (core.KindItem, core.LibraryID, error)
- func (s *Service) GetFacetExpansion(ctx context.Context, pluginID, kindKey, facet, valueKey string) (FacetExpansion, bool, error)
- func (s *Service) GetKind(ctx context.Context, pluginID, kindKey string) (KindRecord, error)
- func (s *Service) GetKindByLibrary(ctx context.Context, libraryID core.LibraryID) (KindRecord, error)
- func (s *Service) GetPartByKey(ctx context.Context, key core.RatingKey) (StoredPart, core.KindItem, core.LibraryID, error)
- func (s *Service) GetPartCandidates(ctx context.Context, ref core.ItemRef, partIdx *int) ([]core.PlayableSource, bool, error)
- func (s *Service) GetPartResolution(ctx context.Context, ref core.ItemRef, partIdx *int) (core.PlayableSource, bool, error)
- func (s *Service) GetPartsByKeys(ctx context.Context, keys []core.RatingKey) (map[core.RatingKey]StoredPart, error)
- func (s *Service) GetResolution(ctx context.Context, ref core.ItemRef) (core.PlayableSource, bool, error)
- func (s *Service) InvalidatePartResolution(ctx context.Context, ref core.ItemRef, partIdx *int) error
- func (s *Service) InvalidateResolution(ctx context.Context, ref core.ItemRef) error
- func (s *Service) IsSyncRunning(pluginID, kindKey string) bool
- func (s *Service) ItemHidden(ctx context.Context, lib core.Library, ref core.ItemRef) (bool, error)
- func (s *Service) KeepExistingItems(ctx context.Context, pluginID, kindKey string) (SyncState, error)
- func (s *Service) KindBackends() plugins.KindBackends
- func (s *Service) KindDelete(ctx context.Context, pluginID, kindKey string, externalIDs []string) error
- func (s *Service) KindItems(ctx context.Context, pluginID, kindKey, cursor string, limit int) (core.KindPage, error)
- func (s *Service) KindItemsByID(ctx context.Context, pluginID, kindKey string, externalIDs []string) ([]core.KindItem, error)
- func (s *Service) KindUpsert(ctx context.Context, pluginID, kindKey string, items []core.KindItem) (int, error)
- func (s *Service) KindUpsertWithStats(ctx context.Context, pluginID, kindKey string, items []core.KindItem) (plugins.KindUpsertResult, error)
- func (s *Service) LibraryPolicy(ctx context.Context, lib core.Library) (*libraryfilter.Filter, error)
- func (s *Service) LibraryTally(ctx context.Context, libraryID core.LibraryID) (map[string]int, error)
- func (s *Service) ListKinds(ctx context.Context, pluginID string) ([]KindRecord, error)
- func (s *Service) ListMatches(ctx context.Context, itemRef core.ItemRef) ([]MatchRecord, error)
- func (s *Service) ListParts(ctx context.Context, itemRef core.ItemRef) ([]StoredPart, error)
- func (s *Service) LookupPersonFacetByName(ctx context.Context, libraryID core.LibraryID, field, name string) (personID int64, canonicalName string, ok bool, err error)
- func (s *Service) LookupPersonFacetsByID(ctx context.Context, libraryID core.LibraryID, fields []string, personID int64) ([]PersonFacetMatch, error)
- func (s *Service) MarkFacetExpansionRunning(ctx context.Context, pluginID, kindKey string, libraryID core.LibraryID, ...) error
- func (s *Service) MatchItem(ctx context.Context, caller Caller, matcherPluginID, kindKey string, ...) ([]core.KindMatchScore, error)
- func (s *Service) MaxItemsFor(pluginID string) int
- func (s *Service) Now() time.Time
- func (s *Service) PersonByID(ctx context.Context, libraryID core.LibraryID, policy *libraryfilter.Filter, ...) (PersonMatch, bool, error)
- func (s *Service) PinItem(ctx context.Context, ref core.ItemRef) error
- func (s *Service) PinItemAsync(ref core.ItemRef)
- func (s *Service) PinMatch(ctx context.Context, itemRef core.ItemRef, candidateRef string, ...) error
- func (s *Service) PluginItemCount(ctx context.Context, pluginID string) (int, error)
- func (s *Service) PreviewVisibility(ctx context.Context, lib core.LibraryID, specs []core.LibraryExclusion, ...) (any, error)
- func (s *Service) PurgeKind(ctx context.Context, pluginID, kindKey string) error
- func (s *Service) PurgePlugin(ctx context.Context, pluginID string) error
- func (s *Service) SaveMatches(ctx context.Context, itemRef core.ItemRef, source string, ...) error
- func (s *Service) SaveNegativePartResolution(ctx context.Context, ref core.ItemRef, partIdx *int) error
- func (s *Service) SaveNegativeResolution(ctx context.Context, ref core.ItemRef) error
- func (s *Service) SavePartCandidates(ctx context.Context, ref core.ItemRef, partIdx *int, ...) error
- func (s *Service) SavePartResolution(ctx context.Context, ref core.ItemRef, partIdx *int, src core.PlayableSource) error
- func (s *Service) SaveParts(ctx context.Context, itemRef core.ItemRef, parts []core.KindItemPart, ...) ([]StoredPart, error)
- func (s *Service) SaveResolution(ctx context.Context, ref core.ItemRef, src core.PlayableSource) error
- func (s *Service) Search(ctx context.Context, q SearchQuery) (BrowsePage, error)
- func (s *Service) SearchPeople(ctx context.Context, libraryID core.LibraryID, policy *libraryfilter.Filter, ...) ([]PersonMatch, error)
- func (s *Service) SetCaller(c Caller)
- func (s *Service) SetHealth(h HealthReporter)
- func (s *Service) SetJobTracker(t SyncJobTracker)
- func (s *Service) SetOnSyncEvent(fn func(SyncEvent))
- func (s *Service) StartKindSync(parentCtx context.Context, pluginID, kindKey string, interval time.Duration)
- func (s *Service) StartManualSync(pluginID, kindKey string, opts SyncOptions) (<-chan SyncRunResult, bool)
- func (s *Service) StopKindSync(pluginID, kindKey string)
- func (s *Service) StopPluginSync(pluginID string)
- func (s *Service) SyncGeneration() uint64
- func (s *Service) SyncKind(ctx context.Context, pluginID, kindKey string, opts SyncOptions) (SyncResult, error)
- func (s *Service) SyncStateOf(ctx context.Context, pluginID, kindKey string) (SyncState, error)
- func (s *Service) UpsertItems(ctx context.Context, pluginID, kindKey string, items []core.KindItem) (int, error)
- func (s *Service) UpsertItemsWithAdded(ctx context.Context, pluginID, kindKey string, items []core.KindItem) (int, int, error)
- func (s *Service) UpsertItemsWithStats(ctx context.Context, pluginID, kindKey string, items []core.KindItem) (UpsertStats, error)
- func (s *Service) UpsertKind(ctx context.Context, pluginID string, libraryID core.LibraryID, ...) (KindRecord, error)
- func (s *Service) UpsertPinnedItems(ctx context.Context, pluginID, kindKey string, items []core.KindItem) (int, error)
- func (s *Service) UpsertPinnedItemsWithAdded(ctx context.Context, pluginID, kindKey string, items []core.KindItem) (int, int, error)
- type StoredPart
- type SyncDeleteGuard
- type SyncEvent
- type SyncJobHandle
- type SyncJobTracker
- type SyncOptions
- type SyncOutcome
- type SyncResult
- type SyncRunResult
- type SyncState
- type TextResolver
- type UpsertStats
- type ValidatedItem
Constants ¶
const ( ExpansionStateRunning = "running" ExpansionStateDone = "done" ExpansionStateError = "error" )
const ( DefaultMaxPluginItems = plugins.DefaultMaxPluginItems MaxTitleRunes = 500 MaxSummaryRunes = 20_000 MaxFieldRunes = 4_000 MaxPersonThumbBytes = 2_048 MaxArtRoles = plugins.MaxKindArtRoles MaxHintsBytes = plugins.MaxKindHintsBytes MaxFTSTextBytes = 8 << 10 DefaultBrowseLimit = 200 MaxBrowseLimit = 1000 // MaxBrowseFacetValues bounds the total facet values across the // any/all/none facet maps of one browse or search query, so the // generated indexed predicates stay bounded. MaxBrowseFacetValues = 256 MaxBrowseBodyBytes = 8 << 20 MaxSyncConcurrency = 4 DeleteGuardRatio = 0.5 )
Store and item validation caps (spec §2.4, §3.2, §3.3, §3.5, §10).
const ( ResolutionCacheMaxTTL = 15 * time.Minute ResolutionNegativeCacheTTL = 60 * time.Second )
ResolutionCacheMaxTTL is the maximum positive cache window for a resolved PlayableSource (spec §4.4: min(expiresAt, now+15m)).
const ( DefaultWalkPageLimit = 200 DefaultChangesLimit = 500 MaxUpsertBatch = plugins.MaxKindUpsertItems )
const DefaultMatchThreshold = 0.85
DefaultMatchThreshold is the default confidence score at or above which an automatic match is accepted as chosen when no manual pin exists (spec §7.2).
Variables ¶
var ( // ErrMaxItemsExceeded is returned when an upsert would push a plugin // past its total item cap across kinds (spec §2.4). ErrMaxItemsExceeded = fmt.Errorf("%w: plugin item cap exceeded", plugins.ErrQuotaExceeded) // ErrInvalidItem is returned when an item fails envelope or field validation. ErrInvalidItem = errors.New("pluginitems: invalid item") // ErrDeleteGuard is returned when a sync walk or changes batch would // delete more than 50% of a library's items (spec §3.5). ErrDeleteGuard = errors.New("pluginitems: sync aborted by 50% delete guard") )
Functions ¶
func EffectiveCard ¶
func EffectiveCard(cardShape string, decl plugins.KindLibraryDecl) string
EffectiveCard resolves a plugin library's card shape: the owner's CardShape choice first, then the plugin's declared library.card ("poster" by default).
func FoldFieldText ¶
FoldFieldText returns space-separated folded words for v_fold indexing on plugin_item_fields.
func FoldSortTitle ¶
FoldSortTitle normalizes an explicit sort title to lowercase with Latin diacritics and ligatures folded to base ASCII letters and numeric collation.
func Project ¶
func Project(item core.KindItem, decl plugins.MediaKindMeta, present core.Presentations, cardShape ...string) core.Title
Project maps a plugin KindItem into a core.Title for legacy Plex/Jellyfin/Emby frontends per §6.3.
Mapping rules:
- Title.Key = item.Key (a PluginKey(seq))
- Title.Type:
- Single-level playable kind -> TypeMovie
- 2-level hierarchy (e.g. channel -> video) -> root = TypeShow, leaf = TypeEpisode
- 3-level hierarchy (e.g. series -> season -> episode) -> TypeShow / TypeSeason / TypeEpisode
- Title.Title = item.Title
- Title.SortTitle = SortTitle(item.Title) or FoldSortTitle(item.SortTitle)
- Title.Summary = item.Summary + formatted declared non-empty fields at the end
- Title.Year = item.Year
- Title.Released = time.Unix(item.Released, 0)
- Title.Runtime = duration field (e.g. "duration" / "runtime") when present
- Title.Genres = item.Fields["genre"/"genres"/"tags"] + facet fields
- Title.PosterPath = art["poster"] (falling back to art["thumb"])
- Title.BackdropPath = art["backdrop"]
- Title.StillPath = art["thumb"] (for episode-like items)
- Title.LogoPath = art["logo"]
Any "$t:" field labels without a text resolver fall back to the field key so unresolved i18n tokens are never emitted.
func ProjectWithText ¶
func ProjectWithText(item core.KindItem, decl plugins.MediaKindMeta, present core.Presentations, resolve TextResolver, cardShape ...string) core.Title
ProjectWithText behaves like Project and resolves "$t:" field labels through resolve (falling back to the field key when unresolved).
func ResolveMediaClassAndRole ¶
func ResolveMediaClassAndRole(level string, decl plugins.MediaKindMeta, present core.Presentations) (core.MediaClass, core.MediaRole)
ResolveMediaClassAndRole derives the effective MediaClass and per-level MediaRole for a declared kind and level via libraries.ResolveKindPresentations.
func RuleFields ¶
func RuleFields(decl plugins.MediaKindMeta) map[string]string
RuleFields exposes only rule facts backed by indexed storage.
func SeriesFacetField ¶
func SeriesFacetField(decl plugins.MediaKindMeta) string
SeriesFacetField returns the declared string/string[] field key that acts as a series facet for decl (such as "series" on 1-level book/audiobook kinds), or "" when the kind declares no such facet.
func SortTitle ¶
SortTitle derives the normalized lowercase sort key for a display title, matching catalog.SortTitle rules (spec §3.2): strips invisible format characters, ignores leading non-alphanumerics, removes a leading English article ("the ", "a ", "an "), folds Latin accents/diacritics and ligatures to base ASCII letters, and applies numeric collation.
Types ¶
type BrowsePage ¶
type BrowsePage struct {
Items []core.KindItem `json:"items"`
Total int `json:"total"`
TotalExact bool `json:"-"`
NextCursor string `json:"nextCursor,omitempty"`
}
BrowsePage is a keyset page of plugin items.
type BrowseQuery ¶
type BrowseQuery struct {
// NoTotal avoids count queries for clients using cursor continuation.
NoTotal bool
// CheapTotal, when combined with NoTotal, still populates Total (and sets
// BrowsePage.TotalExact) when the exact count is available cheaply from
// plugin_item_tally or a single-parent child count, without scanning the
// whole library.
CheapTotal bool
Policy *libraryfilter.Filter
TabPolicy *libraryfilter.Filter
ViewerID int64
Hidden bool
LibraryID core.LibraryID
ParentRef core.ItemRef
Level string
Levels []string
AnyLevel bool
PersonID int64
Sort string // title (default), added, released, year, rating, index, lastViewed
Desc bool // false = default direction for Sort; true = reverse
Facets map[string][]string // field key -> values, any of (OR within key, AND across keys)
// AllFacets requires every listed value per field; ExcludeFacets
// drops items having any listed value. Both combine with Facets
// using AND and the same per-type value handling.
AllFacets map[string][]string
ExcludeFacets map[string][]string
// Watched filters on the viewer's watch state in SQL (ViewerID):
// true keeps items with a state_watch view_count > 0, false keeps
// items without one. Nil applies no watched predicate.
Watched *bool
// MaxContentRating caps items at this content-rating enforcement
// level in SQL (persisted rating_level). Unrated items never pass a
// cap, matching contentrating.EnforceExceeds. Empty is uncapped.
MaxContentRating string
// ExcludeKeys drops these plugin items by RatingKey. Callers bound
// the list; non-plugin keys are ignored.
ExcludeKeys []core.RatingKey
Cursor string // opaque keyset cursor
Limit int
}
BrowseQuery specifies a keyset-paged browse over a plugin library and level (spec §2.3, §3.4).
type Caller ¶
type Caller interface {
Call(ctx context.Context, pluginID string, req plugins.Request) (plugins.Response, error)
}
Caller invokes one plugin route (satisfied by *plugins.Manager).
type DeleteGuardError ¶
type DeleteGuardError struct {
PluginID string
KindKey string
Source string
Missing int
Total int
Protected int
}
DeleteGuardError wraps ErrDeleteGuard with exact counts so callers and the console API never have to parse an error string to build the owner choice.
func (*DeleteGuardError) Error ¶
func (e *DeleteGuardError) Error() string
func (*DeleteGuardError) PlainMessage ¶
func (e *DeleteGuardError) PlainMessage() string
func (*DeleteGuardError) State ¶
func (e *DeleteGuardError) State() SyncDeleteGuard
func (*DeleteGuardError) Unwrap ¶
func (e *DeleteGuardError) Unwrap() error
type FacetBucket ¶
type FacetBucket struct {
ID string `json:"id"`
Label string `json:"label"`
Count int `json:"count"`
}
FacetBucket is one discrete facet bucket (id, label, count) for browse UIs.
type FacetCollection ¶
type FacetCollection struct {
ID string `json:"id"`
Label string `json:"label"`
Count int `json:"count"`
NewestItem *core.KindItem `json:"-"`
}
FacetCollection is one facet-backed collection bucket with its newest item.
type FacetCollectionsPage ¶
type FacetCollectionsPage struct {
Items []FacetCollection
More bool
}
FacetCollectionsPage is a single page of facet collections.
type FacetCollectionsQuery ¶
type FacetCollectionsQuery struct {
LibraryID core.LibraryID
Level string
Policy *libraryfilter.Filter
FieldKey string
Order string // "count" (default) | "name"
Query string
Offset int
Limit int
}
FacetCollectionsQuery requests a single page of facet-backed collections ordered by item count (default) or bucket name, hydrating artwork only for the newest item of each bucket on the page in one batched query.
type FacetCount ¶
FacetCount is a single facet value and item count.
type FacetExpansion ¶
type FacetExpansion struct {
PluginID string
KindKey string
LibraryID core.LibraryID
Facet string
ValueKey string
State string
StartedAt time.Time
FinishedAt time.Time
ItemsAdded int64
Error string
}
FacetExpansion is one durable row in plugin_facet_expansions recording the latest on-demand expansion of a (plugin, kind, facet, value) slice.
type FacetPage ¶
type FacetPage struct {
Values []FacetCount `json:"values"`
Truncated bool `json:"truncated,omitempty"`
}
FacetPage is one field's filter values in display order. Truncated means the field has more distinct values than the limit returned.
type FacetPeoplePage ¶
type FacetPeoplePage struct {
Items []FacetPerson
Total int
More bool
}
FacetPeoplePage is one page of people for a library people tab.
type FacetPeopleQuery ¶
type FacetPeopleQuery struct {
LibraryID core.LibraryID
Level string
Policy *libraryfilter.Filter
FieldKey string
Order string // "name" (default) | "count"
Query string
Offset int
Limit int
}
FacetPeopleQuery requests a single page of distinct people from one declared type:"people" field at a library's root level, ordered by name (default) or item count, with sample items resolved in a single batched query for the page.
type FacetPerson ¶
type FacetPerson struct {
PersonID int64
Name string
Count int
Thumb string
SampleItem *core.KindItem
}
FacetPerson is one distinct person entry for a people tab, with item count and a sample credited item for headshot authorization.
type HealthReporter ¶
HealthReporter records plugin health issues discovered by sync or item validation (satisfied by *plugins.Manager via RecordFailure, or custom hooks).
type IndexedFieldValue ¶
IndexedFieldValue is one typed EAV row for plugin_item_fields (spec §2.3).
type KindRecord ¶
type KindRecord struct {
PluginID string
KindKey string
LibraryID core.LibraryID
Decl plugins.MediaKindMeta
DeclHash string
SchemaVersion int64
}
KindRecord is one installed (plugin, kind) row in plugin_kinds (spec §2.3).
type MatchRecord ¶
type MatchRecord struct {
ItemRef core.ItemRef `json:"itemRef"`
CandidateRef string `json:"candidateRef"`
Score float64 `json:"score"`
Reasons []string `json:"reasons,omitempty"`
Source string `json:"source"` // "auto" | "manual" | pluginID
Chosen bool `json:"chosen"`
UpdatedAt int64 `json:"updatedAt"`
}
MatchRecord is a persisted cross-kind match row in plugin_matches (spec §2.3, §7).
type Options ¶
type Options struct {
Logger *slog.Logger
Now func() time.Time
Caller Caller
Health HealthReporter
Jobs SyncJobTracker
IsLeader func() bool
MaxPluginItems int
// MaxPluginItemsFor returns the live owner-configured stored-item ceiling
// for pluginID when set, overriding MaxPluginItems.
MaxPluginItemsFor func(pluginID string) int
// OnAttention is an optional hook notified when a sync guard or
// contract error flags a plugin for owner attention (e.g. 50%-delete
// guard, unknown fields dropped, auth required).
OnAttention func(ctx context.Context, pluginID, reason string)
// OnSyncEvent is an optional non-blocking observer for plugin library sync lifecycle.
OnSyncEvent func(SyncEvent)
}
Options configures the pluginitems Service.
type PersonFacetMatch ¶
PersonFacetMatch identifies one (field, display name) credit for a synthetic plugin person ID within a library.
type PersonMatch ¶
type PersonMatch struct {
ID int64
Name string
CreditCount int
Thumb string
SampleItem core.KindItem
Roles map[string]int
Items []core.KindItem
}
PersonMatch describes a credited person and their visible plugin items within a single plugin library.
type SearchQuery ¶
type SearchQuery struct {
// NoTotal skips exact full-text COUNT(*) scans when total is not needed.
NoTotal bool
// CheapTotal, paired with NoTotal, still populates TotalExact when the
// result fits on one page or is already cached for the current generation.
CheapTotal bool
Policy *libraryfilter.Filter
TabPolicy *libraryfilter.Filter
ViewerID int64
Hidden bool
LibraryID core.LibraryID
Query string
Level string
Levels []string
PersonID int64
Facets map[string][]string
// AllFacets requires every listed value per field; ExcludeFacets
// drops items having any listed value (see BrowseQuery).
AllFacets map[string][]string
ExcludeFacets map[string][]string
Limit int
}
SearchQuery scopes a full-text search to a single library (spec §2.3, §3.4).
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service manages plugin kinds, items, browse, search, sync, projections, matches and resolutions.
func (*Service) BestMatch ¶
func (s *Service) BestMatch(ctx context.Context, itemRef core.ItemRef, threshold float64) (MatchRecord, bool, error)
BestMatch returns the active match for itemRef: either a chosen/manual pin or the highest-scoring automated match with score >= threshold (spec §7.2).
func (*Service) Browse ¶
func (s *Service) Browse(ctx context.Context, q BrowseQuery) (BrowsePage, error)
Browse returns a keyset-paged slice of items in a library (spec §2.3, §3.4). Unfiltered totals are read from plugin_item_tally in O(1); filtered or child-scoped totals execute an exact COUNT(*) with the same WHERE clauses, so a filtered total is never a capped count presented as the total.
func (*Service) BumpGeneration ¶
BumpGeneration increments and returns the monotonic sync generation so cached frontend ETag/revision scopes observe completed background expansions even when zero new items were added.
func (*Service) CancelKindSync ¶
CancelKindSync cancels any running background sync worker for (pluginID, kindKey) without blocking the caller on an in-flight network or plugin call. Subsequent StartKindSync, StopKindSync, PurgeKind, or Close calls still wait for the cancelled worker to exit.
func (*Service) Children ¶
func (s *Service) Children(ctx context.Context, parentRef core.ItemRef, cursor string, limit int) (BrowsePage, error)
Children returns the direct children of parentRef ordered by (idx ASC, sort_title ASC, item_ref ASC).
func (*Service) ChildrenCountAndFreshness ¶
func (s *Service) ChildrenCountAndFreshness(ctx context.Context, libraryID core.LibraryID, parentRef core.ItemRef) (int, time.Time, error)
ChildrenCountAndFreshness returns the stored direct child count and newest seen/updated timestamp for parentRef using the (library_id, parent_ref) index. Used to detect partially populated containers whose ChildCount exceeds the currently stored children.
func (*Service) ChildrenFreshness ¶
func (s *Service) ChildrenFreshness(ctx context.Context, libraryID core.LibraryID, parentRef core.ItemRef) (bool, time.Time, error)
ChildrenFreshness checks in O(1) via the (library_id, parent_ref) index whether parentRef currently has at least one stored child row and returns a sample freshness timestamp (the newer of seen_at and updated_at).
func (*Service) ClearManualMatch ¶
ClearManualMatch removes manual pin rows for itemRef.
func (*Service) Close ¶
func (s *Service) Close()
Close stops all background sync workers, reindexers, and planner statistics refreshes.
func (*Service) CompilePolicy ¶
func (s *Service) CompilePolicy(ctx context.Context, lib core.LibraryID, specs []core.LibraryExclusion, fallback string) (*libraryfilter.Filter, error)
CompilePolicy resolves the declaration for this library before validating rules.
func (*Service) CountKindItems ¶
CountKindItems returns the stored item count for (pluginID, kindKey).
func (*Service) CountPartsMany ¶
func (s *Service) CountPartsMany(ctx context.Context, refs []core.ItemRef) (map[core.ItemRef]int, error)
CountPartsMany returns the count of persisted parts for each ref in refs.
func (*Service) DeleteItems ¶
func (s *Service) DeleteItems(ctx context.Context, pluginID, kindKey string, externalIDs []string) error
DeleteItems deletes the named externalIDs (and any descendant items) from (pluginID, kindKey), maintaining tallies, FTS, matches and resolutions.
func (*Service) EnsurePartsFromHints ¶
func (s *Service) EnsurePartsFromHints(ctx context.Context, item core.KindItem) ([]StoredPart, error)
EnsurePartsFromHints returns persisted parts for item (from /resolve or prior hint materialisation), materialising item's declared hints.parts / fields.parts into plugin_item_parts when none have been stored yet.
func (*Service) FacetBuckets ¶
func (s *Service) FacetBuckets(ctx context.Context, libraryID core.LibraryID, level string, policy *libraryfilter.Filter, fieldKey string) ([]FacetBucket, error)
FacetBuckets returns discrete filter buckets for a declared or envelope facet field on libraryID, respecting library visibility policy:
- date (and envelope released): UTC years ("2024"), newest year first
- <date>-decade (and envelope decade): UTC decades ("1990" / "1990s"), newest first
- duration: discrete duration ranges ("Under 10 min", ...), omitting empty
- int (and envelope year): distinct values when <= 50, else clean ranges
- float (and envelope rating): distinct values when <= 50, else clean ranges
- enum: declared order
- string, strings, bool, people: alphabetical order
func (*Service) FacetCollections ¶
func (s *Service) FacetCollections(ctx context.Context, q FacetCollectionsQuery) (FacetCollectionsPage, error)
FacetCollections returns one page of facet buckets ordered most-items-first (default) or alphabetically by name (Order: "name"), resolving the newest visible item + artwork across the whole page in one batched lookup.
func (*Service) FacetPeople ¶
func (s *Service) FacetPeople(ctx context.Context, q FacetPeopleQuery) (FacetPeoplePage, error)
FacetPeople lists distinct people in a declared people-type field at the library's root level, grouped by synthetic plugin person ID (v_int), with label from v_text and item count, ordered by name (case-insensitive, default) or count, and resolves sample items for headshots in a single batched query.
func (*Service) Facets ¶
func (s *Service) Facets(ctx context.Context, libraryID core.LibraryID, level, fieldKey string, limit int) (FacetPage, error)
Facets lists a field's values. The query keeps the most common values when a field has more than limit; the page is then ordered for reading: an enum in its declared order, text values alphabetically, numbers by count.
func (*Service) FilterVisibleIDs ¶
func (s *Service) FilterVisibleIDs(ctx context.Context, pluginID, kindKey string, lib core.Library, externalIDs []string) ([]string, error)
FilterVisibleIDs evaluates lib's visibility policy for externalIDs belonging to (pluginID, kindKey) in bounded SQL chunks, returning the subset of stored external IDs allowed by lib's LibraryPolicy in deduplicated input order. Unknown or syntactically invalid IDs are omitted even when the policy is passive so behavior stays identical whether or not Rules are configured.
func (*Service) FilterVisibleRefs ¶
func (s *Service) FilterVisibleRefs(ctx context.Context, lib core.Library, refs []core.ItemRef) (map[core.ItemRef]bool, error)
FilterVisibleRefs evaluates lib's visibility policy for refs in one batched SQL query per chunk, returning the subset of refs that are NOT hidden.
func (*Service) FindPersonID ¶
func (s *Service) FindPersonID(ctx context.Context, libraryID core.LibraryID, policy *libraryfilter.Filter, match func(personID int64, name string) bool) (int64, bool, error)
FindPersonID scans distinct indexed person IDs in libraryID and returns the first ID satisfying match. Used when resolving opaque person facet hashes on a cold server before the person has been browsed.
func (*Service) FinishFacetExpansion ¶
func (s *Service) FinishFacetExpansion(ctx context.Context, pluginID, kindKey string, libraryID core.LibraryID, facet, valueKey, state string, itemsAdded int, errMsg string) error
FinishFacetExpansion records completion or failure of a background facet expansion in plugin_facet_expansions.
func (*Service) Generation ¶
Generation returns the monotonic sync generation across all plugin kinds (spec §3.5, §6.4: feeds frontend.PageFreshness.KindSync).
func (*Service) GetByExternal ¶
func (s *Service) GetByExternal(ctx context.Context, pluginID, kindKey, externalID string) (core.KindItem, core.LibraryID, error)
GetByExternal returns one stored KindItem and its LibraryID by (pluginID, kindKey, externalID).
func (*Service) GetByKey ¶
func (s *Service) GetByKey(ctx context.Context, key core.RatingKey) (core.KindItem, core.LibraryID, error)
GetByKey returns one stored KindItem and its LibraryID by its PluginKey RatingKey.
func (*Service) GetByKeys ¶
func (s *Service) GetByKeys(ctx context.Context, keys []core.RatingKey) (map[core.RatingKey]KeyedItem, error)
GetByKeys fetches stored KindItems and their hydrated artwork in bounded SQL batches rather than issuing one query per key.
func (*Service) GetByRef ¶
func (s *Service) GetByRef(ctx context.Context, ref core.ItemRef) (core.KindItem, core.LibraryID, error)
GetByRef returns one stored KindItem and its LibraryID by ItemRef.
func (*Service) GetFacetExpansion ¶
func (s *Service) GetFacetExpansion(ctx context.Context, pluginID, kindKey, facet, valueKey string) (FacetExpansion, bool, error)
GetFacetExpansion looks up the durable expansion record for (pluginID, kindKey, facet, valueKey).
func (*Service) GetKindByLibrary ¶
func (s *Service) GetKindByLibrary(ctx context.Context, libraryID core.LibraryID) (KindRecord, error)
GetKindByLibrary returns the installed KindRecord for libraryID.
func (*Service) GetPartByKey ¶
func (s *Service) GetPartByKey(ctx context.Context, key core.RatingKey) (StoredPart, core.KindItem, core.LibraryID, error)
GetPartByKey resolves a plugin RatingKey belonging to plugin_item_parts back to the StoredPart and its owning parent KindItem + LibraryID.
func (*Service) GetPartCandidates ¶
func (s *Service) GetPartCandidates(ctx context.Context, ref core.ItemRef, partIdx *int) ([]core.PlayableSource, bool, error)
GetPartCandidates looks up a non-expired cached /resolve candidate list for ref and optional partIdx. If a negative cache entry is active, it returns (nil, true, core.ErrNotAvailable).
func (*Service) GetPartResolution ¶
func (s *Service) GetPartResolution(ctx context.Context, ref core.ItemRef, partIdx *int) (core.PlayableSource, bool, error)
GetPartResolution looks up a non-expired cached resolution for ref and optional partIdx (spec §4.4, #576).
func (*Service) GetPartsByKeys ¶
func (s *Service) GetPartsByKeys(ctx context.Context, keys []core.RatingKey) (map[core.RatingKey]StoredPart, error)
GetPartsByKeys batch-resolves plugin RatingKeys belonging to plugin_item_parts.
func (*Service) GetResolution ¶
func (s *Service) GetResolution(ctx context.Context, ref core.ItemRef) (core.PlayableSource, bool, error)
GetResolution looks up a non-expired cached resolution for ref (spec §4.4). If a negative cache entry is active, it returns (zero, true, core.ErrNotAvailable).
func (*Service) InvalidatePartResolution ¶
func (s *Service) InvalidatePartResolution(ctx context.Context, ref core.ItemRef, partIdx *int) error
InvalidatePartResolution deletes a single part's cached resolution when partIdx is non-nil, or invalidates the whole item (and its parts) when nil.
func (*Service) InvalidateResolution ¶
InvalidateResolution deletes cached whole-item and per-part resolutions for ref, e.g. on a mid-stream upstream failure (spec §4.4, #576).
func (*Service) IsSyncRunning ¶
IsSyncRunning reports whether a sync or reindex pass is active for (pluginID, kindKey).
func (*Service) ItemHidden ¶
func (*Service) KeepExistingItems ¶
func (s *Service) KeepExistingItems(ctx context.Context, pluginID, kindKey string) (SyncState, error)
KeepExistingItems acknowledges a paused 50%-delete guard without removing any stored items: it clears the persisted guard/error state and resets missed_walks so existing items remain intact.
func (*Service) KindBackends ¶
func (s *Service) KindBackends() plugins.KindBackends
KindBackends returns a plugins.KindBackends struct with KindUpsert, KindDelete, KindItems, KindItemsByID and KindItemCount wired to this store (spec §3.6, §12 slice C).
func (*Service) KindDelete ¶
func (s *Service) KindDelete(ctx context.Context, pluginID, kindKey string, externalIDs []string) error
KindDelete implements the store side of plugins.KindBackends.KindDelete (spec §3.6).
func (*Service) KindItems ¶
func (s *Service) KindItems(ctx context.Context, pluginID, kindKey, cursor string, limit int) (core.KindPage, error)
KindItems implements the store side of plugins.KindBackends.KindItems (spec §3.6): reads the plugin's own library back, keyset-paged across all levels by external_id.
func (*Service) KindItemsByID ¶
func (s *Service) KindItemsByID(ctx context.Context, pluginID, kindKey string, externalIDs []string) ([]core.KindItem, error)
KindItemsByID implements the store side of plugins.KindBackends.KindItemsByID: fetches only the matching stored items for (pluginID, kindKey) by external_id via primary-key lookups on item_ref, hydrating art only for matching rows.
func (*Service) KindUpsert ¶
func (s *Service) KindUpsert(ctx context.Context, pluginID, kindKey string, items []core.KindItem) (int, error)
KindUpsert implements the store side of plugins.KindBackends.KindUpsert (spec §3.6): validates and upserts items into the kind's library, updates tallies and FTS, and bumps the sync generation.
func (*Service) KindUpsertWithStats ¶
func (s *Service) KindUpsertWithStats(ctx context.Context, pluginID, kindKey string, items []core.KindItem) (plugins.KindUpsertResult, error)
KindUpsertWithStats is KindUpsert reporting what the batch did, for the host wire reply (#646).
func (*Service) LibraryPolicy ¶
func (*Service) LibraryTally ¶
func (*Service) ListKinds ¶
ListKinds returns all installed kinds for pluginID (or all plugins when pluginID == "").
func (*Service) ListMatches ¶
ListMatches returns all stored match candidates for itemRef, ordered with chosen / manual pins first, then descending score.
func (*Service) ListParts ¶
ListParts returns all persisted parts for itemRef ordered by part_index.
func (*Service) LookupPersonFacetByName ¶
func (s *Service) LookupPersonFacetByName(ctx context.Context, libraryID core.LibraryID, field, name string) (personID int64, canonicalName string, ok bool, err error)
LookupPersonFacetByName resolves a people-field bucket label within libraryID to its synthetic plugin person ID and canonical display name when present.
func (*Service) LookupPersonFacetsByID ¶
func (s *Service) LookupPersonFacetsByID(ctx context.Context, libraryID core.LibraryID, fields []string, personID int64) ([]PersonFacetMatch, error)
LookupPersonFacetsByID returns the distinct (field, name) pairs among fields crediting personID in libraryID.
func (*Service) MarkFacetExpansionRunning ¶
func (s *Service) MarkFacetExpansionRunning(ctx context.Context, pluginID, kindKey string, libraryID core.LibraryID, facet, valueKey string) error
MarkFacetExpansionRunning upserts a running expansion record for (pluginID, kindKey, facet, valueKey).
func (*Service) MatchItem ¶
func (s *Service) MatchItem(ctx context.Context, caller Caller, matcherPluginID, kindKey string, item core.KindItem, candidates []core.SourceCandidate, settings map[string]any, threshold float64) ([]core.KindMatchScore, error)
MatchItem invokes a matcher plugin's POST /ether/v1/kinds/{kind}/match route for an item against candidate releases and persists the resulting scores in plugin_matches (spec §7).
func (*Service) MaxItemsFor ¶
MaxItemsFor returns the effective stored-item cap across all libraries owned by pluginID, consulting MaxPluginItemsFor when wired.
func (*Service) PersonByID ¶
func (s *Service) PersonByID(ctx context.Context, libraryID core.LibraryID, policy *libraryfilter.Filter, personID int64, itemLimit int) (PersonMatch, bool, error)
PersonByID resolves a single plugin person by synthetic personID within libraryID.
func (*Service) PinItem ¶
PinItem marks one stored plugin item as pinned so missed-walk pruning never removes it simply because a subsequent /browse walk omitted it.
func (*Service) PinItemAsync ¶
PinItemAsync records that a viewer opened or resolved ref, persisting pinned=1 on a single background worker with zero read-path latency.
func (*Service) PinMatch ¶
func (s *Service) PinMatch(ctx context.Context, itemRef core.ItemRef, candidateRef string, reasons []string) error
PinMatch sets a manual match override (source='manual', chosen=1, score=1.0) for itemRef and clears chosen on any other candidates for itemRef (spec §7.2).
func (*Service) PluginItemCount ¶
LibraryTally returns the maintained per-level item counts for libraryID from plugin_item_tally (spec §2.3, §3.4). PluginItemCount returns the total stored item count across all libraries owned by pluginID, read in O(1) from plugin_item_tally.
func (*Service) PreviewVisibility ¶
func (s *Service) PreviewVisibility(ctx context.Context, lib core.LibraryID, specs []core.LibraryExclusion, fallback string) (any, error)
PreviewVisibility aggregates in the indexed item store and fetches at most twelve examples per side. It never projects or loads the whole library.
func (*Service) PurgeKind ¶
PurgeKind removes all items, fields, art, tallies, matches, resolutions, sync state and kind registration for one (pluginID, kindKey) (spec §2.5).
func (*Service) PurgePlugin ¶
PurgePlugin is the idempotent removal sequence for all kinds owned by pluginID (spec §2.5): stops sync goroutines, deletes watch-state rows for the plugin's RatingKeys, and purges items, fields, art, FTS, tallies, matches, resolutions, sync state and plugin_kinds rows.
func (*Service) SaveMatches ¶
func (s *Service) SaveMatches(ctx context.Context, itemRef core.ItemRef, source string, scores []core.KindMatchScore, threshold float64) error
SaveMatches persists automated match scores for itemRef from source (e.g. "auto" or matcherPluginID). Rows with source='manual' or a manual pin on itemRef are never overwritten by automated matcher runs (spec §7.2).
func (*Service) SaveNegativePartResolution ¶
func (s *Service) SaveNegativePartResolution(ctx context.Context, ref core.ItemRef, partIdx *int) error
SaveNegativePartResolution caches a not_available resolution result for ref and optional partIdx for 60s (spec §4.4, #576).
func (*Service) SaveNegativeResolution ¶
SaveNegativeResolution caches a not_available resolution result for 60s so a dead kind cannot stampede the plugin (spec §4.4).
func (*Service) SavePartCandidates ¶
func (s *Service) SavePartCandidates(ctx context.Context, ref core.ItemRef, partIdx *int, sources []core.PlayableSource) error
SavePartCandidates caches the full ordered list of PlayableSources returned by a plugin's /resolve for ref and optional partIdx until min(min(src.ExpiresAt), now+15m). An existing winning source in the row is preserved while still positive.
func (*Service) SavePartResolution ¶
func (s *Service) SavePartResolution(ctx context.Context, ref core.ItemRef, partIdx *int, src core.PlayableSource) error
SavePartResolution caches a successful PlayableSource for ref and optional zero-based partIdx until min(src.ExpiresAt, now+15m) (spec §4.4, #576).
func (*Service) SaveParts ¶
func (s *Service) SaveParts(ctx context.Context, itemRef core.ItemRef, parts []core.KindItemPart, source string) ([]StoredPart, error)
SaveParts upserts ordered parts for itemRef, preserving existing seq values per part_index so RatingKeys and watch/resume progress remain stable across re-resolves, allocating fresh sequence numbers from plugin_items_seq only for newly added part indices, and pruning stale indices >= len(parts).
func (*Service) SaveResolution ¶
func (s *Service) SaveResolution(ctx context.Context, ref core.ItemRef, src core.PlayableSource) error
SaveResolution caches a successful PlayableSource for ref until min(src.ExpiresAt, now+15m) (spec §4.4).
func (*Service) Search ¶
func (s *Service) Search(ctx context.Context, q SearchQuery) (BrowsePage, error)
Search executes a library-scoped full-text search over plugin items (SQLite FTS5 or PostgreSQL tsvector, spec §2.3, §3.4, §10).
func (*Service) SearchPeople ¶
func (s *Service) SearchPeople(ctx context.Context, libraryID core.LibraryID, policy *libraryfilter.Filter, query string, personLimit, itemLimit int) ([]PersonMatch, error)
SearchPeople finds people credited in any declared type:"people" field of libraryID whose name word-prefixes match query, returning up to personLimit people and up to itemLimit visible items per matched person.
func (*Service) SetHealth ¶
func (s *Service) SetHealth(h HealthReporter)
SetHealth sets or replaces the health reporter after construction.
func (*Service) SetJobTracker ¶
func (s *Service) SetJobTracker(t SyncJobTracker)
SetJobTracker installs or replaces the background job tracker used to mirror library sync runs into the plugin's Activity / Background jobs list.
func (*Service) SetOnSyncEvent ¶
SetOnSyncEvent installs an optional observer for plugin library sync lifecycle.
func (*Service) StartKindSync ¶
func (s *Service) StartKindSync(parentCtx context.Context, pluginID, kindKey string, interval time.Duration)
StartKindSync starts (or restarts) a background pull-sync worker for a kind without blocking the caller on an in-flight previous pass. Any superseded worker is cancelled immediately and drained by the new worker goroutine before starting the next pass, preserving strict per-kind serialization.
func (*Service) StartManualSync ¶
func (s *Service) StartManualSync(pluginID, kindKey string, opts SyncOptions) (<-chan SyncRunResult, bool)
StartManualSync launches an owner-started SyncKind on the service's long-lived background context (never tied to an HTTP request) so switching console tabs or proxies timing out never cancel the walk. If a sync is already running for (pluginID, kindKey), alreadyRunning is true.
func (*Service) StopKindSync ¶
StopKindSync stops the background sync and reindex workers for (pluginID, kindKey) and waits for any in-flight pass to exit.
func (*Service) StopPluginSync ¶
StopPluginSync stops all background sync and reindex workers belonging to pluginID.
func (*Service) SyncGeneration ¶
SyncGeneration is an alias for Generation (feeds PageFreshness.KindSync).
func (*Service) SyncKind ¶
func (s *Service) SyncKind(ctx context.Context, pluginID, kindKey string, opts SyncOptions) (SyncResult, error)
SyncKind executes a pull sync for a registered plugin kind (spec §3.5, §4.4).
Sync algorithm:
- Initial sync (when cursor is empty and the store has 0 items for the kind): walks /ether/v1/kinds/{kind}/browse from the root level (parentId="") with limit=200, then breadth-first into child levels with bounded concurrency (4).
- Delta sync (when cursor != "" and storedCount > 0 and !opts.FullWalk): calls POST /ether/v1/kinds/{kind}/changes with {"cursor": cursor, "limit": 500}. If the plugin returns 404/501 (changes not implemented), falls back to re-walk diff. Otherwise chains while complete == false, and records nextCursor in plugin_sync_state.
- Fallback re-walk (when changes is not supported or FullWalk is requested on an already-populated kind): re-walks /browse, diffs by etag (skipping unchanged items), resets missed_walks=0 on seen items, increments missed_walks on unseen items, and deletes items unseen in 2 consecutive complete walks.
- Guardrail: if >50% of existing items in a library would be deleted in a single pass (and the library has at least 2 items) and !opts.Force, the delete is aborted, plugin_sync_state records the error, OnAttention/Health is notified, and ErrDeleteGuard is returned.
func (*Service) SyncStateOf ¶
SyncStateOf returns the current SyncState row for (pluginID, kindKey).
func (*Service) UpsertItems ¶
func (s *Service) UpsertItems(ctx context.Context, pluginID, kindKey string, items []core.KindItem) (int, error)
UpsertItems validates and writes a batch of KindItems for (pluginID, kindKey), maintaining tallies, typed EAV fields, art and FTS. The batch commits in bounded chunks under the per-kind lock (#646).
func (*Service) UpsertItemsWithAdded ¶
func (s *Service) UpsertItemsWithAdded(ctx context.Context, pluginID, kindKey string, items []core.KindItem) (int, int, error)
UpsertItemsWithAdded validates and writes a batch of KindItems for (pluginID, kindKey), returning both accepted items and newly inserted items.
func (*Service) UpsertItemsWithStats ¶
func (s *Service) UpsertItemsWithStats(ctx context.Context, pluginID, kindKey string, items []core.KindItem) (UpsertStats, error)
UpsertItemsWithStats is UpsertItemsWithAdded plus the updated/unchanged split: unchanged items are detected by content hash and not rewritten.
func (*Service) UpsertKind ¶
func (s *Service) UpsertKind(ctx context.Context, pluginID string, libraryID core.LibraryID, decl plugins.MediaKindMeta, replaceContents bool) (KindRecord, error)
UpsertKind installs or upgrades one (plugin, kind) declaration in plugin_kinds (spec §2.3, §2.5). On upgrade, decl_hash is compared against the stored declaration: additive changes bump schema_version; non-additive changes are refused with a ValidationError unless replaceContents is true, in which case existing items for that kind are purged and sync state reset.
func (*Service) UpsertPinnedItems ¶
func (s *Service) UpsertPinnedItems(ctx context.Context, pluginID, kindKey string, items []core.KindItem) (int, error)
UpsertPinnedItems writes items discovered on demand (such as live search results) and pins them so missed-walk pruning does not drop them when a subsequent /browse walk omits them.
func (*Service) UpsertPinnedItemsWithAdded ¶
func (s *Service) UpsertPinnedItemsWithAdded(ctx context.Context, pluginID, kindKey string, items []core.KindItem) (int, int, error)
UpsertPinnedItemsWithAdded writes items discovered on demand (live search or facet/container expansion), pinning them against missed-walk pruning while returning accepted and newly inserted counts.
type StoredPart ¶
type StoredPart struct {
ItemRef core.ItemRef
PartIndex int
Seq int64
Key core.RatingKey
Name string
MIME string
Size int64
DurationSec float64
FileIndex *int
Source string
UpdatedAt int64
}
StoredPart is one persisted ordered part row for a plugin item, carrying a stable sequence number (and therefore RatingKey) shared across watch state and child listings.
func (StoredPart) KindItemPart ¶
func (p StoredPart) KindItemPart() core.KindItemPart
KindItemPart converts StoredPart back to the core wire representation.
type SyncDeleteGuard ¶
type SyncDeleteGuard struct {
Source string `json:"source"` // "walk" or "changes"
Missing int `json:"missing"` // items absent from walk or slated for deletion
Total int `json:"total"` // eligible existing items compared against
Protected int `json:"protected,omitempty"` // opened/played/favourited/searched items excluded from pruning
}
SyncDeleteGuard captures structured details when the 50% delete guard pauses a sync so the console can explain what happened in plain words and offer the owner an explicit keep-or-remove choice.
func ParseDeleteGuardError ¶
func ParseDeleteGuardError(raw string) *SyncDeleteGuard
ParseDeleteGuardError extracts SyncDeleteGuard details from a persisted legacy v0.3.17 last_error string when guard_json has not yet been written.
func (SyncDeleteGuard) PlainMessage ¶
func (g SyncDeleteGuard) PlainMessage() string
PlainMessage returns a plain-language summary of the paused delete guard.
type SyncEvent ¶
type SyncEvent struct {
Phase string // "started", "completed", "failed"
PluginID string
KindKey string
LibraryID int64
LibraryName string
Trigger string
Added int
Updated int
Removed int
DurationMS int64
Error string
}
SyncEvent describes a plugin library sync lifecycle transition.
type SyncJobHandle ¶
type SyncJobHandle interface {
SetProgress(progress string)
Finish(state, code, outcome, errMsg string)
}
SyncJobHandle receives progress and completion updates for one tracked sync run.
type SyncJobTracker ¶
type SyncJobTracker interface {
BeginSyncJob(pluginID, kindKey, routePath, label string, cancel context.CancelFunc) SyncJobHandle
UpdateSyncJob(pluginID, kindKey, state, code, outcome, errMsg string)
}
SyncJobTracker mirrors active and completed library syncs into the plugin's background jobs list so Activity and Overview show live progress and outcome.
type SyncOptions ¶
type SyncOptions struct {
Manual bool // owner-started sync from the console
Force bool // bypass the 50%-delete guard (admin override)
FullWalk bool // force a full browse walk even if a change cursor exists
Concurrency int // max concurrent child browse requests (default MaxSyncConcurrency = 4)
Caller Caller // optional override for Service's configured Caller
}
SyncOptions controls a single SyncKind invocation.
type SyncOutcome ¶
type SyncOutcome struct {
Mode string `json:"mode"` // "sync", "full", "force", "keep"
Upserted int `json:"upserted,omitempty"`
Deleted int `json:"deleted,omitempty"`
Skipped int `json:"skipped,omitempty"`
Protected int `json:"protected,omitempty"`
Total int `json:"total"`
Summary string `json:"summary"`
FinishedAt time.Time `json:"finishedAt"`
}
SyncOutcome summarizes the most recent completed sync or keep action in memory.
type SyncResult ¶
type SyncResult struct {
Upserted int
Deleted int
Skipped int
Protected int
NextCursor string
RetryAfter time.Duration
}
SyncResult reports the outcome of a SyncKind run.
type SyncRunResult ¶
type SyncRunResult struct {
Result SyncResult
Err error
}
SyncRunResult is delivered when an asynchronous manual sync completes.
type SyncState ¶
type SyncState struct {
PluginID string `json:"pluginId"`
KindKey string `json:"kindKey"`
Cursor string `json:"cursor,omitempty"`
Generation uint64 `json:"generation"`
LastStarted time.Time `json:"lastStarted,omitzero"`
LastOK time.Time `json:"lastOk,omitzero"`
LastError string `json:"lastError,omitempty"`
Items int64 `json:"items"`
Running bool `json:"running,omitempty"`
Phase string `json:"phase,omitempty"`
SyncedItems int `json:"syncedItems,omitempty"`
Pages int `json:"pages,omitempty"`
DeleteGuard *SyncDeleteGuard `json:"deleteGuard,omitempty"`
LastOutcome *SyncOutcome `json:"lastOutcome,omitempty"`
}
SyncState is the persisted sync status for one (plugin, kind) (spec §2.3), enriched with live in-memory progress while a background sync or reindex pass is running.
type TextResolver ¶
TextResolver looks up a plugin i18n key (without the "$t:" prefix) in the plugin's strings file for the default locale.
type UpsertStats ¶
UpsertStats is what one upsert batch actually did. Accepted counts the items the caller sent (before in-batch deduplication, as KindUpsert has always reported); Added, Updated and Unchanged count the deduplicated validated items.
type ValidatedItem ¶
type ValidatedItem struct {
Item core.KindItem
IndexedFields []IndexedFieldValue
SearchFields string
SearchPeople string
DroppedFields int
}
ValidatedItem holds a cleaned KindItem plus its extracted indexed field rows and FTS search text.
func ValidateItem ¶
func ValidateItem(decl plugins.MediaKindMeta, it core.KindItem, parentLevel string) (ValidatedItem, error)
ValidateItem validates one KindItem against its MediaKindMeta declaration (spec §3.3): level and optional parentLevel, field types and caps, string lengths, art roles and URLs, hints JSON object cap, and SortTitle derivation. Unknown field keys are dropped and counted in DroppedFields; wrong field types or violated caps reject the item with an error wrapping ErrInvalidItem.