Documentation
¶
Overview ¶
Package hubstore implements the pure-Go storage, search, and tracker-list subsystem for the self-contained EdgeFetch Hub (`edgefetch --hub`).
It provides:
- Store: atomic disk-backed or bounded in-memory gzip blob storage, sanitized Markdown slice-paged artifacts, ETag/304 scrape response cache, per-host WAF/adapter gap telemetry, tenant-isolated async job state, hub settings, and bounded operational events.
- CollectionIndex: multi-tenant BM25 inverted search index over chunked Markdown documents with prefix-match fallback.
- ExecuteWebSearch: Reciprocal Rank Fusion (RRF, k=60) search across local collections and external JSON APIs (SearXNG, Serper, Brave, Tavily) with secret-free OTLP child spans.
- TrackerManager: zero-startup-fetch EasyPrivacy third-party tracker list validator, background refresher, and WebSocket frame builder.
Index ¶
- Constants
- Variables
- func BuildTrackerListFrames(version string, hosts []string) [][]byte
- func CanonicalizeSearchURL(rawURL string) (string, bool)
- func ExecuteWebSearch(ctx context.Context, cfg SearchConfig, p SearchParams) (map[string]any, error)
- func ResolveCollectionKey(userID string, isOwner bool, rawCollection string) (storageKey, displayCollection string)
- func ValidateEasyPrivacyList(rawBytes []byte, previousHostCount int, extraNeverBlock map[string]bool) (version, headerLastMod string, hosts []string, rawParsedCount int, err error)
- type CollectionHit
- type CollectionIndex
- type SearchConfig
- type SearchParams
- type Store
- func (s *Store) AppendEvent(ev map[string]any)
- func (s *Store) ClearEvents()
- func (s *Store) DataDir() string
- func (s *Store) DeleteOrCancelJob(kind, id, callerOwnerID string, callerIsOwner bool) (map[string]any, bool)
- func (s *Store) GetDecodedBlob(namespace, blobSHA string, maxBytes int) ([]byte, bool, error)
- func (s *Store) GetGzipBlob(namespace, blobSHA string) ([]byte, bool, error)
- func (s *Store) GetJob(kind, id, callerOwnerID string, callerIsOwner bool) (map[string]any, bool)
- func (s *Store) GetScrapeCache(cacheKey string, maxAgeMs int64, ifNoneMatch string) (payload map[string]any, etag string, notModified bool, hit bool)
- func (s *Store) GetSetting(key string) (string, bool)
- func (s *Store) ListEvents(limit int) []map[string]any
- func (s *Store) ListHostGaps(limit int) []map[string]any
- func (s *Store) ListHosts(limit int) []map[string]any
- func (s *Store) PersistMarkdownArtifact(ownerID, urlStr, title, markdown string, isPrivate bool) (artifactID string, totalChars int, checkpoints []int, err error)
- func (s *Store) PutGzipBlob(namespace, blobSHA, contentSHA string, gzBytes []byte) error
- func (s *Store) PutJob(kind, id, ownerID string, data map[string]any)
- func (s *Store) PutRawBlob(namespace string, raw []byte) (blobSHA, contentSHA string, contentBytes, storedBytes int, err error)
- func (s *Store) PutScrapeCache(cacheKey string, payload map[string]any) (etag string)
- func (s *Store) ReadArtifactPage(callerOwnerID string, callerIsOwner bool, artifactID string, ...) (page map[string]any, status int, errCode string)
- func (s *Store) RecordHostTelemetry(host, outcome string, status int, wafVendor, contentState, adapterID string, ...)
- func (s *Store) SetSetting(key, val string)
- type TrackerConfig
- type TrackerManager
- func (tm *TrackerManager) CurrentList() (version string, hosts []string)
- func (tm *TrackerManager) IsEnabled() bool
- func (tm *TrackerManager) RefreshNow(ctx context.Context) (updated bool, err error)
- func (tm *TrackerManager) StartBackground(ctx context.Context)
- func (tm *TrackerManager) Status() map[string]any
- func (tm *TrackerManager) Stop()
Constants ¶
const ( DefaultMaxMemBytes = 64 << 20 MaxArtifactContentBytes = 16 << 20 MaxArtifactStoredBytes = 18 << 20 DefaultArtifactPageSize = 65536 MaxArtifactPageSize = 1 << 20 MaxScrapeCacheEntries = 2048 MaxTrackedHostRecords = 4096 MaxRetainedEvents = 500 )
const ( EasyPrivacySourceURL = "https://easylist.to/easylist/easyprivacy.txt" EasyPrivacyLicenseURL = "https://easylist.to/pages/licence.html" TrackerListUserAgent = "EdgeFetch/2.7" DefaultTrackerInitialDelay = 3 * time.Minute DefaultTrackerPollInterval = 6 * time.Hour DefaultTrackerRefreshAge = 24 * time.Hour MinTrackerListBytes = 200 * 1024 MaxTrackerListBytes = 10 * 1024 * 1024 MinTrackerHostCount = 5000 MaxTrackerHostCount = 200000 MaxTrackerHostDeltaRatio = 0.20 MaxSingleTrackerFrameBytes = 768 * 1024 TrackerChunkB64Chars = 450000 )
Variables ¶
var ( ErrInvalidSHA256 = errors.New("hubstore: invalid sha256 hex digest") ErrBlobDigestMismatch = errors.New("hubstore: compressed blob sha256 mismatch") ErrContentHashMismatch = errors.New("hubstore: uncompressed content sha256 mismatch") ErrBlobTooLarge = errors.New("hubstore: blob exceeds byte limit") ErrCorruptGzip = errors.New("hubstore: corrupt gzip payload") )
var ErrInvalidSearchQuery = errors.New("hubstore: search query must be 1..500 characters")
ErrInvalidSearchQuery indicates an empty or oversized search query.
Functions ¶
func BuildTrackerListFrames ¶
BuildTrackerListFrames builds WebSocket JSON frames (`tracker_list` when <= 768 KiB, else `tracker_list_chunk` frames).
func CanonicalizeSearchURL ¶
CanonicalizeSearchURL normalizes a search result URL, stripping fragments and tracking query parameters.
func ExecuteWebSearch ¶
func ExecuteWebSearch(ctx context.Context, cfg SearchConfig, p SearchParams) (map[string]any, error)
ExecuteWebSearch queries local BM25 collections and configured external search APIs, fusing results via RRF (`k=60`).
func ResolveCollectionKey ¶
func ResolveCollectionKey(userID string, isOwner bool, rawCollection string) (storageKey, displayCollection string)
ResolveCollectionKey resolves a raw collection identifier into a tenant-isolated storage key and clean display name.
func ValidateEasyPrivacyList ¶
func ValidateEasyPrivacyList(rawBytes []byte, previousHostCount int, extraNeverBlock map[string]bool) (version, headerLastMod string, hosts []string, rawParsedCount int, err error)
ValidateEasyPrivacyList parses and validates raw EasyPrivacy text enforcing size, header, PSL, allowlist, count, and <=20% drop/delta invariants.
Types ¶
type CollectionHit ¶
type CollectionHit struct {
URL string `json:"url"`
Title string `json:"title"`
Snippet string `json:"snippet"`
Score float64 `json:"score"`
ChunkIndex int `json:"chunkIndex"`
Collection string `json:"collection"`
}
CollectionHit represents one BM25-ranked Markdown chunk hit from a local collection.
type CollectionIndex ¶
type CollectionIndex struct {
// contains filtered or unexported fields
}
CollectionIndex implements a thread-safe, tenant-isolated pure-Go BM25 inverted index.
func NewCollectionIndex ¶
func NewCollectionIndex(dataDir string) (*CollectionIndex, error)
NewCollectionIndex initializes a BM25 collection index backed by `<dataDir>/state/collections_bm25.json` when dataDir != "".
func (*CollectionIndex) ReplacePageChunks ¶
func (idx *CollectionIndex) ReplacePageChunks(storageKey, displayCollection, pageURL, title, markdown string) (chunkCount int, pageID string)
ReplacePageChunks sanitizes title & Markdown, splits into ~1,000-char chunks, and atomically replaces prior chunks for (storageKey, pageURL).
func (*CollectionIndex) Search ¶
func (idx *CollectionIndex) Search(storageKey, query string, limit int, hostFilter string) []CollectionHit
Search ranks chunks in storageKey via BM25 (`k1=1.2`, `b=0.75`) with prefix-match fallback and optional host filtering.
type SearchConfig ¶
type SearchConfig struct {
SearxngURL string
SerperAPIKey string
BraveAPIKey string
TavilyAPIKey string
CollectionIndex *CollectionIndex
CollectionStorageKey string
OperatorClient *http.Client
OtelExporter *otel.Exporter
}
SearchConfig holds external provider credentials, local BM25 collection index, HTTP client, and OTLP exporter.
type SearchParams ¶
type SearchParams struct {
Query string `json:"query"`
Limit int `json:"limit"`
Sources []string `json:"sources,omitempty"`
Providers []string `json:"providers,omitempty"`
Collection string `json:"collection,omitempty"`
Category string `json:"category,omitempty"`
TimeRange string `json:"timeRange,omitempty"`
Country string `json:"country,omitempty"`
Language string `json:"language,omitempty"`
}
SearchParams configures a federated RRF search invocation.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store manages persistent disk-backed or bounded in-memory Hub state and gzipped artifacts.
func NewStore ¶
NewStore initializes a Hub store rooted at dataDir (or pure in-memory when dataDir == "").
func (*Store) AppendEvent ¶
AppendEvent appends an operational event to the bounded ring (`MaxRetainedEvents`).
func (*Store) ClearEvents ¶
func (s *Store) ClearEvents()
ClearEvents removes all retained operational events.
func (*Store) DataDir ¶
DataDir returns the configured persistent root directory, or "" in memory-only mode.
func (*Store) DeleteOrCancelJob ¶
func (s *Store) DeleteOrCancelJob(kind, id, callerOwnerID string, callerIsOwner bool) (map[string]any, bool)
DeleteOrCancelJob marks an authorized async job as cancelled (`"status": "cancelled"`, `"cancelled": true`).
func (*Store) GetDecodedBlob ¶
GetDecodedBlob retrieves, gunzips (capped at maxBytes), and verifies a stored blob.
func (*Store) GetGzipBlob ¶
GetGzipBlob retrieves and hash-verifies a stored gzip blob.
func (*Store) GetScrapeCache ¶
func (s *Store) GetScrapeCache(cacheKey string, maxAgeMs int64, ifNoneMatch string) (payload map[string]any, etag string, notModified bool, hit bool)
GetScrapeCache looks up a cached scrape response honoring maxAgeMs and If-None-Match (304).
func (*Store) GetSetting ¶
GetSetting returns a Hub setting value by key.
func (*Store) ListEvents ¶
ListEvents returns up to limit most recent events (newest first).
func (*Store) ListHostGaps ¶
ListHostGaps returns unadapted hosts ranked by WAF/challenge friction and request volume.
func (*Store) PersistMarkdownArtifact ¶
func (s *Store) PersistMarkdownArtifact(ownerID, urlStr, title, markdown string, isPrivate bool) (artifactID string, totalChars int, checkpoints []int, err error)
PersistMarkdownArtifact sanitizes and stores a derived Markdown document + slice checkpoints.
func (*Store) PutGzipBlob ¶
PutGzipBlob verifies compressed + uncompressed SHA-256 digests and stores gzBytes under namespace.
func (*Store) PutJob ¶
PutJob stores or updates an async job (`batch_scrape`, `crawl`, `agent`, `catalog`).
func (*Store) PutRawBlob ¶
func (s *Store) PutRawBlob(namespace string, raw []byte) (blobSHA, contentSHA string, contentBytes, storedBytes int, err error)
PutRawBlob compresses raw with gzip and persists the verified blob.
func (*Store) PutScrapeCache ¶
PutScrapeCache stores a scrape response payload and returns its strong HTTP ETag.
func (*Store) ReadArtifactPage ¶
func (s *Store) ReadArtifactPage(callerOwnerID string, callerIsOwner bool, artifactID string, offset, maxChars int) (page map[string]any, status int, errCode string)
ReadArtifactPage returns a fence-safe sanitized Markdown slice page enforcing private tenant isolation.
func (*Store) RecordHostTelemetry ¶
func (s *Store) RecordHostTelemetry(host, outcome string, status int, wafVendor, contentState, adapterID string, latencyMs int64)
RecordHostTelemetry records per-host outcome, WAF classification, adapter hit, and latency.
func (*Store) SetSetting ¶
SetSetting updates and persists a Hub setting value.
type TrackerConfig ¶
type TrackerConfig struct {
Store *Store
SourceURL string
Client *http.Client
InitialDelay time.Duration
PollInterval time.Duration
RefreshMaxAge time.Duration
SelfHost string
PublicOrigin string
Getenv func(string) string
OnUpdate func(version string, hosts []string)
}
TrackerConfig configures TrackerManager lifecycle, storage, HTTP transport, and update notifications.
type TrackerManager ¶
type TrackerManager struct {
// contains filtered or unexported fields
}
TrackerManager manages runtime EasyPrivacy validation, persistence, and delayed background refreshes.
func NewTrackerManager ¶
func NewTrackerManager(cfg TrackerConfig) (*TrackerManager, error)
NewTrackerManager creates a TrackerManager, loading any persisted list from Store with ZERO network I/O.
func (*TrackerManager) CurrentList ¶
func (tm *TrackerManager) CurrentList() (version string, hosts []string)
CurrentList returns the active tracker list version and a copy of the host slice.
func (*TrackerManager) IsEnabled ¶
func (tm *TrackerManager) IsEnabled() bool
IsEnabled reports whether runtime EasyPrivacy tracker blocking is enabled via env and Hub settings.
func (*TrackerManager) RefreshNow ¶
func (tm *TrackerManager) RefreshNow(ctx context.Context) (updated bool, err error)
RefreshNow downloads, validates, persists, and activates the EasyPrivacy list immediately.
func (*TrackerManager) StartBackground ¶
func (tm *TrackerManager) StartBackground(ctx context.Context)
StartBackground schedules the initial delayed refresh (`InitialDelay`) followed by `PollInterval` checks.
func (*TrackerManager) Status ¶
func (tm *TrackerManager) Status() map[string]any
Status returns the current tracker list readiness and metadata snapshot.
func (*TrackerManager) Stop ¶
func (tm *TrackerManager) Stop()
Stop halts background refresh timers.