diagnostics

package
v0.0.0-...-4c3468c Latest Latest
Warning

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

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

Documentation

Overview

Package diagnostics holds the ADR-037 Sprint 2 "site health" domain on the control-plane side. The agent ships:

  • A 14-category diagnostics blob via POST /agent/v1/diagnostics. We persist one row per (site, category) keyed by `category`; the agent overwrites the row each time it ships.
  • A batch of fingerprint-deduped PHP errors via POST /agent/v1/errors. We upsert by (site, md5) and increment occurrence_count on conflict.

Operators read:

  • GET /api/v1/sites/{siteId}/diagnostics — latest row per category + freshness timestamps (the Health tab renders 9 cards).
  • GET /api/v1/sites/{siteId}/errors — fingerprint-grouped table.
  • POST /api/v1/sites/{siteId}/errors/{md5}/silence — silence toggle.
  • POST /api/v1/sites/{siteId}/diagnostics/refresh — enqueue an on-demand diagnostics command to the agent.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ValidCategory

func ValidCategory(c Category) bool

ValidCategory reports whether c is one of the known buckets (14 legacy WPMgr-extra categories + the v0.9.14 `wp_native` full Site-Health dump).

Types

type AgentDiagnosticsClient

type AgentDiagnosticsClient interface {
	Diagnostics(ctx context.Context, siteID uuid.UUID, siteURL string, req agentcmd.DiagnosticsRequest) ([]byte, error)
}

AgentDiagnosticsClient is the subset of agentcmd.Client the enqueuer needs. Declared as an interface so tests can substitute a fake without spinning up the SSRF transport. *agentcmd.Client satisfies it via its Diagnostics method (added alongside this file).

type AgentErrorConfigClient

type AgentErrorConfigClient interface {
	SyncErrorConfig(ctx context.Context, siteID uuid.UUID, siteURL string, req agentcmd.ErrorConfigRequest) (agentcmd.ErrorConfigResult, error)
}

AgentErrorConfigClient is the subset of agentcmd.Client the service needs to push an error config to the agent. *agentcmd.Client satisfies it via its SyncErrorConfig method. Declared as an interface so tests can substitute a fake without spinning up the SSRF transport.

type Category

type Category string

Category is one of the 14 diagnostics buckets the agent ships. Strings match the agent's JSON keys verbatim.

const (
	CategoryIdentity    Category = "identity"
	CategoryPHP         Category = "php"
	CategoryMySQL       Category = "mysql"
	CategoryFilesystem  Category = "filesystem"
	CategoryHTTP        Category = "http"
	CategoryCron        Category = "cron"
	CategoryThemes      Category = "themes"
	CategoryPlugins     Category = "plugins"
	CategoryUsers       Category = "users"
	CategorySecurity    Category = "security"
	CategoryHTTPS       Category = "https"
	CategoryMail        Category = "mail"
	CategoryPerformance Category = "performance"
	CategoryHosting     Category = "hosting"
	// CategoryWPNative is the verbatim WP_Debug_Data::debug_data() dump (the
	// full Site Health > Info screen), shipped by the Site-Health-Full agent
	// build (v0.9.14+). The payload is a multi-section structure shaped like
	//   { "wp-core": { "label": "...", "fields": {...} }, ... }
	// with one section per WP_Debug_Data category (wp-core, wp-paths-sizes,
	// wp-dropins, wp-active-theme, wp-parent-theme, wp-themes-inactive,
	// wp-mu-plugins, wp-plugins-active, wp-plugins-inactive, wp-media,
	// wp-server, wp-database, wp-constants, wp-filesystem) plus any
	// `debug_information` filter contributions from third-party plugins
	// (Yoast SEO, WooCommerce, ACF, etc.). Stored as JSONB on the existing
	// agent_diagnostics row keyed by (tenant, site, "wp_native").
	CategoryWPNative Category = "wp_native"
)

func AllCategories

func AllCategories() []Category

AllCategories lists every category we expect the agent to populate. Used by the operator GET handler to emit a "card" entry per category even when the agent has never shipped a payload for it (so the UI can render an "awaiting first sync" placeholder rather than silently omitting the card).

type DBSizeHistorySink

type DBSizeHistorySink interface {
	RecordDBSizeHistoryFromDiagnostics(ctx context.Context, tenantID, siteID uuid.UUID, dbSizeBytes int64, scannedAt time.Time) error
}

