Documentation
¶
Overview ¶
Package objectcache is the control-plane domain for per-site object cache management (M68). It owns config CRUD (with age-encrypted password), signed agent commands (apply_config / test / enable / disable / flush), stats-report ingest, time-series history, SSE event publication, and flush audit.
The package follows the per-file-not-per-subpackage layering convention: model.go (domain types), repo.go (DB access), service.go (business logic), handler.go (Gin handlers), dto.go (wire <-> domain mapping), worker.go (River).
Index ¶
- Variables
- type Config
- type ConfigDTO
- type ConfigPutDTO
- type FlushInput
- type Handler
- type HeartbeatBlock
- type IngestStatsInput
- type OCState
- type ObjectCacheStatsHistoryGCArgs
- type ObjectCacheStatsHistoryGCWorker
- type Repo
- func (r *Repo) GetConfig(ctx context.Context, tenantID, siteID uuid.UUID) (Config, error)
- func (r *Repo) GetConfigWithSecret(ctx context.Context, tenantID, siteID uuid.UUID) (sqlc.SiteObjectCacheConfig, error)
- func (r *Repo) GetStatsHistory(ctx context.Context, tenantID, siteID uuid.UUID, since time.Time) ([]StatsHistoryPoint, error)
- func (r *Repo) InsertStatsHistory(ctx context.Context, tenantID uuid.UUID, p StatsPoint) error
- func (r *Repo) PruneHistory(ctx context.Context, cutoff time.Time) (int64, error)
- func (r *Repo) UpdateDrift(ctx context.Context, tenantID, siteID uuid.UUID, drift bool) error
- func (r *Repo) UpdateEnabled(ctx context.Context, tenantID, siteID uuid.UUID, enabled bool) (Config, error)
- func (r *Repo) UpdateHeartbeatState(ctx context.Context, tenantID, siteID uuid.UUID, state OCState, latencyMs int, ...) (Config, error)
- func (r *Repo) UpdateTestResult(ctx context.Context, tenantID, siteID uuid.UUID, configHash string, ...) (Config, error)
- func (r *Repo) UpsertConfig(ctx context.Context, tenantID uuid.UUID, cfg Config, passwordEncrypted []byte, ...) (Config, error)
- type Service
- func (s *Service) Disable(ctx context.Context, tenantID, siteID uuid.UUID) (Config, error)
- func (s *Service) Enable(ctx context.Context, tenantID, siteID uuid.UUID) (Config, error)
- func (s *Service) Flush(ctx context.Context, input FlushInput) (string, error)
- func (s *Service) GetConfig(ctx context.Context, tenantID, siteID uuid.UUID) (Config, error)
- func (s *Service) GetStatsHistory(ctx context.Context, tenantID, siteID uuid.UUID, days int) (StatsHistoryResponse, error)
- func (s *Service) IngestHeartbeat(ctx context.Context, tenantID, siteID uuid.UUID, block *HeartbeatBlock) error
- func (s *Service) IngestStats(ctx context.Context, input IngestStatsInput) error
- func (s *Service) Test(ctx context.Context, tenantID, siteID uuid.UUID, passwordRaw string) (Config, *agentcmd.ObjectCacheTestResult, error)
- func (s *Service) UpdateConfig(ctx context.Context, tenantID, siteID uuid.UUID, input UpdateConfigInput) (Config, error)
- type SiteURLer
- type StatsHistoryPoint
- type StatsHistoryResponse
- type StatsPoint
- type TestInput
- type UpdateConfigInput
Constants ¶
This section is empty.
Variables ¶
var ErrNotFound = errors.New("objectcache: not found")
ErrNotFound is returned when no site_object_cache_config row exists for the requested site.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
SiteID uuid.UUID
TenantID uuid.UUID
Enabled bool
// Connection topology (v1: tcp | unix | tls; schema reserved for future).
Scheme string
Host string
Port int
SocketPath string
Database int
Username string
// HasPassword is a derived field set by the repo: true when password_encrypted
// is non-nil in the DB. The plaintext password is NEVER carried in this struct.
HasPassword bool
// Key prefix applied to every Redis key written by this site.
Prefix string
// TTL knobs (seconds).
MaxTTLSeconds int
QueryTTLSeconds int
// Connection resilience knobs.
ConnectTimeoutMs int
ReadTimeoutMs int
RetryCount int
RetryIntervalMs int
// Serializer and compression options.
Serializer string
Compression string
// Flush configuration.
AsyncFlush bool
FlushStrategy string
FlushOnFailback bool
// Analytics toggle.
AnalyticsEnabled bool
// DebugHeaderEnabled when true causes the apply_config push to include the
// flag so the drop-in emits a per-request X-WPMgr-Cache debug response
// header. Default false (silent in production).
DebugHeaderEnabled bool
// Test gate: non-empty when the most recent test PASSED for the config hash.
// Enable is rejected when this is empty (handshake gate).
LastTestConfigHash string
// LastTestResultJSON is the raw JSON payload from the most recent test result.
// Stored for display; not used for gate logic.
LastTestResultJSON []byte
LastTestedAt *time.Time
// Live status fields sourced from the heartbeat. Used for SSE transition
// detection without hitting the agent.
OCState OCState
OCLatencyMs int
OCLastErrorClass string
OCUsedMemoryBytes int64
OCHitRatioPct *float64
// OCConfigDrift is true when the agent's last heartbeat config_hash differs
// from the CP-computed hash of the stored config (indicates live/stored drift).
OCConfigDrift bool
CreatedAt time.Time
UpdatedAt time.Time
}
Config is the domain model for site_object_cache_config. password_encrypted is NEVER included; use the repo's WithSecret variant for command rendering.
type ConfigDTO ¶
type ConfigDTO struct {
Enabled bool `json:"enabled"`
Scheme string `json:"scheme"`
Host string `json:"host"`
Port int `json:"port"`
SocketPath string `json:"socket_path,omitempty"`
Database int `json:"database"`
Username string `json:"username,omitempty"`
HasPassword bool `json:"has_password"`
Prefix string `json:"prefix"`
MaxTTLSeconds int `json:"maxttl_seconds"`
QueryTTLSeconds int `json:"queryttl_seconds"`
ConnectTimeoutMs int `json:"connect_timeout_ms"`
ReadTimeoutMs int `json:"read_timeout_ms"`
RetryCount int `json:"retry_count"`
RetryIntervalMs int `json:"retry_interval_ms"`
Serializer string `json:"serializer"`
Compression string `json:"compression"`
AsyncFlush bool `json:"async_flush"`
FlushStrategy string `json:"flush_strategy"`
FlushOnFailback bool `json:"flush_on_failback"`
AnalyticsEnabled bool `json:"analytics_enabled"`
// DebugHeaderEnabled gates the per-request X-WPMgr-Cache debug response
// header emitted by the drop-in. False by default.
DebugHeaderEnabled bool `json:"debug_header_enabled"`
LastTestConfigHash string `json:"last_test_config_hash,omitempty"`
LastTestedAt *time.Time `json:"last_tested_at,omitempty"`
// LastTestResult is the stored agent test result (including the server
// capability report) passed through verbatim so the dashboard renders
// server requirements without re-running a test.
LastTestResult json.RawMessage `json:"last_test_result,omitempty"`
// Live status (from heartbeat).
OCState string `json:"oc_state"`
OCLatencyMs int `json:"oc_latency_ms"`
OCLastErrorClass string `json:"oc_last_error_class,omitempty"`
OCUsedMemoryBytes int64 `json:"oc_used_memory_bytes"`
OCHitRatioPct *float64 `json:"oc_hit_ratio_pct,omitempty"`
// ConfigDrift is true when the agent's live config hash differs from the
// CP-computed hash of the stored config (requires a config re-push).
ConfigDrift bool `json:"config_drift,omitempty"`
// PushWarning is set when the config was saved but the apply_config push to
// the agent failed. The value is a capped error string for display.
PushWarning string `json:"push_warning,omitempty"`
CreatedAt time.Time `json:"created_at,omitempty"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
}
ConfigDTO is the wire shape returned by GET /object-cache/config. password_encrypted is never included; has_password signals its presence.
type ConfigPutDTO ¶
type ConfigPutDTO struct {
Enabled *bool `json:"enabled,omitempty"`
Scheme string `json:"scheme,omitempty"`
Host string `json:"host,omitempty"`
Port int `json:"port,omitempty"`
SocketPath string `json:"socket_path,omitempty"`
Database int `json:"database,omitempty"`
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"` // write-only; empty = keep stored
Prefix string `json:"prefix,omitempty"`
MaxTTLSeconds int `json:"maxttl_seconds,omitempty"`
QueryTTLSeconds int `json:"queryttl_seconds,omitempty"`
ConnectTimeoutMs int `json:"connect_timeout_ms,omitempty"`
ReadTimeoutMs int `json:"read_timeout_ms,omitempty"`
RetryCount int `json:"retry_count,omitempty"`
RetryIntervalMs int `json:"retry_interval_ms,omitempty"`
Serializer string `json:"serializer,omitempty"`
Compression string `json:"compression,omitempty"`
AsyncFlush *bool `json:"async_flush,omitempty"`
FlushStrategy string `json:"flush_strategy,omitempty"`
FlushOnFailback *bool `json:"flush_on_failback,omitempty"`
AnalyticsEnabled *bool `json:"analytics_enabled,omitempty"`
DebugHeaderEnabled *bool `json:"debug_header_enabled,omitempty"`
}
ConfigPutDTO is the wire shape accepted by PUT /object-cache/config. Password is write-only: empty string means "keep stored password".
type FlushInput ¶
type FlushInput struct {
SiteID uuid.UUID
TenantID uuid.UUID
Scope string // "all" | "site" | "group"
Group string // required when Scope=="group"
InitiatorID uuid.UUID
}
FlushInput carries the operator's flush request.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler serves the operator-facing Object Cache routes under /api/v1/sites/{siteId}/perf/object-cache/... All routes require RequireSiteAccess("siteId") (applied by Register via the parent group) and per-route permission gates.
func NewHandler ¶
NewHandler wires the handler.
func (*Handler) Register ¶
func (h *Handler) Register(r *gin.RouterGroup)
Register mounts the routes on the authenticated /api/v1 group. The caller MUST apply RequireSiteAccess("siteId") to the group before calling Register (the perf handler already does this for the parent /sites/:siteId group).
type HeartbeatBlock ¶
type HeartbeatBlock struct {
State OCState `json:"state"`
LatencyMs int `json:"latency_ms"`
LastErrorClass string `json:"last_error_class,omitempty"`
UsedMemoryBytes int64 `json:"used_memory_bytes"`
HitRatioPct float64 `json:"hit_ratio_window_pct"`
// ConfigHash is the sha256 hex of the config file the drop-in is actually
// reading, as reported by class-object-cache-heartbeat.php (0.42.0+).
// Empty on pre-0.42.0 agents; the drift check is skipped when absent.
ConfigHash string `json:"config_hash,omitempty"`
}
HeartbeatBlock is the optional object_cache block the agent appends to its heartbeat push. Every field is optional; absent block = disabled state.
type IngestStatsInput ¶
type IngestStatsInput struct {
SiteID uuid.UUID
TenantID uuid.UUID
// Delta counts since the agent's last emission window.
HitCount int64 `json:"hit_count"`
MissCount int64 `json:"miss_count"`
// Server INFO snapshot.
UsedMemoryBytes int64 `json:"used_memory_bytes"`
AvgWaitMs float64 `json:"avg_wait_ms"`
// OpsPerSec is float64 at the domain boundary because the PHP agent emits
// round($ops/$elapsed, 2), which produces a fractional JSON number. The repo
// rounds to int32 at the call site (ops_per_sec DB column is integer).
OpsPerSec float64 `json:"ops_per_sec"`
EvictedKeysDelta int64 `json:"evicted_keys_delta"`
ConnectedClients int `json:"connected_clients"`
}
IngestStatsInput is the agent stats-report optional object_cache block. Mirrors the agent's wire format (tolerant ingest: unknown fields ignored).
type OCState ¶
type OCState string
OCState enumerates the object-cache connectivity states reported by the agent.
const ( // OCStateUnknown is the zero value used when the agent sends an unrecognised // state string. The heartbeat update is skipped to preserve the stored state. OCStateUnknown OCState = "" // OCStateDisabled means the drop-in is configured but the engine is not serving // (e.g. toggled off at the WordPress layer while config still exists). OCStateDisabled OCState = "disabled" // OCStateConnected means the last command cycle completed without errors. OCStateConnected OCState = "connected" // OCStateDegraded means array-fallback is active or reconnect-once fired. OCStateDegraded OCState = "degraded" // OCStateDown means the boot failover to in-memory cache is engaged. OCStateDown OCState = "down" )
type ObjectCacheStatsHistoryGCArgs ¶
type ObjectCacheStatsHistoryGCArgs struct{}
ObjectCacheStatsHistoryGCArgs is the River job payload for the periodic stats-history GC. No fields: the worker uses fixed retention windows (7 days for raw rows: D4 decision).
func (ObjectCacheStatsHistoryGCArgs) Kind ¶
func (ObjectCacheStatsHistoryGCArgs) Kind() string
Kind implements river.JobArgs.
type ObjectCacheStatsHistoryGCWorker ¶
type ObjectCacheStatsHistoryGCWorker struct {
river.WorkerDefaults[ObjectCacheStatsHistoryGCArgs]
// contains filtered or unexported fields
}
ObjectCacheStatsHistoryGCWorker deletes site_object_cache_stats_history rows older than the raw retention window (7 days, per D4). It runs cross-tenant under InAgentTx (app.agent = 'on'), matching the CacheHitRatioHistoryGCWorker pattern. LIMIT 2000 per pass keeps each transaction short.
func NewObjectCacheStatsHistoryGCWorker ¶
func NewObjectCacheStatsHistoryGCWorker(repo *Repo, logger *slog.Logger) *ObjectCacheStatsHistoryGCWorker
NewObjectCacheStatsHistoryGCWorker builds the GC worker.
func (*ObjectCacheStatsHistoryGCWorker) Work ¶
func (w *ObjectCacheStatsHistoryGCWorker) Work(ctx context.Context, _ *river.Job[ObjectCacheStatsHistoryGCArgs]) error
Work deletes rows older than 7 days in a single cross-tenant pass (InAgentTx).
type Repo ¶
type Repo struct {
// contains filtered or unexported fields
}
Repo is the persistence layer for the Object Cache domain. Operator reads/writes run under InTenantTx; agent heartbeat/GC writes run under InAgentTx. The repo NEVER sets GUCs; the pool helpers do. updated_at is set by now() in the queries (no trigger, project convention).
func (*Repo) GetConfig ¶
GetConfig returns the per-site object cache config without the encrypted password. HasPassword reflects whether ciphertext exists in the DB. Returns ErrNotFound when no row exists yet.
func (*Repo) GetConfigWithSecret ¶
func (r *Repo) GetConfigWithSecret(ctx context.Context, tenantID, siteID uuid.UUID) (sqlc.SiteObjectCacheConfig, error)
GetConfigWithSecret fetches the full row including password_encrypted. Used ONLY by the service when rendering a signed agent command.
func (*Repo) GetStatsHistory ¶
func (r *Repo) GetStatsHistory(ctx context.Context, tenantID, siteID uuid.UUID, since time.Time) ([]StatsHistoryPoint, error)
GetStatsHistory returns daily-aggregated history points for the trend chart.
func (*Repo) InsertStatsHistory ¶
InsertStatsHistory appends one stats data point. ON CONFLICT DO NOTHING makes it idempotent within the same second. Runs under InTenantTx (the perf service forwards tenant context).
func (*Repo) PruneHistory ¶
PruneHistory deletes rows older than cutoff across all tenants (InAgentTx).
func (*Repo) UpdateDrift ¶
UpdateDrift persists the oc_config_drift indicator for a site. Called from IngestHeartbeat when the agent-reported config_hash is compared against the CP-computed hash of the stored config. Runs under InAgentTx.
func (*Repo) UpdateEnabled ¶
func (r *Repo) UpdateEnabled(ctx context.Context, tenantID, siteID uuid.UUID, enabled bool) (Config, error)
UpdateEnabled flips the enabled flag. The service layer must verify the handshake gate (non-empty LastTestConfigHash) before calling this.
func (*Repo) UpdateHeartbeatState ¶
func (r *Repo) UpdateHeartbeatState(ctx context.Context, tenantID, siteID uuid.UUID, state OCState, latencyMs int, lastErrorClass string, usedMemoryBytes int64, hitRatioPct *float64) (Config, error)
UpdateHeartbeatState updates the live status columns from a heartbeat push. Returns the updated row so the service can detect state transitions. tenantID is required for defence-in-depth: the explicit WHERE predicate prevents a cross-tenant write even though InAgentTx sets app.agent='on'. Runs under InAgentTx (cross-tenant heartbeat path).
func (*Repo) UpdateTestResult ¶
func (r *Repo) UpdateTestResult(ctx context.Context, tenantID, siteID uuid.UUID, configHash string, resultJSON []byte, passedAt *time.Time) (Config, error)
UpdateTestResult records the outcome of an objectcache.test command. configHash is the hash of the config snapshot that was tested. passedAt should be non-nil on a passing test and nil on failure (so we do not advance last_tested_at on failures).
func (*Repo) UpsertConfig ¶
func (r *Repo) UpsertConfig(ctx context.Context, tenantID uuid.UUID, cfg Config, passwordEncrypted []byte, clearTestHash bool) (Config, error)
UpsertConfig inserts or updates the per-site object cache config. passwordEncrypted must be nil to preserve a stored secret (nil-sentinel). clearTestHash controls whether last_test_config_hash is set to NULL (call with true whenever connection-critical fields changed).
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service implements the Object Cache control-plane business logic.
func NewService ¶
func NewService(repo *Repo, box *cryptbox.AgeIdentity, cmdClient *agentcmd.Client, urler SiteURLer, pub site.EventPublisher) *Service
NewService wires the service with its dependencies.
func (*Service) Enable ¶
Enable installs the object-cache drop-in. Rejected unless a passing test result exists for the current config (handshake gate).
func (*Service) Flush ¶
Flush sends the objectcache.flush command and publishes a flushed SSE event. Returns the flush result detail string.
func (*Service) GetConfig ¶
GetConfig returns the per-site object cache config (without the password).
func (*Service) GetStatsHistory ¶
func (s *Service) GetStatsHistory(ctx context.Context, tenantID, siteID uuid.UUID, days int) (StatsHistoryResponse, error)
GetStatsHistory returns the daily-aggregated stats history for the trend chart.
func (*Service) IngestHeartbeat ¶
func (s *Service) IngestHeartbeat(ctx context.Context, tenantID, siteID uuid.UUID, block *HeartbeatBlock) error
IngestHeartbeat handles the optional object_cache block from a heartbeat push. tenantID is required and must come from the verified agent identity; it is threaded through to the UPDATE WHERE clause to prevent cross-tenant writes. If the state changed, publishes objectcache.status_changed immediately. Publishes objectcache.stats_updated for non-transition updates (caller throttles). When block.ConfigHash is non-empty (0.42.0+ agent), the hash is compared against the CP-computed hash of the stored config; drift is persisted and WARN-logged so the operator can be notified via the dashboard.
func (*Service) IngestStats ¶
func (s *Service) IngestStats(ctx context.Context, input IngestStatsInput) error
IngestStats handles the optional object_cache block from a stats-report push. Missing or empty block is a no-op (tolerant ingest).
func (*Service) Test ¶
func (s *Service) Test(ctx context.Context, tenantID, siteID uuid.UUID, passwordRaw string) (Config, *agentcmd.ObjectCacheTestResult, error)
Test sends the objectcache.test command with the candidate config and stores the result. Returns the updated config with the test result embedded.
func (*Service) UpdateConfig ¶
func (s *Service) UpdateConfig(ctx context.Context, tenantID, siteID uuid.UUID, input UpdateConfigInput) (Config, error)
UpdateConfig saves the per-site object cache config. If passwordRaw is non-empty it is encrypted with the cryptbox and stored; otherwise the stored ciphertext is preserved (nil-sentinel). Connection-critical field changes clear the test hash (enable gate resets). Returns the saved config.
A non-nil error from the agent push (apply_config) is returned alongside a valid saved config so the handler can surface it as a warning rather than a failure (the save succeeded; only the live-push failed).
type SiteURLer ¶
type SiteURLer interface {
GetSiteURL(ctx context.Context, tenantID, siteID uuid.UUID) (string, error)
}
SiteURLer returns the current URL for a site (needed to send agent commands).
type StatsHistoryPoint ¶
type StatsHistoryPoint struct {
SampledAt time.Time `json:"sampled_at"`
RatioPct *float64 `json:"ratio_pct"`
HitCount int64 `json:"hit_count"`
MissCount int64 `json:"miss_count"`
UsedMemoryBytes int64 `json:"used_memory_bytes"`
AvgWaitMs float64 `json:"avg_wait_ms"`
OpsPerSec int `json:"ops_per_sec"`
EvictedKeysDelta int64 `json:"evicted_keys_delta"`
}
StatsHistoryPoint is one aggregated (daily-bucketed) point as returned by GetObjectCacheStatsHistory.
type StatsHistoryResponse ¶
type StatsHistoryResponse struct {
Points []StatsHistoryPoint `json:"points"`
AvgRatioPct float64 `json:"avg_ratio_pct"`
}
StatsHistoryResponse is the payload for GET /object-cache/stats-history.
type StatsPoint ¶
type StatsPoint struct {
ID uuid.UUID
SiteID uuid.UUID
TenantID uuid.UUID
HitCount int64
MissCount int64
RatioPct *float64
UsedMemoryBytes int64
AvgWaitMs float64
// OpsPerSec is float64 at the domain boundary to accommodate the PHP agent
// emitting round($ops/$elapsed, 2) as a fractional JSON number. The repo
// rounds to the nearest int32 when writing to the integer DB column.
OpsPerSec float64
EvictedKeysDelta int64
ConnectedClients int
SampledAt time.Time
CreatedAt time.Time
}
StatsPoint is one row of site_object_cache_stats_history.
type TestInput ¶
type TestInput struct {
SiteID uuid.UUID
TenantID uuid.UUID
// Password is the plaintext secret supplied by the operator in this request.
// Empty means "use the stored password" (the service decrypts from DB).
Password string
}
TestInput carries the candidate config to test (before saving to DB).
type UpdateConfigInput ¶
type UpdateConfigInput struct {
Config
// PasswordRaw is the plaintext password the operator entered. Empty means
// "keep stored password" (nil-sentinel).
PasswordRaw string
}
UpdateConfigInput carries the operator's config PUT payload.