DBSizeHistorySink appends a site_db_size_history data point sourced from a diagnostics push (GH #196). *perf.Repo satisfies it via RecordDBSizeHistoryFromDiagnostics; wired from main once the perf repo is constructed.

Declared here (rather than importing perf directly) to keep diagnostics free of a cross-domain package import — the concrete wiring lives in cmd/wpmgr. When never wired (nil), ingestDBSizeHistory is a no-op; the pre-existing manual "Scan database" writer (perf.Repo.UpsertDBScanResult) is unaffected either way.

type Diagnostic

type Diagnostic struct {
	ID          uuid.UUID
	TenantID    uuid.UUID
	SiteID      uuid.UUID
	Category    Category
	Payload     json.RawMessage // the category's JSON sub-blob, as the agent shipped it
	CollectedAt time.Time       // agent-side collection time (Unix seconds reported)
	ReceivedAt  time.Time       // CP-side ingestion time
}

Diagnostic is one stored row — the latest payload the agent shipped for the given (site, category).

type ErrorBatch

type ErrorBatch struct {
	Errors []ErrorBatchEntry `json:"errors"`
}

type ErrorBatchEntry

type ErrorBatchEntry struct {
	ID              flexInt64 `json:"id"`
	MD5             string    `json:"md5"`
	Code            flexInt   `json:"code"`
	Severity        string    `json:"severity"`
	Message         string    `json:"message"`
	File            string    `json:"file"`
	Line            flexInt   `json:"line"`
	RequestPath     string    `json:"request_path"`
	FirstSeen       flexInt64 `json:"first_seen"`
	LastSeen        flexInt64 `json:"last_seen"`
	OccurrenceCount flexInt64 `json:"occurrence_count"`
	Backtrace       []struct {
		File     string  `json:"file"`
		Line     flexInt `json:"line"`
		Function string  `json:"function"`
	} `json:"backtrace"`
}

IngestErrorBatch takes the agent-shipped batch of newest unsilenced rows and upserts each. Returns the highest agent-side row id we processed (the agent uses this to advance its local ship cursor on a 2xx).

Wire shape: wpdb ARRAY_A delivers every column as a string, so the numeric scalars (id, code, line, first_seen, last_seen, occurrence_count) arrive as either a Go number (when the caller is a test) or a quoted numeric string (when the agent serialises its ARRAY_A result with json_encode). We decode them via flexInt64 / flexInt so both paths work without panicking.

backtrace is a JSON array of {file,line,function} objects (max 10 frames, most-recent-call-first). Missing or null → treated as empty slice.

type ErrorConfig

type ErrorConfig struct {
	TenantID   uuid.UUID
	SiteID     uuid.UUID
	Enabled    bool
	ErrorLevel int
	IgnoreMD5s []string
	UpdatedAt  time.Time
}

ErrorConfig is the per-site PHP error reporting configuration stored in site_error_config and pushed to the agent via the sync_error_config command.

Enabled controls whether the agent installs the early-boot error-trap mu-plugin (pre-plugins_loaded bootstrap-fatal trap). Defaults true so existing sites keep the mu-plugin after the 0.48.4+ agent upgrade. ErrorLevel is the PHP E_* bitmask (e.g. 6143 = E_ALL & ~E_STRICT, the WP default). IgnoreMD5s is the ordered list of md5 fingerprints the agent must suppress without counting or reporting. An empty list clears all suppression.

type ErrorFrame

type ErrorFrame struct {
	File     string `json:"file"`
	Line     int    `json:"line"`
	Function string `json:"function"`
}

ErrorFrame is one frame in a PHP backtrace. Frame order is most-recent-call- first (the agent ships them that way; we store and expose them in that order).

type ErrorsGCArgs

type ErrorsGCArgs struct{}

ErrorsGCArgs is the River job payload for the periodic PHP-error retention GC. It carries no fields; the worker deletes stale rows across all tenants using the agent GUC (app.agent = 'on') so the per-tenant RLS isolation policy is bypassed for this cross-tenant maintenance sweep, exactly as the backup retention GC does.

func (ErrorsGCArgs) Kind

func (ErrorsGCArgs) Kind() string

Kind implements river.JobArgs.

type ErrorsGCWorker

type ErrorsGCWorker struct {
	river.WorkerDefaults[ErrorsGCArgs]
	// contains filtered or unexported fields
}

ErrorsGCWorker deletes agent_php_errors rows whose last_seen_at is older than the configured retention window. The default retention is 30 days — stale fingerprints that haven't re-appeared are unlikely to be actionable and accumulate over time on busy sites.

The DELETE runs cross-tenant under app.agent (the same GUC the backup GC uses) so a single job pass sweeps the whole table without needing to enumerate tenant IDs. The WHERE clause is intentionally simple (no site filter) so Postgres can use the existing agent_php_errors_site_lastseen_idx via a bitmap scan; LIMIT 5000 caps the per-pass blast radius and keeps the transaction short.

func NewErrorsGCWorker

func NewErrorsGCWorker(repo *Repo, retention time.Duration, logger *slog.Logger) *ErrorsGCWorker

NewErrorsGCWorker builds the PHP-error GC worker. retention is the last_seen_at age threshold after which a row is eligible for deletion; pass 0 to use the default of 30 days.

func (*ErrorsGCWorker) Work

Work runs one GC pass.

type Handler

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

Handler serves the operator-facing diagnostics + errors routes under /api/v1/sites/{siteId}/...

GET    /diagnostics                  — latest payload per category + freshness
POST   /diagnostics/refresh          — enqueue on-demand agent push
GET    /errors                       — fingerprint-grouped php-error list
POST   /errors/{md5}/silence         — toggle silence

func NewHandler

func NewHandler(svc *Service, rec *audit.Recorder) *Handler

NewHandler builds the operator handler.

func (*Handler) Register

func (h *Handler) Register(r *gin.RouterGroup)

Register mounts the routes on the authenticated /api/v1 group.

type HostResolver

type HostResolver interface {
	Resolve(ip string) ipprovider.Result
}

HostResolver infers a hosting provider from an IP (M28). *ipprovider.Resolver satisfies it. Declared as an optional interface so the service composes with or without the feature and tests can substitute a fake.

type IngestSink

type IngestSink interface {
	IngestDiagnostics(ctx context.Context, tenantID, siteID uuid.UUID, body []byte) (int, error)
	// ResolveHostProvider runs the M28 host inference. On this refresh (CP->agent
	// pull) path there is no observed egress IP, so it relies on the agent-
	// reported hosting.public_ip carried in the body (0.12.5+ agents).
	ResolveHostProvider(ctx context.Context, tenantID, siteID uuid.UUID, observedIP string, body []byte)
}

IngestSink is the subset of *Service used to feed the raw 14-category blob back into the per-category upsert path. Provided as an interface for two reasons: (1) the enqueuer is created BEFORE the service value is fully configured in main; (2) tests can capture the ingested bytes without round- tripping through Postgres.

type ListPHPErrorsFilter

type ListPHPErrorsFilter struct {
	Since    time.Time // last_seen_at > since (zero = no filter)
	Silenced *bool     // nil = both
	Limit    int
	// Cursor is the opaque keyset cursor for the next page; see encoding above.
	Cursor string
}

ListPHPErrorsFilter narrows ListPHPErrorsBySite. Zero-value fields are ignored.

Cursor encoding: base64(url, std) of "<unix-microseconds>:<uuid-string>" where unix-microseconds is the last_seen_at of the last row on the previous page and uuid-string is its id. The keyset predicate is (last_seen_at, id) < ($ts, $id) matching the ORDER BY last_seen_at DESC, id DESC sort.

Known caveat: a fingerprint whose last_seen_at is updated mid-pagination (new PHP-error occurrence while the operator is paging) may shift its position in the result set. This is acceptable for a monitoring UI and is not worth the complexity of a snapshot-based approach.

type PHPError

type PHPError struct {
	ID              uuid.UUID
	TenantID        uuid.UUID
	SiteID          uuid.UUID
	MD5             string
	Code            int
	Severity        string
	Message         string
	File            string
	Line            int
	RequestPath     string
	FirstSeenAt     time.Time
	LastSeenAt      time.Time
	OccurrenceCount int64
	Silenced        bool
	Backtrace       []ErrorFrame
	CreatedAt       time.Time
	UpdatedAt       time.Time
}

PHPError is one stored fingerprint-deduped error.

type RefreshEnqueuer

type RefreshEnqueuer interface {
	EnqueueRefreshDiagnostics(ctx context.Context, tenantID, siteID uuid.UUID) error
}

RefreshEnqueuer enqueues an on-demand diagnostics command to the agent. Optional; when nil the /diagnostics/refresh endpoint returns a 501 pointing at the missing wire (mirrors the InspectionDeps pattern in backups).

type RefreshEnqueuerImpl

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

RefreshEnqueuerImpl satisfies diagnostics.RefreshEnqueuer (defined in service.go) by dispatching a signed CP->agent `diagnostics` command, reading the agent's synchronous 14-category response, and feeding it into the same IngestDiagnostics path the daily /agent/v1/diagnostics push uses. The trade-off vs an async River job:

  • operator-paced: the "Re-run check" button is a single human click, so blocking the HTTP request on one signed agent POST is fine; the data lands BEFORE the 202 returns, and the UI can refetch immediately.
  • no River queue dependency: V1 ships without a River-backed enqueuer for diagnostics. The existing agentcmd transport already has the SSRF cap, the per-attempt timeout, and the jti single-use guarantee.

A future revision can swap this for a River-backed enqueuer (mirror update's RefreshInventoryWorker) without changing the RefreshEnqueuer interface in service.go — that interface is intentionally (tenantID, siteID)-only.

func NewRefreshEnqueuer

func NewRefreshEnqueuer(cmd AgentDiagnosticsClient, sites SiteLookup, sink IngestSink) *RefreshEnqueuerImpl

NewRefreshEnqueuer builds a RefreshEnqueuerImpl. All deps are required; passing nil is a programmer error (the constructor returns nil to make the nil-deref obvious during boot rather than at first call).

func (*RefreshEnqueuerImpl) EnqueueRefreshDiagnostics

func (r *RefreshEnqueuerImpl) EnqueueRefreshDiagnostics(ctx context.Context, tenantID, siteID uuid.UUID) error

EnqueueRefreshDiagnostics dispatches one signed `diagnostics` command to the site's agent, ingests the response into the per-category store, and returns. "Enqueue" in the name preserves the original V1 contract (which envisioned a River-backed enqueuer); the body is synchronous because the operator's "Re-run check" UX wants the data visible on the next GET.

A failure of the signed call, and a reply that is not the agent's JSON, are the site's doing. They come back as a domain.BadGateway (HTTP 502) carrying a stable code and fixed operator copy (agentcmd.DescribeSiteFailure), after one warn log line. The copy may carry only the bounded values the mapper allows (a status number, an allow-listed refusal code, a sanitised redirect address); neither the body of the site's reply nor err.Error() reaches the response or the log. A domain error keeps its kind: the 404 for an unknown site, the 422 for a reply without collected_at. Anything else, such as a database failure while storing the report, comes back as it is, and the handler answers it with a 500.

type Repo

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

Repo is the tenant-scoped persistence layer for diagnostics + php-error rows. Mutating calls run inside InTenantTx so the RLS policy filters every row by the active tenant.

The agent ingestion paths set BOTH `app.tenant_id` (so the WITH CHECK clause passes) AND `app.agent` (so the agent-write policy applies); the `InTenantTxAsAgent` helper centralises that. Operator reads use the standard InTenantTx.

func NewRepo

func NewRepo(pool *db.Pool) *Repo

NewRepo wires a Repo with the shared pgx pool.

func (*Repo) DeleteStaleErrors

func (r *Repo) DeleteStaleErrors(ctx context.Context, retention time.Duration) (int64, error)

DeleteStaleErrors removes agent_php_errors rows whose last_seen_at is older than the given retention window. It runs cross-tenant under app.agent = 'on' (the same GUC the backup retention GC uses) so a single pass sweeps the whole table without needing to enumerate tenant IDs. LIMIT 5000 per pass caps the blast radius and keeps each transaction short. Returns the number of rows deleted.

func (*Repo) GetErrorConfig

func (r *Repo) GetErrorConfig(ctx context.Context, tenantID, siteID uuid.UUID) (ErrorConfig, bool, error)

GetErrorConfig returns the stored error config for (tenantID, siteID). found=false (and no error) when no row exists yet; callers should default to agentcmd.DefaultErrorLevel with an empty ignore list.

func (*Repo) ListDiagnosticsBySite

func (r *Repo) ListDiagnosticsBySite(ctx context.Context, tenantID, siteID uuid.UUID) ([]Diagnostic, error)

ListDiagnosticsBySite returns every category row stored for the site, in no particular order — the handler keys them into a category-string map.

func (*Repo) ListPHPErrorsBySite

func (r *Repo) ListPHPErrorsBySite(ctx context.Context, tenantID, siteID uuid.UUID, f ListPHPErrorsFilter) ([]PHPError, string, error)

func (*Repo) SetSilenced

func (r *Repo) SetSilenced(ctx context.Context, tenantID, siteID uuid.UUID, md5 string, silenced bool) error

SetSilenced flips the silenced flag on a (site, md5) row. NotFound when the row doesn't exist within the tenant scope.

func (*Repo) SetSiteHostProvider

func (r *Repo) SetSiteHostProvider(ctx context.Context, tenantID, siteID uuid.UUID, provider, org, ip string) error

SetSiteHostProvider records the CP-inferred hosting provider for a site, derived from the agent's observed public egress IP (M28). Mirrors UpdateSiteTimezone: a raw tenant-scoped UPDATE inside InTenantTx (RLS-safe). `provider` may be "" when the IP could not be attributed to a known provider; the observed IP and checked-at timestamp are still recorded so the inference is auditable and re-resolves naturally on the next diagnostics push.

func (*Repo) UpdateSiteTimezone

func (r *Repo) UpdateSiteTimezone(ctx context.Context, tenantID, siteID uuid.UUID, wpTimezone string, wpGMTOffset float64) error

UpdateSiteTimezone writes the WordPress timezone fields onto the site row. It runs inside InTenantTx (tenant-scoped, no agent flag needed) so the standard tenant_isolation RLS policy permits the UPDATE.

Both fields are optional — empty timezone or zero offset are stored as-is (the migration defaults are ” and 0 respectively). The caller must guard against a nil/malformed payload before calling this method.

func (*Repo) UpsertDiagnostic

func (r *Repo) UpsertDiagnostic(ctx context.Context, tenantID, siteID uuid.UUID, category Category, payload json.RawMessage, collectedAt time.Time) (Diagnostic, error)

UpsertDiagnostic stores the latest payload for the given (site, category). On conflict (one row per (tenant, site, category) by the unique index) we overwrite payload + collected_at and refresh received_at.

func (*Repo) UpsertErrorConfig

func (r *Repo) UpsertErrorConfig(ctx context.Context, cfg ErrorConfig) (ErrorConfig, error)

UpsertErrorConfig inserts or replaces the error config for (tenantID, siteID). updated_at is refreshed on every upsert. Returns the stored config.

func (*Repo) UpsertPHPError

func (r *Repo) UpsertPHPError(ctx context.Context, tenantID, siteID uuid.UUID, in UpsertPHPErrorInput) error

type ReportedURLSink

type ReportedURLSink interface {
	EnqueueAdoptReportedURL(ctx context.Context, tenantID, siteID uuid.UUID, reported, source, agentVersion string) error
}

ReportedURLSink receives the site address the agent reports in the http category (home_url). The site service implements it: it queues a job that decides whether the address replaces the saved one, and returns without probing the site, so the push is never held up. Optional: nil means the address is ignored.

type Service

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

Service is a thin orchestrator: Repo + RefreshEnqueuer (optional) + AgentErrorConfigClient (optional). Held stateless so handlers can compose it freely.

func NewService

func NewService(repo repository) *Service

NewService builds a Service. Production passes *Repo.

func (*Service) GetErrorConfig

func (s *Service) GetErrorConfig(ctx context.Context, tenantID, siteID uuid.UUID) (ErrorConfig, error)

GetErrorConfig returns the stored error config for (tenantID, siteID). When no row exists yet it returns the default (error_level=6143, empty list).

func (*Service) IngestDiagnostics

func (s *Service) IngestDiagnostics(ctx context.Context, tenantID, siteID uuid.UUID, body []byte) (int, error)

IngestDiagnostics splits the agent-shipped 14-category blob into one upsert per category. The blob is shaped as

{
  "identity": {...},
  "php": {...},
  ...
  "collected_at": 1748505600
}

We extract `collected_at` (agent-side Unix seconds) and apply it to every category's row so a tab of cards can render a single "as of" timestamp.

collected_at is required (GH #618). A push without a positive integer collected_at is refused whole with a validation error (HTTP 422): no category row, no DB-size trend point, no timezone or address update. A report of unknown age is never stored as if it had just been collected, because the operator view would then show it as fresh.

func (*Service) IngestErrorBatch

func (s *Service) IngestErrorBatch(ctx context.Context, tenantID, siteID uuid.UUID, batch ErrorBatch) (int64, error)

func (*Service) LatestBySite

func (s *Service) LatestBySite(ctx context.Context, tenantID, siteID uuid.UUID) (map[Category]Diagnostic, error)

LatestBySite returns a map keyed by category string. Categories the agent has not yet shipped are present in the map only when stored — the handler fills in "awaiting first sync" placeholders for missing ones.

func (*Service) ListErrors

func (s *Service) ListErrors(ctx context.Context, tenantID, siteID uuid.UUID, f ListPHPErrorsFilter) ([]PHPError, string, error)

ListErrors passes through to the repo. Returns the page and the next-page cursor (empty when exhausted).

func (*Service) RefreshAgent

func (s *Service) RefreshAgent(ctx context.Context, tenantID, siteID uuid.UUID) error

RefreshAgent fires the on-demand command. Returns nil on success; when the enqueuer is unwired it returns a stable "feature unwired" error the handler turns into a 501.

func (*Service) ResolveHostProvider

func (s *Service) ResolveHostProvider(ctx context.Context, tenantID, siteID uuid.UUID, observedIP string, body []byte)

ResolveHostProvider infers and records the site's hosting provider from the agent's egress IP (M28). Best-effort and non-fatal, called after a diagnostics push. It prefers the CP-observed source IP, falling back to the agent-reported public IP (hosting.public_ip, fetched by the agent from ipify) ONLY when the observed IP is not globally routable — the self-host-behind-proxy / same-LAN case. The result is recorded even when the provider is unrecognized so the observed IP, raw network org, and checked-at are stored (auditable + visible), and a changed IP re-resolves on the next push.

func (*Service) SaveErrorConfig

func (s *Service) SaveErrorConfig(ctx context.Context, tenantID, siteID uuid.UUID, cfg ErrorConfig) (ErrorConfig, error)

SaveErrorConfig validates the new config, upserts it in the database, and pushes it to the agent via the sync_error_config command. Returns the stored config. If the agentcmd client is not wired the upsert still succeeds and the config is stored — the push is skipped with a logged warning rather than a hard failure (the operator can trigger a manual re-sync later).

func (*Service) SetDBSizeHistorySink

func (s *Service) SetDBSizeHistorySink(sink DBSizeHistorySink)

SetDBSizeHistorySink wires the DB-size trend writer (GH #196). Optional: when never called, ingestDBSizeHistory silently no-ops.

func (*Service) SetErrorConfigClient

func (s *Service) SetErrorConfigClient(client AgentErrorConfigClient, sites SiteLookup)

SetErrorConfigClient wires the agentcmd client for pushing error config to the agent. Must be called before any SyncErrorConfig call. The SiteLookup is required alongside it so the service can resolve the site URL without a hard dependency on the site package.

func (*Service) SetHostResolver

func (s *Service) SetHostResolver(r HostResolver)

SetHostResolver wires the offline IP -> hosting-provider resolver (M28). Optional: when nil, ResolveHostProvider is a no-op and host_provider stays "".

func (*Service) SetRefreshEnqueuer

func (s *Service) SetRefreshEnqueuer(e RefreshEnqueuer)

SetRefreshEnqueuer wires the on-demand refresh enqueuer once it is built (the enqueuer needs the River client; the service is built before River starts).

func (*Service) SetReportedURLSink

func (s *Service) SetReportedURLSink(sink ReportedURLSink)

SetReportedURLSink wires the sink for the agent-reported address. Call once at boot.

func (*Service) SetSilenced

func (s *Service) SetSilenced(ctx context.Context, tenantID, siteID uuid.UUID, md5 string, silenced bool) error

SetSilenced passes through.

type SiteLookup

type SiteLookup interface {
	GetSiteURL(ctx context.Context, tenantID, siteID uuid.UUID) (string, error)
}

SiteLookup resolves the agent URL for a given (tenant, site). The CP keeps the canonical URL in the sites table (RLS-scoped); this interface keeps the diagnostics package out of a hard dependency on the site service. The adapter in cmd/wpmgr wires *site.Service into it.

type UpsertPHPErrorInput

type UpsertPHPErrorInput struct {
	MD5             string
	Code            int
	Severity        string
	Message         string
	File            string
	Line            int
	RequestPath     string
	FirstSeenAt     time.Time
	LastSeenAt      time.Time
	OccurrenceCount int64
	AgentRowID      int64        // the agent's local id for the row (cursor tracking)
	Backtrace       []ErrorFrame // up to 10 frames, most-recent-call-first
}

UpsertPHPError batch-applies the agent-shipped errors. For each row we ON CONFLICT bump occurrence_count by the agent-reported delta, refresh last_seen, and keep the first_seen the existing row already carried. Returns the highest agent-supplied id from the batch so the handler can echo the cursor advance back.

Jump to

Keyboard shortcuts

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