---
id: DisconnectSource
name: Disconnect Source
version: 1.0.0
summary: |
Disconnect a source — clears credentials, removes visibility states, sets status to DISCONNECTED.
badges:
- content: DELETE
backgroundColor: red
textColor: red
- content: CEN-36
backgroundColor: blue
textColor: blue
---
## Overview
`DELETE /visibility/sources/:id`
Disconnects a source by:
1. Deleting all `PageVisibilityState` records for this source
2. Clearing encrypted credentials
3. Setting source status to `DISCONNECTED`
Returns 204 No Content on success.
## Request
| Parameter | Location | Required | Description |
|-----------|----------|----------|-------------|
| `id` | Path | Yes | Source UUID |
| `x-tenant-id` | Header | Yes | Tenant isolation |
## Response
`204 No Content` — no body.
## Errors
| Status | Code | When |
|--------|------|------|
| 404 | `SOURCE_NOT_FOUND` | Source doesn't exist or wrong tenant |
## Side Effects
- All `PageVisibilityState` rows for this source are **permanently deleted**
- OAuth credentials are cleared (encrypted_credentials set to null)
- Pages themselves are **not** deleted — they may have data from other sources
---
id: GetConnectors
name: Get Connectors
version: 1.0.0
summary: Lists all registered connector workers with their capabilities and registration timestamps.
badges:
- content: GET
backgroundColor: green
textColor: green
- content: Phase 3
backgroundColor: orange
textColor: orange
---
## Endpoint
`GET /visibility/connectors`
## Request
No parameters required.
## Response
```json
{
"connectors": [
{
"workerName": "gsc-connector",
"workerURL": "http://gsc-connector:3002",
"sourceTypes": ["GSC"],
"supportedActions": ["indexation", "search_analytics"],
"capabilities": { ... },
"schemaContribution": { ... },
"registeredAt": "2026-04-08T14:30:00.000Z"
}
]
}
```
## Failures
None — always returns a list (empty if no connectors registered).
---
id: GetDiagnostics
name: Get Diagnostics
version: 1.0.0
summary: |
Returns non-indexed URLs grouped by exclusion reason with sample URLs per category. Explains why URLs lack visibility.
schemaPath: schema.json
badges:
- content: GET
backgroundColor: green
textColor: green
---
## Endpoint
```
GET /visibility/diagnostics
```
## Query Parameters
| Parameter | Type | Required | Default | Constraints |
|-----------|------|----------|---------|-------------|
| `project_id` | string | Yes | — | Valid UUID |
| `source_type` | enum | No | all sources | `GSC` \| `BING` \| `GA4` \| `CLOUDFLARE` \| `PRERENDER` |
| `reason_filter` | string | No | — | Filter to specific non-index reason code |
| `section_filter` | string | No | — | Filter to specific URL section |
| `limit` | integer | No | 100 | 1-1000, pagination on reason groups |
| `offset` | integer | No | 0 | >= 0, pagination offset |
## Response
```typescript
ApiResponse<{
by_reason: Array<{
reason_code: string;
reason_label: string; // the reason code, verbatim (Google's wording for indexation reasons)
affected_count: number;
sample_urls: Array<{ // max 10 per reason
url: string;
section_key: string;
last_checked_at: string; // ISO 8601
}>;
urls_is_sample: boolean; // true when affected_count > sample_urls.length
urls_total: number;
render_health?: { // CEN-250: only on reasons a connector declares google_declined
broken: number; // latest render day < 50 % successful renders
healthy: number;
unknown: number; // no render day within 14 days
};
}>;
total_issues: number;
coverage: CoverageInfo;
}>
```
## Failures
| Failure | HTTP Status | Code |
|---------|-------------|------|
| `ProjectNotFoundFailure` | 404 | `PROJECT_NOT_FOUND` |
## Response Schema
## Notes
- Sample URLs are clearly identified as examples, not full coverage (`urls_is_sample` flag)
- Maximum 10 sample URLs per reason group
- Unknown reason codes fall back to the raw code as the label
- Pagination applies to reason groups, not individual URLs
- `render_health` (CEN-250, D068) splits provider-declined reasons by the health of each page's latest render day; the declined states come from the connector's `coverageStateClasses`, never from core
- For full URL enumeration per reason, use the [GetUrls](/docs/queries/GetUrls) endpoint
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft-07/schema#",
"title": "GetDiagnostics Response",
"description": "Non-indexed URLs grouped by exclusion reason with sample URLs",
"type": "object",
"required": ["success", "data", "metadata"],
"properties": {
"success": { "type": "boolean", "const": true },
"data": {
"type": "object",
"required": ["by_reason", "total_issues", "coverage"],
"properties": {
"by_reason": {
"type": "array",
"items": {
"type": "object",
"required": ["reason_code", "reason_label", "affected_count", "sample_urls", "urls_is_sample", "urls_total"],
"properties": {
"reason_code": { "type": "string", "description": "Raw non-index reason code from source" },
"reason_label": { "type": "string", "description": "The reason code, verbatim (Google's coverage state for indexation reasons)" },
"affected_count": { "type": "integer", "minimum": 0 },
"sample_urls": {
"type": "array",
"maxItems": 10,
"items": {
"type": "object",
"required": ["url", "section_key", "last_checked_at"],
"properties": {
"url": { "type": "string" },
"section_key": { "type": "string" },
"last_checked_at": { "type": "string", "format": "date-time" }
}
}
},
"urls_is_sample": { "type": "boolean", "description": "True when affected_count > sample_urls.length" },
"urls_total": { "type": "integer", "minimum": 0 },
"render_health": {
"type": "object",
"description": "CEN-250: pages of a provider-declined reason by latest render-day health",
"required": ["broken", "healthy", "unknown"],
"properties": {
"broken": { "type": "integer", "minimum": 0 },
"healthy": { "type": "integer", "minimum": 0 },
"unknown": { "type": "integer", "minimum": 0 }
}
}
}
}
},
"total_issues": { "type": "integer", "minimum": 0 },
"coverage": {
"type": "object",
"properties": {
"totalSources": { "type": "integer" },
"activeSources": { "type": "integer" },
"coveragePercent": { "type": "number" }
}
}
}
}
}
}
---
id: GetHealthCheck
name: Get Health Check
version: 1.0.0
summary: |
Simple liveness check returning module status, version, and name. No authentication required.
badges:
- content: GET
backgroundColor: green
textColor: green
---
## Endpoint
```
GET /visibility/healthz
```
## Query Parameters
_None_
## Response
```typescript
{
status: 'ok';
version: '1.0.0';
module: 'visibility';
}
```
**HTTP Status:** `200 OK`
## Failures
This endpoint does not return any failure responses.
## Notes
- No authentication or tenant context required
- Returns static values indicating the module is loaded and responsive
- Useful for load balancer health probes and service mesh readiness checks
---
id: GetIndexationVerdicts
name: Get Indexation Verdicts
version: 1.1.0
summary: |
Google's index verdicts for a scope: how many pages sit in each coverage state, grouped by the connector's stable coverage state code, counted on each page's latest URL Inspection in the window (30 days by default). Backs the "Google index status" section on Search Performance. Counts use the same predicate as the `/urls` inspection filter, so a row's count equals the `/urls` total on the indexation view filtered to that `coverage_state_code`.
schemaPath: schema.json
badges:
- content: GET
backgroundColor: green
textColor: green
---
## Endpoint
```
GET /visibility/indexation/verdicts
```
## Query Parameters
| Parameter | Type | Required | Default | Constraints |
| ----------------------- | ------- | -------- | ------- | --------------------------------------------------------------------------- |
| `project_id` | string | Yes | — | Valid UUID |
| `domain` | string | No | — | Domain registered in the project. Mutually exclusive with `property_url` |
| `property_url` | string | No | — | Search Console property URL, byte for byte. Mutually exclusive with `domain` |
| `inspected_within_days` | integer | No | 30 | 1–365; an empty value means 30 |
## Response
```typescript
ApiResponse<{
state: 'never_run' | 'ok'; // never_run: no indexation run has completed for this scope yet
verdicts: Array<{
coverage_state: string | null; // Google's wording, verbatim, for display; a code row shows its most recent inspection's wording; null when Google returned none
coverage_state_code: string | null; // connector's stable snake_case code (e.g. crawled_not_indexed); null when undeclared
coverage_state_class: string | null; // indexed_ok | google_declined | unknown_to_google | intentional_exclusion | technical_failure; null when undeclared
inspection_verdict: string; // INDEXED | NOT_INDEXED | EXCLUDED | UNKNOWN — the verdict most of the row's pages carry
url_count: number; // pages whose latest in-window inspection has this state
}>; // one row per coverage state code (per coverage state when undeclared), largest count first; states with no pages are omitted
inspected_total: number; // sum of url_count
inspected_from: string | null; // ISO 8601 — oldest of the counted inspections
inspected_to: string | null; // ISO 8601 — newest of the counted inspections
last_updated: string | null; // ISO 8601 — when the scope's last indexation run completed
daily_inspection_limit: number; // configured pages per GSC property per night
daily_inspection_limit_scope: 'property';
}>;
```
## Response Schema
## Notes
- **Counting rule.** One count per page: each page's latest inspection in the window among the scope's inspection sources (under a property, its own sources; otherwise one precedence winner per scope key). A page inspected by two sources counts once, under its latest state. One row per coverage state: Google reports the verdict separately, so a state can come back under two verdicts; the row's `inspection_verdict` is the one most of its pages carry, ties to the most recently inspected.
- **`state` and `last_updated`** come from the sync-job record: the newest `COMPLETED` `indexation` job of the scope's sources. Under `domain`, only the sources whose property maps to that domain count, so a newly connected domain reads `never_run` even when another domain of the tenant has run. `ok` with `inspected_total: 0` means a run completed but nothing was inspected in the window. While `never_run`, `verdicts` is empty.
- **`daily_inspection_limit`** is `INDEXATION_PRIORITISED_PAGE_LIMIT` (1,800 when unset; 100 on prod), applied per GSC property per night.
- **Coverage state codes (CEN-359).** Google's coverage state is a free sentence; the GSC connector declares a stable code and class for each wording (`ActionDeclaration.coverageStates`). Rows group by code, so a reworded state declared under its existing code stays one row; the row's `coverage_state` is the wording of its most recent inspection. A wording no connector declares keeps its own row with `coverage_state_code` and `coverage_state_class` null, and is logged once per process (`indexation.coverage-state.undeclared`) so the connector map can be updated. Core names no wording (D059.6).
- **Drilldown.** `GET /visibility/urls?source_type=GSC&action=indexation&inspected=true&coverage_state_code=` with the same scope and `inspected_within_days` lists the pages behind one row. A row with a null code drills down with `coverage_state=`. `/urls` cannot filter a null coverage state.
- Read-cached per tenant data version, like `/urls`.
- Errors: `400` invalid query (including both `domain` and `property_url`), `404` unknown project, domain or property.
## Changelog
- 1.1.0 (CEN-359): rows carry `coverage_state_code` and `coverage_state_class`, and group by code. Additive.
- 1.0.0 (CEN-343): first version.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft-07/schema#",
"title": "GetIndexationVerdicts Response",
"description": "Pages per coverage state code (the connector's stable code for Google's coverage state), counted on each page's latest URL Inspection in the window, with the section's freshness and the configured daily inspection limit.",
"type": "object",
"required": ["success", "data", "metadata"],
"properties": {
"success": { "type": "boolean", "const": true },
"data": {
"type": "object",
"required": [
"state",
"verdicts",
"inspected_total",
"inspected_from",
"inspected_to",
"last_updated",
"daily_inspection_limit",
"daily_inspection_limit_scope"
],
"properties": {
"state": {
"type": "string",
"enum": ["never_run", "ok"],
"description": "never_run until an indexation run has completed for the scope"
},
"verdicts": {
"type": "array",
"description": "One row per coverage state code (per coverage state when undeclared), largest url_count first; states with no pages are omitted",
"items": {
"type": "object",
"required": [
"coverage_state",
"coverage_state_code",
"coverage_state_class",
"inspection_verdict",
"url_count"
],
"properties": {
"coverage_state": {
"type": ["string", "null"],
"description": "Google's coverage state, verbatim, for display; on a code row, the wording of its most recent inspection. null when Google returned none"
},
"coverage_state_code": {
"type": ["string", "null"],
"description": "Stable snake_case code the connector declares for the coverage state (e.g. crawled_not_indexed). Key on this, not on the wording. null when the connector declares none"
},
"coverage_state_class": {
"type": ["string", "null"],
"enum": ["indexed_ok", "google_declined", "unknown_to_google", "intentional_exclusion", "technical_failure", null],
"description": "Platform class of the coverage state; null when the connector declares none"
},
"inspection_verdict": {
"type": "string",
"description": "The verdict most of the row's pages carry; ties to the most recently inspected",
"enum": ["INDEXED", "NOT_INDEXED", "EXCLUDED", "UNKNOWN"]
},
"url_count": { "type": "integer", "minimum": 1 }
}
}
},
"inspected_total": { "type": "integer", "minimum": 0 },
"inspected_from": { "type": ["string", "null"], "format": "date-time" },
"inspected_to": { "type": ["string", "null"], "format": "date-time" },
"last_updated": {
"type": ["string", "null"],
"format": "date-time",
"description": "When the scope's last indexation run completed"
},
"daily_inspection_limit": {
"type": "integer",
"minimum": 1,
"description": "Configured pages inspected per GSC property per night"
},
"daily_inspection_limit_scope": { "type": "string", "const": "property" }
}
},
"metadata": { "type": "object" }
}
}
---
id: GetInspect
name: Get Inspect
version: 1.2.0
summary: |
Deep-dive into a single URL's visibility across all data sources. Shows per-source index status, crawl data, and Prerender state. Optional property_url scopes the read to one Search Console property and its Prerender companion (D052).
schemaPath: schema.json
badges:
- content: GET
backgroundColor: green
textColor: green
---
## Endpoint
```
GET /visibility/inspect
```
## Query Parameters
| Parameter | Type | Required | Default | Constraints |
|-----------|------|----------|---------|-------------|
| `project_id` | string | Yes | — | Valid UUID |
| `url` | string | Yes | — | Valid URL |
| `property_url` | string | No | all properties | Exact `sources.propertyUrl` of a GSC property connected to this tenant (`https://example.com` and `sc-domain:example.com` are distinct). Scopes GSC reads to that property and crawl reads to its PRERENDER companion, any lifecycle — a disconnected property still returns its history. Unknown value, or a property whose host is not a domain of the project → 404 `PROPERTY_NOT_FOUND` |
| `refresh` | boolean | No | — | Accepted but deferred (not implemented) |
## Response
```typescript
ApiResponse<{
url: string;
normalized_url: string;
section_key: string;
sources: Array<{
source_type: string;
source_name: string;
is_indexed: boolean | null;
non_index_reason: string | null;
last_crawled_at: string | null; // ISO 8601
last_seen_at: string | null; // ISO 8601
inspection_origin: 'on_demand' | 'scheduled' | 'manual' | null; // indexation rows; null otherwise (PRE-4012)
raw_payload: Record | null;
}>;
prerender: {
last_render_at: string | null; // ISO 8601
http_status: number | null;
is_cached: boolean;
} | null;
coverage: CoverageInfo;
}>
```
## Failures
| Failure | HTTP Status | Code |
|---------|-------------|------|
| `ProjectNotFoundFailure` | 404 | `PROJECT_NOT_FOUND` |
| `PropertyNotFoundFailure` | 404 | `PROPERTY_NOT_FOUND` |
| `InvalidURLFailure` | 400 | `INVALID_URL` |
## Response Schema
## Notes
- Missing source data uses `null` fields rather than omitting entries, so consumers can distinguish "no data" from "not indexed"
- The `refresh` parameter is accepted for forward-compatibility but has no effect in the current version
- `raw_payload` contains source-specific metadata when available
- Prerender state is `null` when no rendering data exists for the URL
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft-07/schema#",
"title": "GetInspect Response",
"description": "Single URL deep-dive across all data sources",
"type": "object",
"required": ["success", "data", "metadata"],
"properties": {
"success": { "type": "boolean", "const": true },
"data": {
"type": "object",
"required": ["url", "normalized_url", "section_key", "sources", "prerender", "coverage"],
"properties": {
"url": { "type": "string", "description": "Original URL as stored" },
"normalized_url": { "type": "string", "description": "Normalized URL for matching" },
"section_key": { "type": "string" },
"sources": {
"type": "array",
"items": {
"type": "object",
"required": ["source_type", "source_name", "is_indexed", "non_index_reason", "last_crawled_at", "last_seen_at", "inspection_origin", "raw_payload"],
"properties": {
"source_type": { "type": "string", "enum": ["GSC", "BING", "GA4", "CLOUDFLARE", "PRERENDER"] },
"source_name": { "type": "string" },
"is_indexed": { "type": ["boolean", "null"] },
"non_index_reason": { "type": ["string", "null"] },
"last_crawled_at": { "type": ["string", "null"], "format": "date-time" },
"last_seen_at": { "type": ["string", "null"], "format": "date-time" },
"inspection_origin": {
"type": ["string", "null"],
"enum": ["on_demand", "scheduled", "manual", null],
"description": "How an indexation row was produced: on_demand (live inspection), scheduled (daily sync), manual (manual sync); null on other actions and when its operation is unknown"
},
"raw_payload": { "type": ["object", "null"], "description": "Source-specific metadata" }
}
}
},
"prerender": {
"type": ["object", "null"],
"properties": {
"last_render_at": { "type": ["string", "null"], "format": "date-time" },
"http_status": { "type": ["integer", "null"] },
"is_cached": { "type": "boolean" }
}
},
"coverage": {
"type": "object",
"properties": {
"totalSources": { "type": "integer" },
"activeSources": { "type": "integer" },
"coveragePercent": { "type": "number" }
}
}
}
}
}
}
---
id: GetLiveInspectionUsage
name: Get Live Inspection Usage
version: 1.1.0
summary: |
Today's live-inspection usage for one GSC property of a project: used, budget, remaining, and the UTC reset time.
schemaPath: schema.json
badges:
- content: GET
backgroundColor: green
textColor: green
- content: CEN-362
backgroundColor: blue
textColor: blue
---
## Endpoint
```
GET /visibility/inspect/live/usage
```
## Query Parameters
| Parameter | Type | Required | Constraints |
|-----------|------|----------|-------------|
| `project_id` | string | Yes | Valid UUID |
| `property_url` | string | No | Exact `sources.propertyUrl` of a property of the project: the project has the domain of the property's host, as on the read routes. Without it the project must have exactly one such property. |
## Response
```typescript
ApiResponse<{
source_id: string;
property_url: string;
used: number;
budget: number;
remaining: number;
resets_at: string; // ISO 8601, next UTC midnight
}>
```
## Failures
| Failure | HTTP Status | Code |
|---------|-------------|------|
| `ProjectNotFoundFailure` | 404 | `PROJECT_NOT_FOUND` |
| `PropertyNotFoundFailure` (unknown, or not a property of this project) | 404 | `PROPERTY_NOT_FOUND` |
| `LiveInspectionSourceNotFoundFailure` | 404 | `NO_GSC_SOURCE` (no `url` field) |
| `AmbiguousLiveInspectionSourceFailure` | 409 | `PROPERTY_REQUIRED` (+ `property_urls[]`, no `url` field) |
## Response Schema
## Notes
- 1.1.0 (CEN-376): a `property_url` of another project answers 404; without `property_url`, a property on a subdomain the project does not register no longer counts.
- Read-only: never reserves budget. The counter covers every live inspection reserved today, failed ones included.
- Background: `packages/visibility-docs/explanation/about-live-inspection.md` and `packages/visibility-docs/reference/live-inspection.md`.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft-07/schema#",
"title": "GetLiveInspectionUsage Response",
"description": "Today's live-inspection usage for one GSC property",
"type": "object",
"required": ["success", "data", "metadata"],
"properties": {
"success": { "type": "boolean", "const": true },
"data": {
"type": "object",
"required": ["source_id", "property_url", "used", "budget", "remaining", "resets_at"],
"properties": {
"source_id": { "type": "string", "format": "uuid" },
"property_url": { "type": "string" },
"used": {
"type": "integer",
"description": "Live inspections reserved today (UTC), failed ones included"
},
"budget": { "type": "integer", "description": "Knob inspection.liveDailyBudget" },
"remaining": { "type": "integer" },
"resets_at": { "type": "string", "format": "date-time", "description": "Next UTC midnight" }
}
}
}
}
---
id: GetOperationDetail
name: Get Operation Detail
version: 1.0.0
summary: Returns one operation plus its ordered event timeline. 404 when the operation does not belong to the tenant.
badges:
- content: GET
backgroundColor: green
textColor: green
- content: TenantGuard
backgroundColor: red
textColor: red
---
## Endpoint
`GET /visibility/operations/:id`
Served by `OperationsController`, backed by [Operation Tracker Service](/docs/services/OperationTrackerService). Requires the `x-tenant-id` header (UUID).
## Request
| Param | Type | Notes |
|---|---|---|
| `:id` | uuid | Operation id. |
## Response
```json
{
"operation": {
"id": "0d2c…",
"type": "daily_sync",
"status": "COMPLETED",
"summary": "Daily sync completed",
"startedAt": "2026-06-17T02:00:00.000Z",
"completedAt": "2026-06-17T02:04:31.000Z"
},
"events": [
{ "stage": "operation", "status": "STARTED", "message": "Daily sync started" },
{ "stage": "sync_stage", "status": "COMPLETED", "message": "Stage GSC sync completed" },
{ "stage": "ranking", "status": "COMPLETED", "message": "Daily ranking completed" },
{ "stage": "operation", "status": "COMPLETED", "message": "Daily sync completed" }
]
}
```
Events are ordered by `createdAt` ascending. Returns **404** when no operation with that id exists for the tenant (`OperationNotFoundFailure` → `NotFoundException`).
---
id: GetOperations
name: Get Operations
version: 1.0.0
summary: Lists sync operations (daily / manual) for the tenant, newest first, with optional status and type filters.
badges:
- content: GET
backgroundColor: green
textColor: green
- content: TenantGuard
backgroundColor: red
textColor: red
---
## Endpoint
`GET /visibility/operations`
Served by `OperationsController`, backed by [Operation Tracker Service](/docs/services/OperationTrackerService). Requires the `x-tenant-id` header (UUID) — missing or malformed → 401.
## Request
| Query param | Type | Notes |
|---|---|---|
| `status` | enum | `RUNNING` / `COMPLETED` / `COMPLETED_WITH_ERRORS` / `FAILED`. Optional. |
| `type` | enum | `daily_sync` / `manual_source_sync` / `manual_tenant_sync`. Optional. |
| `limit` | number | Positive integer, capped at 100. Defaults to 25. |
## Response
```json
[
{
"id": "0d2c…",
"tenantId": "a1b2…",
"type": "daily_sync",
"status": "COMPLETED_WITH_ERRORS",
"summary": "Daily sync completed with warnings",
"startedAt": "2026-06-17T02:00:00.000Z",
"completedAt": "2026-06-17T02:04:31.000Z",
"metadata": { "timedOut": false, "failedSteps": 1 }
}
]
```
Tenant-scoped: only the calling tenant's operations are returned.
---
id: GetOverview
name: Get Overview
version: 1.1.0
summary: |
Returns aggregate visibility metrics including totals, percentages, per-section breakdown, and source coverage for a project. Optional property_url scopes the read to one Search Console property and its Prerender companion (D052).
schemaPath: schema.json
badges:
- content: GET
backgroundColor: green
textColor: green
---
## Endpoint
```
GET /visibility/overview
```
## Query Parameters
| Parameter | Type | Required | Default | Constraints |
|-----------|------|----------|---------|-------------|
| `project_id` | string | Yes | — | Valid UUID |
| `domain` | string | No | all domains | A domain registered in the project; unknown domains fail with 404 |
| `property_url` | string | No | all properties | Exact `sources.propertyUrl` of a GSC property connected to this tenant (`https://example.com` and `sc-domain:example.com` are distinct). Scopes GSC reads to that property and crawl reads to its PRERENDER companion, any lifecycle — a disconnected property still returns its history. Indexation totals / `by_section` follow the property's host domain (as with `domain`), not its sources. Unknown value, or a property whose host is not a domain of the project → 404 `PROPERTY_NOT_FOUND`. Mutually exclusive with `domain` (400) |
| `source_type` | enum | No | all sources | `GSC` \| `BING` \| `GA4` \| `CLOUDFLARE` \| `PRERENDER` |
| `date_start` | date | No | — | ISO 8601 date |
| `date_end` | date | No | — | ISO 8601 date |
## Response
```typescript
ApiResponse<{
domain: string;
totals: {
total_urls: number; // denominator for percentages
indexed: number;
not_indexed: number;
excluded: number;
unknown: number;
};
percentages: {
indexed: number; // 0-100
not_indexed: number;
excluded: number;
unknown: number;
};
by_section: Array<{ // max 20 sections
section_key: string;
total: number;
indexed: number;
indexed_percent: number; // 0-100
}>;
coverage: CoverageInfo;
url_coverage: {
total_urls: number; // |served ∪ found|, each URL counted once
served_and_found: number;
served_only: number;
found_only: number;
};
}>
```
### url_coverage
Role-based URL set decomposition for the requested window. Always present; zeros when no data.
| Field | Meaning |
| --- | --- |
| `total_urls` | URLs recorded by either signal, each counted once |
| `served_and_found` | Served to a search crawler AND has search presence |
| `served_only` | Served, no search presence recorded |
| `found_only` | Search presence, never served |
Invariant: `total_urls = served_and_found + served_only + found_only` (computed in a single set-decomposition query).
Signal roles are source-agnostic: `served` is fulfilled today by Prerender crawl stats (`googlebot_request_count > 0`), `found` by Search Console metrics (`impressions > 0`). New sources map to roles in `coverage-signals.ts` without an API change.
## Failures
| Failure | HTTP Status | Code |
|---------|-------------|------|
| `ProjectNotFoundFailure` | 404 | `PROJECT_NOT_FOUND` |
| `DomainNotFoundFailure` | 404 | `DOMAIN_NOT_FOUND` |
| `PropertyNotFoundFailure` | 404 | `PROPERTY_NOT_FOUND` |
## Response Schema
## Notes
- Percentages use `total_urls` as denominator; all are 0 when `total_urls` is 0
- Maximum of 20 sections returned in `by_section`
- Represents search visibility metrics, not definitive index status
- Response metadata includes source freshness and staleness indicators
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft-07/schema#",
"title": "GetOverview Response",
"description": "Aggregate visibility metrics for a project",
"type": "object",
"required": ["success", "data", "metadata"],
"properties": {
"success": { "type": "boolean", "const": true },
"data": {
"type": "object",
"required": ["domain", "totals", "percentages", "by_section", "coverage", "url_coverage"],
"properties": {
"domain": { "type": "string", "description": "Domain name" },
"totals": {
"type": "object",
"required": ["total_urls", "indexed", "not_indexed", "excluded", "unknown"],
"properties": {
"total_urls": { "type": "integer", "description": "Denominator for all percentages" },
"indexed": { "type": "integer", "description": "URLs visible in search results" },
"not_indexed": { "type": "integer", "description": "URLs not visible" },
"excluded": { "type": "integer", "description": "URLs explicitly excluded" },
"unknown": { "type": "integer", "description": "URLs with unknown status" }
}
},
"percentages": {
"type": "object",
"required": ["indexed", "not_indexed", "excluded", "unknown"],
"properties": {
"indexed": { "type": "number", "minimum": 0, "maximum": 100 },
"not_indexed": { "type": "number", "minimum": 0, "maximum": 100 },
"excluded": { "type": "number", "minimum": 0, "maximum": 100 },
"unknown": { "type": "number", "minimum": 0, "maximum": 100 }
}
},
"by_section": {
"type": "array",
"maxItems": 20,
"items": {
"type": "object",
"required": ["section_key", "total", "indexed", "indexed_percent"],
"properties": {
"section_key": { "type": "string" },
"total": { "type": "integer" },
"indexed": { "type": "integer" },
"indexed_percent": { "type": "number", "minimum": 0, "maximum": 100 }
}
}
},
"coverage": { "$ref": "#/$defs/CoverageInfo" },
"url_coverage": {
"type": "object",
"required": ["total_urls", "served_and_found", "served_only", "found_only"],
"properties": {
"total_urls": { "type": "integer", "minimum": 0, "description": "URLs recorded by either signal, each counted once" },
"served_and_found": { "type": "integer", "minimum": 0, "description": "Served to a search crawler AND has search presence" },
"served_only": { "type": "integer", "minimum": 0, "description": "Served, no search presence recorded" },
"found_only": { "type": "integer", "minimum": 0, "description": "Search presence, never served" }
}
}
}
},
"metadata": { "$ref": "#/$defs/ResponseMetadata" }
},
"$defs": {
"CoverageInfo": {
"type": "object",
"required": ["totalSources", "activeSources", "coveragePercent"],
"properties": {
"totalSources": { "type": "integer" },
"activeSources": { "type": "integer" },
"coveragePercent": { "type": "number", "minimum": 0, "maximum": 100 }
}
},
"ResponseMetadata": {
"type": "object",
"required": ["requestId", "timestamp", "sources", "freshness", "coverage"],
"properties": {
"requestId": { "type": "string", "format": "uuid" },
"timestamp": { "type": "string", "format": "date-time" },
"sources": {
"type": "array",
"items": {
"type": "object",
"properties": {
"type": { "type": "string", "enum": ["GSC", "BING", "GA4", "CLOUDFLARE", "PRERENDER"] },
"name": { "type": "string" },
"lastSyncAt": { "type": ["string", "null"], "format": "date-time" },
"isEnabled": { "type": "boolean" }
}
}
},
"freshness": {
"type": "object",
"properties": {
"oldestDataAt": { "type": ["string", "null"] },
"newestDataAt": { "type": ["string", "null"] },
"staleSources": { "type": "array", "items": { "type": "string" } },
"isStale": { "type": "boolean" }
}
},
"coverage": { "$ref": "#/$defs/CoverageInfo" }
}
}
}
}
---
id: GetRankingLatest
name: Get Ranking Latest
version: 1.0.0
summary: |
Returns the latest URL ranking run for a (tenant, source). Three buckets — `proveValue`, `findProblems`, `expandCoverage` — each carrying count, paginated URL rows, and a stable narrative string.
badges:
- content: GET
backgroundColor: green
textColor: green
- content: Phase 3C
backgroundColor: orange
textColor: orange
---
## Endpoint
```
GET /visibility/ranking/latest
```
Tenant-scoped — requires the `x-tenant-id` header (`TenantGuard`, CEN-60).
## Query Parameters
| Parameter | Type | Required | Default | Constraints |
|-----------|------|----------|---------|-------------|
| `source_id` | string | Yes | — | Valid UUID |
| `bucket` | enum | No | `all` | `prove_value` \| `find_problems` \| `expand_coverage` \| `all` |
| `limit` | int | No | `100` | 1–1000 |
| `offset` | int | No | `0` | >= 0 |
## Response
```typescript
{
runId: string;
createdAt: string; // ISO 8601
scorerVersion: string; // e.g. 'composite-v1' | 'topsis-v1'
totalEligible: number; // size of the union of all buckets
buckets: {
proveValue: { count: number; urls: RankedUrlDto[]; narrative: string };
findProblems: { count: number; urls: RankedUrlDto[]; narrative: string };
expandCoverage: { count: number; urls: RankedUrlDto[]; narrative: string };
};
}
type RankedUrlDto = {
pageId: string;
url: string;
score: number;
reason: string | null;
bucket: 'prove_value' | 'find_problems' | 'expand_coverage';
};
```
`count` and `narrative` always reflect the **full** bucket. `urls` is the paginated slice (`offset..offset+limit`). When `bucket !== 'all'` and the bucket doesn't match, `urls` is empty.
## Failures
| HTTP Status | Condition |
|-------------|-----------|
| 401 | Missing or malformed `x-tenant-id` header |
| 404 | No ranking run exists for `(tenantId, source_id)` |
## Notes
- Narratives are rendered server-side by `NarrativeTemplateService` (CEN-78) and are stable across `limit`/`offset` changes.
- `findProblems` scoring varies by `RANKING_SCORER_TOKEN` injection (`composite` default, `topsis` opt-in per D024).
---
id: GetSchemaActions
name: Get Schema Actions
version: 1.0.0
summary: Lists actions for a source type with per-action field counts and temporal modes.
badges:
- content: GET
backgroundColor: green
textColor: green
- content: Phase 3
backgroundColor: orange
textColor: orange
---
## Endpoint
`GET /visibility/schema/sources/:sourceType/actions`
## Request
| Location | Parameter | Required | Description |
|----------|-----------|----------|-------------|
| Path | `sourceType` | Yes | Source type identifier (e.g., `gsc`, case-insensitive) |
## Response
```json
{
"sourceType": "GSC",
"actions": [
{
"action": "indexation",
"label": "URL Indexation Status",
"temporalMode": "SNAPSHOT_ONLY",
"fieldCount": 2
},
{
"action": "search_analytics",
"label": "Search Analytics",
"temporalMode": "TIME_SERIES",
"fieldCount": 4
}
]
}
```
## Failures
| Failure | HTTP Status | When |
|---------|------------|------|
| NotFoundException | 404 | Source type not registered |
---
id: GetSchemaFields
name: Get Schema Fields
version: 1.0.0
summary: Returns typed field metadata for a specific source type and action, enabling dynamic UI rendering.
badges:
- content: GET
backgroundColor: green
textColor: green
- content: Phase 3
backgroundColor: orange
textColor: orange
---
## Endpoint
`GET /visibility/schema/sources/:sourceType/actions/:action/fields`
## Request
| Location | Parameter | Required | Description |
|----------|-----------|----------|-------------|
| Path | `sourceType` | Yes | Source type identifier (e.g., `gsc`, case-insensitive) |
| Path | `action` | Yes | Action name (e.g., `indexation`, `search_analytics`) |
## Response
```json
{
"sourceType": "GSC",
"action": "indexation",
"fields": [
{
"path": "indexing_status",
"type": "text",
"sourceType": "GSC",
"action": "indexation",
"label": "Indexing Status",
"description": "Google indexation verdict: INDEXED, NOT_INDEXED, or EXCLUDED",
"filterable": true,
"sortable": true
},
{
"path": "non_index_reason",
"type": "text",
"sourceType": "GSC",
"action": "indexation",
"label": "Non-Index Reason",
"description": "Reason a URL is not indexed (e.g., noindex, redirect, crawl anomaly)",
"filterable": true,
"sortable": false
}
]
}
```
## Failures
| Failure | HTTP Status | When |
|---------|------------|------|
| NotFoundException | 404 | Source type not registered, or action not found for source |
---
id: GetSchemaSources
name: Get Schema Sources
version: 1.0.0
summary: Lists all registered connector source types with action and field counts.
badges:
- content: GET
backgroundColor: green
textColor: green
- content: Phase 3
backgroundColor: orange
textColor: orange
---
## Endpoint
`GET /visibility/schema/sources`
## Request
No parameters required.
## Response
```json
{
"sources": [
{
"sourceType": "GSC",
"name": "Google Search Console",
"actionCount": 3,
"fieldCount": 7
}
]
}
```
## Failures
None — always returns a list (empty if no connectors registered).
---
id: GetSections
name: Get Sections
version: 1.0.0
summary: |
Returns section-level health aggregation with diagnostic indicators. Health status (HEALTHY/WARNING/CRITICAL) is based on indexation percentage.
schemaPath: schema.json
badges:
- content: GET
backgroundColor: green
textColor: green
---
## Endpoint
```
GET /visibility/sections
```
## Query Parameters
| Parameter | Type | Required | Default | Constraints |
|-----------|------|----------|---------|-------------|
| `project_id` | string | Yes | — | Valid UUID |
| `source_type` | enum | No | all sources | `GSC` \| `BING` \| `GA4` \| `CLOUDFLARE` \| `PRERENDER` |
## Response
```typescript
ApiResponse<{
sections: Array<{
section_key: string;
total: number;
indexed: number;
not_indexed: number;
indexed_percent: number; // 0-100
health_status: 'HEALTHY' | 'WARNING' | 'CRITICAL';
top_issues: Array<{ // max 3 per section
reason_code: string;
reason_label: string;
affected_count: number;
}>;
}>;
total_sections: number;
coverage: CoverageInfo;
}>
```
## Health Status Thresholds
| Status | Condition |
|--------|-----------|
| `HEALTHY` | indexed\_percent > 80% |
| `WARNING` | 50% <= indexed\_percent <= 80% |
| `CRITICAL` | indexed\_percent < 50% |
## Failures
| Failure | HTTP Status | Code |
|---------|-------------|------|
| `ProjectNotFoundFailure` | 404 | `PROJECT_NOT_FOUND` |
## Response Schema
## Notes
- Health status is a diagnostic indicator, not a guarantee of search engine behavior
- Top issues are limited to 3 per section (the most impactful non-index reasons)
- All counts are non-negative integers
- Coverage metadata indicates whether data represents full coverage or sampled data
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft-07/schema#",
"title": "GetSections Response",
"description": "Section-level health aggregation with diagnostic indicators",
"type": "object",
"required": ["success", "data", "metadata"],
"properties": {
"success": { "type": "boolean", "const": true },
"data": {
"type": "object",
"required": ["sections", "total_sections", "coverage"],
"properties": {
"sections": {
"type": "array",
"items": {
"type": "object",
"required": ["section_key", "total", "indexed", "not_indexed", "indexed_percent", "health_status", "top_issues"],
"properties": {
"section_key": { "type": "string" },
"total": { "type": "integer", "minimum": 0 },
"indexed": { "type": "integer", "minimum": 0 },
"not_indexed": { "type": "integer", "minimum": 0 },
"indexed_percent": { "type": "number", "minimum": 0, "maximum": 100 },
"health_status": { "type": "string", "enum": ["HEALTHY", "WARNING", "CRITICAL"] },
"top_issues": {
"type": "array",
"maxItems": 3,
"items": {
"type": "object",
"required": ["reason_code", "reason_label", "affected_count"],
"properties": {
"reason_code": { "type": "string" },
"reason_label": { "type": "string" },
"affected_count": { "type": "integer", "minimum": 0 }
}
}
}
}
}
},
"total_sections": { "type": "integer", "minimum": 0 },
"coverage": {
"type": "object",
"properties": {
"totalSources": { "type": "integer" },
"activeSources": { "type": "integer" },
"coveragePercent": { "type": "number" }
}
}
}
}
}
}
---
id: GetSectionsCoverage
name: Get Sections Coverage
version: 1.1.0
summary: |
Section-level coverage rollup: the three role-decomposition buckets (served_and_found / served_only / found_only) plus impressions, clicks, SQL-derived CTR, and delivery-error counts per first-level section. Sortable on every column, paginated, reconciles with the overview url_coverage totals. Optional property_url scopes the read to one Search Console property and its Prerender companion (D052).
schemaPath: schema.json
badges:
- content: GET
backgroundColor: green
textColor: green
---
## Endpoint
```
GET /visibility/sections/coverage
```
## Query Parameters
| Parameter | Type | Required | Default | Constraints |
|-----------|------|----------|---------|-------------|
| `project_id` | string | Yes | — | Valid UUID |
| `domain` | string | No | all domains | Registered in the project |
| `property_url` | string | No | all properties | Exact `sources.propertyUrl` of a GSC property connected to this tenant (`https://example.com` and `sc-domain:example.com` are distinct). Scopes GSC reads to that property and crawl reads to its PRERENDER companion, any lifecycle — a disconnected property still returns its history. Unknown value, or a property whose host is not a domain of the project → 404 `PROPERTY_NOT_FOUND`. Mutually exclusive with `domain` (400) |
| `date_start` | string | No | unbounded | `YYYY-MM-DD` |
| `date_end` | string | No | unbounded | `YYYY-MM-DD` |
| `sort_by` | enum | No | `section_key` | Any returned column, including `ctr` |
| `sort_order` | enum | No | `asc` | `asc` \| `desc` |
| `limit` | number | No | 50 | 1–200 |
| `offset` | number | No | 0 | ≥ 0 |
## Response
```typescript
ApiResponse<{
sections: Array<{
section_key: string; // pages.section; null → 'uncategorized'
served_and_found: number; // served to a crawler AND search presence
served_only: number; // served, no search presence in window
found_only: number; // search presence, never served in window
impressions: number | null; // null = no search data for this section
clicks: number | null;
ctr: number | null; // clicks/impressions; null at 0 impressions
error_pages: number | null; // pages with googlebot errors in window
}>;
pagination: { total: number; limit: number; offset: number; has_more: boolean };
freshness: {
latest_crawl_date: string | null; // unwindowed max crawl_date
latest_search_data_date: string | null; // unwindowed max data_date (GSC lags 2-3 days)
};
}>
```
## Failures
| Failure | HTTP Status | Code |
|---------|-------------|------|
| `ProjectNotFoundFailure` | 404 | `PROJECT_NOT_FOUND` |
| `DomainNotFoundFailure` | 404 | `DOMAIN_NOT_FOUND` |
| `PropertyNotFoundFailure` | 404 | `PROPERTY_NOT_FOUND` |
## Semantics
- Bucket membership reuses the overview coverage-signals predicates verbatim — per-bucket sums across all sections equal `GET /visibility/overview` `url_coverage` for the same window.
- Metric `null` means "no data of that kind in the window"; a real `0` means the source reported zeros. Rendering (`—`) is a consumer concern.
- Overlapping GSC registrations behind one property dedupe to one winning row per page-day; disconnected sources' collected data stays readable (FW1).
- Every sort is `NULLS LAST` with a deterministic `section_key` tiebreak.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft-07/schema#",
"title": "GetSectionsCoverage Response",
"description": "Section-level coverage rollup: role-decomposition buckets plus search metrics and delivery errors per first-level section",
"type": "object",
"required": ["success", "data", "metadata"],
"properties": {
"success": { "type": "boolean", "const": true },
"data": {
"type": "object",
"required": ["sections", "pagination", "freshness"],
"properties": {
"sections": {
"type": "array",
"items": {
"type": "object",
"required": [
"section_key",
"served_and_found",
"served_only",
"found_only",
"impressions",
"clicks",
"ctr",
"error_pages"
],
"properties": {
"section_key": { "type": "string" },
"served_and_found": { "type": "integer", "minimum": 0 },
"served_only": { "type": "integer", "minimum": 0 },
"found_only": { "type": "integer", "minimum": 0 },
"impressions": { "type": ["integer", "null"], "minimum": 0 },
"clicks": { "type": ["integer", "null"], "minimum": 0 },
"ctr": { "type": ["number", "null"], "minimum": 0, "maximum": 1 },
"error_pages": { "type": ["integer", "null"], "minimum": 0 }
}
}
},
"pagination": {
"type": "object",
"required": ["total", "limit", "offset", "has_more"],
"properties": {
"total": { "type": "integer", "minimum": 0 },
"limit": { "type": "integer", "minimum": 1 },
"offset": { "type": "integer", "minimum": 0 },
"has_more": { "type": "boolean" }
}
},
"freshness": {
"type": "object",
"required": ["latest_crawl_date", "latest_search_data_date"],
"properties": {
"latest_crawl_date": { "type": ["string", "null"], "format": "date" },
"latest_search_data_date": { "type": ["string", "null"], "format": "date" }
}
}
}
},
"metadata": { "type": "object" }
}
}
---
id: GetSemanticMetadata
name: Get Semantic Metadata
version: 1.0.0
summary: |
Returns resolved `FieldMetadata[]` for a `(workerName, sourceType, action)` triple. Each field carries a `semantic` block plus a `semanticSource` tag — `'declared' | 'heuristic' | 'override'` — so the reviewer UI can highlight what came from where.
badges:
- content: GET
backgroundColor: green
textColor: green
- content: Phase 3C
backgroundColor: orange
textColor: orange
---
## Endpoint
```
GET /visibility/connectors/:workerName/semantic-metadata
```
## Path / Query Parameters
| Parameter | Location | Type | Required |
|-----------|----------|------|----------|
| `workerName` | path | string | Yes |
| `sourceType` | query | string | Yes |
| `action` | query | string | Yes |
## Response
```typescript
{
workerName: string;
sourceType: string;
action: string;
fields: ResolvedFieldMetadata[];
}
type ResolvedFieldMetadata = FieldMetadata & {
semantic: SemanticFieldMetadata;
semanticSource: 'declared' | 'heuristic' | 'override';
};
```
## Resolution Order
`ConnectorRegistryService.getSemanticMetadata` resolves `semantic` per field in priority:
1. **override** — durable per-(sourceType, action, path) override persisted on the owning worker's `connector_registrations.semanticOverrides` JSONB (CEN-87).
2. **declared** — value the connector shipped with the field.
3. **heuristic** — proposal from `SemanticClassifierService` regex rules.
No LLM call is made at runtime.
## Failures
| HTTP Status | Condition |
|-------------|-----------|
| 404 | Unknown `workerName` |
---
id: GetSourceDetail
name: Get Source Detail
version: 1.0.0
summary: |
Detailed view of a single source including capabilities, supported actions, and recent sync job history.
badges:
- content: GET
backgroundColor: green
textColor: green
- content: CEN-36
backgroundColor: blue
textColor: blue
---
## Overview
`GET /visibility/sources/:id`
Returns full source detail including capabilities JSONB, supported actions from connector config, and the 20 most recent sync jobs.
## Request
| Parameter | Location | Required | Description |
|-----------|----------|----------|-------------|
| `id` | Path | Yes | Source UUID |
| `x-tenant-id` | Header | Yes | Tenant isolation |
## Response
```json
{
"id": "uuid",
"name": "Google Search Console",
"type": "GSC",
"status": "ACTIVE",
"propertyUrl": "sc-domain:example.com",
"disconnectReason": null,
"connectedAt": "2026-03-23T12:00:00Z",
"supportedActions": [...],
"lastSyncAt": "2026-04-02T02:00:00Z",
"capabilities": {
"supportsIndexStatus": true,
"supportsCrawlData": true,
"supportsTrafficData": false,
"supportsHistoricalData": true,
"dataRetentionDays": 480
},
"recentJobs": [
{
"id": "uuid",
"action": "indexation",
"status": "COMPLETED",
"recordsProcessed": 1500,
"startedAt": "2026-04-02T02:00:00Z",
"completedAt": "2026-04-02T02:15:00Z",
"error": null
}
]
}
```
`disconnectReason` (`user` | `token_revoked` | `replaced` | `access_lost` | `null`) carries the same values as
`GET /visibility/sources` — see List Sources for the meaning of each.
## Errors
| Status | Code | When |
|--------|------|------|
| 404 | `SOURCE_NOT_FOUND` | Source doesn't exist or wrong tenant |
---
id: GetSourceJobs
name: Get Source Job History
version: 1.0.0
summary: |
Sync job history for a source, filterable by action. Returns up to 50 most recent jobs.
badges:
- content: GET
backgroundColor: green
textColor: green
- content: CEN-36
backgroundColor: blue
textColor: blue
---
## Overview
`GET /visibility/sources/:id/jobs`
Returns sync job history for a source, ordered by creation date descending. Optionally filterable by action.
## Request
| Parameter | Location | Required | Description |
|-----------|----------|----------|-------------|
| `id` | Path | Yes | Source UUID |
| `action` | Query | No | Filter by action (e.g., `indexation`, `search_analytics`) |
| `x-tenant-id` | Header | Yes | Tenant isolation |
## Response
```json
[
{
"id": "uuid",
"action": "indexation",
"status": "COMPLETED",
"recordsProcessed": 1500,
"startedAt": "2026-04-02T02:00:00Z",
"completedAt": "2026-04-02T02:15:00Z",
"error": null
},
{
"id": "uuid",
"action": "search_analytics",
"status": "FAILED",
"recordsProcessed": 0,
"startedAt": "2026-04-02T02:15:00Z",
"completedAt": "2026-04-02T02:15:05Z",
"error": "Token refresh failed"
}
]
```
## Job Status Values
| Status | Meaning |
|--------|---------|
| `PENDING` | Job created, waiting to start |
| `RUNNING` | Currently fetching data |
| `COMPLETED` | Finished successfully |
| `FAILED` | Error occurred (see `error` field) |
---
id: GetSources
name: List Sources
version: 1.0.0
summary: |
List all configured data sources for a tenant with status, supported actions, and last sync timestamp.
badges:
- content: GET
backgroundColor: green
textColor: green
- content: CEN-36
backgroundColor: blue
textColor: blue
---
## Overview
`GET /visibility/sources`
Returns all sources for the tenant including connection status, supported actions (from connector config), and the most recent completed sync timestamp.
## Request
| Parameter | Location | Required | Description |
|-----------|----------|----------|-------------|
| `x-tenant-id` | Header | Yes | Tenant isolation |
## Response
```json
[
{
"id": "uuid",
"name": "Google Search Console",
"type": "GSC",
"status": "ACTIVE",
"propertyUrl": "sc-domain:example.com",
"disconnectReason": null,
"connectedAt": "2026-03-23T12:00:00Z",
"supportedActions": [
{ "action": "indexation", "label": "URL Indexation Status", "temporalMode": "SNAPSHOT_ONLY" },
{ "action": "search_analytics", "label": "Search Analytics", "temporalMode": "TIME_SERIES" }
],
"lastSyncAt": "2026-04-02T02:00:00Z"
}
]
```
## Status Values
| Status | Meaning |
|--------|---------|
| `PENDING` | Created, OAuth not completed |
| `ACTIVE` | Connected and syncing |
| `ERROR` | Connection or sync failure |
| `DISCONNECTED` | No longer syncing — `disconnectReason` says why |
## Disconnect Reasons
`disconnectReason` is `null` unless `status` is `DISCONNECTED`. It is the typed discriminator
clients should branch on instead of matching `statusMessage` text.
| Reason | Meaning | Reconnect prompt? |
|--------|---------|-------------------|
| `user` | The customer disconnected the source on purpose | No |
| `token_revoked` | Google revoked or expired the OAuth grant; every property row from that grant is flipped together | Yes — send the user through the OAuth consent flow (`?reconnect=1`) |
| `replaced` | Superseded by another live property on the same domain (`activate-selection` with `replace: true`) | No |
| `access_lost` | Google answered the property with 403 during a sync — the property was removed from the connected account or the user's permission was revoked; the sync disconnected the source and cleared its credentials | Yes — same prompt as `token_revoked` |
---
id: GetTrends
name: Get Trends
version: 1.0.0
summary: |
Historical trend data for visibility metrics over time. MVP skeleton — currently returns 422 for all sources as no connector supports TIME_SERIES yet.
schemaPath: schema.json
badges:
- content: GET
backgroundColor: green
textColor: green
- content: MVP Skeleton
backgroundColor: yellow
textColor: yellow
---
## Endpoint
```
GET /visibility/trends
```
## Query Parameters
| Parameter | Type | Required | Default | Constraints |
|-----------|------|----------|---------|-------------|
| `project_id` | string | Yes | — | Valid UUID |
| `source_type` | enum | Yes | — | `GSC` \| `BING` \| `GA4` \| `CLOUDFLARE` \| `PRERENDER` |
| `metric` | string | Yes | — | e.g., `indexed`, `not_indexed` (min 1 char) |
| `date_start` | date | Yes | — | ISO 8601 date |
| `date_end` | date | Yes | — | ISO 8601 date |
| `granularity` | enum | No | `day` | `day` \| `week` \| `month` |
## Response (when TIME_SERIES connectors exist)
```typescript
ApiResponse<{
metric: string;
granularity: 'day' | 'week' | 'month';
points: Array<{
date: string; // ISO 8601 date
value: number;
}>;
}>
```
## Failures
| Failure | HTTP Status | Code |
|---------|-------------|------|
| `CapabilityNotSupportedFailure` | 422 | `CAPABILITY_NOT_SUPPORTED` |
## Current Behavior (MVP)
All sources are `SNAPSHOT_ONLY` — every valid request returns **422 Unprocessable Entity** with:
```json
{
"message": "Trend data is not available for this source",
"code": "CAPABILITY_NOT_SUPPORTED",
"source_type": "",
"capability": "TIME_SERIES",
"reason": "This data source does not support historical trend data."
}
```
## Response Schema
## Notes
- This is an MVP skeleton endpoint that validates inputs and checks connector capabilities
- No `TrendsService` exists until at least one connector supports `TIME_SERIES`
- The connector capability system (`ConnectorCapabilities.config.ts`) makes it easy to enable trends per source by switching `temporalMode` from `SNAPSHOT_ONLY` to `TIME_SERIES`
- GSC has `dataRetentionDays: 480` (~16 months) so it's the most likely first candidate for TIME_SERIES support
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft-07/schema#",
"title": "GetTrends Response",
"description": "Historical trend data for visibility metrics (MVP: always returns 422)",
"type": "object",
"required": ["success", "data", "metadata"],
"properties": {
"success": { "type": "boolean", "const": true },
"data": {
"type": "object",
"required": ["metric", "granularity", "points"],
"properties": {
"metric": { "type": "string", "description": "The metric being trended (e.g., indexed, not_indexed)" },
"granularity": { "type": "string", "enum": ["day", "week", "month"] },
"points": {
"type": "array",
"items": {
"type": "object",
"required": ["date", "value"],
"properties": {
"date": { "type": "string", "format": "date", "description": "ISO 8601 date" },
"value": { "type": "number" }
}
}
}
}
}
}
}
---
id: GetUrls
name: Get URLs
version: 1.11.0
summary: |
Paginated, filterable, sortable URL listing. Each row carries `page_id` and only the columns its listing view's source owns — GSC views: windowed search metrics and `metric_state`; PRERENDER views: crawler-served status and timestamp. Coverage-bucket presence filters and status filters work on every view. Backs the Pages drill-down tabs. Optional property_url scopes the read to one Search Console property and its Prerender companion (D052). `page_ids` pins the listing to an explicit set of pages so a consumer holding one view's rows can fetch the same pages from another view and join on `page_id`.
schemaPath: schema.json
badges:
- content: GET
backgroundColor: green
textColor: green
---
## Endpoint
```
GET /visibility/urls
```
## Query Parameters
| Parameter | Type | Required | Default | Constraints |
| ------------------------ | -------- | -------- | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `project_id` | string | Yes | — | Valid UUID |
| `source_type` | enum | No | all sources | `GSC` \| `BING` \| `GA4` \| `CLOUDFLARE` \| `PRERENDER` \| `SITEMAP` \| `PSI` |
| `action` | string | No | source type's default view | URL-capable source action (e.g. `indexation`, `search_pages`, `rendering`, `crawl_stats`, `discover`, `lighthouse_audit`) |
| `indexing_status` | enum | No | — | `indexed` \| `not_indexed` \| `excluded` \| `unknown` |
| `non_index_reason` | string | No | — | Filter by specific non-index reason code |
| `section_key` | string | No | — | Filter by URL section |
| `url_contains` | string | No | — | Substring match on URL (min 1 char) |
| `domain` | string | No | all domains | A domain registered in the project; unknown domains fail with 404 |
| `property_url` | string | No | all properties | Exact `sources.propertyUrl` of a GSC property connected to this tenant (`https://example.com` and `sc-domain:example.com` are distinct). Scopes GSC reads to that property and crawl reads to its PRERENDER companion, any lifecycle — a disconnected property still returns its history. Unknown value, or a property whose host is not a domain of the project → 404 `PROPERTY_NOT_FOUND`. Mutually exclusive with `domain` (400) |
| `date_start` | string | No | — | `YYYY-MM-DD`; bounds the search-metrics window, the presence filters, and the crawler-status probe |
| `date_end` | string | No | — | `YYYY-MM-DD`; bounds the search-metrics window, the presence filters, and the crawler-status probe |
| `served_in_period` | boolean | No | — | `true` keeps pages Prerender served to Googlebot inside the window; `false` excludes them |
| `found_in_period` | boolean | No | — | `true` keeps pages with winning GSC impressions inside the window; `false` excludes them |
| `delivery_error` | boolean | No | — | `true` keeps pages whose latest in-window crawler-served status is not 200; `false` keeps pages whose latest status is 200 or that have none. Works on every view |
| `last_status_code` | integer | No | — | 100-599; keeps pages whose latest in-window crawler-served status equals this code. Works on every view |
| `last_status_code_class` | string[] | No | — | `2xx` \| `3xx` \| `4xx` \| `5xx` \| `other`; repeat the key or send a single unbracketed value. Classes OR together. `other` is any non-null status whose hundreds digit is not 2–5 (1xx, 0, 6xx+, …). Pages with no in-window status match no class. Omitted or empty = no filter. ANDs with `last_status_code` when both are set |
| `page_ids` | string[] | No | — | 1–200 UUIDs (`pages.id`, the `page_id` of any `/urls` row); repeat the key (`page_ids=a&page_ids=b`), send a single value, or comma-separate (`page_ids=a,b` — the form that keeps 200 ids under the ingress request-line limit); forms may be mixed, empty segments are dropped. A bracketed `page_ids[]` key is dropped by the server and the filter is absent. Keeps only these pages; ANDs with every other filter, so a requested page that fails the view, a presence filter, `domain` or `property_url` is simply absent. Ids the tenant or project does not own are absent, never `404`. `pagination.total` counts the matching pages; pass `limit` ≥ the number of ids to get them in one response |
| `inspected_within_days` | integer | No | — (empty value: 30) | 1–365. Opt-in for the inspection fields: every row carries `inspection_verdict`, `coverage_state`, `coverage_state_code`, `coverage_state_class` and `inspected_at` (see [Inspection fields](#inspection-fields-inspected_within_days)). Absent, these keys are omitted and the listing runs exactly as without the parameter |
| `coverage_state` | string[] | No | — | Google coverage state, verbatim (e.g. `Crawled - currently not indexed`); repeat the key or send a single value, values OR together. Keeps pages whose latest inspection inside the `inspected_within_days` window (default 30) has one of the states. Every view (see [Inspection filters](#inspection-filters-coverage_state-inspected)) |
| `coverage_state_code` | string[] | No | — | Connector's stable code for a coverage state (e.g. `crawled_not_indexed`, see `GET /visibility/indexation/verdicts`); repeat the key or comma-separate, codes OR together. Matches every coverage state the connector maps to the code; an undeclared code matches no page. ANDs with `coverage_state`. Every view |
| `inspected` | boolean | No | — | `true` keeps pages with an inspection inside the `inspected_within_days` window (default 30); `false` keeps pages never inspected or last inspected before it. Every view |
| `sort_by` | enum | No | `url` | `url` \| `last_crawled_at` \| `last_seen_at` \| `impressions` \| `clicks` \| `ctr` \| `position`. `impressions` / `clicks` / `ctr` / `position` only on GSC views; `last_crawled_at` only on PRERENDER views; any other combination is `400` |
| `sort_order` | enum | No | `asc` | `asc` \| `desc` |
| `limit` | integer | No | 50 | 1-200 |
| `offset` | integer | No | 0 | >= 0 |
## Response
```typescript
ApiResponse<{
urls: Array<{
page_id: string; // UUID — stable page identity, the join key across views
url: string;
section_key: string;
is_indexed: boolean | null;
non_index_reason: string | null;
source_type: string | null;
last_crawled_at: string | null; // ISO 8601 — latest Googlebot request served by Prerender (PRERENDER views only)
last_seen_at: string | null; // ISO 8601 — listed view's row timestamp
last_status_code: number | null; // crawler-served HTTP status, same windowed probe as delivery_error (PRERENDER views only)
metric_state: 'metrics_recorded' | 'zero_in_period' | 'no_gsc_history' | null; // null off GSC views
impressions: number | null; // GSC views only
clicks: number | null; // GSC views only
ctr_pct: number | null; // derived at read, 1 decimal (GSC views only)
position: number | null; // impression-weighted, 1 decimal (GSC views only)
// Only with inspected_within_days; the keys are absent otherwise:
inspection_verdict?: string | null; // latest in-window URL Inspection verdict (GSC views only)
coverage_state?: string | null; // Google's coverage state, verbatim (GSC views only)
coverage_state_code?: string | null; // connector's stable code for it; null when undeclared (GSC views only)
coverage_state_class?: string | null; // its platform class; null when undeclared (GSC views only)
inspected_at?: string | null; // ISO 8601 — that inspection's time (GSC views only)
inspection_origin?: 'on_demand' | 'scheduled' | 'manual' | null; // how it was produced (GSC views only)
}>;
pagination: {
total: number;
limit: number;
offset: number;
has_more: boolean;
};
coverage: CoverageInfo;
}>;
```
## Column ownership
A row carries only the columns its listing view's source owns. Filters may reference any source.
| View | Populates | Always `null` |
| ------------------------------------------------------ | -------------------------------------------------------------- | ------------------------------------- |
| `GSC` / `indexation`, `GSC` / `search_pages` | `metric_state`, `impressions`, `clicks`, `ctr_pct`, `position` | `last_status_code`, `last_crawled_at` |
| `PRERENDER` / `rendering`, `PRERENDER` / `crawl_stats` | `last_status_code`, `last_crawled_at` | `metric_state` and the search metrics |
| `SITEMAP` / `discover`, `PSI` / `lighthouse_audit` | — | both groups |
`page_id`, `url`, `section_key`, `source_type` and `last_seen_at` are populated on every view;
`is_indexed` / `non_index_reason` come from the `indexation` view as before. To compose search
metrics and crawler status for one page, list it through both views and join on `page_id`.
`metric_state: null` means "not this view's column" — it is never a claim about GSC history.
## Inspection fields (`inspected_within_days`)
Opt-in per request (CEN-341): only a request carrying `inspected_within_days` reads inspections,
so a consumer that does not send it gets exactly the 1.7.0 response. With `inspected_within_days=N`
(an empty value means 30), GSC views (`indexation`, `search_pages`) set the page's latest URL
Inspection inside the last N days from the core read model `cur_indexation` (D065):
`inspection_verdict` (`INDEXED`, `NOT_INDEXED`, `EXCLUDED`, `UNKNOWN`), `coverage_state`
(Google's string, verbatim, for every verdict), `coverage_state_code` and `coverage_state_class`
(the connector's declaration for that wording, `null` when undeclared; CEN-359), `inspected_at`
and `inspection_origin` (`on_demand` for a live inspection, `scheduled` for the daily sync, `manual`
for a manual sync, `null` when the row has no known operation; PRE-4012).
All are `null` when the page has no inspection inside the window. PRERENDER, SITEMAP and PSI views
return them as `null` (D050).
The inspections are read for the returned page only (at most `limit` rows) and never change which
pages are listed, the sort or `pagination.total`. Sources follow the `indexation` view: the
property's GSC source under `property_url`, else one precedence winner per page (D042), any
lifecycle. `search_pages` still lists only pages with retained search data; to read an
inspected page with no search data, list it through `GSC`/`indexation` by `page_ids` — that row
carries the inspection fields with `metric_state: no_gsc_history` and null metrics.
## Inspection filters (`coverage_state`, `coverage_state_code`, `inspected`)
Row filters, valid on every view (D050 item 1: only the projection is gated). Both read each
page's latest inspection inside the `inspected_within_days` window (30 when the parameter is
absent) from `cur_indexation`, with the same sources as the inspection fields (property source
under `property_url`, else the D042 precedence winner, any lifecycle). A row's displayed
`coverage_state` therefore always matches the filter. They AND with every other filter and with
every sort, so `PRERENDER`/`crawl_stats` + `coverage_state=…` + `sort_by=last_crawled_at` lists the
crawled pages of one reason by last crawl, and its total equals the same filter on `GSC`/`indexation`
for the same presence tab. Sending a filter does not opt into the inspection fields; send
`inspected_within_days` for those.
`coverage_state_code` (CEN-359) matches every wording the connector of the view's inspection
sources maps to the code, so a reworded state keeps matching, and codes contain no commas, so a
comma-separated list works. New consumers filter by code; `coverage_state` stays for wordings no
connector declares and for compatibility. Both together AND, like any two filters.
The `GSC`/`indexation` view lists **one row per page**: the page's latest inspection among the
view's sources (any age), the same rule as the inspection filters and `GET
/visibility/indexation/verdicts`. `cur_indexation` holds a row per page and source, so a property
with a disconnected twin source used to list a page once per source; a verdict row's `url_count`
now equals `inspected=true&coverage_state_code=` on this view, and `page_ids` returns each page once.
Legacy `indexing_status` / `non_index_reason` stay as they are: filters on the `indexation`
view's own row (`cur_indexation`, unwindowed, `non_index_reason` null when indexed), which is
now the page's latest inspection. On every
other view they still return an empty list. New consumers use `coverage_state` / `inspected`.
## Per-URL metric state
| `metric_state` | Meaning | `impressions`/`clicks` | `ctr_pct` | `position` |
| ------------------ | ---------------------------------------------------------------------------- | ---------------------- | --------- | ------------------- |
| `metrics_recorded` | GSC search metrics exist for the URL inside the requested window | GSC values | derived | impression-weighted |
| `zero_in_period` | The URL appears in GSC data retained by Prerender, but not inside the window | `0` | `null` | `null` |
| `no_gsc_history` | No GSC history observed in data retained by Prerender | `null` | `null` | `null` |
| `null` | The listing view's source does not own search metrics (any non-GSC view) | `null` | `null` | `null` |
`no_gsc_history` makes no claim about Google Search itself — it only says no retained,
synchronized GSC data mentions the URL. Consumers read `metric_state` instead of inferring
state from `null` metrics.
Sorting by `impressions` or `clicks` ranks `zero_in_period` as numeric `0` and places
`no_gsc_history` after all numeric values in both directions. Sorting by `ctr` places both
no-impression states last in both directions, while recorded zero-click pages rank as `0`.
## Coverage-bucket presence filters (Pages drill-down tabs)
`served_in_period` and `found_in_period` are windowed `EXISTS` predicates built from the same
SQL bodies as the `/overview` `url_coverage` buckets, so tab totals reconcile with the KPI
cards by construction. The dashboard tab compositions:
| Tab | View | Filters |
| -------------------- | --------------------------- | ------------------------------------------------ |
| Top | `GSC` / `search_pages` | `found_in_period=true`, sort `impressions desc` |
| With impressions | `PRERENDER` / `crawl_stats` | `served_in_period=true`, `found_in_period=true` |
| No impressions | `PRERENDER` / `crawl_stats` | `served_in_period=true`, `found_in_period=false` |
| Delivery errors | `PRERENDER` / `crawl_stats` | `served_in_period=true`, `delivery_error=true` |
| Not Prerender-served | `GSC` / `search_pages` | `found_in_period=true`, `served_in_period=false` |
The `GSC`/`search_pages` listing is one row per page ever seen in retained GSC search data —
from any property regardless of lifecycle — with the Prerender columns `null` (crawler status is
a PRERENDER-view column). `GET /urls` reads a tenant/project-scoped `DISTINCT ON (page_id)` over
the platform search read model `day_search_analytics` (read by name, D069); the unscoped
`v_gsc_search_pages` view it replaced was dropped in CEN-347 (a view-level `DISTINCT ON` cannot
push those filters down, so nothing read it).
`delivery_error`, `last_status_code`, and `last_status_code_class` share one `LEFT JOIN LATERAL`
(latest in-window crawl day carrying a status) with the `last_status_code` projection, so on
PRERENDER views the displayed status can never contradict the filter; on other views the filter
still applies and the column is `null`. Without date params the join reads the unwindowed latest
status. `last_status_code_class` classifies that column by hundreds digit (`2xx`…`5xx`); `other`
is every remaining non-null status. Multiple classes OR together.
## Composing rows across views (`page_ids`)
`page_id` is the join key (D050 item 5); `page_ids` is how the other view is fetched for it. A
consumer holding one view's page — say the `GSC`/`search_pages` rows of a server-sorted tab —
sends those rows' `page_id` values as `page_ids` to the `PRERENDER`/`crawl_stats` view and gets
exactly those pages with the crawler columns, in one request, to compose the full row client-side:
```
GET /visibility/urls?project_id=…&source_type=PRERENDER&action=crawl_stats&page_ids=uuid-1,uuid-2,uuid-3&limit=3
```
The predicate is `page_id = ANY(:pageIds)` on the routed view's WHERE clause, so tenant scoping,
the view's source scope and every other filter still apply — a page that fails them is absent.
## Failures
| Failure | HTTP Status | Code |
| --------------------------- | ----------- | ----------------------- |
| `ProjectNotFoundFailure` | 404 | `PROJECT_NOT_FOUND` |
| `DomainNotFoundFailure` | 404 | `DOMAIN_NOT_FOUND` |
| `PropertyNotFoundFailure` | 404 | `PROPERTY_NOT_FOUND` |
| `InvalidSortForViewFailure` | 400 | `INVALID_SORT_FOR_VIEW` |
## Response Schema
## Notes
- 1.11.0 (PRE-4012): `inspection_origin` inspection field, from the operation that wrote the latest inspection. Additive; rows promoted before the release read `null`.
- 1.10.0 (CEN-359): `coverage_state_code` filter (repeated or comma-separated) and `coverage_state_code` / `coverage_state_class` inspection fields. Additive.
- 1.9.0: `coverage_state` (OR'd list) and `inspected` row filters on every view, windowed by `inspected_within_days` (default 30). Legacy `indexing_status` / `non_index_reason` kept unchanged (indexation view only). Additive
- 1.8.0: `inspected_within_days` opt-in adds `inspection_verdict`, `coverage_state`, `inspected_at` to every row (set on GSC views, `null` elsewhere). Additive; absent, responses are unchanged
- 1.7.0: `page_ids` filter (1–200 UUIDs; repeated, single or comma-separated) pins a listing to an explicit page set — the decoration half of the cross-view join. Additive
- 1.6.0: `property_url` scopes the read to one property and its Prerender companion (D052). Additive
- 1.5.0 (column ownership): PRERENDER-listed rows report `metric_state: null` and null metrics; GSC-listed rows report `last_status_code` / `last_crawled_at` as `null` even for crawled pages; cross-source `sort_by` is `400`. `page_id` added on every view. Not additive for consumers that read cross-source columns — compose across views via `page_id` instead
- The listed URL set is unwindowed by default — `date_start`/`date_end` bound the search metrics and the status probe; the set narrows only when a presence filter asks
- `last_crawled_at` is the crawler-served timestamp from Prerender crawl stats (PRERENDER views; null when never crawled); `last_seen_at` carries the listed view's own row timestamp
- Search metrics dedupe overlapping GSC registrations per page-day via the shared source-precedence rule; source lifecycle (disabled/disconnected) never gates collected data
- Supports URL exploration, not completeness guarantees
- Coverage metadata explains sampling when applicable
- Combine with `indexing_status` and `non_index_reason` filters to drill down from diagnostics
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft-07/schema#",
"title": "GetUrls Response",
"description": "Paginated URL listing. Each row carries page_id plus only the columns its listing view's source owns: GSC views populate the windowed search metrics and metric_state, PRERENDER views populate the crawler-served status and timestamp, everything else is null. The page_ids query filter pins the listing to an explicit set of page_id values so rows from two views can be composed client-side.",
"type": "object",
"required": ["success", "data", "metadata"],
"properties": {
"success": { "type": "boolean", "const": true },
"data": {
"type": "object",
"required": ["urls", "pagination", "coverage"],
"properties": {
"urls": {
"type": "array",
"items": {
"type": "object",
"required": [
"page_id",
"url",
"section_key",
"is_indexed",
"non_index_reason",
"source_type",
"last_crawled_at",
"last_seen_at",
"last_status_code",
"metric_state",
"impressions",
"clicks",
"ctr_pct",
"position"
],
"properties": {
"page_id": {
"type": "string",
"format": "uuid",
"description": "Stable page identity; the same page returns the same page_id from every view, so rows can be joined across listings"
},
"url": { "type": "string" },
"section_key": { "type": "string" },
"is_indexed": { "type": ["boolean", "null"] },
"non_index_reason": { "type": ["string", "null"] },
"source_type": { "type": ["string", "null"] },
"last_crawled_at": {
"type": ["string", "null"],
"format": "date-time",
"description": "Latest Googlebot request timestamp served by Prerender, windowed when date params are given. Populated on PRERENDER views only; null on other views and when never crawled"
},
"last_seen_at": { "type": ["string", "null"], "format": "date-time" },
"last_status_code": {
"type": ["integer", "null"],
"description": "Crawler-served HTTP status from the latest in-window crawl day carrying one; same probe as the delivery_error filter. Populated on PRERENDER views only; null on other views"
},
"metric_state": {
"type": ["string", "null"],
"enum": ["metrics_recorded", "zero_in_period", "no_gsc_history", null],
"description": "Explicit per-URL GSC search-metric state on GSC views. null on every other view: the view made no claim, which is not the same as no_gsc_history (no GSC history observed in data retained by Prerender)"
},
"impressions": {
"type": ["integer", "null"],
"minimum": 0,
"description": "GSC views only; null elsewhere"
},
"clicks": {
"type": ["integer", "null"],
"minimum": 0,
"description": "GSC views only; null elsewhere"
},
"ctr_pct": {
"type": ["number", "null"],
"minimum": 0,
"description": "GSC views only; null elsewhere"
},
"position": {
"type": ["number", "null"],
"minimum": 0,
"description": "GSC views only; null elsewhere"
},
"inspection_verdict": {
"type": ["string", "null"],
"description": "Only with inspected_within_days (key absent otherwise). Latest URL Inspection verdict inside the window on GSC views; null when none, and on every other view"
},
"coverage_state": {
"type": ["string", "null"],
"description": "Only with inspected_within_days. Google's coverage state of that inspection, verbatim; null when none, and on every other view"
},
"coverage_state_code": {
"type": ["string", "null"],
"description": "Only with inspected_within_days. The connector's stable code for that coverage state; null when undeclared or no inspection, and on every other view"
},
"coverage_state_class": {
"type": ["string", "null"],
"enum": ["indexed_ok", "google_declined", "unknown_to_google", "intentional_exclusion", "technical_failure", null],
"description": "Only with inspected_within_days. Platform class of that coverage state; null when undeclared or no inspection, and on every other view"
},
"inspected_at": {
"type": ["string", "null"],
"format": "date-time",
"description": "Only with inspected_within_days. Time of that inspection; null when none, and on every other view"
},
"inspection_origin": {
"type": ["string", "null"],
"enum": ["on_demand", "scheduled", "manual", null],
"description": "Only with inspected_within_days. How that inspection was produced: on_demand (live inspection), scheduled (daily sync), manual (manual sync); null when none, when its operation is unknown, and on every other view"
}
}
}
},
"pagination": {
"type": "object",
"required": ["total", "limit", "offset", "has_more"],
"properties": {
"total": { "type": "integer", "minimum": 0 },
"limit": { "type": "integer", "minimum": 1 },
"offset": { "type": "integer", "minimum": 0 },
"has_more": { "type": "boolean" }
}
},
"coverage": {
"type": "object",
"properties": {
"totalSources": { "type": "integer" },
"activeSources": { "type": "integer" },
"coveragePercent": { "type": "number" }
}
}
}
}
}
}
---
id: GetVersion
name: Get Version
version: 1.0.0
summary: Returns the semver label and git SHA the running visibility-api was deployed from.
badges:
- content: GET
backgroundColor: green
textColor: green
- content: CEN-176
backgroundColor: orange
textColor: orange
---
## Endpoint
`GET /visibility/version`
Bearer-guarded (`ApiTokenGuard`), tenant-agnostic — no `x-tenant-id` required.
## Response
```json
{
"service": "visibility-api",
"version": "visibility@v1.1.0",
"sha": "5ee74c1f00e6c1f0a3b2c4d5e6f708192a3b4c5d"
}
```
`version` and `sha` are `null` when the deployment carries no stamp (e.g. local
dev without `VISIBILITY_VERSION` / `VISIBILITY_GIT_SHA` env). The stamp is
resolved at deploy time from `visibility@v*` git tags at the SHA the API image
was built from; a deploy racing the release job may briefly trail by one
release and self-heals on the next deploy (see CEN-176 spec).
---
id: GetViewHealth
name: Get View Health
version: 1.0.0
summary: Returns health status for all materialized views including last refresh time and row counts.
badges:
- content: GET
backgroundColor: green
textColor: green
- content: Phase 3
backgroundColor: orange
textColor: orange
---
## Endpoint
`GET /visibility/views/health`
## Request
No parameters required.
## Response
```json
{
"views": [
{
"name": "mv_prerender_crawl_stats_daily",
"sourceType": "PRERENDER",
"action": "crawl_stats",
"refreshSchedule": "after_sync",
"lastRefreshedAt": "2026-04-08T02:15:30.000Z",
"rowCount": 15230
},
{
"name": "day_search_analytics",
"sourceType": "GSC",
"action": "search_analytics",
"refreshSchedule": "after_sync",
"lastRefreshedAt": "2026-04-08T02:15:45.000Z",
"rowCount": 48100
}
]
}
```
## Notes
- `lastRefreshedAt` may be `null` if the view has never been refreshed
- `rowCount` is approximate (from `pg_stat_user_tables.n_live_tup`)
- Useful for operational monitoring — detect stale views that haven't refreshed after sync
---
id: GetViews
name: Get Views
version: 1.0.0
summary: Lists all registered materialized views with their source type, action, and refresh schedule.
badges:
- content: GET
backgroundColor: green
textColor: green
- content: Phase 3
backgroundColor: orange
textColor: orange
---
## Endpoint
`GET /visibility/views`
## Request
No parameters required.
## Response
```json
{
"views": [
{
"name": "mv_prerender_crawl_stats_daily",
"sourceType": "PRERENDER",
"action": "crawl_stats",
"refreshSchedule": "after_sync"
},
{
"name": "day_search_analytics",
"sourceType": "GSC",
"action": "search_analytics",
"refreshSchedule": "after_sync"
}
]
}
```
## Failures
None — always returns a list.
---
id: OAuthActivate
name: OAuth Activate Source
version: 1.0.0
summary: |
Activate a source after OAuth — test API access to selected property, set status to ACTIVE, store capabilities.
badges:
- content: POST
backgroundColor: orange
textColor: orange
- content: CEN-27
backgroundColor: blue
textColor: blue
---
## Overview
`POST /oauth/gsc/activate`
After the user selects a GSC property from the callback response, this endpoint tests API access and activates the source.
## Request
```json
{
"source_id": "uuid",
"property_url": "sc-domain:example.com"
}
```
| Parameter | Location | Required | Description |
|-----------|----------|----------|-------------|
| `source_id` | Body | Yes | UUID of the source |
| `property_url` | Body | Yes | GSC property URL to connect |
| `x-tenant-id` | Header | Yes | Tenant isolation |
## Response
Returns the updated SourceEntity with status=ACTIVE.
```json
{
"id": "uuid",
"status": "ACTIVE",
"propertyUrl": "sc-domain:example.com",
"connectedAt": "2026-04-02T12:00:00Z",
"capabilities": { "supportsIndexStatus": true, ... }
}
```
## Errors
| Status | When |
|--------|------|
| 400 | No credentials stored (OAuth flow not completed) |
| 403 | No access to the selected property |
| 404 | Source not found |
| 409 | Exact duplicate: another live source of this type (ACTIVE, PENDING, or ERROR) already holds this exact `property_url` (`source-already-connected`) |
| 409 | Domain conflict: another live source already feeds this www-stripped domain via a different property representation (`domain-already-connected`) |
## What Happens
1. Retrieve encrypted credentials from SourceEntity
2. Call GSC API to verify access to the selected property
3. Set status=ACTIVE, store propertyUrl, connectedAt, capabilities from config
---
id: OAuthAuthorize
name: OAuth Authorize
version: 1.0.0
summary: |
Initiate GSC OAuth flow — validates source is PENDING, generates HMAC-signed state, returns Google consent URL.
badges:
- content: GET
backgroundColor: green
textColor: green
- content: CEN-27
backgroundColor: blue
textColor: blue
---
## Overview
`GET /oauth/gsc/authorize?source_id=`
Starts the OAuth2 authorization code flow for connecting a GSC property. Returns a URL to redirect the user to Google's consent screen.
## Request
| Parameter | Location | Required | Description |
|-----------|----------|----------|-------------|
| `source_id` | Query | Yes | UUID of the source to connect |
| `x-tenant-id` | Header | Yes | Tenant isolation |
## Response
```json
{
"authorizationUrl": "https://accounts.google.com/o/oauth2/v2/auth?scope=...&state=...&redirect_uri=..."
}
```
## Errors
| Status | When |
|--------|------|
| 404 | Source not found or wrong tenant |
| 409 | Source already ACTIVE (use disconnect first) |
## Security
The `state` parameter is HMAC-signed (SHA-256) with the encryption key to prevent OAuth CSRF attacks.
---
id: OAuthCallback
name: OAuth Callback
version: 1.0.0
summary: |
Handle Google OAuth callback — verify state HMAC, exchange code for tokens, encrypt and store, list GSC properties.
badges:
- content: GET
backgroundColor: green
textColor: green
- content: CEN-27
backgroundColor: blue
textColor: blue
---
## Overview
`GET /oauth/gsc/callback?code=&state=`
Called by Google after user grants consent. Exchanges the authorization code for access/refresh tokens, encrypts and stores them, then lists available GSC properties for the user to select.
## Request
| Parameter | Location | Required | Description |
|-----------|----------|----------|-------------|
| `code` | Query | Yes | Authorization code from Google |
| `state` | Query | Yes | HMAC-signed state (contains tenantId + sourceId) |
## Response
```json
{
"sourceId": "uuid",
"properties": [
{ "siteUrl": "sc-domain:example.com", "permissionLevel": "siteOwner" },
{ "siteUrl": "https://example.com/", "permissionLevel": "siteFullUser" }
]
}
```
## Errors
| Status | When |
|--------|------|
| 400 | Invalid state HMAC, token exchange failed |
| 404 | Source not found |
## What Happens
1. Verify HMAC signature on state parameter
2. Exchange authorization code for tokens via Google OAuth2
3. Encrypt tokens with AES-256-GCM (D011) and store in SourceEntity
4. Call GSC API to list available properties
5. Return property list for user to select
---
id: OAuthDisconnect
name: OAuth Disconnect
version: 1.0.0
summary: |
Disconnect OAuth credentials — clear tokens, set source to DISCONNECTED status.
badges:
- content: POST
backgroundColor: orange
textColor: orange
- content: CEN-27
backgroundColor: blue
textColor: blue
---
## Overview
`POST /oauth/gsc/disconnect`
Clears OAuth credentials and sets the source status to DISCONNECTED. Unlike `DELETE /visibility/sources/:id`, this only handles the OAuth credential cleanup — it does NOT delete visibility state data.
## Request
```json
{
"source_id": "uuid"
}
```
| Parameter | Location | Required | Description |
|-----------|----------|----------|-------------|
| `source_id` | Body | Yes | UUID of the source to disconnect |
| `x-tenant-id` | Header | Yes | Tenant isolation |
## Response
`204 No Content`
## Errors
| Status | When |
|--------|------|
| 404 | Source not found |
## Difference from DELETE /visibility/sources/:id
| Endpoint | Credentials | Visibility Data | Status |
|----------|-------------|-----------------|--------|
| `POST /oauth/gsc/disconnect` | Cleared | **Preserved** | DISCONNECTED |
| `DELETE /visibility/sources/:id` | Cleared | **Deleted** | DISCONNECTED |
Use OAuth disconnect to revoke access but keep historical data. Use DELETE to fully remove a source.
---
id: OAuthMintSelectionSession
name: OAuth Mint Selection Session
version: 1.0.0
summary: |
Mint a property selection session from stored OAuth tokens — refresh, list properties, persist — so Manage Domains can re-select GSC properties without re-running the Google consent flow.
badges:
- content: POST
backgroundColor: orange
textColor: orange
- content: CEN-237
backgroundColor: blue
textColor: blue
---
## Overview
`POST /oauth/gsc/selection-sessions`
Mints the same single-use, 24h selection session the OAuth callback produces, but from the
tokens already stored on a connected source — no consent screen. The caller's `source_id` is a
credentials donor (any ACTIVE GSC source); the session is persisted against a PENDING *seed*
source — the tenant's single enabled pending GSC slot (unique index), reused whichever flow
created it — and the response's `sourceId` is that seed — pass it to `activate-selection`
unchanged. When the seed already has a live un-consumed session (e.g. one a just-completed
OAuth callback handed to the property picker), minting refreshes that session in place — same
id, fresh property list, extended expiry — so no live session is ever invalidated; only
expired un-consumed sessions are pruned.
## Request
```json
{
"source_id": "uuid"
}
```
| Parameter | Location | Required | Description |
|-----------|----------|----------|-------------|
| `source_id` | Body | Yes | Donor source UUID — any non-disconnected, credentials-bearing GSC source |
| `x-tenant-id` | Header | Yes | Tenant isolation |
## Response
Same shape as `GET /oauth/gsc/selection-sessions/:id`.
```json
{
"id": "uuid",
"sourceId": "uuid (the seed — use this for activate-selection)",
"sourceType": "GSC",
"properties": [{ "siteUrl": "sc-domain:example.com", "permissionLevel": "siteOwner" }],
"expiresAt": "2026-08-25T12:00:00Z",
"consumedAt": null,
"createdAt": "2026-08-24T12:00:00Z"
}
```
## Errors
| Status | Body `error` | Meaning |
|---|---|---|
| 404 | — | Donor source not found for the tenant |
| 409 | `reconnect-required` (`reason`: `token_revoked` \| `user` \| `replaced` \| `access_lost` \| `no_credentials` \| `disconnected`) | Stored access is gone — for an already-DISCONNECTED donor `reason` is its stored `disconnectReason` (`disconnected` only for legacy rows without one); send the user through the OAuth consent flow (`?reconnect=1`) |
| 502 | `oauth-refresh-unavailable` | Google token refresh failed transiently; nothing changed, retry |
| 503 | `mint-not-persisted` | The seed/session write failed; retry |
| 400 | — | Other OAuth errors |
A `token_revoked` mint also flips the donor source — and every other live source of the tenant
holding the same refresh token — to `DISCONNECTED` with `disconnectReason: token_revoked`
(`refreshCredentials` side effect), so the dashboard's source list reflects the revocation at once.
---
id: PostLiveInspection
name: Post Live Inspection
version: 1.1.1
summary: |
Inspects one URL with Google URL Inspection now, saves the result into the normal history → promote flow, and counts it against the property's daily live-inspection budget.
schemaPath: schema.json
badges:
- content: POST
backgroundColor: orange
textColor: orange
- content: CEN-362
backgroundColor: blue
textColor: blue
- content: CEN-376
backgroundColor: blue
textColor: blue
---
## Endpoint
```
POST /visibility/inspect/live
```
Synchronous: one call takes ~7 s on dev (p95 7.1 s over 18 calls, 2026-11-06); the worst case with Google 429 retries is about 1 min. Callers need a timeout of at least 90 s.
## Body
| Field | Type | Required | Constraints |
|-------|------|----------|-------------|
| `project_id` | string | Yes | Valid UUID |
| `url` | string | Yes | Absolute http(s) URL whose host is a domain of the project (or a subdomain of one) and whose page belongs to this project. Known URLs and typed URLs both work; an unknown URL becomes a page. |
| `property_url` | string | No | Exact `sources.propertyUrl` of the GSC property to inspect against. Needed only when several properties of the project cover the URL. Must be a property of the project (the project has the domain of the property's host, as on the read routes) and cover the URL host. |
## Response
```typescript
ApiResponse<{
page_id: string; // page the result is saved to, as on /urls
url: string; // that page's stored URL
normalized_url: string;
inspection_url: string | null; // URL submitted to Google
property_url: string;
source_id: string;
inspected_at: string; // ISO 8601, the time stored on the inspection row
is_indexed: boolean; // verdict === 'INDEXED'
verdict: 'INDEXED' | 'NOT_INDEXED' | 'EXCLUDED' | 'UNKNOWN';
coverage_state: string | null; // Google's wording, verbatim
coverage_state_code: string | null; // connector's stable code; null when undeclared
coverage_state_class: string | null; // platform class; null when undeclared
raw_payload: Record;
usage: { used: number; budget: number; remaining: number; resets_at: string };
}>
```
## Failures
| Failure | HTTP Status | Code |
|---------|-------------|------|
| `InvalidURLFailure` (not an absolute http(s) URL) | 400 | `INVALID_URL` |
| `URLNotInProjectFailure` (host not a project domain, or page of another project) | 400 | `URL_NOT_IN_PROJECT` |
| `URLNotInPropertyFailure` | 400 | `URL_NOT_IN_PROPERTY` (+ `url`, `property_url`) |
| `ProjectNotFoundFailure` | 404 | `PROJECT_NOT_FOUND` |
| `PropertyNotFoundFailure` (unknown, or not a property of this project) | 404 | `PROPERTY_NOT_FOUND` |
| `LiveInspectionSourceNotFoundFailure` | 404 | `NO_GSC_SOURCE` |
| `AmbiguousLiveInspectionSourceFailure` | 409 | `PROPERTY_REQUIRED` (+ `property_urls[]`) |
| `LiveInspectionFailedFailure` `credentials` | 409 | `RECONNECT_REQUIRED` |
| `LiveInspectionFailedFailure` `access_denied` | 403 | `PROPERTY_ACCESS_DENIED` |
| `LiveInspectionFailedFailure` `out_of_scope` | 422 | `URL_OUTSIDE_PROPERTY` |
| `LiveInspectionBudgetExhaustedFailure` | 429 | `LIVE_INSPECTION_BUDGET_EXHAUSTED` (+ `budget`, `resets_at`, `Retry-After` header) |
| `LiveInspectionFailedFailure` `upstream` | 502 | `GOOGLE_INSPECTION_FAILED` |
## Response Schema
## Notes
- Budget: knob `inspection.liveDailyBudget` (default 50) per GSC property per UTC day. Every reserved call counts, failed ones included. Every 400 and 404, and 409 `PROPERTY_REQUIRED`, is answered before the reservation.
- 1.1.1 (PRE-4013): `inspected_at` is the time stored on the inspection row, so it equals `inspected_at` on `/urls` and `last_seen_at` on `/inspect` once promoted. A stored read has caught up when its time is at or after this one: later means a row saved after it replaced it, which can hold an older answer from Google. It was the connector's completion time, a few milliseconds earlier.
- 1.1.0 (CEN-376): adds `page_id`, `coverage_state_code`, `coverage_state_class` and `URL_NOT_IN_PROPERTY`; `url` is the stored page URL; `URL_NOT_IN_PROJECT` also rejects a URL whose page belongs to another project; a `property_url` of another project answers 404, and without `property_url` only properties of the project are candidates. Not purely additive: see the reference page.
- The result is written as a `live_inspection` operation and a COMPLETED `sync_jobs` row; the promote sweep (≤ ~60 s) folds it into `GET /visibility/inspect` and `/urls`.
- Background: `packages/visibility-docs/explanation/about-live-inspection.md` (stored vs live inspection) and `packages/visibility-docs/reference/live-inspection.md`.
## Raw Schema:schema.json
{
"$schema": "https://json-schema.org/draft-07/schema#",
"title": "PostLiveInspection Response",
"description": "Result of one on-demand Google URL Inspection, plus the property's live-inspection usage after it",
"type": "object",
"required": ["success", "data", "metadata"],
"properties": {
"success": { "type": "boolean", "const": true },
"data": {
"type": "object",
"required": [
"page_id",
"url",
"normalized_url",
"inspection_url",
"property_url",
"source_id",
"inspected_at",
"is_indexed",
"verdict",
"coverage_state",
"coverage_state_code",
"coverage_state_class",
"raw_payload",
"usage"
],
"properties": {
"page_id": {
"type": "string",
"format": "uuid",
"description": "Page the result is saved to; the id /visibility/urls returns for it"
},
"url": {
"type": "string",
"description": "Stored URL of that page, as /visibility/urls returns it"
},
"normalized_url": { "type": "string" },
"inspection_url": {
"type": ["string", "null"],
"description": "URL submitted to Google"
},
"property_url": { "type": "string", "description": "GSC property inspected against" },
"source_id": { "type": "string", "format": "uuid" },
"inspected_at": { "type": "string", "format": "date-time", "description": "The time stored on the inspection row: equal to inspected_at on /urls and last_seen_at on /inspect once promoted, until a row saved later for the page replaces it" },
"is_indexed": { "type": "boolean" },
"verdict": { "type": "string", "enum": ["INDEXED", "NOT_INDEXED", "EXCLUDED", "UNKNOWN"] },
"coverage_state": {
"type": ["string", "null"],
"description": "Google's coverage wording, verbatim"
},
"coverage_state_code": {
"type": ["string", "null"],
"description": "Connector's stable code for the wording; null when undeclared"
},
"coverage_state_class": {
"type": ["string", "null"],
"enum": [
"indexed_ok",
"google_declined",
"unknown_to_google",
"intentional_exclusion",
"technical_failure",
null
],
"description": "Platform class of the wording; null when undeclared"
},
"raw_payload": {
"type": "object",
"description": "Connector payload of the inspection row"
},
"usage": { "$ref": "#/definitions/usage" }
}
}
},
"definitions": {
"usage": {
"type": "object",
"required": ["used", "budget", "remaining", "resets_at"],
"properties": {
"used": {
"type": "integer",
"description": "Live inspections reserved today (UTC), failed ones included"
},
"budget": { "type": "integer", "description": "Knob inspection.liveDailyBudget" },
"remaining": { "type": "integer" },
"resets_at": { "type": "string", "format": "date-time", "description": "Next UTC midnight" }
}
}
}
}
---
id: RegisterConnector
name: Register Connector
version: 1.0.0
summary: Registers a connector worker with the Visibility API, providing capabilities and schema metadata.
badges:
- content: POST
backgroundColor: orange
textColor: orange
- content: Phase 3
backgroundColor: orange
textColor: orange
---
## Endpoint
`POST /visibility/connectors/register`
## Request
```json
{
"workerName": "gsc-connector",
"workerURL": "http://gsc-connector:3002",
"sourceName": "Google Search Console",
"sourceTypes": ["GSC"],
"supportedActions": ["indexation", "search_analytics"],
"capabilities": {
"temporalMode": "SNAPSHOT_ONLY",
"supportedActions": [
{ "action": "indexation", "label": "Indexation", "temporalMode": "SNAPSHOT_ONLY" }
]
},
"schemaContribution": {
"indexedPaths": [...],
"materializedViews": [...],
"fields": [...]
}
}
```
## Response
```json
{
"registered": true,
"workerName": "gsc-connector"
}
```
## Side Effects
On registration, the API cascades metadata to:
- **SchemaDictionaryService** — fields become discoverable via `/visibility/schema/` endpoints
- **ViewRegistryService** — materialized views become available via `/visibility/views/` endpoints
---
id: ReviewSemanticMetadata
name: Review Semantic Metadata
version: 1.0.0
summary: |
Applies a batch of approve / override / reject decisions to the semantic metadata of a connector's fields. Overrides are persisted on the owning worker's `connector_registrations.semanticOverrides` JSONB (CEN-87) so they survive restarts.
badges:
- content: POST
backgroundColor: orange
textColor: orange
- content: Phase 3C
backgroundColor: orange
textColor: orange
---
## Endpoint
```
POST /visibility/connectors/:workerName/semantic-metadata/review
```
## Request
```typescript
{
sourceType: string;
action: string;
reviews: Array<
| { path: string; decision: 'approve' }
| { path: string; decision: 'override'; semantic: SemanticFieldMetadata }
| { path: string; decision: 'reject' }
>;
}
```
`reviews` is a discriminated union on `decision`. `min(1)` — at least one review must be supplied.
## Response
```typescript
{
workerName: string;
sourceType: string;
action: string;
counts: {
approved: number;
overridden: number;
rejected: number;
};
fields: ResolvedFieldMetadata[]; // resolved post-application
}
```
## Per-Decision Behaviour
| Decision | Effect |
|----------|--------|
| `approve` | No-op against the override map; counted only |
| `override` | Calls `applySemanticOverride(...)` — persists on the owning worker's `semanticOverrides` JSONB (CEN-87) |
| `reject` | Calls `clearSemanticOverride(...)` — removes any existing override |
Durable since CEN-87: the in-memory `semanticOverrides` map is mirrored to the row that owns `(sourceType, action)`. If no worker owns the action, the override is in-memory only and won't survive restart.
## Failures
| HTTP Status | Condition |
|-------------|-----------|
| 404 | Unknown `workerName` |
| 400 | Invalid review payload (Zod validation) |
---
id: TriggerDailySync
name: Trigger Daily Sync
version: 2.0.0
summary: |
Dispatch the daily multi-source sync as a Trigger.dev background run. Returns a run id immediately; work executes async on the Trigger.dev worker (CEN-58, 2026-04-27).
badges:
- content: POST
backgroundColor: orange
textColor: orange
- content: CEN-58
backgroundColor: blue
textColor: blue
- content: Async
backgroundColor: purple
textColor: purple
---
## Overview
`POST /visibility/sync/daily`
Dispatches a `daily-sync-fanout` Trigger.dev run for the tenant and returns the run id synchronously. The run executes asynchronously on a Trigger.dev worker — wrapping `MultiSourceOrchestrator.runDailySync(tenantId)` (canonical fan-out per CEN-49).
Pre-CEN-58, this endpoint iterated all sources inline on the API request thread and could block for minutes. After CEN-58 the API thread is free in under 500ms; sync work runs in a separate worker pod.
## Request
| Parameter | Location | Required | Description |
|-----------|----------|----------|-------------|
| `x-tenant-id` | Header | Yes | Tenant UUID. Enforced by `TenantGuard` (CEN-60). Missing/malformed → 401. |
## Response
```json
{
"runId": "run_abc123"
}
```
The run id can be used to query Trigger.dev's API/UI for status, logs, and outcome.
## Behaviour Inside the Run
The `daily-sync-fanout` task body delegates to `MultiSourceOrchestrator`, which:
1. Discovers active sources via `ConnectorRegistryService`
2. Builds a `SyncDAG` (Prerender stage 0 → GSC stage 1)
3. Executes each step in parallel within a stage via `SyncJobRunner`
4. Refreshes per-source materialized views after each stage
5. Refreshes cross-source views once if any rendering or indexation step succeeded
## Retry Policy
Configured in `packages/visibility-tasks/trigger.config.ts`:
- `maxAttempts`: 3
- `factor`: 2 (exponential)
- `minTimeoutInMs`: 500
- `maxTimeoutInMs`: 30000
Retries fire on transient failures (`progress.status = FAILED`). Permanent rejections (Result-level `Failure` like source-not-found) return `outcome=rejected` from the underlying `source-action-chunk` task and do not retry.
## Scheduled Counterpart
`dailySyncCron` (`schedules.task` at `0 3 * * *`) dispatches one `daily-sync-fanout` run per active tenant on a daily cadence. v1 hardcodes a single zero-GUID tenant — multi-tenant enumeration is OP-033.
## Failures
| Failure | HTTP Status |
|---------|-------------|
| Missing `x-tenant-id` header | 401 (`MISSING_TENANT_ID`) |
| Malformed `x-tenant-id` (non-UUID) | 401 (`MISSING_TENANT_ID`) |
| Trigger.dev SDK unreachable | 500 (env: `TRIGGER_API_URL`, `TRIGGER_SECRET_KEY`) |
---
id: TriggerSourceSync
name: Trigger Source Sync
version: 1.0.0
summary: |
Manually trigger a sync for a specific source. Optionally target a single action.
badges:
- content: POST
backgroundColor: orange
textColor: orange
- content: CEN-36
backgroundColor: blue
textColor: blue
---
## Overview
`POST /visibility/sources/:id/sync`
Triggers a manual sync for the specified source. Without the `action` parameter, runs both `search_analytics` and `indexation` sequentially. With `?action=indexation`, runs only that action.
## Request
| Parameter | Location | Required | Description |
|-----------|----------|----------|-------------|
| `id` | Path | Yes | Source UUID |
| `action` | Query | No | Specific action to sync (`indexation` or `search_analytics`) |
| `x-tenant-id` | Header | Yes | Tenant isolation |
## Response
```json
{
"results": [
{
"action": "search_analytics",
"success": true,
"pagesProcessed": 25000,
"error": null
},
{
"action": "indexation",
"success": true,
"pagesProcessed": 100,
"error": null
}
]
}
```
## Errors
Per-action errors are returned in the results array (not HTTP errors). The endpoint always returns 200 — check `success` per action.
| Error | When |
|-------|------|
| `SyncJobAlreadyRunningFailure` | Job for this (source, action) already running |
| `ConnectorNotFoundFailure` | Source type has no registered connector |
| Token refresh failure | OAuth credentials expired/revoked |
---
id: ConnectorFactory
name: Connector Factory
version: 1.0.0
summary: |
Transitional in-process factory that maps SourceType to SourceConnector implementations. Being replaced by ConnectorRegistryService (CEN-56) with HTTP-based worker delegation.
badges:
- content: Deprecated
backgroundColor: red
textColor: red
- content: Transitional
backgroundColor: yellow
textColor: yellow
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Overview
`ConnectorFactory` is the **transitional** connector resolution mechanism. It creates `SourceConnector` instances in-process by mapping `SourceType` to constructor calls.
**Deprecation path**: `ConnectorRegistryService` (CEN-56) is the dynamic replacement. Workers register via HTTP on startup, and the registry routes requests to the correct worker pod. The factory remains until `SyncJobRunner` is refactored to use HTTP delegation (CEN-45).
## Current State
| Source Type | Connector | Resolution |
|-------------|-----------|------------|
| GSC | `GscConnector` | In-process (transitional) |
| PRERENDER | `PrerenderConnector` | In-process (transitional) |
| Others | — | `ConnectorNotFoundFailure` |
## Migration Plan
```
Phase 2 (current): SyncJobRunner → ConnectorFactory → connector.fetchAction() (in-process)
Phase 3 (target): SyncJobRunner → ConnectorRegistryService → HTTP POST to worker pod
```
When HTTP delegation is complete (CEN-45), this factory will be deleted.
## SourceConnector Interface
Every connector implements the two-method `SourceConnector` contract (defined in `@prerender-core/connector-sdk`):
| Method | Signature | Purpose |
|--------|-----------|---------|
| `testConnection` | `() => Promise` | Validates credentials and API access |
| `fetchAction` | `(action: Action, context: SyncContext) => Promise` | Fetches data for a specific action within a sync context |
---
id: ConnectorGscMock
name: GSC Mock Connector
version: 1.0.0
summary: |
Dev-only GSC simulator — schema-faithful deterministic search-analytics/indexation with configurable latency, QPM and daily-quota dials (CEN-205).
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Dev only
backgroundColor: red
textColor: red
---
Testing connector for validating execution configs (CEN-195) against quota, latency and
load behavior before prod ramps. Registers as source type `GSC_MOCK` with the same action
pair as the real GSC connector; search-analytics rows seed page inventory through the normal
discovery path, indexation then inspects it through three independently-switchable constraint
dials (`MOCK_INSPECTION_LATENCY_MS`, `MOCK_QPM_CAP`, `MOCK_DAILY_CAP`; `MOCK_TOTAL_URLS` sets
volume; 0 disables a constraint). Respects `SyncContext.tuning` with the same knob keys and
clamps as connector-gsc, so Settings-page configs drive it identically.
Never reaches production: source creation requires `MOCK_CONNECTORS_ENABLED=true`, the
terraform module is count-gated on `mock_connectors_enabled` (prod tfvars: false), and
`deploy-prod.yml` neither builds nor promotes the image.
Details: `packages/visibility/docs/specs/CEN-205-gsc-mock-connector.md`.
---
id: ConnectorRegistryService
name: Connector Registry Service
version: 1.0.0
summary: |
Durable registry of connected connector workers (CEN-87). Persists registrations on `connector_registrations`, hot-caches them in memory, rehydrates cache on bootstrap, and cascades schema metadata into SchemaDictionaryService and ViewRegistryService. Owns per-(sourceType, action, path) semantic overrides (CEN-75 / CEN-87).
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
- content: Phase 3
backgroundColor: orange
textColor: orange
sends:
- id: RegisterConnector
version: 1.0.0
- id: GetConnectors
version: 1.0.0
- id: GetSemanticMetadata
version: 1.0.0
- id: ReviewSemanticMetadata
version: 1.0.0
receives:
- id: RegisterConnector
version: 1.0.0
- id: ReviewSemanticMetadata
version: 1.0.0
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Overview
`ConnectorRegistryService` is the dynamic replacement for the old hardcoded `ConnectorFactory`.
Workers self-register over HTTP on startup, providing routing metadata, capabilities, and schema metadata.
Since CEN-87, the registry is durable: register, deregister, and semantic override writes persist on `connector_registrations`; in-memory maps are hot caches.
On registration, the service cascades to:
1. `SchemaDictionaryService` for field metadata used by frontend discovery.
2. `ViewRegistryService` for materialized view definitions used by query routing.
## Lifecycle
| Event | Action |
|-------|--------|
| `onModuleInit` | Hydrates rows from `connector_registrations`, applies them to cache, and merges per-worker `semanticOverrides` |
| `register(params)` | Saves the row, applies cache, cascades schema and view definitions |
| `deregister(workerName)` | Deletes the row, removes cache entries, and removes semantic overrides owned by that worker |
| `applySemanticOverride(...)` | Sets override in memory and writes through to owning worker `semanticOverrides` JSONB |
| `clearSemanticOverride(...)` | Removes override in memory and rewrites owning worker JSONB |
This resolves OP-024: API restart no longer requires every worker to re-register.
## Persistence
```text
connector_registrations
PK: workerName text
workerURL text
sourceName text
sourceTypes text[]
supportedActions text[]
capabilities jsonb
schemaContribution jsonb
semanticOverrides jsonb // keyed `${sourceType}:${action}:${path}`
registeredAt timestamptz
```
Per-field semantic overrides are persisted per worker on `semanticOverrides`.
Override ownership is determined by `(sourceType, action)`: a worker owns an override only if it declares that source type and action.
## Methods
| Method | Returns | Description |
|--------|---------|-------------|
| `register(params)` | `Promise` | Persists row, applies cache, cascades schema/views |
| `deregister(workerName)` | `Promise` | Deletes row, drops cache and owned overrides |
| `getConnector(workerName)` | `ConnectorRegistration \| undefined` | Cache lookup by worker name |
| `getConnectorForSourceType(sourceType)` | `ConnectorRegistration \| undefined` | First worker handling a source type |
| `sourceTypesFor(action)` | `SourceType[]` | Source types whose worker supports the action; core's coverage roles (`crawl_stats` served, `search_analytics` found) |
| `getAllConnectors()` | `ConnectorRegistration[]` | List all cached registrations |
| `getSemanticMetadata(sourceType, action)` | `ResolvedFieldMetadata[]` | Resolves fields with `semantic` and `semanticSource` |
| `applySemanticOverride(sourceType, action, path, semantic)` | `Promise` | Persists override on owning worker row |
| `clearSemanticOverride(sourceType, action, path)` | `Promise` | Removes override from owning worker row |
| `hydrateOnBootstrap()` | `Promise` | Idempotent rehydrate from `connector_registrations` |
## Registration Flow
```text
Worker starts
-> POST /visibility/connectors/register with registration secret
-> ConnectorRegistryService.register()
-> repo.save(connector_registrations)
-> applyToCache(row)
-> SchemaDictionaryService.registerSource(...)
-> ViewRegistryService.registerSourceViews(...)
```
## Security Contract
`ConnectorController` accepts register and deregister calls only when the caller sends:
```http
x-prerender-connector-registration-secret:
```
Missing or wrong caller secret returns `401`.
Missing server-side `CONNECTOR_REGISTRATION_SECRET` returns `503`, so registration fails closed instead of opening the endpoint.
The registry persists `workerURL`, but dispatch does not trust it blindly.
`RemoteConnectorDispatcher` sends sync and OAuth payloads only when `workerURL.hostname` is a single-label host equal to `workerName`.
Valid worker URLs use `http://:`.
External hosts, IP literals, userinfo-smuggled URLs, and dotted FQDNs are blocked before credentials are serialized.
NetworkPolicy egress allow-listing remains the platform follow-up for defense in depth.
## Semantic Resolution Order (CEN-75 / CEN-87)
For `getSemanticMetadata(sourceType, action)`:
1. **override** — durable, per-(sourceType, action, path), persisted on owning worker `semanticOverrides` JSONB.
2. **declared** — value shipped by connector field metadata.
3. **heuristic** — proposal from `SemanticClassifierService`.
No LLM call is made at runtime.
## Dependencies
| Dependency | Purpose |
|------------|---------|
| `SchemaDictionaryService` | Receives field metadata on registration |
| `ViewRegistryService` | Receives materialized view definitions on registration |
| `SemanticClassifierService` | Proposes `semantic` fields lacking declared block |
| `ConnectorRegistrationEntity` repo | Durable persistence |
## Architecture Context (D013 Amendment + CEN-87)
This service enables zero-code-change connector addition.
Deploy a worker pod; it authenticates, registers on startup, persists a row, and API immediately knows its capabilities, fields, and views across restarts.
---
id: CoverageService
name: Coverage Service
version: 1.0.0
summary: |
Calculates source coverage metrics — how many configured data sources are actively enabled.
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Singleton
backgroundColor: green
textColor: green
---
## Overview
`CoverageService` computes a simple coverage metric from the list of configured sources.
## Output
```typescript
type CoverageInfo = {
totalSources: number; // All configured sources
activeSources: number; // Sources with isEnabled = true
coveragePercent: number; // (active / total) * 100, rounded
};
```
## Logic
1. Count total sources passed in
2. Count sources where `isEnabled === true`
3. Calculate percentage: `Math.round((active / total) * 100)`
4. If no sources exist, returns `coveragePercent: 0`
---
id: DailyRankingJob
name: Daily Ranking Job
version: 1.0.0
summary: |
Daily orchestrator for the V2 URL ranking pipeline (CEN-115 / 3C.9). Walks the four V2 layers per tenant via the `RankingDataLoader` port; SAW or TOPSIS V2 scorer per the `rankingScorer` flag.
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
- content: CEN-115
backgroundColor: orange
textColor: orange
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Overview
`DailyRankingJob` is the V2 orchestrator that runs the four-layer ranking pipeline once per tenant per day. It is the only ranking write path (the v1 `RankingService` was deleted in CEN-347).
Source: `packages/visibility/src/jobs/DailyRankingJob.ts`.
## Pipeline (V2)
```
loader.loadActiveSources(tenantId)
loader.loadCandidates(tenantId)
→ Layer 0: RankingExclusionService.apply(candidates) [if ranking.exclusionEnabled = 1, read once per run]
→ Layer 1: SAWScorer or TopsisScorerV2 per source per group [picks per rankingScorer flag]
→ Layer 2: cross-source aggregation [composite vs TOPSIS V2]
→ Layer 3: anomaly detector V2 [3+ sources → MAD; 2 sources → enableTwoSourceAnomaly]
→ Layer 4: BucketAllocatorV2.allocate(35/35/30, budget=1800)
rankingRepo.saveRun({ runId, tenantId, scorerVersion: 'saw-v1' | 'topsis-v2', rows })
```
The Daily Ranking Job is dispatched from `dailySyncFanout` after every connector's sync completes.
## Scorer selection (D024')
| `rankingScorer` flag | Scorer | scorerVersion column |
| -------------------- | ------------------------------ | -------------------- |
| `'composite'` | runs as SAW (retired v1 value) | `saw-v1` |
| `'topsis'` | V2 TopsisScorerV2 | `topsis-v2` |
| `'saw'` | V2 SAWScorer | `saw-v1` |
Default at module bootstrap is `'saw'` (D024').
## Dependencies
| Dependency | Purpose |
| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `RANKING_DATA_LOADER_PORT` | Reads active sources + candidates + signals + last-inspection + coverage inputs. Default adapter: `TypeOrmRankingDataLoader`. Tests inject a fake. |
| `RankingExclusionService` | Layer 0 filter (gated by the runtime knob `ranking.exclusionEnabled`). |
| `UrlRankingRepository` | Persists the run rows. |
| `ENABLE_TWO_SOURCE_ANOMALY_TOKEN` | Layer 3 2-source path gate. |
| `RANKING_SCORER_TOKEN` | Picks the Layer 1 scorer. |
| `RENDER_HEALTH_READER_PORT` | Mode 2 only (CEN-250, D068): latest render day of provider-declined pages + last run's `render broken` picks. Default: `TypeOrmRenderHealthReader`. |
## Triggers
- Daily via `dailySyncFanout` after a tenant's sync completes.
- Manually via `POST /visibility/ranking/run` (admin endpoint).
## See also
- [About URL ranking — V2 pipeline](https://prerender.github.io/visibility-docs/explanation/about-url-ranking#v2-pipeline-cen-115-2026-05-20)
- `RankingExclusionService`
---
id: DailySyncCronTask
name: Daily Sync Cron (Trigger.dev schedule)
version: 1.0.0
summary: |
Trigger.dev scheduled task firing 03:00 UTC daily. Fetches active tenants from Visibility Worker and dispatches one daily-sync-fanout run per tenant.
badges:
- content: Trigger.dev schedule
backgroundColor: blue
textColor: blue
- content: CEN-58
backgroundColor: orange
textColor: orange
- content: cron 0 3 * * *
backgroundColor: green
textColor: green
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Task
`schedules.task({ id: 'daily-sync-cron', cron: '0 3 * * *', run: ... })`
## Body
1. Calls `GET /visibility/internal/tasks/daily-sync/tenants` on `visibility-worker`.
2. Dispatches one `daily-sync-fanout` run per tenant.
3. Uses `daily-sync::` idempotency keys so retried cron executions do not queue duplicate full syncs.
## Result
```ts
{
tenantsDispatched: number;
runs: { tenantId: string; runId: string }[];
}
```
## Runtime
The cron task uses `VISIBILITY_INTERNAL_API_URL` for tenant discovery and `TRIGGER_SECRET_KEY` for internal endpoint auth. It does not bootstrap NestJS in the Trigger.dev runner.
---
id: DailySyncFanoutTask
name: Daily Sync Fanout (Trigger.dev task)
version: 1.0.0
summary: |
Trigger.dev task that calls Visibility Worker to execute one tenant daily sync.
badges:
- content: Trigger.dev task
backgroundColor: blue
textColor: blue
- content: CEN-58
backgroundColor: orange
textColor: orange
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Task
`task({ id: 'daily-sync-fanout', run: ... })`
Calls `POST /visibility/internal/tasks/daily-sync` on `visibility-worker` through `VISIBILITY_INTERNAL_API_URL`. The worker executes the canonical daily sync flow; the Trigger.dev runner stays thin HTTP glue.
## Payload
```ts
{ tenantId: string }
```
## Result
```ts
{
tenantId: string;
stagesCompleted: number;
stepsExecuted: number;
viewsRefreshed: string[];
timedOut?: boolean;
}
```
## Runtime
The task authenticates with `x-prerender-internal-secret` using `TRIGGER_SECRET_KEY`. It does not bootstrap NestJS or resolve Visibility providers inside the Trigger.dev runner.
## Worker Behaviour
Inside `visibility-worker`, the daily sync executor:
1. Discovers active sources.
2. Builds the sync plan.
3. Runs each action through durable sync chunks/windowed execution where configured.
4. Refreshes per-source and cross-source materialized views.
5. Emits operation timeline events.
---
id: DashboardTimingService
name: Dashboard Timing Service
version: 1.0.0
summary: |
Measures the Prerender dashboard's API calls every morning and stores each run, compared run to run in the playground Fleet → Timings tab (CEN-327).
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Reporting
backgroundColor: purple
textColor: purple
---
Server-side replacement for the laptop dashboard-timings harness. A Trigger.dev cron
(`dashboard-timings-cron`, 09:30 UTC) calls `POST /visibility/internal/tasks/dashboard-timings` on
the worker; the worker answers **409 while a `daily_sync` is RUNNING or the shared refresh ledger
is behind**, and the task retries every 15 minutes until 13:30 UTC.
For each site (every live GSC property of the tenants in `DASHBOARD_TIMINGS_TENANTS`) the worker
calls the API service as the dashboard does: 8 screens, each three times — the first with
`x-cache: bypass` — with the decoration call after URL tabs. Each run lands in
`dashboard_timing_runs` / `dashboard_timing_samples` behind the `DashboardTimingStore` port.
The playground reads runs through `GET /visibility/tenants/overview/timings[/:runId?compare=]`:
typical (p50), 9 out of 10 (p90), slowest, total, errors and repeat loads over the rows both runs
measured. The same tab shows the nightly night by night from
`GET /visibility/tenants/overview/nights`, computed on read from operations and jobs.
Configuration: `DASHBOARD_TIMINGS_ENABLED`, `DASHBOARD_TIMINGS_TENANTS`, `DASHBOARD_TIMINGS_API_URL`
(default `http://visibility-api:3001`), `API_BEARER_TOKEN`. Details:
`packages/visibility/docs/specs/CEN-327-fleet-v2.md`, runbook
`packages/visibility/docs/runbooks/dashboard-timings.md`.
---
id: DiagnosticsService
name: Diagnostics Service
version: 1.0.0
summary: |
Groups non-indexed URLs by exclusion reason with sample URLs per category. Phase 3D / 3D.6 migrated the service onto the GSC indexation MV — direct `JOIN pages → domains → sources` is gone; predicates use `mv.project_id` / `mv.source_type` directly.
sends:
- id: GetDiagnostics
version: 1.0.0
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
---
## Overview
`DiagnosticsService` is the domain service behind `GET /visibility/diagnostics`. It answers _"Why are my URLs not indexed?"_ by grouping over `non_index_reason` on the resolved indexation MV.
## Responsibilities
1. **Verify project** exists and belongs to the requesting tenant
2. **Get reason counts** — `GROUP BY mv.non_index_reason` paginated by `limit`/`offset`
3. **Get sample URLs** — bounded fetch ordered by `last_seen_at DESC`, capped at 10 per reason in memory
4. **Build reason summaries**: an indexation reason's label is Google's coverage state, verbatim (CEN-359 retired the core label map); a render reason's label comes from the connector's `reasonLabels`
5. **Split declined reasons by render health** (CEN-250, D068) — `RenderHealthAnnotator` adds `render_health` to the reasons the connector declares `google_declined`, via `RenderHealthSplitQuery`
6. **Calculate coverage** via `CoverageService`
## Predicate Shape (CEN-86)
```sql
WHERE mv.project_id = $1 AND mv.tenant_id = $2
[AND mv.source_type = $3]
[AND mv.non_index_reason = $4]
[AND mv.section_key = $5]
```
The MV is resolved via `QueryRouterService.resolve(GSC, 'indexation')`.
## Constants
| Name | Value | Description |
|------|-------|-------------|
| `MAX_SAMPLES_PER_REASON` | 10 | Max sample URLs returned per reason group |
## Filters
Supports filtering by: `source_type`, `reason_filter`, `section_filter`.
## Dependencies
| Service | Purpose |
|---------|---------|
| `QueryRouterService` | Resolves the indexation MV route |
| `CoverageService` | Source coverage metrics |
---
id: ExecutionConfigService
name: Execution Config Service
version: 1.0.0
summary: |
Named immutable snapshots of runtime parallelization knobs — effective-value resolution, nightly run binding, and per-chunk tuning dispatch (CEN-195).
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Settings
backgroundColor: purple
textColor: purple
---
## Overview
`ExecutionConfigService` manages **execution configs**: named immutable versions of runtime-setting values stored in `execution_configs`. The active config is the latest activation; saving a config activates it. Values are validated against the code-defined knob registry (`runtime-settings.registry.ts`) — unknown keys, deploy-time keys, and out-of-bounds values are rejected with itemized issues.
## Resolution
Precedence per knob: `config > env > default`, applied only to **wired** knobs (readers that consult settings). Unwired knobs never resolve from config, so the effective view always matches what code actually reads.
## Consumers
| Method | Consumer | Purpose |
|---|---|---|
| `getEffectiveSettings()` | `SettingsController` (`GET /visibility/settings/knobs`) | Effective value + provenance per knob for the playground Settings page |
| `createConfig()` / `listConfigs()` | `SettingsController` | Save-and-activate, version history |
| `snapshotForRun()` | `DailyChunkedSyncStarter` | Stamps `operation.metadata.executionConfig` at nightly start; never fails (store outage degrades to env/default capture) |
| `tuningForDispatch()` | `SourceActionChunkRunner`, `SyncJobRunner` | Effective values for wired knobs, sent to workers as `SyncContext.tuning` per chunk — config changes apply next chunk, no restart |
## Wired knobs
`gsc.inspectionConcurrency` and `gsc.inspectionBatchSize` ride the sync context to `GscConnector`, which prefers them over its env inside the existing safety clamps (≤ 60 / ≤ 500). Trigger.dev queue limits are deploy-time only and surface read-only.
---
id: FailureMapperService
name: Failure Mapper Service
version: 1.0.0
summary: |
Converts domain Failure classes to HTTP error responses at the adapter boundary. Maps each failure type to an appropriate HTTP status code and error code.
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Singleton
backgroundColor: green
textColor: green
---
## Overview
`FailureMapperService` bridges the gap between the domain layer (which uses `Result` types and `Failure` classes) and the HTTP layer (which needs status codes and structured error responses). It uses `isFailure()` type guards — never `instanceof`.
## Failure Mapping Table
| Failure Class | HTTP Status | Error Code | Message Template |
|---------------|-------------|------------|------------------|
| `ProjectNotFoundFailure` | 404 | `PROJECT_NOT_FOUND` | `Project not found: {projectId}` |
| `SourceNotFoundFailure` | 404 | `SOURCE_NOT_FOUND` | `Source not found: {sourceId}` |
| `SourceUnavailableFailure` | 503 | `SOURCE_UNAVAILABLE` | `Source {sourceType} is unavailable: {reason}` |
| `QuotaExceededFailure` | 429 | `QUOTA_EXCEEDED` | `Quota exceeded for {sourceType}. Limit: {limit}` |
| `CapabilityNotSupportedFailure` | 422 | `CAPABILITY_NOT_SUPPORTED` | `Capability '{capability}' is not supported by {sourceType}` |
| `ConnectorNotFoundFailure` | 404 | `CONNECTOR_NOT_FOUND` | `No connector registered for source type: {sourceType}` |
| `InvalidURLFailure` | 400 | `INVALID_URL` | `Invalid URL '{url}': {reason}` |
| `SyncJobNotFoundFailure` | 404 | `SYNC_JOB_NOT_FOUND` | `Sync job not found: {jobId}` |
| `SyncJobAlreadyRunningFailure` | 409 | `SYNC_JOB_ALREADY_RUNNING` | `A sync job is already running for source {sourceId} action {action}` |
| `SyncJobTransitionFailure` | 422 | `SYNC_JOB_TRANSITION` | `Invalid state transition from {from} to {to}` |
| `OAuthFailure` | 400 | `OAUTH_ERROR` | `OAuth error: {detail}` (codes: TOKEN_EXCHANGE_FAILED, TOKEN_REFRESH_FAILED, INVALID_STATE, ENCRYPTION_FAILED, PROPERTY_ACCESS_DENIED, API_ERROR) |
| `SourceAlreadyConnectedFailure` | 409 | `SOURCE_ALREADY_CONNECTED` | `Source already connected: {sourceId}` |
| _(fallback)_ | 500 | `INTERNAL_ERROR` | `An unexpected error occurred` |
## Error Response Shape
```typescript
type ApiErrorResponse = {
success: false;
error: {
code: ErrorCode;
message: string;
details?: ErrorDetail[];
requestId: string;
timestamp: string;
};
};
```
---
id: FreshnessService
name: Freshness Service
version: 1.0.0
summary: |
Calculates data freshness and staleness indicators from sync job completion times. Configurable stale threshold (default: 24 hours).
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Singleton
backgroundColor: green
textColor: green
---
## Overview
`FreshnessService` determines how fresh the visibility data is by analyzing sync job completion timestamps.
## Configuration
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `staleThresholdHours` | number | 24 | Hours after which a source is considered stale |
## Output
```typescript
type FreshnessInfo = {
oldestDataAt: string | null; // ISO 8601
newestDataAt: string | null; // ISO 8601
staleSources: string[]; // Source IDs past stale threshold
isStale: boolean; // true if any source is stale
};
```
## Logic
1. Filter sync jobs to `COMPLETED` status with a `completedAt` timestamp
2. Sort completion times to find oldest and newest
3. Compare each source's latest completion against `now - staleThresholdHours`
4. Return stale source IDs and overall staleness flag
5. If no completed jobs exist, returns `isStale: true` with null timestamps
## Per-Action Freshness (CEN-34)
### calculateFreshnessByAction()
Extends freshness calculation to operate per `(source, action)` pair rather than per source only. This enables the system to distinguish between stale indexation data and fresh search analytics data for the same source.
```typescript
type ActionFreshness = {
action: string;
lastCompletedAt: string | null; // ISO 8601
isStale: boolean;
hoursElapsed: number | null;
};
```
Returns an `ActionFreshness` entry for each action that the source supports, based on the most recent `COMPLETED` sync job for that `(source, action)` pair.
---
id: GscClusterPlanService
name: GSC Cluster Plan Service
version: 1.0.0
summary: |
Partitions large GSC properties' URL space into page-regex clusters so
search-analytics syncs escape the 50k rows/day exposure cap.
badges:
- content: Visibility API
backgroundColor: green
textColor: green
---
Owns cluster-plan lifecycle for GSC sources. The daily sync stage queue
asks it for the active plan before dispatching every GSC search-analytics
step; the chunk runner resolves each cluster's filters from the persisted
plan version pinned in the chunk chain's input.
- **Inventory**: raw tenant page URLs scoped to the property host
(`sc-domain:` includes subdomains, URL-prefix properties do not).
- **Activation**: only above the 40k-URL planner budget; smaller
properties keep the single unfiltered query.
- **Staleness**: rebuilds when no plan is active, the inventory grew more
than 20%, or a cluster was flagged at the 50k exposure boundary.
- **Storage**: `gsc_cluster_plans` — one ACTIVE plan per source,
superseded versions retained for in-flight chunk chains.
---
id: GscConnector
name: GSC Connector
version: 1.0.0
summary: |
Google Search Console connector implementing SourceConnector. Fully functional: testConnection via OAuth, fetchAction for search_analytics and indexation with checkpointed pagination.
badges:
- content: SourceConnector
backgroundColor: green
textColor: green
- content: Phase 3
backgroundColor: orange
textColor: orange
sends:
- id: RegisterConnector
version: 1.0.0
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Overview
`GscConnector` is the first concrete `SourceConnector` implementation, targeting Google Search Console. Constructed by `ConnectorFactory` with `SourceEntity`, `GscOAuthService`, `GscAPIPort`, `URLNormalizerService`, and TypeORM repositories for data persistence.
## Implementation Status
| Method | Status | Ticket |
|--------|--------|--------|
| `testConnection()` | **Functional** | CEN-27 |
| `fetchAction('search_analytics')` | **Functional** | CEN-30 |
| `fetchAction('indexation')` | **Functional** | CEN-31 |
| `fetchAction('clustering')` | Pending | Future |
## testConnection() Flow
1. Refresh OAuth credentials via `GscOAuthService.refreshCredentials()`
2. Verify the source has a `propertyUrl` configured
3. Test API access to the property via `GscAPIPort.testAccess()`
4. Return `{ success: true }` or `{ success: false, error: { code, message, retryable } }`
## fetchAction('search_analytics') — CEN-30
1. Refresh OAuth credentials (5-min expiry buffer)
2. Call `gscAPI.fetchSearchAnalytics()` — 25,000 rows/batch, paginated via startRow
3. Map via `GscAnalyticsMapper` + `URLNormalizerService`
4. For each row: find-or-create PageEntity, upsert PageVisibilityState
5. Checkpoint: `{ startRow }` for resume
## fetchAction('indexation') — CEN-31
1. Refresh OAuth credentials
2. Take the next batch off `context.prioritisedPages` (ranking-ordered, resumed after the checkpoint) — `GSC_INSPECTION_BATCH_SIZE`, default 25 (checkpoint granularity, not speed)
3. Pick the URL Google knows (CEN-355): Search Analytics (dimension `page`, settled 28 days, include-regex on the batch's paths) names the exact reported URL per page; pages without impressions take the `www` and trailing-slash form their host reports; outside a URL-prefix property the host rewrite to the property origin applies. Our page key drops `www`, the slash and case, which Google answers with "URL is unknown" or "Page with redirect". The inspected URL is kept in the payload as `inspection_url`
4. Inspect through a sliding concurrency window via `gscAPI.inspectUrl(url, propertyUrl)` — `GSC_INSPECTION_CONCURRENCY`, default 9, prod-tuned in terraform; this is the throughput lever (~7.5s measured latency per inspection)
5. Map via `GscInspectionMapper` (verdict → indexing_status, coverageState → non_index_reason)
6. Upsert PageVisibilityState with `action='indexation'`
7. Checkpoint: `{ lastInspectedPageId }` for resume
**Quota note**: No enforcement in connector (F.4 owns this). Google allows 2,000 URL Inspection calls/day and 600/minute per property; the daily budget is set in `visibility` (`INDEXATION_PRIORITISED_PAGE_LIMIT`, default 1,800).
**Retry**: 429 / 5xx / dropped connections are retried per URL with exponential backoff, honouring `Retry-After` — `googleapis` does not retry POSTs on its own. Tunables in `packages/connector-gsc/README.md`.
## Supported Actions
| Action | Label | Temporal Mode |
|--------|-------|---------------|
| `indexation` | URL Indexation Status | `SNAPSHOT_ONLY` |
| `search_analytics` | Search Analytics | `TIME_SERIES` |
| `clustering` | URL Clustering | `SNAPSHOT_ONLY` |
Capabilities declare `scopeKey: { hostPrefixes: ['sc-domain:'] }`: a domain property `sc-domain:x` and a URL-prefix property on `x` share one scope key, so core reads one precedence winner among them (CEN-349).
The `indexation` declaration carries `coverageStates` (CEN-359): every URL Inspection `coverageState` seen on prod mapped to a stable snake_case code and a platform class (`indexed_ok`, `google_declined`, `unknown_to_google`, `intentional_exclusion`, `technical_failure`), e.g. `'Crawled - currently not indexed' → { code: 'crawled_not_indexed', class: 'google_declined' }`. When Google rewords a state, the new wording goes under the existing code. Core serves the code on `/indexation/verdicts` and `/urls`, branches on the class, and never names the GSC string (D059.6). `coverageStateClasses` (CEN-250) is still declared, derived from the same map, for readers on the previous release.
## Schema Contribution
### Indexed JSONB Paths
| Path | Type | Action |
|------|------|--------|
| `indexing_status` | text | `indexation` |
| `non_index_reason` | text | `indexation` |
| `impressions` | int | `search_analytics` |
| `clicks` | int | `search_analytics` |
| `ctr` | float | `search_analytics` |
| `position` | float | `search_analytics` |
| `cluster_label` | text | `clustering` |
### Materialized Views
| View | Action | Refresh | Columns |
|------|--------|---------|---------|
| `day_search_analytics` | `search_analytics` | `after_sync` | `page_id`, `source_id`, `fetched_at`, `impressions`, `clicks`, `ctr`, `position` |
Indexation (URL Inspection) declares no view: core reads its own `cur_indexation` read model (CEN-340, D065).
### History Projections (D059)
Declared in `src/config/GscProjections.config.ts` as `GSC_SCHEMA_CONTRIBUTION.projections`. Core creates and folds the table; the connector only declares it.
| Projection | Table | Action | Day | Columns |
| ----------------- | -------------------------- | ------------------ | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `search_daily` v1 | `proj_gsc_search_daily_v1` | `search_analytics` | `metrics.metric_date` | `clicks` (sum `metrics.clicks`), `impressions` (sum `metrics.impressions`), `position` (weightedAvg by `impressions`, `metrics.position`), `ctr` (ratio `clicks`/`impressions`) |
## Dependencies
| Service | Purpose |
|---------|---------|
| `GscOAuthService` | Token refresh for API authentication |
| `GscAPIPort` | Search Analytics API, URL Inspection API, property access |
| `URLNormalizerService` | URL normalization for page matching (D010) |
| `PageEntity` repository | Find-or-create pages during import |
| `PageVisibilityStateEntity` repository | Upsert visibility state with action-based JSONB |
| `DomainEntity` repository | Resolve domain for new page creation |
---
id: GscOAuthService
name: GSC OAuth Service
version: 1.0.0
summary: |
Manages the full GSC OAuth2 lifecycle: authorization, token exchange, encrypted storage, refresh, activation, and disconnection. Port/adapter architecture (D012) with real and mock implementations.
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
- content: D011
backgroundColor: orange
textColor: orange
- content: D012
backgroundColor: orange
textColor: orange
sends:
- id: OAuthAuthorize
version: 1.0.0
- id: OAuthCallback
version: 1.0.0
- id: OAuthActivate
version: 1.0.0
- id: OAuthMintSelectionSession
version: 1.0.0
- id: OAuthDisconnect
version: 1.0.0
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Overview
`GscOAuthService` is the domain service for managing Google Search Console OAuth2 connections. It orchestrates the full flow from authorization through to source activation, using port interfaces for all external interactions (Google API, credential storage, GSC API).
## API
| Method | Purpose | Returns |
|--------|---------|---------|
| `initiateOAuth(tenantId, sourceId)` | Generate Google consent URL with HMAC-signed state | `Result<{ authorizationUrl }, SourceNotFoundFailure \| SourceAlreadyConnectedFailure>` |
| `handleCallback(code, state)` | Exchange code for tokens, store encrypted, list properties | `Result<{ sourceId, properties[] }, OAuthFailure \| SourceNotFoundFailure>` |
| `activateSource(tenantId, sourceId, propertyUrl)` | Test access, set ACTIVE, store capabilities; guards one-live-property-per-domain (CEN-216) | `Result` |
| `activateSelectedProperties(tenantId, sourceId, projectId, propertyUrls, selectionSessionId, replace?)` | Activate one or more properties from a selection session; guards one-live-property-per-domain (CEN-216) | `Result<{ sources, domains, replacedSources }, SourceNotFoundFailure \| SourceAlreadyConnectedFailure \| OAuthFailure \| ProjectNotFoundFailure \| DomainCapExceededFailure \| OverlappingPropertySelectionFailure \| DomainAlreadyConnectedFailure>` |
| `refreshCredentials(sourceId, tenantId)` | Return valid token, auto-refresh if within 5min of expiry | `Result` |
| `disconnectSource(tenantId, sourceId)` | Clear credentials, set DISCONNECTED | `Result` |
## Port Dependencies (D012)
| Port | Real Adapter | Mock Adapter |
|------|-------------|-------------|
| `GoogleOAuthPort` | `GoogleOAuthClient` (google-auth-library) | `MockGoogleOAuthClient` |
| `CredentialStoragePort` | `EncryptedDBCredentialStorage` (AES-256-GCM) | `MockCredentialStorage` (in-memory Map) |
| `GscAPIPort` | `GoogleSearchConsoleClient` (googleapis) | `MockGscAPIClient` |
Selection: `GSC_OAUTH_MOCK=true` env var switches to mock implementations.
## Credential Security (D011)
- Tokens encrypted with AES-256-GCM before storage in `SourceEntity.encryptedCredentials`
- Format: `iv:authTag:ciphertext` (all base64)
- Encryption key from `GSC_ENCRYPTION_KEY` env var (32 bytes, hex-encoded)
- HMAC-signed state parameter prevents OAuth CSRF
## Source Status Transitions
```
PENDING → (initiateOAuth) → PENDING → (handleCallback) → PENDING → (activateSource) → ACTIVE
ACTIVE → (disconnectSource) → DISCONNECTED
ACTIVE → (token revocation detected) → ERROR
```
## Same-Domain Guard (CEN-216)
Only one live GSC property per canonical (www-stripped) domain is allowed, scoped per source type. Two gates enforce it:
- **Selection guard** — within one `activate-selection` call, two submitted `property_urls` resolving to the same www-stripped domain (e.g. `sc-domain:example.com` and `https://www.example.com/`) reject with `OverlappingPropertySelectionFailure` → `400 overlapping-property-selection { domain, property_urls }`.
- **Cross-session guard** — a submitted property whose canonical domain matches an already-live source of the same type (different `propertyUrl`) rejects with `DomainAlreadyConnectedFailure` → `409 domain-already-connected { replaceable: true, conflicts: [{ domain, existing_source_id, existing_property_url, existing_source_status, selected_property_url }] }`. Exact-`propertyUrl` matches are unaffected — those keep the existing `SourceAlreadyConnectedFailure` (ACTIVE) / CEN-201 revive (PENDING/ERROR/DISCONNECTED) behavior.
`activate-selection` accepts a `replace` flag (default `false`). With `replace: true`, once property access tests pass, every conflicting live GSC source plus its exact-propertyUrl live PRERENDER companion is disconnected first (credentials cleared, `statusMessage` set, `sourceDisconnected` Slack notification fires with `reason: 'replaced'`), then the new selection activates. These are sequential steps, not one transaction: a crash between them leaves the domain with zero live properties, never two, and recovery is reconnecting. The response carries `replacedSources: [{ id, type, propertyUrl }]`.
The single-property `activateSource` path applies the same domain check (reject-only, no `replace`) plus the exact-duplicate check it was previously missing.
Accepted, documented gap: `sc-domain:example.com` vs a subdomain-prefix property like `https://blog.example.com/` is not caught by www-stripped domain equality. Full design: `packages/visibility/docs/specs/CEN-216-one-live-gsc-property-per-domain.md`; decision record: D042 in `packages/visibility/docs/DECISIONS.md`.
## Open Points
- **OP-010**: Google Cloud project setup needed before production
- **OP-011**: HMAC key derived from encryption key — consider separate secret
- **OP-012**: Token revocation detection during sync (CEN-30)
---
id: HistoryOutboxParityTask
name: History Outbox Parity (Trigger.dev schedule)
version: 1.0.0
summary: |
Nightly read-only check that every outbox table equals the fold computed directly from history.
badges:
- content: Trigger.dev schedule
backgroundColor: blue
textColor: blue
- content: CEN-324
backgroundColor: orange
textColor: orange
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Task
`schedules.task({ id: 'history-outbox-parity', cron: { pattern: '0 9 * * *', timezone: 'UTC' }, queue: { concurrencyLimit: 1 }, run: ... })`
Calls `POST /visibility/internal/tasks/history-outbox/parity` with `{}` on `visibility-worker`. With `HISTORY_OUTBOX_PARITY_ENABLED=true` the worker takes one tenant at a time and compares, over the 7 data days before the run:
- each connector-declared projection table (`proj___v`) with the projection's own fold run over the tenant's stamped history of terminal jobs, the winner across jobs taken by the core rule (completed, freshest, id);
- `page_visibility_current` with `current_state_check_tenant(tenant, 'history')`.
Diffs are `missing`, `extra` or `differing` (every declared column, floats within a relative 1e-9) and classed `aged_out`, `completed_beats_newer`, `unstamped_legacy` (current state only: the key's history winner is an unstamped row ingested before the tenant's first stamped row) or `unexplained`; only `unexplained` gates. Projection comparisons are READ ONLY transactions with `statement_timeout = 120s`. Logs: `outbox.parity` per tenant × table, `outbox.parity.failed` per comparison that could not run, `outbox.parity.summary`. With the flag off the endpoint answers zeros without touching the database.
## Result
```ts
{
tenants: number;
tables: number;
unexplained: number;
failed: number;
}
```
## Runtime
Authenticates with `x-prerender-internal-secret` (`TRIGGER_SECRET_KEY`). Non-2xx responses throw. Runbook: `packages/visibility/docs/runbooks/history-promote.md` ("Parity").
---
id: HistoryOutboxRetentionTask
name: History Outbox Retention (Trigger.dev schedule)
version: 1.0.0
summary: |
Nightly monthly rollup of the projection tables, then the trim of daily rows past the daily window and of monthly rows past the monthly window.
badges:
- content: Trigger.dev schedule
backgroundColor: blue
textColor: blue
- content: CEN-328
backgroundColor: orange
textColor: orange
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Task
`schedules.task({ id: 'history-outbox-retention', cron: { pattern: '0 8 * * *', timezone: 'UTC' }, queue: { concurrencyLimit: 1 }, run: ... })`
Calls `POST /visibility/internal/tasks/history-outbox/retention` with `{}` on `visibility-worker`. With `HISTORY_OUTBOX_RETENTION_ENABLED=true` the worker, per connector-declared projection:
- recomputes, from the per-day table, the months of every (tenant, source) promoted since its watermark into `proj___monthly_v` (one transaction per month under the promote lock `0x5052`), then moves the watermark;
- for every whole month older than `outbox.dailyRetentionDays` (default 90): recomputes it, deletes its daily rows and seals it, in one transaction;
- deletes monthly rows older than `outbox.monthlyRetentionMonths` (default 24).
Raw history (`page_visibility_states`) is never touched. Logs: `outbox.rollup`, `outbox.retention.trim`, `outbox.retention.monthly_trim`, `outbox.retention.late_days`, `outbox.retention.failed`, `outbox.retention.summary`. With the flag off the endpoint answers zeros without touching the database. A step that cannot run is counted in `failed`; the run then answers 500 so Trigger.dev records it.
## Result
```ts
{
projections: number;
pairsRolledUp: number;
monthsRolledUp: number;
monthsTrimmed: number;
dailyRowsDeleted: number;
monthlyRowsDeleted: number;
lateDailyRows: number;
failed: number;
}
```
## Runtime
Authenticates with `x-prerender-internal-secret` (`TRIGGER_SECRET_KEY`). Non-2xx responses throw. Runbook: `packages/visibility/docs/runbooks/history-promote.md` ("Monthly rollups and retention").
---
id: IndexationVerdictsService
name: Indexation Verdicts Service
version: 1.0.0
summary: |
Counts pages per Google coverage state for a scope, on each page's latest URL Inspection in the window, and reports the scope's indexation freshness and daily inspection limit (CEN-343).
sends:
- id: GetIndexationVerdicts
version: 1.0.0
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
---
## Overview
`IndexationVerdictsService` is the domain service behind `GET /visibility/indexation/verdicts`.
## Responsibilities
1. **Verify project** exists and belongs to the requesting tenant
2. **Resolve the scope** (`domain` or `property_url`) with `ReadScopeResolver`, the same rules as `/urls`
3. **Pick the inspection sources** with the indexation feature's shared rule (`resolveInspectionSources`): sources whose connector declares `indexation`; a property's own sources, otherwise one precedence winner per scope key
4. **Read freshness** from the newest completed `indexation` sync job of the scope's sources (`IndexationRunQuery`); none means `state: never_run`
5. **Count** pages per (coverage state, verdict) through `IndexationViewQuery.countLatestInspections`, which builds its window CTE from the same `latestInspectionsSQL` the `/urls` inspection filter uses
6. **Report** the configured daily inspection limit (`INDEXATION_PRIORITISED_PAGE_LIMIT`)
## Reads
- `cur_indexation` (platform read model, D065): latest inspection per page and source
- `sync_jobs`: completed `indexation` runs
---
id: InspectService
name: Inspect Service
version: 1.0.0
summary: |
Deep-dive into a single URL's visibility across all data sources. Shows per-source index status, crawl data, and Prerender rendering state.
sends:
- id: GetInspect
version: 1.0.0
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
---
## Overview
`InspectService` is the domain service behind `GET /visibility/inspect`. It provides a URL-level deep-dive across all sources.
## Responsibilities
1. **Verify project** exists and belongs to the requesting tenant
2. **Normalize URL** via `URLNormalizerService` (D010) — configurable per-domain rules
3. **Find page** — exact match first, then normalized fallback
4. **Get visibility states** with source joins for all sources that have data
5. **Build source visibilities** — one entry per source with index status, reason, timestamps, raw payload
6. **Extract Prerender state** — rendering-specific fields from the PRERENDER source
7. **Extract section key** — falls back to `URLNormalizerService.extractSectionKey()` when page has no stored section
8. **Calculate coverage** via `CoverageService`
## Dependencies
| Service | Purpose |
|---------|---------|
| `URLNormalizerService` | Normalizes URLs with configurable per-domain rules (D010) |
| `CoverageService` | Calculates source coverage metrics |
## URL Resolution
1. Exact match on `page.url`
2. Fallback: case-insensitive match on normalized URL (`LOWER(page.url) = LOWER(:normalizedUrl)`)
## Repositories
Injects TypeORM repositories for: `ProjectEntity`, `DomainEntity`, `PageEntity`, `PageVisibilityStateEntity`, `SourceEntity`
---
id: LiveInspectionService
name: Live Inspection Service
version: 1.0.0
summary: |
On-demand Google URL Inspection for one URL: resolves the GSC property, reserves one unit of the property's daily budget, dispatches the connector's existing indexation action, and saves the row through the normal history → promote flow.
sends:
- id: PostLiveInspection
version: 1.0.0
- id: GetLiveInspectionUsage
version: 1.0.0
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
---
## Overview
`LiveInspectionService` (`features/live-inspection/`) is the domain service behind `POST /visibility/inspect/live` and `GET /visibility/inspect/live/usage`. It runs on the API tier, synchronously. `InspectService` (`GET /visibility/inspect`) only reads what the nightly stored; this service calls Google now.
## Flow
1. **Resolve target** (`LiveInspectionTargetResolver`): project → GSC property whose scope covers the URL host (`property_url` picks one when several match) → page id, or a new id for a typed URL.
2. **Reserve budget** (`LIVE_INSPECTION_USAGE_STORE`): advisory lock per source, count today's (UTC) `live_inspection` operations, insert the RUNNING operation. Over budget → `LiveInspectionBudgetExhaustedFailure`.
3. **Dispatch** (`LiveInspectionDispatch`): resolve credentials, call the worker's `indexation` action through `RemoteConnectorDispatcher` with `prioritisedPages: [ref]`. No connector or SDK change.
4. **Persist**: `ROW_PERSISTER_PORT.persistBatch` under the operation id.
5. **Register for promote**: `SyncJobRepository.recordCompleted` writes a COMPLETED `sync_jobs` row (`jobType: live_inspection`); the worker's promote sweep (60 s) folds it into `page_visibility_current`.
6. **Complete** the operation with `completeUnpublished` (no view-publication gate).
A failure after step 2 fails the operation; the budget unit stays spent (Google charges failed calls).
## Dependencies
| Dependency | Purpose |
|---------|---------|
| `LiveInspectionTargetResolver` | Project, property and page resolution plus URL validation |
| `LIVE_INSPECTION_USAGE_STORE` | Budget reservation and daily usage |
| `ExecutionConfigService` | Knob `inspection.liveDailyBudget` (default 50) |
| `CONNECTOR_TRANSPORT_PORT` | Connector that serves `indexation` for the source type |
| `LiveInspectionDispatch` | Credentials, remote call, row persist (the feature's only try/catch) |
| `SyncJobRepository` | COMPLETED job row for the promote sweep |
| `OperationTrackerService` | Operation completion or failure |
## Logs
`live-inspection.started`, `live-inspection.completed` (`durationMs`), `live-inspection.failed` (`reason`, `durationMs`), `live-inspection.budget-exhausted`, `live-inspection.finalize-failed` (`step`). All carry `tenantId` and `sourceId`.
---
id: MultiSourceOrchestrator
name: Multi-Source Orchestrator
version: 1.0.0
summary: |
Orchestrates multi-source sync cycles using a stage-based DAG. Discovers sources and actions via ConnectorRegistryService, builds a SyncDAG with ordered stages (Prerender before GSC), delegates each step to SyncJobRunner, refreshes per-source materialized views after each stage, and refreshes cross-source correlation views after all stages complete.
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
- content: Phase 3
backgroundColor: orange
textColor: orange
sends:
- id: TriggerDailySync
version: 1.0.0
- id: TriggerSourceSync
version: 1.0.0
receives:
- id: TriggerDailySync
version: 1.0.0
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Overview
`MultiSourceOrchestrator` is the canonical multi-source fan-out. As of CEN-58 (2026-04-27), it is invoked from the `daily-sync-fanout` Trigger.dev task — `SyncController` no longer iterates inline. Instead of a hardcoded sequence of GSC actions, it dynamically discovers all registered sources and their actions via `ConnectorRegistryService`, builds a dependency-ordered execution plan (SyncDAG), and runs it stage by stage.
## SyncDAG Construction
On each run the orchestrator:
1. **Discovers sources** — queries `ConnectorRegistryService.getAllConnectors()` to find every registered source type and its declared actions.
2. **Builds stages** — groups actions into ordered stages based on source-type priority. Prerender actions run first (stage 0) so that cache/render data is available before GSC inspection runs.
3. **Returns a SyncDAG** — an ordered list of stages, each containing one or more sync steps that can execute in parallel within the stage.
```
Stage 0: Prerender → [cache_status]
Stage 1: GSC → [search_analytics, indexation]
```
## Execution Flow
```
buildDAG(tenantId)
→ for each stage:
→ for each step in stage (parallel):
→ SyncJobRunner.run(sourceId, action)
→ ViewRefreshService.refresh{Indexation|SearchMetrics|Rendering}Views() // per-source
→ return OrchestratorResult with per-step outcomes and refreshed view names
```
Per-source views are refreshed stage by stage so downstream consumers can observe fresh data incrementally.
## Failure Isolation
Each sync step runs independently with its own error boundary:
- A failed step does **not** abort the current stage or subsequent stages.
- The orchestrator collects per-step outcomes (`COMPLETED` | `FAILED` | `SKIPPED`) and returns them in the `OrchestratorResult`.
- View refresh runs after a stage even if some steps in that stage failed — completed steps still produced data worth materializing.
- A step is `SKIPPED` when its source has no remaining quota or when the connector is not currently registered.
## Dependencies
| Service | Purpose |
| -------------------------- | ------------------------------------------------------- |
| `ConnectorRegistryService` | Discovers registered sources and their declared actions |
| `SyncJobRunner` | Executes individual sync jobs per step |
| `ViewRefreshService` | Refreshes per-source views after each stage |
| `QuotaTrackerService` | Checks remaining quota before starting a step |
## Historical Note
This service replaced `DailySyncOrchestrator` (deleted in OP-034). The previous orchestrator was GSC-only with a hardcoded sequence; the multi-source version discovers sources dynamically via `ConnectorRegistryService`, runs a stage-based DAG with parallel steps inside each stage, isolates step failures, and refreshes per-source views per stage. Adding a new source is now zero-code — register the worker and the orchestrator picks it up. The end-of-run cross-source refresh went with the cross-source views (CEN-347).
---
id: NarrativeTemplateService
name: Narrative Template Service
version: 1.0.0
summary: |
CEN-78 — single-pass `{name}` placeholder substitution with non-recursive replacement. Substituted values that themselves contain `{x}` are left literal (injection guard); missing keys render as `[unknown]`.
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
- content: Phase 3C
backgroundColor: orange
textColor: orange
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Overview
`NarrativeTemplateService` renders the bucket narratives shown by `RankingReadService`. Single regex pass — no recursion, no template engine.
Source: `packages/visibility/src/features/ranking/NarrativeTemplateService.ts`.
## Contract
```typescript
type TemplateValues = Record;
render(template: string, values: TemplateValues): string;
```
| Behaviour | Detail |
|-----------|--------|
| Placeholder syntax | `{name}` — `[a-zA-Z][a-zA-Z0-9_]*` |
| Substitution | One pass via `String.prototype.replace` |
| Recursion | None — substituted values are not re-resolved |
| Missing key | Renders as the literal `[unknown]` so customer-facing output never leaks `{placeholder}` |
## Templates
Stable bucket templates live in `narrative-templates.ts`. Three buckets × `{ populated, empty }`:
| Bucket | Variant | Required Keys |
|--------|---------|---------------|
| `proveValue` | `populated` | `count`, `sourceLabel`, `clicks` |
| `proveValue` | `empty` | — |
| `findProblems` | `populated` | `count`, `topReason` |
| `findProblems` | `empty` | — |
| `expandCoverage` | `populated` | `count`, `sectionsTouched` |
| `expandCoverage` | `empty` | — |
Template strings are **stable contracts** — copy tweaks fine, structural changes need coordination.
---
id: NightlyReportService
name: Nightly Report Service
version: 1.0.0
summary: |
Generates the fleet-wide nightly ops report after the daily sync completes and stores it in DO Spaces (CEN-200).
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Reporting
backgroundColor: purple
textColor: purple
---
Server-side replacement for the laptop launchd nightly report (CEN-200). A Trigger.dev cron
(`nightly-report-cron`, 05:30 UTC) calls `POST /visibility/internal/tasks/nightly-report`; the
endpoint answers **409 `{ deferred: true, runningOperations }` while any `daily_sync` operation is
still RUNNING** (logged at info, not as an error), and the task's retry ladder (37× / 10 min, until
~11:30 UTC) is what binds "report generated" to "nightly completed".
The report is built from four fleet-wide queries (operations including
`metadata->'executionConfig'`, error events, sync jobs, sources), rendered as a self-contained
HTML page whose header names the execution config (CEN-195) the night ran with, and stored as
`visibility-nightly-YYYY-MM-DD.html` behind the `NightlyReportStore` port (DO Spaces adapter;
disabled adapter when credentials are absent). The playground Reports page lists and opens the
stored nights via `GET /visibility/reports/nightly[/:name]` — a cross-tenant ops surface like
the tenant overview.
Configuration: `NIGHTLY_REPORT_SPACES_{ENDPOINT,BUCKET,ACCESS_KEY,SECRET_KEY,REGION,PREFIX}`,
`NIGHTLY_REPORT_WINDOW_HOURS`, `NIGHTLY_REPORT_EXCLUDED_TENANTS`, `NIGHTLY_REPORT_SCHEDULE_LABEL`.
Details: `packages/visibility/docs/specs/CEN-200-nightly-report.md`.
---
id: OperationTrackerService
name: Operation Tracker Service
version: 1.0.0
summary: |
Records sync runs as tenant-scoped operations with an append-only event timeline. The user-facing audit trail over daily and manual syncs.
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Overview
`OperationTrackerService` sits one level above `SyncJobRunner`. A *sync job* is one (source, action) pull; an *operation* is the whole run that fans out into many sync jobs, view refreshes, and ranking. The tracker is the audit trail that ties them together at the level a human reads.
It owns two tables:
- `visibility_operations` — one row per run. `type` (`daily_sync` / `manual_source_sync` / `manual_tenant_sync`), `status` (`RUNNING` → `COMPLETED` / `COMPLETED_WITH_ERRORS` / `FAILED`), `summary`, `startedAt`, `completedAt`, JSONB `metadata`.
- `visibility_operation_events` — append-only timeline. One row per `stage` (`operation`, `sync_stage`, `source_action`, `view_refresh`, `ranking`) with a `status` (`STARTED` / `INFO` / `COMPLETED` / `WARNING` / `FAILED`), `message`, and JSONB `metadata`.
`sync_jobs.operationId` links each job back to its operation (nullable FK, `ON DELETE SET NULL`).
## Lifecycle
```
start → event* → complete | fail
```
| Method | Effect |
|--------|--------|
| `start(tenantId, { type, summary })` | Inserts a `RUNNING` operation and a `STARTED` event. Returns the operation. |
| `event(tenantId, operationId, { stage, status, message, metadata })` | Appends a timeline event. `Fail(OperationNotFoundFailure)` if the operation is missing for the tenant. |
| `complete(tenantId, operationId, { status?, summary?, metadata? })` | Marks `COMPLETED` (default) or `COMPLETED_WITH_ERRORS`, merges metadata, stamps `completedAt`, appends a closing event. |
| `fail(tenantId, operationId, message, metadata?)` | Marks `FAILED`, appends a `FAILED` event. |
| `list(tenantId, { status?, type?, limit? })` | Newest-first, `limit` capped at 100. |
| `get(tenantId, operationId)` | Operation plus its ordered events, or `Fail(OperationNotFoundFailure)`. |
A run with any failed step or a timeout resolves as `COMPLETED_WITH_ERRORS` (partial data still landed); `FAILED` is reserved for the run throwing before it could finish.
## How the pipeline feeds it
`DailySyncExecutorService.execute` opens the operation, then threads `operationId` into `MultiSourceOrchestrator.runDailySync` and `SyncJobRunner.run`. Both take the tracker as an `@Optional()` dependency and no-op when no `operationId` is present — instrumentation is additive, never a hard dependency on the run path. `SourcesController` opens `manual_source_sync` / `manual_tenant_sync` operations for on-demand syncs.
## Read API
Exposed by `OperationsController` under `TenantGuard`:
- [Get Operations](/docs/queries/GetOperations) — `GET /visibility/operations`
- [Get Operation Detail](/docs/queries/GetOperationDetail) — `GET /visibility/operations/:id`
## Multi-tenant security
Every query carries `tenantId` in the `WHERE` clause; `findOperation` resolves by `{ id, tenantId }`, so one tenant can never read another's operations or events.
## Repositories
Injects TypeORM repositories for: `VisibilityOperationEntity`, `VisibilityOperationEventEntity`.
---
id: OverviewService
name: Overview Service
version: 1.0.0
summary: |
Computes aggregate visibility metrics (totals, percentages, per-section breakdown) for a project. Phase 3D / 3D.6 migrated the service onto QueryRouter — direct `JOIN pages → domains → sources` is gone; predicates use `mv.project_id` / `mv.source_type` directly.
sends:
- id: GetOverview
version: 1.0.0
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
---
## Overview
`OverviewService` is the domain service behind `GET /visibility/overview`. It orchestrates queries against the GSC indexation materialized views to produce a unified visibility snapshot.
## Responsibilities
1. **Verify project** exists and belongs to the requesting tenant
2. **Aggregate visibility states** (indexed, not_indexed, excluded, unknown) via Strategy A view selection
3. **Calculate section breakdown** (top 20 sections by URL count) from the same view
4. **Compute totals + percentages** with `total_urls` as denominator
5. **Aggregate Prerender rendering summary** via `SourceDataAggregator` when a Prerender source exists
6. **Calculate coverage** via `CoverageService`
## Strategy A — view selection (Phase 3D coverage audit)
The service bifurcates between the per-row and summary indexation read models (via `IndexationViewQuery`) based on whether a date filter is present:
| Has `date_start` / `date_end` | View used |
|------------------------------|-----------|
| Yes | `cur_indexation` (per-row plain VIEW, live) |
| No | `cur_indexation_summary` (MV) — pre-aggregated, O(distinct dimensions) |
The summary drops `fetched_at`, so it cannot serve a date-bounded query. Both are core-owned platform read models (CEN-340, D059 item 6), read by name rather than through `QueryRouter`.
## Predicate Shape (CEN-86)
Both MVs now project `project_id` and `source_type` (3D.6 cleanup), so predicates are direct equality:
```sql
WHERE mv.project_id = $1
AND mv.tenant_id = $2
AND mv.source_type = $3 -- when source_type filter present
AND mv.fetched_at BETWEEN ... -- per-row branch only
```
The earlier `EXISTS` subquery joining `pages → domains → sources` is gone.
## Dependencies
| Service | Purpose |
|---------|---------|
| `QueryRouterService` | Resolves the per-row view route for the per-row branch |
| `CoverageService` | Calculates source coverage metrics |
| `SourceDataAggregator` | Rendering summary across Prerender sources |
## Repositories
Injects TypeORM repositories for: `ProjectEntity`, `DomainEntity`, `PageEntity`, `SourceEntity`, plus `DataSource` for raw SQL.
---
id: PageDiscoveryService
name: Page Discovery Service
version: 1.0.0
summary: |
Reconciles URLs discovered during sync with existing Page entities. Creates new pages for unknown URLs and matches existing pages using normalized URL comparison.
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
---
## Overview
`PageDiscoveryService` handles URL reconciliation during data import. When a sync job encounters a URL, this service determines whether it maps to an existing `Page` entity or needs a new one created. It uses `URLNormalizerService` for consistent URL matching across data sources.
## Methods
| Method | Returns | Description |
|--------|---------|-------------|
| `findOrCreatePage(tenantId, domainId, url)` | `Result` | Finds existing page by normalized URL or creates a new one |
| `reconcileUrls(tenantId, domainId, urls)` | `Result` | Batch reconciliation: maps each URL to existing or new Page |
## Output
```typescript
type ReconciliationResult = {
matched: number; // URLs mapped to existing pages
created: number; // New pages created
pages: Map; // URL -> Page mapping
};
```
## Dependencies
| Service | Purpose |
|---------|---------|
| `URLNormalizerService` | Normalizes URLs for consistent matching |
| `PageEntity` repository | CRUD operations on pages |
| `DomainEntity` repository | Validates domain ownership |
---
id: PartitionMaintenanceService
name: Partition Maintenance Service
version: 1.1.0
summary: |
Monthly partition reclamation for `page_visibility_states`. Drops monthly partitions outside `max(retentionDays) + bufferDays`; pre-creates next month's partition.
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
- content: CEN-122
backgroundColor: orange
textColor: orange
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Overview
`PartitionMaintenanceService` is the cold layer of the data-retention rework. Daily DELETE keeps the hot edge clean (CEN-120); this service drops whole monthly partitions once they're guaranteed empty under the retention ceiling.
Source: `packages/visibility/src/services/PartitionMaintenanceService.ts`.
## Algorithm
1. Compute `ceiling = MAX(retentionDays across project_subscription WHERE effectiveTo IS NULL) + bufferDays` (default `bufferDays = 30`).
2. List child partitions matching `page_visibility_states_YYYY_MM` (skip `_legacy` + `_default` by name).
3. For each candidate, compute the bucket's end (first day of the next month). If end ≤ `now - ceiling`, `DROP TABLE`, then (same implicit transaction) `current_state_forget_ingest_range` re-derives the `page_visibility_current` keys whose winner lived in that month — a dropped partition fires no trigger (CEN-314). A failure keeps the partition.
4. Pre-create next month's partition via `CREATE TABLE IF NOT EXISTS … PARTITION OF …`. Idempotent. `current_state_sync_triggers()` then gives it the current-state triggers when the history root carries them; a failure there is a warning, never a missing month.
Both hooks live in `createMonthPartitionSql` / `dropMonthPartitionSql` (`storage/page-visibility-partitions.ts`), so the on-demand creator (`TypeOrmHistoryPartitions`) gets them too, and they are no-ops until the triggers are attached (see `docs/runbooks/current-state-table.md`).
`MAX(retentionDays) == null` → no-op (nothing to drop without a known policy).
## Triggers
- `partitionReclamationCron` schedules.task at `0 4 1 * *` UTC (1st of every month, 04:00 UTC).
## Dependencies
| Dependency | Purpose |
|------------|---------|
| `DataSource` | Raw SQL — partition discovery + `DROP TABLE` + `CREATE TABLE … PARTITION OF`. |
| `ProjectSubscriptionRepository` | `maxRetentionDays()` for the ceiling. |
## Why two retention layers
| Layer | Cost | When |
|-------|------|------|
| Daily DELETE (`RetentionService`) | O(rows / 10k) per project — many short transactions | Hot edge, per-project |
| Monthly DROP PARTITION (this service) | O(1) regardless of row count | Cold layer, global |
Once a partition is fully outside the retention ceiling, DROP TABLE reclaims its storage immediately — much cheaper than the per-row DELETE the daily pass would take.
## See also
- [About data retention](https://prerender.github.io/visibility-docs/explanation/about-data-retention)
- `RetentionService` — the daily-cron sibling
---
id: PrerenderAPIClient
name: Prerender API Client
version: 1.0.0
summary: |
HTTP adapter for the Prerender.io API. Implements PrerenderAPIPort with X-Prerender-Token authentication, paginated fetching, and Result-based error handling.
badges:
- content: Adapter
backgroundColor: purple
textColor: purple
- content: Phase 3
backgroundColor: orange
textColor: orange
- content: Port/Adapter D012
backgroundColor: orange
textColor: orange
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Overview
`PrerenderAPIClient` is the real HTTP adapter implementing `PrerenderAPIPort`. It calls the Prerender.io REST API to fetch rendering performance data and cache status information.
Uses port/adapter pattern (D012) — swappable with `MockPrerenderAPIClient` via the `PRERENDER_API_MOCK` environment variable.
## Methods
| Method | Returns | Description |
|--------|---------|-------------|
| `testConnection(token)` | `Result` | Validates API token by making a lightweight request |
| `fetchRenderedPages(token, params)` | `Result` | Fetches paginated rendered page data |
| `fetchCacheStatuses(token, params)` | `Result` | Fetches paginated cache status data |
## API Endpoints
| Method | Endpoint | Description |
|--------|----------|-------------|
| `GET` | `/api/renders?page={page}&limit={limit}` | Rendered pages with status, timing, HTTP code |
| `GET` | `/api/cache-statuses?page={page}&limit={limit}` | Cache entries with state, age, TTL |
## Authentication
All requests include an `X-Prerender-Token` header with the API token from `SourceEntity.encryptedCredentials`.
## Error Handling
| HTTP Status | Failure Code | Retryable |
|------------|-------------|-----------|
| 401, 403 | `AUTH_FAILED` | No |
| 429 | `RATE_LIMITED` | Yes |
| 5xx | `API_ERROR` | No |
| Network error | `CONNECTION_FAILED` | Yes |
## Configuration
| Environment Variable | Default | Description |
|---------------------|---------|-------------|
| `PRERENDER_API_URL` | `http://localhost:8080` | Base URL for the Prerender API |
| `PRERENDER_API_TOKEN` | — | API authentication token |
| `PRERENDER_API_MOCK` | `false` | Set to `true` to use MockPrerenderAPIClient |
## Dependencies
| Dependency | Purpose |
|------------|---------|
| Native `fetch()` | HTTP client (Node 24 built-in) |
| `PrerenderAPIPort` | Port interface this adapter implements |
| `PrerenderAPIFailure` | Error type for Result failures |
---
id: PrerenderConnector
name: Prerender Connector
version: 1.0.0
summary: |
Prerender.io data source adapter implementing SourceConnector. Provides render status/timing, cache status, and crawler-served page data via the Prerender API.
badges:
- content: SourceConnector
backgroundColor: green
textColor: green
- content: Phase 3
backgroundColor: orange
textColor: orange
sends:
- id: RegisterConnector
version: 1.0.0
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Overview
`PrerenderConnector` is the second `SourceConnector` implementation, targeting Prerender.io. It provides rendering performance data, cache health data, and crawler-served page data including Googlebot requests and returned status codes.
Uses the port/adapter pattern (D012) — `PrerenderAPIPort` is injected at construction, with real (`PrerenderAPIClient`) and mock (`MockPrerenderAPIClient`) implementations.
## Implementation Status
| Method | Status | Ticket |
| ----------------------------- | ---------------------------------------------- | ------- |
| `testConnection()` | **Functional** (calls Prerender API) | CEN-44 |
| `fetchAction('rendering')` | **Functional** (paginated fetch) | CEN-44 |
| `fetchAction('cache_status')` | **Functional** (paginated fetch) | CEN-44 |
| `fetchAction('crawl_stats')` | **Functional** (daily crawl-event aggregation) | CEN-132 |
## Pagination
`rendering` and `cache_status` use checkpoint-based pagination. The checkpoint stores `{ page: number }` and each call fetches 100 records. The `hasMore` flag from the API response drives continuation.
`crawl_stats` fetches one calendar day at a time from `/v3/analytics/crawled-pages`, paginates internally, and aggregates crawl events into one row per normalized URL for that day.
## Supported Actions
| Action | Label | Temporal Mode |
| -------------- | ---------------------- | --------------- |
| `rendering` | Render Status & Timing | `SNAPSHOT_ONLY` |
| `cache_status` | Cache Status | `SNAPSHOT_ONLY` |
| `crawl_stats` | Crawler-Served Pages | `TIME_SERIES` |
## Schema Contribution
### Rendering Fields
| Path | Type | Label | Filterable | Sortable |
| ---------------- | ---- | ---------------- | ---------- | -------- |
| `render_status` | text | Render Status | Yes | Yes |
| `render_time_ms` | int | Render Time (ms) | Yes | Yes |
| `status_code` | int | HTTP Status Code | Yes | Yes |
### Cache Status Fields
| Path | Type | Label | Filterable | Sortable |
| ----------------- | ---- | ----------------- | ---------- | -------- |
| `cache_state` | text | Cache State | Yes | Yes |
| `cache_age_hours` | int | Cache Age (hours) | No | Yes |
| `ttl_hours` | int | TTL (hours) | No | Yes |
### Crawl Stats Fields
| Path | Type | Label | Filterable | Sortable |
| ------------------------------- | --------- | ---------------------- | ---------- | -------- |
| `googlebot_request_count` | int | Googlebot Requests | Yes | Yes |
| `total_crawl_requests` | int | Total Crawl Requests | Yes | Yes |
| `crawler_request_counts` | jsonb | Crawler Counts | No | No |
| `status_code_counts` | jsonb | Status Code Counts | No | No |
| `crawl_date` | date | Crawl Date | Yes | Yes |
| `last_status_code` | int | Last Crawl Status Code | Yes | Yes |
| `last_crawler` | text | Last Crawler | Yes | Yes |
| `last_crawled_at` | timestamp | Last Crawl Seen | Yes | Yes |
| `cache_hit_count` | int | Cache Hits | Yes | Yes |
| `cache_miss_count` | int | Cache Misses | Yes | Yes |
| `last_cache_state` | text | Last Cache State | Yes | Yes |
| `avg_crawl_time_ms` | int | Average Crawl Time | Yes | Yes |
| `error_request_count` | int | Crawl Errors | Yes | Yes |
| `googlebot_error_request_count` | int | Googlebot Crawl Errors | Yes | Yes |
| `adaptive_type` | text | Adaptive Type | Yes | Yes |
### Materialized Views
- `mv_prerender_crawl_stats_daily` — per-page daily crawl projection used by overview coverage and trends.
- The latest per-page rendering and crawl state are core-owned platform read models (`cur_rendering*`, `cur_crawl_stats`, CEN-348); the connector declares no view for them. It declares `reasonLabels` / `labelPrefix` on `rendering`: diagnostics labels a render status as `${labelPrefix}: ${reasonLabels[status] ?? status}`.
- Capabilities declare `scopeKey: { hostPrefixes: ['sc-domain:'] }`: companion sources copy the GSC property URL, domain properties included (CEN-349).
### History Projections (D059)
Declared in `src/config/PrerenderProjections.config.ts` as `PRERENDER_SCHEMA_CONTRIBUTION.projections`. Core creates and folds the table; the connector only declares it.
`crawl_daily` v1 → `proj_prerender_crawl_daily_v1`, action `crawl_stats`, day `metrics.metric_date` (fallback `ingestDate`):
| Column | Type | Fold | Source |
| ------------------------------- | ----- | ------------------------------------- | -------------------------------- |
| `googlebot_request_count` | int | sum | `metrics.requests` |
| `total_crawl_requests` | int | sum | `payload.total_crawl_requests` |
| `last_status_code` | int | latest | `metrics.http_status` |
| `last_crawler` | text | latest | `payload.last_crawler` |
| `last_crawled_at` | text | latest | `metrics.last_crawled_at` |
| `cache_hit_count` | int | sum | `payload.cache_hit_count` |
| `cache_miss_count` | int | sum | `payload.cache_miss_count` |
| `last_cache_state` | text | latest | `payload.last_cache_state` |
| `avg_crawl_time_ms` | float | weightedAvg by `total_crawl_requests` | `payload.avg_crawl_time_ms` |
| `error_request_count` | int | sum | `payload.error_request_count` |
| `googlebot_error_request_count` | int | sum | `metrics.errors` |
| `adaptive_type` | text | latest | `payload.adaptive_type` |
| `crawler_request_counts` | jsonb | sumMap | `payload.crawler_request_counts` |
| `status_code_counts` | jsonb | sumMap | `payload.status_code_counts` |
## Dependencies
| Dependency | Purpose |
| -------------------- | ---------------------------------------------------------------- |
| `PrerenderAPIClient` | HTTP adapter for fetching render, cache, and crawler-served data |
| `PrerenderAPIPort` | Port interface (D012) for API abstraction |
## Authentication
API token stored in `SourceEntity.encryptedCredentials`. No OAuth flow needed — Prerender uses `X-Prerender-Token` header authentication.
## Error Handling
| Failure Code | Meaning | Retryable |
| ------------------- | ------------------------ | --------- |
| `MISSING_API_TOKEN` | No token configured | No |
| `AUTH_FAILED` | Invalid or expired token | No |
| `CONNECTION_FAILED` | Network/DNS error | Yes |
| `RATE_LIMITED` | 429 Too Many Requests | Yes |
| `API_ERROR` | Unexpected server error | No |
---
id: QueryRouterService
name: Query Router Service
version: 1.0.0
summary: |
Routes metric queries to the correct materialized view. Resolves per-source views by (sourceType, action). Source-agnostic — adding a connector requires zero endpoint changes.
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
- content: Phase 3
backgroundColor: orange
textColor: orange
receives:
- id: GetViews
version: 1.0.0
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Overview
`QueryRouterService` is the routing layer of D015 (Materialized View Query Routing). It resolves per-source materialized view names (keyed by `sourceType` + `action`) via `ViewRegistryService`. This decouples feature services from specific view names. The cross-source routes went with the cross-source views (CEN-347).
## Methods
### Per-source routes
| Method | Returns | Description |
| ----------------------------- | -------------------------- | ---------------------------------------------------- |
| `resolve(sourceType, action)` | `RouteResult \| undefined` | Find the **per-row** view for a source type + action |
| `resolveAll(sourceType)` | `RouteResult[]` | List all view routes for a source type |
## Route Resolution
```
resolve(SITEMAP, 'discover') → { viewName: 'mv_sitemap_discovery', sourceType: SITEMAP, action: 'discover' }
resolve(PRERENDER, 'crawl_stats') → { viewName: 'mv_prerender_crawl_stats_daily', ... }
resolve(BING, 'rendering') → undefined // not registered yet
```
The platform read models (`cur_indexation*`, CEN-340; `cur_rendering*`, `cur_crawl_stats`, CEN-348) are core-owned and read by name, not routed.
## Dependencies
| Dependency | Purpose |
| --------------------- | -------------------------------------------- |
| `ViewRegistryService` | View discovery and lookup (per-source views) |
## Consumers
The router is available throughout the visibility domain. Registered consumers:
- **CEN-46** (Prerender Optimization Layer) — routes between GSC and Prerender per-source views
- **CEN-48** (Multi-Source Aggregation) — source-agnostic per-source query routing
- **Phase 3D / 3D.6** (`OverviewService`, `SectionsService`, `DiagnosticsService`, `UrlsService`) — feature services migrated off base-table joins onto router-resolved MVs; the indexation reads moved to the core-owned `cur_indexation*` read models in CEN-340
`InspectService` stays on direct JSONB queries (D026 — no MV fits the per-page deep-dive freshness expectation).
---
id: QuotaTrackerService
name: Quota Tracker Service
version: 1.0.0
summary: |
In-memory daily quota counter per (source, action). Tracks GSC API usage against configured limits and provides budget-aware gating for sync operations.
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
---
## Overview
`QuotaTrackerService` maintains an in-memory counter of API calls consumed per `(source, action)` pair within a calendar day. It enables sync operations to check remaining budget before making external API calls, preventing quota overruns.
## Quotas
| Source | Action | Daily Limit |
|--------|--------|-------------|
| GSC | `indexation` | 2,000 |
| GSC | `search_analytics` | 25,000 |
## Methods
| Method | Returns | Description |
|--------|---------|-------------|
| `increment(sourceId, action, count)` | `void` | Adds `count` to the daily counter for `(source, action)` |
| `getUsage(sourceId, action)` | `QuotaUsage` | Returns current count, limit, and remaining budget |
| `canProceed(sourceId, action, needed)` | `boolean` | Returns `true` if remaining budget >= `needed` |
| `isNearLimit(sourceId, action)` | `boolean` | Returns `true` when usage exceeds 90% of daily limit |
## Output
```typescript
type QuotaUsage = {
used: number;
limit: number;
remaining: number;
resetAt: string; // ISO 8601, midnight UTC next day
};
```
## Reset Behavior
Counters reset automatically at midnight UTC. The `resetAt` timestamp in `QuotaUsage` indicates when the current window expires.
---
id: RankingExclusionService
name: Ranking Exclusion Service
version: 1.0.0
summary: |
Layer 0 of the V2 ranking pipeline (CEN-115 / 3C.2). Filters candidate URLs against per-tenant exclusion patterns before scoring; persists the exclusion set per run for inspection. Runtime knob `ranking.exclusionEnabled`, default OFF (CEN-249).
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
- content: CEN-115
backgroundColor: orange
textColor: orange
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Overview
`RankingExclusionService` is the Layer 0 step of the V2 ranking pipeline (CEN-115). Before any scorer runs, URLs matching per-tenant exclusion patterns (`/wp-json/*`, `/feed`, `/embed/*`, etc.) are filtered out so the ranking budget isn't spent on pages the customer doesn't care about.
Source: `packages/visibility/src/services/RankingExclusionService.ts`.
## Pipeline position
```
candidates → [Layer 0: RankingExclusionService.filter()]
→ Layer 1 SAW or TOPSIS V2
→ Layer 2 cross-source aggregation
→ Layer 3 anomaly detector
→ Layer 4 bucket allocator V2
```
The filter step is glob-pattern based and per-tenant. Patterns live in `visibility_settings.rankingExclusionPatterns` (JSON array of glob strings). Default empty.
## Persistence
Every excluded URL per run is written to `url_ranking_exclusions` (keyed `(tenant, source, run, pageId)`). The `/visibility/ranking/exclusions?source_id=…` endpoint surfaces the latest run's exclusions for the calling tenant — operators can see *why* a URL didn't make it into the latest ranking.
## Gating
Runtime knob `ranking.exclusionEnabled` (env `RANKING_EXCLUSION_ENABLED`, 0/1, default 0; CEN-249), set through `POST /visibility/settings/configs`. `DailyRankingJob` reads it once per run via `RankingExclusionService.isEnabled()` (30 s settings cache) and calls `apply()` only when it is `1`; it applies in every `ranking.selectionMode`. Off: no pattern read, nothing persisted. The read endpoint stays accessible and reports the current knob as `enabled`. Excluded rows are recorded under the tenant's lowest active source id.
## Dependencies
| Dependency | Purpose |
|------------|---------|
| `VisibilitySettingsRepository` | Per-tenant exclusion patterns. |
| `UrlRankingExclusionRepository` | Persists the excluded set per run. |
| `ExecutionConfigService` | Resolves `ranking.exclusionEnabled`. |
## See also
- [About URL ranking — V2 pipeline](https://prerender.github.io/visibility-docs/explanation/about-url-ranking#v2-pipeline-cen-115-2026-05-20)
- [Execution settings reference](https://prerender.github.io/visibility-docs/reference/execution-settings)
---
id: RankingReadService
name: Ranking Read Service
version: 1.0.0
summary: |
Read-side projection of the latest ranking run for a (tenant, source). Loads via `UrlRankingRepository.getLatestRun`, paginates per bucket, and renders bucket narratives via `NarrativeTemplateService`. Distinct from `DailyRankingJob` (the write side that executes a pass).
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
- content: Phase 3C
backgroundColor: orange
textColor: orange
sends:
- id: GetRankingLatest
version: 1.0.0
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Overview
`RankingReadService` is the domain service behind `GET /visibility/ranking/latest`. It loads the latest run per `(tenantId, sourceId)` and projects it onto the wire shape with bucket-scoped pagination.
Source: `packages/visibility/src/features/ranking/RankingReadService.ts`.
## Responsibilities
1. Load the latest run via `UrlRankingRepository.getLatestRun(tenantId, sourceId)`.
2. Compute `totalEligible` from the union of all three buckets.
3. Return `null` when no run exists (controller maps to 404).
4. Slice each bucket by `offset`/`limit`; counts reflect the full bucket, not the slice.
5. Render a narrative per bucket via `NarrativeTemplateService` (CEN-78). Aggregates feeding the narrative are computed across the **full** bucket so narratives stay stable as `limit`/`offset` change.
## Bucket Filter Semantics
The `bucket` query param filters which buckets return URL rows; `count` and `narrative` always reflect the full bucket. When `bucket !== 'all'`, the non-matching buckets return `urls: []` with their full `count` and `narrative`.
## Narrative Inputs
| Bucket | Inputs |
| ---------------- | ------------------------------------------------------------------------------- |
| `proveValue` | `count`, `sourceLabel='GSC'`, `clicks` (sum of `score`) |
| `findProblems` | `count`, `topReason` (most frequent `reason` head) |
| `expandCoverage` | `count`, `sectionsTouched` (distinct sections from `(...)` capture in `reason`) |
## Dependencies
| Dependency | Purpose |
| -------------------------- | ----------------------------------------- |
| `UrlRankingRepository` | Loads the latest run per (tenant, source) |
| `NarrativeTemplateService` | Renders per-bucket narratives |
---
id: ReadCacheService
name: Read Cache Service
version: 1.0.0
summary: |
Version-keyed Redis cache for dashboard reads — one loader per key per pod, fail-open, invalidated by the tenant data version (CEN-191).
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Redis
backgroundColor: red
textColor: red
---
## Overview
`ReadCacheService` wraps [async-cache-dedupe](https://github.com/mcollina/async-cache-dedupe) over the in-cluster Redis (process memory when no client is provided). `ReadCacheInterceptor` puts it in front of the four data-bearing dashboard reads via `@ReadCached(route, schema)`; `ReadCacheSettings` resolves the kill switch and route list.
## Key and invalidation
```
rc:::v:
```
`version` comes from `TenantDataVersionService` (table `tenant_data_versions`, 5 s per-pod memo). It is bumped inside `OperationTrackerService.complete()`, after `DailySyncFinalizerEffects.runRanking`, and after `HistoryPromoteService.fold()` folds a live inspection job (PRE-4000), so a publish invalidates by construction. TTL 26 h ± 15 min is garbage collection only.
## Behaviour
| Case | Result |
|---|---|
| Valid query, entry present | `x-cache: hit`, handler not run |
| Valid query, entry absent | handler runs once per pod for identical concurrent misses, stored unless > 1 MB, `x-cache: miss` |
| Invalid query, `offset > 3 × limit` | `x-cache: skip`, handler runs, nothing stored |
| `x-cache: bypass` request header | `x-cache: bypass`, handler runs, nothing stored |
| Handler throws | error propagates, nothing stored |
| Redis unreachable | miss (offline queue off, 100 ms command timeout), never an error |
| Knob `api.readCacheEnabled` = 0 or route not in `READ_CACHE_ROUTES` | untouched pass-through, no headers |
| Any successful tenant write (`POST`/`PUT`/`PATCH`/`DELETE`, not `visibility/internal/*`) | `DataVersionWriteInterceptor` bumps the tenant version; the write response is returned even if the bump fails |
## Consumers
| Method | Consumer | Purpose |
|---|---|---|
| `fetch(key, load)` | `ReadCacheInterceptor` | Hit / dedupe / store around `next.handle()` |
| `flush()` | `ReadCacheController` (`POST /visibility/cache/flush`) | Delete every cached read (`read~*` prefix) |
| `stats()`, `counters()` | `ReadCacheController` (`GET /visibility/cache/status`) | Backend, connection state, key count, `used_memory_human`, per-pod hit / miss / skip / bypass counters |
| `TenantDataVersionService.bump()` | `ReadCacheController` (`POST /visibility/cache/invalidate`) | Rebuild one tenant on next read |
---
id: ResponseBuilderService
name: Response Builder Service
version: 1.0.0
summary: |
Request-scoped service that assembles the ApiResponse envelope with metadata (sources, freshness, coverage) for every endpoint response.
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Request-scoped
backgroundColor: yellow
textColor: yellow
---
## Overview
`ResponseBuilderService` is a **request-scoped** NestJS injectable that wraps feature data in the standard `ApiResponse` envelope. A new instance is created per HTTP request, ensuring each response gets a unique `requestId`.
## Scope
`Scope.REQUEST` — a new instance is created for every incoming HTTP request.
## Fluent API
```typescript
const response = responseBuilder
.withSources(sources)
.withSyncJobs(syncJobs)
.build(data);
```
## Responsibilities
1. **Generate requestId** — UUID created in constructor
2. **Collect sources** via `.withSources()`
3. **Collect sync jobs** via `.withSyncJobs()`
4. **Build metadata** — delegates to `FreshnessService` and `CoverageService`
5. **Wrap data** in `ApiResponse` envelope via `.build()`
## Dependencies
| Service | Purpose |
|---------|---------|
| `FreshnessService` | Calculates data freshness and staleness from sync jobs |
| `CoverageService` | Calculates source coverage percentage |
---
id: RetentionService
name: Retention Service
version: 1.0.0
summary: |
Per-project batched DELETE pass over the partitioned history table. Loops `HistoryQueryExecutor.deleteOlderThan` in 10k-row batches until the cutoff is empty. Daily-cron-driven, idempotent.
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
- content: CEN-120
backgroundColor: orange
textColor: orange
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Overview
`RetentionService` is the policy-enforcing layer of the data-retention rework (CEN-116 → CEN-124). Append-only ingestion (CEN-118) means rows accumulate forever unless something deletes them — this service is that something.
Source: `packages/visibility/src/services/RetentionService.ts`.
## Loop shape
```
const cutoff = now - retentionDays * 24h
while (true):
deleted = history.deleteOlderThan(projectId, cutoff, 10_000)
if deleted == 0: break
```
Each `deleteOlderThan` call is its own short transaction inside `TypeOrmHistoryQueryExecutor` (`WITH deleted AS (DELETE ... LIMIT 10_000) ...`). Lock-hold windows stay bounded; the loop just keeps iterating.
## Idempotency
Re-running mid-day produces zero deletes — the first pass removes every row older than `now - retentionDays`, so the second pass returns 0 on the first batch and exits.
## Concurrency
`retentionFanout` (the Trigger.dev task) carries `queue.concurrencyLimit = 2`. With a 25-conn PG pool (~12 usable) the 2-parallel cap leaves plenty of headroom for normal API traffic during the 03:00 UTC window.
## Tier changes
The service reads `getCurrent(projectId)` on every run — no caching. A subscription change (upgrade / downgrade) picks up automatically on the next daily pass:
- Downgrade (shorter `retentionDays`): older rows that were within the wider window now fall outside; they're deleted on the next pass.
- Upgrade (wider `retentionDays`): nothing to do. Existing rows stay.
## Dependencies
| Dependency | Purpose |
|------------|---------|
| `HISTORY_QUERY_EXECUTOR_PORT` | Append-only storage adapter (CEN-121). Default: `TypeOrmHistoryQueryExecutor`. |
| `ProjectSubscriptionRepository` | Reads `project_subscription` rows where `effectiveTo IS NULL`. |
## Triggers
- `retentionCron` schedules.task at `0 3 * * *` UTC enumerates eligible projects and dispatches `retentionFanout` per project.
- `retentionFanout` task runs `runForProject(projectId)`.
## See also
- [About data retention](https://prerender.github.io/visibility-docs/explanation/about-data-retention)
- `packages/visibility/docs/runbooks/data-retention-cutover.md`
---
id: SchemaDictionaryService
name: Schema Dictionary Service
version: 1.0.0
summary: |
Aggregates field metadata from all registered connectors and exposes it via REST endpoints. Frontend discovers available columns, filters, and sorts without reading code.
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
- content: Phase 3
backgroundColor: orange
textColor: orange
sends:
- id: GetSchemaSources
version: 1.0.0
- id: GetSchemaActions
version: 1.0.0
- id: GetSchemaFields
version: 1.0.0
receives:
- id: RegisterConnector
version: 1.0.0
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Overview
`SchemaDictionaryService` is the core of D014 (Schema Dictionary for Dynamic Payloads). It maintains an in-memory registry of field metadata from all registered connectors, enabling frontend and API consumers to discover what data is available without reading connector source code.
GSC is pre-registered in the constructor. Future connectors (Prerender, Bing, GA4) call `registerSource()` on startup to add their own field metadata.
## Methods
| Method | Returns | Description |
|--------|---------|-------------|
| `getSources()` | `SourceSummary[]` | Lists all registered source types with action and field counts |
| `getActions(sourceType)` | `ActionSummary[] \| undefined` | Lists actions for a source with per-action field counts |
| `getFields(sourceType, action)` | `FieldMetadata[] \| undefined` | Returns typed field metadata for a specific source + action |
| `registerSource(sourceType, name, actions, fields)` | `void` | Registers a new connector's metadata (called by connectors on startup) |
## Field Metadata
Each field declares:
| Property | Type | Purpose |
|----------|------|---------|
| `path` | string | JSONB path in `rawSourcePayload` |
| `type` | `'int' \| 'text' \| 'float' \| 'timestamp'` | Data type for casting and display |
| `label` | string | Human-readable column name |
| `description` | string | Tooltip/help text for the field |
| `filterable` | boolean | Whether frontend should render a filter for this field |
| `sortable` | boolean | Whether frontend should allow sorting by this field |
## Registered Sources
| Source | Actions | Fields | Registration |
|--------|---------|--------|-------------|
| GSC | 3 (indexation, search_analytics, clustering) | 7 | Built-in (constructor) |
| Prerender | TBD | TBD | Dynamic (CEN-43) |
## Dependencies
| Dependency | Purpose |
|------------|---------|
| `GSC_ACTION_DECLARATIONS` | GSC action definitions (static config) |
| `GSC_SCHEMA_CONTRIBUTION` | GSC field metadata (static config) |
## Architecture Context (D014)
With D006 (full JSONB commitment), the shape of data in `rawSourcePayload` is opaque to consumers. The Schema Dictionary solves this by providing a discoverable API:
```
Connector declares fields → SchemaDictionaryService aggregates → SchemaController serves → Frontend renders dynamically
```
This enables the frontend dashboard (CEN-51) to render columns, filters, and sorts based on metadata rather than hardcoded field names — and makes AI Builder (Phase 4) possible by providing schema validation for generated connectors.
---
id: SectionCoverageService
name: Section Coverage Service
version: 1.0.0
summary: |
Serves the Performance-by-path rollup (CEN-215): the three coverage buckets, search metrics, SQL-derived CTR, and delivery-error counts per section, paginated and sortable. Bucket predicates are shared with the overview url_coverage block, so path totals never drift from the KPI cards.
sends:
- id: GetSectionsCoverage
version: 1.0.0
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
---
## Overview
`SectionCoverageService` is the domain service behind `GET /visibility/sections/coverage`. It rolls the crawl ∪ GSC page universe up to `pages.section` and decomposes each section into `served_and_found` / `served_only` / `found_only`.
## Responsibilities
1. **Verify project and optional domain** belong to the requesting tenant
2. **Delegate to `SectionCoverageQuery`** — one paged rows statement, one count statement, one unwindowed freshness statement
3. **Assemble pagination** (`total`, `has_more`)
4. **Provide response-metadata inputs** (tenant sources + recent completed sync jobs) for the `ResponseBuilderService` envelope
## Invariants
- Bucket membership reuses `servedPagesSQL` / `foundPagesSQL` from `features/overview/coverage-signals.ts` — per-bucket sums across all sections equal the overview `url_coverage` totals for the same window (integration-tested).
- GSC page-days dedupe through `winningGscPageDaysSQL`; disconnected sources' collected data stays readable (FW1), `served` stays `isEnabled`-gated pending the crawl-side migration.
- Metric fields are `null` when a section has no data of that kind in the window — never coerced to 0.
- Every sort is `NULLS LAST` with a deterministic `section_key` tiebreak.
## Dependencies
| Service | Purpose |
|---------|---------|
| `SectionCoverageQuery` | SQL execution against the crawl/search MVs |
| `ResponseBuilderService` | Standard response envelope (via controller) |
---
id: SectionsService
name: Sections Service
version: 1.0.0
summary: |
Computes section-level health aggregation (HEALTHY / WARNING / CRITICAL) plus top issues per section. Phase 3D / 3D.6 migrated the service onto the GSC indexation MV — direct `JOIN pages → domains → sources` is gone; predicates use `mv.project_id` / `mv.source_type` directly.
sends:
- id: GetSections
version: 1.0.0
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
---
## Overview
`SectionsService` is the domain service behind `GET /visibility/sections`. It provides a health-at-a-glance view of URL sections.
## Responsibilities
1. **Verify project** exists and belongs to the requesting tenant
2. **Aggregate by section** — `GROUP BY mv.section_key` over the resolved indexation MV
3. **Determine health status** via `HealthThresholds.config.ts`
4. **Get top issues** — top 3 non-index reasons per section by affected count
5. **Calculate coverage** via `CoverageService`
## Predicate Shape (CEN-86)
Predicates run directly against MV columns post-3D.6:
```sql
WHERE mv.project_id = $1 AND mv.tenant_id = $2 [AND mv.source_type = $3]
GROUP BY mv.section_key
ORDER BY total DESC
LIMIT 20
```
The MV is resolved via `QueryRouterService.resolve(GSC, 'indexation')`.
## Health Thresholds
Configured in `HealthThresholds.config.ts`:
| Status | Condition |
|--------|-----------|
| HEALTHY | indexed\_percent > 80% |
| WARNING | 50% <= indexed\_percent <= 80% |
| CRITICAL | indexed\_percent < 50% |
## Constants
| Name | Value | Description |
|------|-------|-------------|
| `MAX_TOP_ISSUES` | 3 | Max issues returned per section |
## Dependencies
| Service | Purpose |
|---------|---------|
| `QueryRouterService` | Resolves the indexation MV route |
| `CoverageService` | Source coverage metrics |
---
id: SemanticClassifierService
name: Semantic Classifier Service
version: 1.0.0
summary: |
Heuristic-only v1 (D014 amendment, OP-031). Proposes semantic metadata for connector fields lacking a `semantic` block via regex rules over (path | label | description) tokens. No runtime LLM call. Returns proposals tagged `source: 'declared' | 'heuristic'`.
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
- content: Phase 3C
backgroundColor: orange
textColor: orange
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Overview
`SemanticClassifierService` proposes `SemanticFieldMetadata` at registration time for fields that don't declare it. Anthropic-backed variant deferred per OP-031 (cost validation pending) — runtime stays LLM-free.
Source: `packages/visibility/src/services/SemanticClassifierService.ts`.
## Contract
```typescript
type ClassifierProposal = {
path: string;
proposal: SemanticFieldMetadata;
source: 'declared' | 'heuristic';
};
classify(fields: FieldMetadata[]): ClassifierProposal[];
```
If a field declares `semantic`, the declared value passes through with `source: 'declared'`. Otherwise the proposer runs and tags the result `source: 'heuristic'`.
## Rule Set (priority-ordered)
| # | Match | Group / Direction / Importance / Category |
|---|-------|-------------------------------------------|
| 1 | `cache \| hit \| miss \| ttl` | health / higher-is-better / 0.5 / cache |
| 2 | `error \| fail \| failure \| broken \| stale \| expired \| reason` | health / lower-is-better / 0.7 / errors |
| 3 | `time \| latency \| duration \| elapsed \| ms \| seconds` | health / lower-is-better / 0.7 / latency |
| 4 | `status \| verdict \| state \| coverage \| index(ing\|ation)? \| inspect` | health / higher-is-better / 0.8 / indexation |
| 5 | `click \| impression \| visit \| session \| traffic \| view` | performance / higher-is-better / 0.85 / traffic |
| 6 | `ctr \| engagement \| bounce \| dwell` | performance / higher-is-better / 0.6 / engagement |
| 7 | `rank \| position \| placement` | performance / lower-is-better / 0.85 / ranking |
Rule 1 fires before Rule 4 to keep `cache_state` from matching the generic `state` token.
## Default Proposal
When nothing matches, returns a low-importance default so reviewers can override:
```typescript
{ group: 'performance', direction: 'higher-is-better', importance: 0.2, category: 'uncategorized' }
```
## Consumer
`ConnectorRegistryService.getSemanticMetadata(...)` calls `classify()` for every `(sourceType, action)` lookup. Human overrides take priority over both `declared` and `heuristic` sources (CEN-87, persisted on the owning worker's `semanticOverrides` JSONB).
---
id: SemanticConfigProposalService
name: Semantic Config Proposal Service
version: 1.0.0
summary: |
LLM-assisted proposer for connector semantic YAML configs. Operator-driven propose-then-approve flow; runtime ranking never calls the LLM. Default OFF per `enableLlmSemanticClassifier` flag.
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
- content: CEN-115
backgroundColor: orange
textColor: orange
- content: V1.1
backgroundColor: gray
textColor: gray
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Overview
`SemanticConfigProposalService` is the application-layer surface for CEN-115 / 3C.15 — the LLM Semantic Classifier (V1.1). Operators ask Claude to propose a `semantic.yaml` for a connector + a set of categories; the service validates the response, persists the draft, and exposes it for review + approval.
Source: `packages/visibility/src/services/SemanticConfigProposalService.ts`.
## Flow
```
POST /visibility/connectors/:id/semantic/propose
→ service.propose({ connectorId, categories, constraints })
→ SEMANTIC_CONFIG_PROPOSER_PORT.propose(...)
→ validate response against SemanticConfig Zod schema
→ persist draft + rationale
→ return { proposed: { config, rationale }, runId }
POST /visibility/connectors/:id/semantic/approve
→ service.approve({ runId, edits? })
→ ConnectorRegistry.updateSemanticConfig(connectorId, config)
→ 204
```
The two endpoints are intentionally distinct: a human reviews + edits the draft before the registry write. The LLM is never the source of truth — same guideline as the [D014 amendment](https://prerender.github.io/visibility-docs/reference/decisions).
## Gating
| Setting | Effect |
|---------|--------|
| `enableLlmSemanticClassifier = false` | Both endpoints return `503`. Default in prod. |
| `enableLlmSemanticClassifier = true` + `ANTHROPIC_API_KEY` set | Real proposer (`AnthropicSemanticConfigProposer`) is bound. |
| `enableLlmSemanticClassifier = true` + `ANTHROPIC_API_KEY` unset | Sentinel proposer (`UnconfiguredSemanticConfigProposer`) is bound. Every `propose` returns `transport_error`. Bootstrap doesn't crash — the gate just blocks calls instead of failing init. |
## Dependencies
| Dependency | Purpose |
|------------|---------|
| `SEMANTIC_CONFIG_PROPOSER_PORT` | The proposer adapter (Anthropic real or sentinel). |
| `ConnectorRegistryService` | Persists approved configs to `connector_registrations.semanticConfig`. |
| `ENABLE_LLM_SEMANTIC_CLASSIFIER_TOKEN` | Module-level boolean flag. |
## What V1.1 doesn't cover yet
- No prompt eval suite.
- No per-tenant cost ceiling on Anthropic spend.
- Flag is module-wide, not per-tenant.
Tracked as follow-ups before any tenant gets the flag flipped ON.
## See also
- [About URL ranking — V2 pipeline](https://prerender.github.io/visibility-docs/explanation/about-url-ranking#v2-pipeline-cen-115-2026-05-20)
- [About the LLM semantic classifier](https://prerender.github.io/visibility-docs/explanation/about-llm-semantic-classifier)
- [Feature flags reference](https://prerender.github.io/visibility-docs/reference/feature-flags)
---
id: SourceManagementService
name: Source Management Service
version: 1.0.0
summary: |
Manages connected sources: list all sources, get source detail, view job history, and disconnect a source. Serves supportedActions from GscCapabilities.config.
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
sends:
- id: GetSources
version: 1.0.0
- id: GetSourceDetail
version: 1.0.0
- id: GetSourceJobs
version: 1.0.0
- id: DisconnectSource
version: 1.0.0
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Overview
`SourceManagementService` provides CRUD-like operations for managing data sources connected to a tenant's visibility instance. It exposes the list of supported actions per source type as declared in `GscCapabilities.config` (static configuration, not user-editable).
## Methods
| Method | Returns | Description |
|--------|---------|-------------|
| `listSources(tenantId)` | `Result` | Lists all sources for tenant with status and last sync info |
| `getSourceDetail(tenantId, sourceId)` | `Result` | Full source detail including capabilities and supported actions |
| `getJobHistory(tenantId, sourceId)` | `Result` | Recent sync jobs for a source, ordered by creation date descending |
| `disconnect(tenantId, sourceId)` | `Result` | Disables source and clears stored OAuth credentials |
## Supported Actions
Actions are served from the static `GscCapabilities.config` object per source type. They are not user-configurable.
| Source Type | Actions |
|-------------|---------|
| `gsc` | `indexation`, `search_analytics`, `clustering` |
## Error Handling
- Source not found -> `SourceNotFoundFailure`
- Source belongs to different tenant -> `SourceNotFoundFailure` (same, for security)
## Dependencies
| Service | Purpose |
|---------|---------|
| `SourceEntity` repository | CRUD operations on sources |
| `SyncJobEntity` repository | Query job history for a source |
| `GscOAuthService` | Credential cleanup on disconnect |
---
id: SyncJobAggregator
name: Sync Job Aggregator
version: 1.0.0
summary: |
Computes per-action observability aggregates from page_visibility_states. Called by SyncJobRunner before each COMPLETED transition (CEN-59, 2026-04-27).
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
- content: CEN-59
backgroundColor: orange
textColor: orange
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Overview
`SyncJobAggregator` produces the metadata payload that `SyncJobRunner` writes to `SyncJob.metadata` on every successful sync. Single SQL per action over `page_visibility_states`, scoped by `(tenantId, sourceId, action)`. Resolves OP-025.
The metadata is what playground trend, sections, and overview charts read. Pre-CEN-59 it was null in production; charts ran on dev seeds.
## Method
```ts
aggregate(action: string, scope: { sourceId, tenantId, pagesProcessed }): Promise
```
## Per-Action Output
| Action | Aggregation Strategy | Fields Returned |
|---|---|---|
| `indexation` | Count by `rawSourcePayload->>'indexing_status'` | `indexed`, `notIndexed`, `excluded`, `unknown`, `pagesProcessed` |
| `search_analytics` | SUM/AVG over GSC click metrics | `totalClicks`, `totalImpressions`, `avgCtr`, `avgPosition`, `pagesProcessed` |
| `rendering` | Count by `rawSourcePayload->>'render_status'` | `rendered`, `failed`, `pagesProcessed` |
| _unknown_ | Short-circuit — no query | `pagesProcessed` only |
## Robustness
- NULL row from query → all counts coerced to zero.
- Non-numeric strings (`"NaN"`, empty) → coerced to zero via `toInt`/`toFloat` helpers.
- Unknown actions never hit the DB.
## Dependencies
| Repository | Purpose |
|---|---|
| `PageVisibilityStateEntity` | Source of truth for all aggregates — JSONB extraction at query time |
## Why This Is a Service, Not Inline Code
Schema-dictionary-driven aggregates (D014) will plug in here without touching `SyncJobRunner`. Future connector actions can register their own aggregation strategy against the same interface.
## Notes
- Mirrors the SQL pattern of `OverviewService.getVisibilityAggregation` — same JSONB extraction + SUM/CASE pattern.
- Unique constraint `(page_id, source_id, action)` on `page_visibility_states` means each row contributes to exactly one action's aggregate.
- Aggregates the **current state** of all rows for the source, not just the rows touched in this run — this matches what dashboards need.
---
id: SyncJobRepository
name: Sync Job Repository
version: 1.0.0
summary: |
Result-returning CRUD for SyncJobEntity with state machine transition guards. Prevents concurrent runs via exclusive job creation.
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
---
## Overview
`SyncJobRepository` wraps TypeORM operations on `SyncJobEntity` with the Result pattern and enforces the sync job state machine. It prevents race conditions on job creation via PostgreSQL transactional locking.
## State Machine
```
PENDING → RUNNING → COMPLETED
→ FAILED
```
Transitions are enforced at the application layer — invalid transitions return `SyncJobTransitionFailure`.
## API
| Method | Returns | Purpose |
|--------|---------|---------|
| `createExclusive(sourceId, action, tenantId)` | `Result` | Creates job only if no PENDING/RUNNING job exists for the same (source, action). Uses `SELECT ... FOR UPDATE` |
| `markRunning(jobId, tenantId)` | `Result` | Transitions PENDING → RUNNING |
| `markCompleted(jobId, tenantId)` | `Result` | Transitions RUNNING → COMPLETED |
| `markFailed(jobId, error, tenantId)` | `Result` | Transitions RUNNING → FAILED with error message |
| `updateCheckpoint(jobId, checkpoint, recordsProcessed, tenantId)` | `Result` | Updates checkpoint and record count mid-run |
| `findById(jobId, tenantId)` | `Result` | Lookup with tenant isolation |
## Failure Types
| Failure | When |
|---------|------|
| `SyncJobNotFoundFailure` | Job ID doesn't exist or wrong tenant |
| `SyncJobAlreadyRunningFailure` | Concurrent job for same (source, action) |
| `SyncJobTransitionFailure` | Invalid state transition (e.g., COMPLETED → RUNNING) |
## Concurrency Safety
`createExclusive()` uses a PostgreSQL transaction with `SELECT ... FOR UPDATE` to atomically check for existing active jobs and create a new one. This eliminates race conditions at the application layer (OP-006 resolved).
---
id: SyncJobRunner
name: Sync Job Runner
version: 1.1.0
summary: |
Orchestrates the lifecycle of a single (source, action) sync job: validate source, create exclusive job, run fetch loop with checkpointing, aggregate metadata, mark COMPLETED or FAILED.
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
sends:
- id: TriggerSourceSync
version: 1.0.0
receives:
- id: TriggerSourceSync
version: 1.0.0
- id: TriggerDailySync
version: 2.0.0
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Overview
`SyncJobRunner` drives a single sync job from creation to completion. Called by `MultiSourceOrchestrator` (one call per DAG step) and indirectly by Trigger.dev tasks (`source-action-chunk`).
## Lifecycle
```
validateSource → createExclusiveJob → fetchLoop → aggregateMetadata → markCompleted
↘ catch → markFailed (with pagesProcessed)
```
1. **Validate source** — verify source exists for tenant (multi-tenant security).
2. **Create exclusive job** — `SyncJobRepository.createExclusive()` blocks parallel runs for the same `(source, action)` via `SELECT ... FOR UPDATE`.
3. **Fetch loop** — `connector.fetchAction(action, context)` repeatedly while `hasMore === true`; checkpoint and record count saved after each batch.
4. **Aggregate metadata** (CEN-59) — `SyncJobAggregator.aggregate(action, scope)` computes per-action statistics from `page_visibility_states`.
5. **Mark COMPLETED** — `updateStatus(COMPLETED, { completedAt, metadata })` in one write.
6. **On error → FAILED** — `updateStatus(FAILED, { completedAt, error, metadata: { pagesProcessed } })`.
## Metadata Persistence (CEN-59)
Before CEN-59, `metadata` was always `null` on COMPLETED jobs and playground charts ran on dev seeds. After CEN-59, every COMPLETED job carries per-action aggregates:
| Action | Metadata Shape |
|---|---|
| `indexation` | `{ pagesProcessed, indexed, notIndexed, excluded, unknown }` |
| `search_analytics` | `{ pagesProcessed, totalClicks, totalImpressions, avgCtr, avgPosition }` |
| `rendering` | `{ pagesProcessed, rendered, failed }` |
| _other_ | `{ pagesProcessed }` |
FAILED jobs always carry `{ pagesProcessed: }`.
## Dependencies
| Service | Purpose |
|---------|---------|
| `ConnectorFactory` | Creates the appropriate `SourceConnector` for the source type |
| `SyncJobRepository` | CRUD with state machine guards |
| `SyncJobAggregator` | Computes per-action metadata before COMPLETED transition |
| `PageDiscoveryService` | Find-or-create page records for incoming rows |
| `ViewRefreshService` | Refresh per-action materialized views after success |
## Error Handling
- Source not found → `Fail(SourceNotFoundFailure)` (no retry from caller)
- Duplicate running job → `Fail(SyncJobAlreadyRunningFailure)`
- Connector not registered → `Fail(ConnectorNotFoundFailure)`
- Connector throws mid-fetch → caught, job marked `FAILED`, `Ok(progress)` returned with the error message — caller (Trigger.dev task) decides whether to retry.
## Repositories
Injects TypeORM repositories for: `SourceEntity`, `PageVisibilityStateEntity`.
## View Refresh After Sync
| Action | View Refreshed |
|--------|---------------|
| `indexation` | `refreshIndexationViews()` |
| `search_analytics` | `refreshSearchMetricsViews()` |
| `rendering` | `refreshRenderingViews()` |
View refresh failures are logged but do not mark the sync job as failed — data is already persisted; the next cycle refreshes anyway.
---
id: SyncJobTracker
name: Sync Job Tracker
version: 1.0.0
summary: |
Provides read-only progress queries for sync jobs: current status, job history per source, and last checkpoint retrieval for incremental sync.
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
---
## Overview
`SyncJobTracker` is the read-side counterpart to `SyncJobRunner`. It queries sync job state without modifying it — used by API endpoints and the scheduler to check progress and retrieve checkpoints for incremental sync.
## API
| Method | Purpose |
|--------|---------|
| `getJobStatus(jobId, tenantId)` | Current status of a specific job |
| `getJobHistory(sourceId, tenantId, options?)` | Paginated list of past jobs for a source |
| `getLastCheckpoint(sourceId, action, tenantId)` | Last checkpoint from the most recent completed job — enables incremental sync |
## Dependencies
| Service | Purpose |
|---------|---------|
| `SyncJobRepository` | Read-only queries on `SyncJobEntity` |
## Checkpoint Pattern
Checkpoints are opaque (`unknown`) values persisted per job. The tracker retrieves the last successful checkpoint so the next sync run can resume from where it left off:
```
Tracker.getLastCheckpoint(sourceId, 'indexation', tenantId)
→ { lastCursor: 'abc123', lastPage: 5 } // or whatever the connector stored
```
---
id: TasksDispatcher
name: Tasks Dispatcher
version: 1.0.0
summary: |
Port-and-adapter abstraction for dispatching Trigger.dev runs from the Visibility API. Concrete impl is TriggerDevTasksDispatcher; tests use FakeTasksDispatcher (CEN-58, 2026-04-27).
badges:
- content: Port
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
- content: CEN-58
backgroundColor: orange
textColor: orange
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Overview
`TasksDispatcher` is the port the Visibility API uses to enqueue Trigger.dev runs. It hides the SDK behind a Result-friendly interface so controllers stay testable and the SDK boundary is replaceable.
## Interface
```ts
interface TasksDispatcher {
dispatchDailySync(payload: { tenantId: string }): Promise<{ runId: string }>;
}
```
## Adapters
| Adapter | When | What it does |
|---|---|---|
| `TriggerDevTasksDispatcher` | Production / dev with real Trigger stack | Calls `tasks.trigger(, payload)` via `@trigger.dev/sdk@^4.4.4`. Excluded from coverage (SDK boundary). |
| `FakeTasksDispatcher` (testing/fakes) | Unit tests | Records dispatched payloads; configurable runId via `withRunId()`. |
## Wiring
```ts
{ provide: TASKS_DISPATCHER_PORT, useClass: TriggerDevTasksDispatcher }
```
Consumers inject via the `TASKS_DISPATCHER_PORT` symbol token (avoids depending on a concrete class — keeps the test seam clean).
## Why a Port
Three reasons:
1. **Test isolation** — `SyncController` unit tests don't need a running Trigger.dev stack.
2. **Adapter swappability** — production may swap SDK versions or move to managed Trigger.dev Cloud without controller changes.
3. **Dependency direction** — Visibility API does not depend on `@prerender-core/visibility-tasks` (the package that defines the tasks). The dispatch is a string-based call.
## Consumers
- `SyncController.triggerDailySync` → `dispatchDailySync({ tenantId })`
---
id: URLNormalizerService
name: URL Normalizer Service
version: 1.0.0
summary: |
Deterministic URL normalization with configurable per-domain rules. The "join key" between GSC URLs and Prerender pages.
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
- content: D010
backgroundColor: orange
textColor: orange
---
## Overview
`URLNormalizerService` transforms raw URLs into a canonical form for consistent matching across data sources. When GSC reports `https://WWW.Example.COM/blog/?utm=1` and Prerender has `https://example.com/blog`, normalization produces the same output so they match.
Every normalization rule is configurable per domain via `NormalizationRules` and `DomainOverrides`.
## API
| Method | Signature | Returns |
|--------|-----------|---------|
| `normalize` | `(rawUrl: string) => NormalizationResult` | `{ normalized, sectionKey, changed }` |
| `extractSectionKey` | `(urlOrPath: string) => string` | First path segment, `'root'`, or `'uncategorized'` |
## Normalization Rules (D010)
All rules have sensible defaults and are overridable per domain.
| Rule | Default | What it does |
|------|---------|--------------|
| Lowercase hostname | Always | `EXAMPLE.COM` → `example.com` |
| Strip default ports | Always | `:443` / `:80` removed |
| `stripWWW` | `true` | `www.example.com` → `example.com` |
| `lowercasePath` | `false` | `/Blog/Post` stays `/Blog/Post` |
| `stripQueryParams` | `true` | All query params removed |
| `keepQueryParams` | `[]` | Allowlist when `stripQueryParams` is on |
| `removeQueryParams` | `[]` | Blocklist when `stripQueryParams` is off |
| `sortQueryParams` | `true` | `?z=1&a=2` → `?a=2&z=1` |
| `stripTrailingSlash` | `true` | `/blog/` → `/blog` |
| `stripFragment` | `true` | `#section` removed |
| `decodeUnreserved` | `true` | `/%41BC` → `/ABC` (RFC 3986) |
| `ignoreProtocol` | `false` | `http://` and `https://` kept distinct |
## Per-Domain Overrides
```typescript
type DomainOverrides = Record>;
```
Domain lookup checks the original hostname first, then falls back to hostname without `www.` prefix.
```typescript
domainOverrides: {
'shop.example.com': {
stripQueryParams: true,
keepQueryParams: ['id', 'variant'],
},
}
```
## Section Key Extraction
Extracts the first path segment from a normalized URL:
| Input | Section Key |
|-------|-------------|
| `/blog/post` | `blog` |
| `/` | `root` |
| `/en/blog/post` | `en` (literal, no locale stripping) |
| invalid URL | `uncategorized` |
## Open Points
- **OP-007**: `lowercasePath` off by default — case-insensitive sites need per-domain override
- **OP-008**: `stripQueryParams` on by default — sites with meaningful params need `keepQueryParams` allowlist
- **OP-009**: section_key is literal first segment — no locale stripping yet
## Configuration
Registered in `Visibility.module.ts` via `useFactory` with optional `NormalizationConfig`:
```typescript
{
provide: URLNormalizerService,
useFactory: () => new URLNormalizerService(options.normalizationConfig),
}
```
## Dependencies
None — pure computation, no external service dependencies.
---
id: UrlsService
name: URLs Service
version: 1.0.0
summary: |
Paginated, filterable, sortable URL listing with per-URL visibility status. Phase 3D / 3D.6 migrated the service onto the GSC indexation MV. URL search uses `mv."normalizedUrl" ILIKE` — accelerated at scale by the `pg_trgm` GIN index added in CEN-86.
sends:
- id: GetUrls
version: 1.0.0
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
---
## Overview
`UrlsService` is the domain service behind `GET /visibility/urls`. It provides a searchable, paginated URL explorer.
## Responsibilities
1. **Verify project** exists and belongs to the requesting tenant
2. **Build base query** against the resolved indexation MV with tenant + project + (optional) source_type predicates
3. **Apply filters** — indexing status, non-index reason, section key, URL substring
4. **Count total** for pagination metadata
5. **Fetch paginated results** with configurable sort column and direction
6. **Calculate coverage** via `CoverageService`
## Predicate Shape (CEN-86)
```sql
WHERE mv.project_id = $1 AND mv.tenant_id = $2
[AND mv.source_type = $3]
[AND mv.indexing_status = $4]
[AND mv.section_key = $5]
[AND mv."normalizedUrl" ILIKE $6] -- pg_trgm GIN index added in CEN-86
```
Resolved via `QueryRouterService.resolve(GSC, 'indexation')`. The `pg_trgm` GIN index on `mv."normalizedUrl"` keeps `ILIKE '%substr%'` lookups linear-ish at large MV sizes.
## Sort Columns
| `sort_by` value | MV column |
|-----------------|-----------|
| `url` | `mv.url` |
| `last_crawled_at` | `mv.last_crawled_at` |
| `last_seen_at` | `mv.last_seen_at` |
## Indexing Status Filter Logic
| Filter value | SQL condition |
|--------------|---------------|
| `indexed` | `mv.indexing_status = 'INDEXED'` |
| `not_indexed` | `mv.indexing_status = 'NOT_INDEXED'` |
| `excluded` | `mv.indexing_status = 'EXCLUDED'` |
| `unknown` | `mv.indexing_status = 'UNKNOWN' OR mv.indexing_status IS NULL` |
## Dependencies
| Service | Purpose |
|---------|---------|
| `QueryRouterService` | Resolves the indexation MV route |
| `CoverageService` | Source coverage metrics |
---
id: ViewRefreshService
name: View Refresh Service
version: 1.0.0
summary: |
Manages creation and concurrent refresh of PostgreSQL materialized views for per-source data (GSC indexation, GSC search metrics, Prerender rendering). Uses REFRESH MATERIALIZED VIEW CONCURRENTLY for zero-downtime updates. The cross-source views were dropped in CEN-347 (no readers).
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
---
## Overview
`ViewRefreshService` is responsible for creating and refreshing the PostgreSQL materialized views that power the Visibility API's read queries. It handles:
- **Platform read models** — over `page_visibility_current`, for any source that emits the action: `cur_indexation` (plain VIEW, live) + `cur_indexation_summary` (MV) (CEN-340); `cur_rendering` + `cur_rendering_summary` and `cur_crawl_stats` (MVs, metric keys only; CEN-348, D066).
- **Per-source views** — GSC (`day_search_analytics`) and the Prerender crawl daily table (`mv_prerender_crawl_stats_daily`), refreshed by the orchestrator after each stage.
All refreshes use `REFRESH MATERIALIZED VIEW CONCURRENTLY` for zero-downtime updates during active reads.
## Methods
### Per-source
| Method | Returns | Description |
| ----------------------------- | --------------- | -------------------------------------------------------------- |
| `createIndexationViews()` | `Promise` | Creates `cur_indexation` + `cur_indexation_summary` if missing |
| `createSearchAnalyticsViews()` | `Promise` | Creates `day_search_analytics` if it does not exist |
| `createRenderingViews()` | `Promise` | Creates `cur_rendering` + `cur_rendering_summary` if missing |
| `refreshIndexationViews()` | `Promise` | Concurrently refreshes `cur_indexation_summary` |
| `refreshSearchAnalyticsViews()` | `Promise` | Concurrently refreshes `day_search_analytics` |
| `refreshRenderingViews()` | `Promise` | Concurrently refreshes `cur_rendering` + summary |
### Utility
| Method | Returns | Description |
| ---------------------- | ------------------ | ---------------------------------------------------- |
| `viewExists(viewName)` | `Promise` | Checks if a materialized view exists in the database |
## Materialized Views
### Per-source
| View | Source | Action | Key Columns | Refresh Trigger |
| ------------------------ | ------ | ------------------ | ----------------------------------------------------------------------- | --------------------------- |
| `cur_indexation` (VIEW) | any | `indexation` | `indexing_status`, `non_index_reason`, `coverage_state`, `inspected_at` | None (live) |
| `cur_indexation_summary` | any | `indexation` | Counted by `section_key` × `indexing_status` × `coverage_state` | After indexation sync |
| `day_search_analytics` | GSC | `search_analytics` | `impressions`, `clicks`, `ctr`, `position` | After search analytics sync |
| `cur_rendering` | any | `rendering` | `render_status`, `render_time_ms`, `status_code`, `rendered_at` | After rendering sync |
| `cur_rendering_summary` | any | `rendering` | Aggregated by `section_key` × `render_status` with `avg_render_time_ms` | After rendering sync |
| `cur_crawl_stats` | any | `crawl_stats` | `requests`, `errors`, `http_status`, `last_crawled_at` | After crawl stats sync |
## Concurrency
All refresh operations use `REFRESH MATERIALIZED VIEW CONCURRENTLY`, which requires a unique index on the materialized view. This allows reads to continue against the old data while the refresh is in progress.
## Dependencies
| Service | Purpose |
| -------------------- | ----------------------------------------- |
| TypeORM `DataSource` | Executes raw SQL for view DDL and refresh |
---
id: ViewRegistryService
name: View Registry Service
version: 1.0.0
summary: |
Registers and discovers materialized views. Tracks per-source views by (sourceType, action), plus view health including last refresh time and row counts.
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
- content: Phase 3
backgroundColor: orange
textColor: orange
sends:
- id: GetViews
version: 1.0.0
- id: GetViewHealth
version: 1.0.0
receives:
- id: RegisterConnector
version: 1.0.0
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Overview
`ViewRegistryService` is the discovery layer of D015 (Materialized View Query Routing). It keeps an in-memory registry of per-source materialized views, declared by each connector via `SchemaContribution.materializedViews` and registered through `registerSourceViews()`. Keyed by `(sourceType, action)`.
## Methods
### Per-source views
| Method | Returns | Description |
| ------------------------------------------- | ----------------------------- | ------------------------------------------------------ |
| `getView(sourceType, action)` | `ViewDefinition \| undefined` | Find the **per-row** view for a source type + action |
| `getViewsBySource(sourceType)` | `ViewDefinition[]` | List all views for a source type |
| `getAllViews()` | `ViewDefinition[]` | List all registered per-source views |
| `registerSourceViews(sourceType, viewDefs)` | `void` | Register views from a new connector |
| `getViewHealth(querier)` | `Promise` | Query PostgreSQL for refresh timestamps and row counts |
`MaterializedViewDefinition` carries a `kind: 'per-row' | 'summary'` discriminator (CEN-86, default `'per-row'`). `getView` returns only `kind: 'per-row'`, so a summary never shadows the per-row route of the same `(sourceType, action)`.
## Registered Views
### Per-source
No connector declares an indexation, rendering or latest-crawl view: those reads go to the core-owned `cur_indexation*` (CEN-340, D065), `cur_rendering*` and `cur_crawl_stats` (CEN-348, D066) by name. The rollout bridge views `mv_gsc_indexation*` (CEN-341) and `mv_prerender_rendering*` / `mv_prerender_crawl_stats` (CEN-325 S4b) are dropped.
| View | Source | Action | Refresh |
| -------------------------------- | --------- | ---------------- | ---------- |
| `day_search_analytics` | GSC | search_analytics | after_sync |
| `mv_prerender_crawl_stats_daily` | Prerender | crawl_stats | after_sync |
## View Health
The `getViewHealth()` method queries `pg_stat_user_tables` for each registered view, returning:
- **lastRefreshedAt** — from `last_autoanalyze` (proxy for last refresh)
- **rowCount** — from `n_live_tup` (approximate live row count)
These power the `GET /visibility/views/health` endpoint for operational monitoring.
## Architecture Context (D015)
The ViewRegistry is the abstraction layer for routing queries to materialized views instead of base tables. CEN-46 (Prerender Optimization Layer) and CEN-48 (Multi-Source Aggregation) added the per-source view set. CEN-50 added a cross-source namespace; it was deleted with the cross-source views in CEN-347 (no readers). Phase 2 feature services still query `page_visibility_states` directly — migration to the view-backed query path is tracked in OP-021.
---
id: VisibilityAPI
name: Visibility API
version: 1.0.0
summary: |
NestJS REST API serving visibility analytics endpoints under /visibility/*. Multi-tenant, project-scoped, with structured error responses.
sends:
- id: GetHealthCheck
version: 1.0.0
- id: GetOverview
version: 1.0.0
- id: GetDiagnostics
version: 1.0.0
- id: GetInspect
version: 1.0.0
- id: PostLiveInspection
version: 1.0.0
- id: GetLiveInspectionUsage
version: 1.0.0
- id: GetSections
version: 1.0.0
- id: GetSectionsCoverage
version: 1.0.0
- id: GetUrls
version: 1.0.0
- id: GetIndexationVerdicts
version: 1.0.0
- id: GetTrends
version: 1.0.0
- id: GetSources
version: 1.0.0
- id: GetSourceDetail
version: 1.0.0
- id: GetSourceJobs
version: 1.0.0
- id: TriggerSourceSync
version: 1.0.0
- id: DisconnectSource
version: 1.0.0
- id: TriggerDailySync
version: 1.0.0
- id: OAuthAuthorize
version: 1.0.0
- id: OAuthCallback
version: 1.0.0
- id: OAuthActivate
version: 1.0.0
- id: OAuthDisconnect
version: 1.0.0
- id: GetSchemaSources
version: 1.0.0
- id: GetSchemaActions
version: 1.0.0
- id: GetSchemaFields
version: 1.0.0
- id: RegisterConnector
version: 1.0.0
- id: GetConnectors
version: 1.0.0
- id: GetViews
version: 1.0.0
- id: GetViewHealth
version: 1.0.0
- id: GetVersion
version: 1.0.0
receives:
- id: RegisterConnector
version: 1.0.0
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: REST
backgroundColor: green
textColor: green
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Overview
The Visibility API is a NestJS dynamic module (`VisibilityModule.forRoot()`) that exposes REST endpoints under the `/visibility/*` route prefix. It is designed to be mounted into any NestJS application as a self-contained feature module.
## Multi-Tenancy
All requests require a tenant context. As of CEN-60 (2026-04-27), `TenantGuard` enforces this at the HTTP boundary:
- Validates `x-tenant-id` is a UUID; missing or malformed → 401 (`MISSING_TENANT_ID`).
- Controllers receive the validated tenant via `@TenantId() tenantId: string` (no more per-controller `getTenantId()` helpers, no more silent zero-GUID fallback).
- Dev-mode opt-in: `NODE_ENV=development` + `VISIBILITY_ALLOW_DEV_TENANT=1` falls back to zero-GUID. Default is reject.
- OAuth callback opts out via `@SkipTenantGuard()` — Google redirects without our header; identity is in the `state` parameter.
Every database query continues to include `tenantId` in its WHERE clause for defence-in-depth.
## Response Envelope
All successful responses use the `ApiResponse` wrapper:
```typescript
type ApiResponse = {
success: true;
data: T;
metadata: {
requestId: string; // UUID per request
timestamp: string; // ISO 8601
sources: SourceInfo[]; // Enabled sources and sync status
freshness: {
oldestDataAt: string | null;
newestDataAt: string | null;
staleSources: string[];
isStale: boolean;
};
coverage: {
totalSources: number;
activeSources: number;
coveragePercent: number;
};
};
};
```
## Failure-to-HTTP Mapping
Domain failures are converted to HTTP error responses by `FailureMapperService`:
| Failure Class | HTTP Status | Error Code |
|---------------|-------------|------------|
| ProjectNotFoundFailure | 404 | `PROJECT_NOT_FOUND` |
| SourceNotFoundFailure | 404 | `SOURCE_NOT_FOUND` |
| SourceUnavailableFailure | 503 | `SOURCE_UNAVAILABLE` |
| QuotaExceededFailure | 429 | `QUOTA_EXCEEDED` |
| CapabilityNotSupportedFailure | 422 | `CAPABILITY_NOT_SUPPORTED` |
| ConnectorNotFoundFailure | 404 | `CONNECTOR_NOT_FOUND` |
| InvalidURLFailure | 400 | `INVALID_URL` |
| _Missing/malformed_ `x-tenant-id` | 401 | `MISSING_TENANT_ID` (thrown by `TenantGuard`) |
## Module Registration
```typescript
@Module({
imports: [VisibilityModule.forRoot({
routePrefix: 'visibility',
freshnessStaleThresholdHours: 24,
})],
})
export class AppModule {}
```
---
id: VisibilityWorker
name: Visibility Worker
version: 1.0.0
summary: |
Internal-only NestJS worker pod that executes Trigger.dev visibility tasks through the same /visibility/internal/tasks/* endpoints as the API image.
badges:
- content: Kubernetes
backgroundColor: blue
textColor: blue
- content: Internal service
backgroundColor: gray
textColor: gray
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Overview
`visibility-worker` runs the same Docker image as `visibility-api`, but it is a separate Kubernetes `Deployment` and `ClusterIP` service with no public ingress.
Trigger.dev runner pods call it through:
```text
VISIBILITY_INTERNAL_API_URL=http://visibility-worker:3001
```
The worker owns DB-heavy sync execution: daily sync, manual source sync, per-source action sync, retention, and partition maintenance. Public `visibility-api` remains the UI/API read and enqueue path.
## Deployment Contract
| Field | Value |
|---|---|
| Deployment | `visibility-worker` |
| Service | `visibility-worker` |
| Image | `visibility-api` image |
| Port | `3001` |
| Public ingress | none |
| DB pool | `DATABASE_POOL_MAX=40` |
| Auth | `x-prerender-internal-secret` matched against `TRIGGER_SECRET_KEY` |
## Related Services
- [Visibility API](/docs/services/VisibilityAPI) — public/UI API and Trigger enqueue path.
- [Visibility Tasks](/docs/domains/VisibilityTasks) — Trigger.dev task definitions that call this worker.
- [InternalTasksController](https://github.com/prerender/prerender-core/tree/main/packages/visibility/src/controllers/internal) — internal endpoint surface executed by this pod.
---
id: WorkerRegistrationService
name: Worker Registration Service
version: 1.0.0
summary: |
Registers a connector worker with the Visibility API on startup. Retries with exponential backoff and controls the readiness probe.
badges:
- content: NestJS
backgroundColor: blue
textColor: blue
- content: Injectable
backgroundColor: purple
textColor: purple
- content: Phase 3
backgroundColor: orange
textColor: orange
sends:
- id: RegisterConnector
version: 1.0.0
repository:
language: TypeScript
url: https://github.com/prerender/prerender-core
---
## Overview
`WorkerRegistrationService` lives in the `@prerender-core/connector-worker-template` package — the shared runtime template that every connector worker copies. On NestJS module initialization, it announces the worker to the Visibility API so the API knows which connectors are available and how to reach them.
## Lifecycle
```
onModuleInit → POST /visibility/connectors/register → set readiness flag
```
1. **Build payload** — combines `WORKER_NAME`, derived `workerURL`, and declared capabilities (`supportedSourceTypes`, `supportedActions`)
2. **POST to API** — sends registration to `{VISIBILITY_API_URL}/visibility/connectors/register`
3. **Retry on failure** — exponential backoff (1s, 2s, 4s), up to 3 attempts
4. **Set readiness** — on success, `isRegistered()` returns `true`, enabling the K8s readiness probe
## Methods
| Method | Returns | Description |
|--------|---------|-------------|
| `onModuleInit()` | `Promise` | NestJS lifecycle hook — triggers registration |
| `register()` | `Promise` | Performs the registration with retry logic |
| `isRegistered()` | `boolean` | Readiness flag — used by `WorkerHealthController` |
## Configuration
| Env Var | Default | Purpose |
|---------|---------|---------|
| `WORKER_NAME` | `connector-worker` | Worker identity and K8s service name |
| `APP_PORT` | `3002` | Port for the worker URL |
| `VISIBILITY_API_URL` | `http://visibility-api:3001` | Target API for registration |
| `SUPPORTED_SOURCE_TYPES` | (empty) | Comma-separated source types this worker handles |
| `SUPPORTED_ACTIONS` | (empty) | Comma-separated actions this worker can fetch |
## Dependencies
| Dependency | Purpose |
|------------|---------|
| `WORKER_CONFIG` | Resolved configuration (name, port, API URL) |
| `HTTP_CLIENT` | Adapter for HTTP POST (default: native `fetch()`) |
| `REGISTRATION_PAYLOAD` | Declared capabilities from env vars |
## Error Behavior
- **API unavailable** — retries 3 times, then starts unregistered
- **Non-200 response** — treated as failure, triggers retry
- **All retries exhausted** — worker runs but `GET /readyz` returns `not_ready`; K8s does not route traffic to the pod
The worker does **not** crash on registration failure. It stays alive for K8s to restart or for manual intervention.
## Package Location
`packages/connector-worker-template/src/services/registration/WorkerRegistrationService.ts`
This is a **template** — when creating a new connector (e.g., Prerender), copy the template package and configure the environment variables. The registration service works without modification.
---
id: GscConnectorWorker
name: GSC Connector Worker
version: 1.0.0
summary: |
Google Search Console connector deployed as an independent K8s pod. Fetches search analytics and URL inspection data via OAuth; authenticates and registers with Visibility API on startup.
services:
- id: GscConnector
version: 1.0.0
- id: GscOAuthService
version: 1.0.0
- id: WorkerRegistrationService
version: 1.0.0
owners:
- visibility-team
badges:
- content: K8s Worker Pod
backgroundColor: green
textColor: green
- content: Phase 3
backgroundColor: orange
textColor: orange
---
## Overview
GSC Connector Worker is a standalone NestJS application that runs in its own Kubernetes pod (D013).
It bridges Google Search Console API data into the Visibility domain.
On startup, `WorkerRegistrationService` registers with Visibility API through `POST /visibility/connectors/register`, sending `x-prerender-connector-registration-secret` plus capabilities, supported actions, and schema contribution.
## Deployment
| Property | Value |
|----------|-------|
| Package | `@prerender-core/connector-gsc` |
| K8s Service | `connector-gsc` |
| Port | 3002 |
| Registered URL | `http://connector-gsc:3002` |
| Health | `GET /healthz` (liveness), `GET /readyz` (readiness) |
| Terraform | `infra/terraform/modules/connector-worker/` |
The registered host must equal `connector-gsc`.
Visibility API dispatch rejects external hosts, IP literals, and dotted FQDNs for this worker.
## Supported Actions
| Action | Label | Temporal Mode |
|--------|-------|---------------|
| `indexation` | URL Indexation Status | `SNAPSHOT_ONLY` |
| `search_analytics` | Search Analytics | `TIME_SERIES` |
| `clustering` | URL Clustering | `SNAPSHOT_ONLY` |
## Registration Payload
On startup, the worker sends its schema contribution to Visibility API, which cascades to:
- `SchemaDictionaryService` for field discovery.
- `ViewRegistryService` for materialized view registration.
---
id: PrerenderConnectorWorker
name: Prerender Connector Worker
version: 1.0.0
summary: |
Prerender.io connector deployed as an independent K8s pod. Fetches render status, cache health, and crawler-served page data via Prerender API; authenticates and registers with Visibility API on startup.
services:
- id: PrerenderConnector
version: 1.0.0
- id: PrerenderAPIClient
version: 1.0.0
- id: WorkerRegistrationService
version: 1.0.0
owners:
- visibility-team
badges:
- content: K8s Worker Pod
backgroundColor: green
textColor: green
- content: Phase 3
backgroundColor: orange
textColor: orange
---
## Overview
Prerender Connector Worker is a standalone NestJS application that runs in its own Kubernetes pod (D013).
It bridges Prerender.io API data into the Visibility domain.
On startup, `WorkerRegistrationService` registers with Visibility API through `POST /visibility/connectors/register`, sending `x-prerender-connector-registration-secret` plus capabilities, supported actions, and schema contribution.
## Deployment
| Property | Value |
|----------|-------|
| Package | `@prerender-core/connector-prerender` |
| K8s Service | `connector-prerender` |
| Port | 3003 |
| Registered URL | `http://connector-prerender:3003` |
| Health | `GET /healthz` (liveness), `GET /readyz` (readiness) |
| Terraform | `infra/terraform/modules/connector-worker/` |
The registered host must equal `connector-prerender`.
Visibility API dispatch rejects external hosts, IP literals, and dotted FQDNs for this worker.
## Supported Actions
| Action | Label | Temporal Mode |
|--------|-------|---------------|
| `rendering` | Render Status & Timing | `SNAPSHOT_ONLY` |
| `cache_status` | Cache Status | `SNAPSHOT_ONLY` |
| `crawl_stats` | Crawler Served Pages | `TIME_SERIES` |
## Architecture
Uses port/adapter pattern (D012):
- `PrerenderAPIPort` — abstract interface for API calls.
- `PrerenderAPIClient` — real HTTP adapter using Prerender token auth.
- `MockPrerenderAPIClient` — synthetic data for tests.
## Registration Payload
On startup, the worker sends its schema contribution to Visibility API, which cascades to:
- `SchemaDictionaryService` for field discovery.
- `ViewRegistryService` for materialized view registration.
---
id: Visibility
name: Visibility Analytics
version: 1.0.0
summary: |
Aggregates SEO visibility data from multiple sources (GSC, Bing, GA4, Cloudflare, Prerender) into unified, multi-tenant analytics for monitoring indexation health across web properties.
entities:
- id: Project
- id: Domain
- id: Page
- id: PageVisibilityState
- id: Source
- id: SyncJob
- id: Projection
- id: HistoryPromotion
services:
- id: VisibilityAPI
version: 1.0.0
- id: VisibilityWorker
version: 1.0.0
- id: OverviewService
version: 1.0.0
- id: DiagnosticsService
version: 1.0.0
- id: SectionsService
version: 1.0.0
- id: SectionCoverageService
version: 1.0.0
- id: InspectService
version: 1.0.0
- id: LiveInspectionService
version: 1.0.0
- id: UrlsService
version: 1.0.0
- id: IndexationVerdictsService
version: 1.0.0
- id: ResponseBuilderService
version: 1.0.0
- id: FreshnessService
version: 1.0.0
- id: CoverageService
version: 1.0.0
- id: FailureMapperService
version: 1.0.0
- id: URLNormalizerService
version: 1.0.0
- id: SyncJobRunner
version: 1.1.0
- id: SyncJobTracker
version: 1.0.0
- id: SyncJobRepository
version: 1.0.0
- id: SyncJobAggregator
version: 1.0.0
- id: TasksDispatcher
version: 1.0.0
- id: MultiSourceOrchestrator
version: 1.0.0
- id: PageDiscoveryService
version: 1.0.0
- id: SourceManagementService
version: 1.0.0
- id: ViewRefreshService
version: 1.0.0
- id: QuotaTrackerService
version: 1.0.0
- id: ConnectorRegistryService
version: 1.0.0
- id: SchemaDictionaryService
version: 1.0.0
- id: ViewRegistryService
version: 1.0.0
- id: QueryRouterService
version: 1.0.0
- id: SemanticClassifierService
version: 1.0.0
- id: RankingReadService
version: 1.0.0
- id: NarrativeTemplateService
version: 1.0.0
sends:
- id: GetHealthCheck
version: 1.0.0
- id: GetOverview
version: 1.0.0
- id: GetDiagnostics
version: 1.0.0
- id: GetInspect
version: 1.0.0
- id: PostLiveInspection
version: 1.0.0
- id: GetLiveInspectionUsage
version: 1.0.0
- id: GetSections
version: 1.0.0
- id: GetUrls
version: 1.0.0
- id: GetIndexationVerdicts
version: 1.0.0
- id: GetTrends
version: 1.0.0
- id: GetSources
version: 1.0.0
- id: GetSourceDetail
version: 1.0.0
- id: GetSourceJobs
version: 1.0.0
- id: TriggerSourceSync
version: 1.0.0
- id: DisconnectSource
version: 1.0.0
- id: TriggerDailySync
version: 1.0.0
- id: OAuthAuthorize
version: 1.0.0
- id: OAuthCallback
version: 1.0.0
- id: OAuthActivate
version: 1.0.0
- id: OAuthDisconnect
version: 1.0.0
- id: GetSchemaSources
version: 1.0.0
- id: GetSchemaActions
version: 1.0.0
- id: GetSchemaFields
version: 1.0.0
- id: RegisterConnector
version: 1.0.0
- id: GetConnectors
version: 1.0.0
- id: GetViews
version: 1.0.0
- id: GetViewHealth
version: 1.0.0
- id: GetRankingLatest
version: 1.0.0
- id: GetSemanticMetadata
version: 1.0.0
- id: ReviewSemanticMetadata
version: 1.0.0
owners:
- visibility-team
badges:
- content: Core domain
backgroundColor: blue
textColor: blue
---
## Overview
The Visibility domain provides unified SEO visibility metrics by aggregating data from multiple external sources into a single, consistent API surface. It answers the question: _"How visible is my website to search engines, and where are the problems?"_
### Data Sources
| Source | Type | Capabilities |
| --------------------------- | ------------- | ----------------------------------------------------- |
| Google Search Console (GSC) | Search engine | Index status, crawl data, historical data (16 months) |
| Bing Webmaster Tools | Search engine | Index status |
| Google Analytics 4 (GA4) | Analytics | Traffic data |
| Cloudflare | CDN/DNS | Performance data |
| Prerender | Rendering | Pre-rendering status |
### Data Model
6 TypeORM entities backed by PostgreSQL (DigitalOcean managed). All entities include `tenantId` for multi-tenant isolation.
```mermaid
erDiagram
Project ||--o{ Domain : "has many"
Domain ||--o{ Page : "has many"
Page ||--o{ PageVisibilityState : "has many"
Source ||--o{ PageVisibilityState : "has many"
Source ||--o{ SyncJob : "has many"
Project {
uuid id PK
uuid tenant_id
varchar name
}
Domain {
uuid id PK
uuid project_id FK
uuid tenant_id
varchar domain
}
Page {
uuid id PK
uuid domain_id FK
uuid tenant_id
varchar url
varchar section
}
PageVisibilityState {
bigserial id PK
uuid page_id FK
uuid source_id FK
uuid tenant_id
text action
jsonb raw_source_payload
timestamptz fetched_at
}
Source {
uuid id PK
uuid tenant_id
varchar type
varchar status
jsonb capabilities
boolean is_enabled
text encrypted_credentials
}
SyncJob {
uuid id PK
uuid source_id FK
uuid tenant_id
varchar action
varchar status
jsonb checkpoint
int records_processed
}
```
### Storage Strategy
| Table | Expected Volume | Write Pattern | Read Pattern |
| ------------------------ | --------------------- | ---------------- | ------------------------------------ |
| `projects` | 1–10 per tenant | Near-static | Lookup by PK |
| `domains` | 1–5 per project | Near-static | By project |
| `pages` | 100K–500K per domain | Grows with sync | Paginated, filtered, sorted |
| `page_visibility_states` | 100K–1.5M per domain | Upsert on sync | Joins with pages, materialized views |
| `sources` | 1–5 per tenant | Near-static | By tenant |
| `sync_jobs` | ~1 per source per day | One per sync run | By source, by status |
**JSONB Strategy (D006)**: All source-specific data is stored in `rawSourcePayload` JSONB on `PageVisibilityState`, scoped by `action` (e.g., `indexation`, `search_analytics`, `rendering`). No typed columns per source. Unique constraint: `(page_id, source_id, action)`. Primary key: bigserial. Optimization via materialized views (D007):
- **Platform (core-owned, any source)**: `cur_indexation` (plain VIEW), `cur_indexation_summary` (CEN-340); `cur_rendering`, `cur_rendering_summary`, `cur_crawl_stats` (CEN-348).
- **Per-source**: `day_search_analytics`, `mv_prerender_crawl_stats_daily` (table).
**URL Storage**: Raw URLs stored as-is in `pages.url`. Normalization computed at query time by `URLNormalizerService` (D010). This preserves the source of truth and allows rule changes without data migration.
### Flows
#### Sync Data Ingestion — How data gets in
#### OAuth Connection — How sources get connected
#### Overview Dashboard — How data gets aggregated
#### Source Management — How sources are managed
#### Daily Sync Cycle — How the system runs automatically
#### Connector Worker Registration — How workers announce themselves
#### Registration Cascade — How worker metadata propagates
#### Schema Discovery — How the frontend discovers fields
#### URL Inspect — How data gets out
### Connector Architecture
The connector layer bridges external data sources to the visibility domain. Starting in Phase 3, connectors are **fully decoupled** into their own packages and K8s pods:
- **SourceConnector interface** — two-method contract (`testConnection`, `fetchAction`) defined in `@prerender-core/connector-sdk`
- **ConnectorRegistryService** — dynamic in-memory registry replacing the static `ConnectorFactory`. Workers self-register via HTTP on startup
- **Action type system** (D009) — string unions providing compile-time safety for known actions (`indexation`, `search_analytics`, `clustering`) while remaining extensible
- **ConnectorCapabilities** — declares temporal modes (`SNAPSHOT_ONLY` vs `TIME_SERIES`) and available actions per connector
- **SchemaContribution** (D007 + D014) — connectors declare fields and materialized views at registration time. Frontend discovers fields via `/visibility/schema/` endpoints
See [ConnectorRegistryService](/docs/services/ConnectorRegistryService), [GSC Connector Worker](/docs/domains/GscConnectorWorker), and [Prerender Connector Worker](/docs/domains/PrerenderConnectorWorker) for details.
### Connector Worker Topology (D013)
Starting in Phase 3, each connector runs as a **separate K8s pod** rather than in-process with the Visibility API. This provides independent scaling, fault isolation, and independent deployment per connector.
```mermaid
flowchart LR
API[Visibility API
Pod] <-->|HTTP| GSC[GSC Connector
Worker Pod]
API <-->|HTTP| PRE[Prerender Connector
Worker Pod]
API <-->|HTTP| BING[Bing Connector
Worker Pod]
GSC -->|OAuth| GSCAPI[GSC API]
PRE -->|REST| PREAPI[Prerender API]
BING -->|OAuth| BINGAPI[Bing API]
```
Workers are deployed from a shared runtime template (`@prerender-core/connector-worker-template`) and register with the Visibility API on startup via the [Worker Registration](/docs/flows/WorkerRegistration) protocol. The Terraform module `infra/terraform/modules/connector-worker/` provisions each worker as a parameterized K8s Deployment + Service.
See [WorkerRegistrationService](/docs/services/WorkerRegistrationService) for the registration handshake.
### URL Normalization (D010)
Deterministic URL normalization is the "join key" between data sources. `URLNormalizerService` transforms raw URLs into a canonical form with 10 configurable rules (all overridable per domain). See [URLNormalizerService](/docs/services/URLNormalizerService) for rule defaults and per-domain override mechanism.
### Sync Job Infrastructure
The sync pipeline orchestrates data ingestion from external sources:
- **SyncJobRunner** — orchestrates the full lifecycle: validate source → create exclusive job → fetch loop with checkpointing → aggregate metadata → complete/fail
- **SyncJobAggregator** (CEN-59) — computes per-action observability metadata (indexation/search_analytics/rendering shapes) from `page_visibility_states` before the COMPLETED transition. Resolves OP-025
- **SyncJobTracker** — read-only progress queries and last checkpoint retrieval for incremental sync
- **SyncJobRepository** — state machine guards (`PENDING → RUNNING → COMPLETED/FAILED`) with concurrent run prevention via `SELECT ... FOR UPDATE`
- **TasksDispatcher** (CEN-58) — port abstracting Trigger.dev run dispatch; controllers depend on this, not on the SDK
### Async Execution (Trigger.dev)
Daily sync no longer runs on the API request thread. As of CEN-58 (2026-04-27):
- `POST /visibility/sync/daily` returns a `{ runId }` in under 500ms via `TasksDispatcher.dispatchDailySync`.
- The actual work runs on a `@prerender-core/visibility-tasks` worker pod (separate package, separate K8s deployment).
- Tasks live in the [Visibility Tasks](/docs/domains/VisibilityTasks) bounded context: `dailySyncFanout`, `dailySyncCron` (cron `0 3 * * *`).
- Retry policy: 3 retries with exponential backoff for transient failures. Domain rejections (source-not-found, etc.) skip retry.
### URL Ranking (Phase 3C)
A separate read/write split for the URL ranking system (CEN-67 → CEN-78). The pipeline replaces the deleted `UrlPrioritySelectorService` (CEN-72 per D023):
- **DailyRankingJob** (write side) — runs the four-layer V2 pipeline once per tenant per day (Layer 0 exclusion, Layer 1 SAW/TOPSIS V2 per source, Layer 2 aggregation, Layer 3 anomaly, Layer 4 `BucketAllocatorV2`) and persists the run to `url_rankings`. Three buckets — `prove_value`, `find_problems`, `expand_coverage`. The v1 `RankingService` + `PrerenderSignalProvider` path was deleted in CEN-347.
- **RankingReadService** (read side) — loads the latest run via `UrlRankingRepository.getLatestRun`, paginates per bucket, renders bucket narratives via `NarrativeTemplateService` (CEN-78). Powers `GET /visibility/ranking/latest`.
- **NarrativeTemplateService** — single-pass `{name}` substitution with non-recursive replacement. Missing keys render as `[unknown]`; substituted values that look like placeholders are left literal (injection guard).
### Semantic Metadata (D014 amendment)
Per-field semantic metadata is resolved at lookup time in priority `override → declared → heuristic`. `SemanticClassifierService` runs a small regex rule set over `path|label|description` tokens — **no runtime LLM call** (Anthropic-backed variant deferred per OP-031). Reviewer flow goes through `ConnectorRegistryService` and is durable since CEN-87: overrides are persisted on the owning worker's `connector_registrations.semanticOverrides` JSONB.
### Tenant Isolation (CEN-60)
`TenantGuard` (NestJS `CanActivate`) is applied to every tenant-scoped controller. UUID validation on `x-tenant-id`; missing or malformed → 401. Dev-mode opt-in: `NODE_ENV=development` + `VISIBILITY_ALLOW_DEV_TENANT=1` falls back to zero-GUID. The OAuth callback opts out via `@SkipTenantGuard()` (Google redirects without our header; identity is in `state`). Replaces the per-controller `getTenantId()` helper that previously fell back to zero-GUID silently.
### Data Flow
```mermaid
flowchart LR
GSC[GSC API] --> GscWorker[GSC Connector
Worker Pod]
PRE[Prerender API] --> PreWorker[Prerender Connector
Worker Pod]
GscWorker -->|HTTP| API[Visibility API]
PreWorker -->|HTTP| API
API --> Runner[SyncJobRunner]
Runner --> |"upsert"| PVS[(PageVisibilityState)]
Runner --> |"update checkpoint"| SJ[(SyncJob)]
Runner --> |"create/match"| Pages[(Page)]
Pages --> Normalizer[URLNormalizerService]
PVS --> |"refresh"| MV[(Materialized Views)]
MV --> API
PVS --> API
Pages --> API
```
### Shared Infrastructure
- **Result pattern** (`Ok`/`Fail`) for type-safe error handling — no exceptions in the domain layer
- **ApiResponse wrapper** with metadata including source coverage, data freshness, and staleness indicators
- **Failure classes** mapped to HTTP status codes at the adapter boundary
- **Multi-tenant isolation** via `tenantId` on every entity and query
---
id: VisibilityTasks
name: Visibility Tasks (Trigger.dev runtime)
version: 1.0.0
summary: |
Trigger.dev task definitions for visibility background work. Tasks are thin HTTP callers into the internal Visibility Worker service.
services:
- id: DailySyncFanoutTask
version: 1.0.0
- id: DailySyncCronTask
version: 1.0.0
- id: HistoryOutboxParityTask
version: 1.0.0
- id: HistoryOutboxRetentionTask
version: 1.0.0
badges:
- content: Trigger.dev v4
backgroundColor: blue
textColor: blue
- content: CEN-58
backgroundColor: orange
textColor: orange
---
## Overview
`@prerender-core/visibility-tasks` hosts Trigger.dev task definitions for Visibility background work. Production task code does not bootstrap NestJS and does not resolve domain services in the runner process. Each task calls authenticated internal endpoints on `visibility-worker` through `VISIBILITY_INTERNAL_API_URL`.
## Bounded Context
```mermaid
flowchart LR
API[Visibility API
public/UI path] -->|tasks.trigger| TR[Trigger.dev
webapp]
TR -->|dispatches run| T[Trigger.dev runner
visibility-tasks]
T -->|HTTP + x-prerender-internal-secret| W[Visibility Worker
internal service]
W --> ORCH[DailySyncExecutorService
SyncJobRunner]
ORCH --> DB[(Postgres)]
```
## Tasks
| Task | Type | Trigger | Body |
|---|---|---|---|
| `daily-sync-fanout` | `task` | `tasks.trigger("daily-sync-fanout", { tenantId })` | `POST /visibility/internal/tasks/daily-sync` |
| `daily-sync-cron` | `schedules.task` | cron `0 3 * * *` | enumerate tenants through internal API, then dispatch `daily-sync-fanout` |
| `history-outbox-parity` | `schedules.task` (queue 1) | cron `0 9 * * *` UTC | `POST /visibility/internal/tasks/history-outbox/parity` |
| `history-outbox-retention` | `schedules.task` (queue 1) | cron `0 8 * * *` UTC | `POST /visibility/internal/tasks/history-outbox/retention` |
The history promote (CEN-323) is not a task any more: the worker's `HistoryPromoteSweeper` folds terminal sync jobs on a timer (`HISTORY_PROMOTE_SWEEP_INTERVAL_MS`, 60 s) inside the [Visibility Worker](/docs/services/VisibilityWorker); the run platform only billed those runs for waiting on the worker.
## Runtime Env
| Variable | Used by | Purpose |
|---|---|---|
| `TRIGGER_API_URL` | deploy CLI / SDK | Self-hosted Trigger webapp. |
| `TRIGGER_PROJECT_REF` | deploy CLI | Target Trigger.dev project. |
| `TRIGGER_SECRET_KEY` | runner + worker | Sent as `x-prerender-internal-secret` to internal task endpoints. |
| `VISIBILITY_INTERNAL_API_URL` | runner | Internal Visibility Worker base URL, currently `http://visibility-worker:3001`. |
## Failure Semantics
The task runner only owns Trigger.dev retry behavior and response shaping. Domain execution happens inside `visibility-worker`, where Visibility services write operation events, sync jobs, chunks, and persisted rows.
| Worker outcome | Task action | Trigger.dev retry? |
|---|---|---|
| Completed response | return `outcome=completed` | no |
| Rejected/domain failure response | return `outcome=rejected` with reason | no |
| HTTP/network/transient failure | throw task error | yes, according to `trigger.config.ts` retry policy |
## Related
- [Visibility Worker](/docs/services/VisibilityWorker)
- [Visibility API](/docs/services/VisibilityAPI)
- [Daily Sync Fanout Task](/docs/services/DailySyncFanoutTask)
- [History Outbox Parity Task](/docs/services/HistoryOutboxParityTask)
- [History Outbox Retention Task](/docs/services/HistoryOutboxRetentionTask)
---
id: Domain
name: Domain
version: 1.0.0
identifier: id
summary: A web domain (e.g., example.com) belonging to a project. Groups pages under a single DNS authority.
properties:
- name: id
type: UUID
required: true
description: Primary key, auto-generated
- name: projectId
type: UUID
required: true
description: Foreign key to Project
references: Project
referencesIdentifier: id
relationType: hasOne
- name: tenantId
type: UUID
required: true
description: Multi-tenant isolation key
- name: domain
type: string
required: true
description: "Bare hostname, e.g. example.com — no protocol, no trailing slash (max 255 chars)"
- name: createdAt
type: DateTime
required: true
description: Auto-generated creation timestamp
- name: pages
type: array
items:
type: Page
required: false
description: URLs under this domain
references: Page
referencesIdentifier: domainId
relationType: hasMany
badges:
- content: TypeORM
backgroundColor: blue
textColor: blue
- content: Immutable
backgroundColor: orange
textColor: orange
---
## Overview
Domain represents a DNS authority (e.g. `example.com`) belonging to a project. It groups individual pages under a single hostname, providing the organizational layer between a project and its tracked URLs.
## Table: `domains`
| Column | Type | Constraints |
|--------|------|------------|
| `id` | `uuid` | PK, auto-generated |
| `project_id` | `uuid` | NOT NULL, FK → `projects.id` |
| `tenant_id` | `uuid` | NOT NULL |
| `domain` | `varchar(255)` | NOT NULL |
| `created_at` | `timestamp` | NOT NULL, default now() |
## Relationships
- **belongs to Project** — every domain is scoped to exactly one project via `projectId`.
- **has many Pages** — a domain owns all URLs under its hostname.
## Storage Format
The `domain` column stores the bare hostname only:
| Input | Stored As |
|-------|-----------|
| `https://www.example.com/` | `example.com` |
| `http://blog.example.com` | `blog.example.com` |
## Expected Scale
| Metric | Estimate |
|--------|----------|
| Rows per project | 1–5 |
| Growth rate | Near-static |
| Query pattern | By `(projectId, tenantId)` |
## Notes
- **Immutable** — no `updatedAt` column. Created once, never modified.
---
id: HistoryPromotion
name: History Promotion
version: 1.0.0
identifier: operationId
summary: "History outbox promote ledger (CEN-321, D058): one row per sync job key (tenant, operation, source, action). Records the sticky mode, progress and errors of the promote. Kept 30 days."
properties:
- name: tenantId
type: UUID
required: true
description: Multi-tenant isolation key; first column of the primary key (`tenant_id`)
- name: operationId
type: UUID
required: true
description: Operation of the job (`operation_id`)
- name: sourceId
type: UUID
required: true
description: Source of the job (`source_id`)
references: Source
referencesIdentifier: id
relationType: hasOne
- name: action
type: string
required: true
description: Connector action of the job
- name: syncJobId
type: UUID
required: false
description: The sync job promoted (`sync_job_id`)
- name: mode
type: string
required: true
description: "`shadow` (replace, history kept) or `outbox` (add, history deleted); fixed at the first promote"
- name: status
type: string
required: true
description: "`pending` (default), `running`, `done`, `failed`, `skipped`"
- name: rowsPromoted
type: bigint
required: true
description: History rows folded so far (`rows_promoted`, default 0)
- name: promotedAt
type: DateTime
required: false
description: Last batch commit (`promoted_at`)
- name: lastError
type: string
required: false
description: Last failure message (`last_error`)
- name: createdAt
type: DateTime
required: true
description: "`created_at`, default now()"
- name: updatedAt
type: DateTime
required: true
description: "`updated_at`, default now(); indexed for the 30-day retention"
badges:
- content: TypeORM
backgroundColor: blue
textColor: blue
- content: History outbox
backgroundColor: orange
textColor: orange
---
## Overview
The promote task (plan `docs/specs/2026-09-30-history-outbox-plan.md`, step 4) writes one row per
job key and updates it after every batch. The sweep finds terminal jobs without a `done` row here.
No FK: the row describes an operation, not a page, and tenant deletion clears it explicitly.
Nothing reads or writes the table before the promote task (step 4).
## Table: `history_promotions`
Primary key `(tenant_id, operation_id, source_id, action)`. Checks `history_promotions_mode_check`
and `history_promotions_status_check`. Index `idx_history_promotions_updated_at (updated_at)` for
retention. `fillfactor = 90`.
---
id: Page
name: Page
version: 1.0.0
identifier: id
summary: An individual URL within a domain. Grouped by section for aggregate reporting. URL identity determined by URLNormalizerService (D010).
properties:
- name: id
type: UUID
required: true
description: Primary key, auto-generated
- name: domainId
type: UUID
required: true
description: Foreign key to Domain
references: Domain
referencesIdentifier: id
relationType: hasOne
- name: tenantId
type: UUID
required: true
description: Multi-tenant isolation key
- name: url
type: string
required: true
description: "Full URL as received from data source (max 2048 chars). Stored raw — normalization is computed at query time."
- name: section
type: string
required: false
description: "URL section (e.g., blog, products). Max 255 chars. Computed by extractSectionKey() during page discovery."
- name: createdAt
type: DateTime
required: true
description: Auto-generated creation timestamp
- name: updatedAt
type: DateTime
required: true
description: Auto-generated last update timestamp
- name: visibilityStates
type: array
items:
type: PageVisibilityState
required: false
description: Per-source visibility records
references: PageVisibilityState
referencesIdentifier: pageId
relationType: hasMany
badges:
- content: TypeORM
backgroundColor: blue
textColor: blue
- content: High Volume
backgroundColor: red
textColor: red
---
## Overview
Page represents an individual URL tracked for SEO visibility within a domain. Pages are grouped by `section` (e.g. `blog`, `products`) for aggregate health reporting via `SectionsService`.
## Table: `pages`
| Column | Type | Constraints |
|--------|------|------------|
| `id` | `uuid` | PK, auto-generated |
| `domain_id` | `uuid` | NOT NULL, FK → `domains.id` |
| `tenant_id` | `uuid` | NOT NULL |
| `url` | `varchar(2048)` | NOT NULL |
| `section` | `varchar(255)` | NULLABLE |
| `created_at` | `timestamp` | NOT NULL, default now() |
| `updated_at` | `timestamp` | NOT NULL, auto-update |
## Relationships
- **belongs to Domain** — scoped to one domain via `domainId`
- **has many PageVisibilityStates** — one visibility record per data source
## URL Storage Strategy
URLs are stored **as received** from data sources — not normalized.
| Concern | Approach |
|---------|----------|
| **Storage** | Raw URL in `url` column, exactly as reported by the source |
| **Normalization** | Computed at query time by `URLNormalizerService.normalize()` (D010) |
| **Matching** | Exact match first, then normalized case-insensitive fallback |
| **Section** | First path segment via `extractSectionKey()` during page discovery |
**Why not store normalized?** Rules are configurable per domain and may change. Storing raw preserves the source of truth; normalization can be recomputed.
## Section Key
| URL | section |
|-----|---------|
| `https://example.com/blog/post-1` | `blog` |
| `https://example.com/products/shoes` | `products` |
| `https://example.com/` | `root` |
| `https://example.com/en/blog/post` | `en` (literal — OP-009) |
## Expected Scale
| Metric | Estimate |
|--------|----------|
| Rows per domain | 100–500K |
| Growth rate | Grows with each sync (page discovery) |
| Query patterns | By `(domainId, tenantId)`, ILIKE on `url`, filter by `section` |
| Hot path | `GET /visibility/urls` — paginated, filtered, sorted |
## Planned Indexes (Phase 2)
| Index | Ticket | Purpose |
|-------|--------|---------|
| `(domain_id, tenant_id)` | F.3 | Domain-scoped queries |
| `(tenant_id, section)` | F.3 | Section aggregation |
| `LOWER(url)` | F.3 | Normalized matching fallback |
---
id: PageVisibilityState
name: Page Visibility State
version: 1.0.0
identifier: id
summary: "Per-source, per-action visibility state. The core join table: one row per (page, source, action) with full JSONB payload. D006 schema — bigserial PK, no typed columns."
properties:
- name: id
type: bigserial
required: true
description: Primary key, auto-increment (switched from UUID per OP-018)
- name: pageId
type: UUID
required: true
description: Foreign key to Page
references: Page
referencesIdentifier: id
relationType: hasOne
- name: sourceId
type: UUID
required: true
description: Foreign key to Source
references: Source
referencesIdentifier: id
relationType: hasOne
- name: tenantId
type: UUID
required: true
description: Multi-tenant isolation key
- name: action
type: string
required: true
description: "Connector action (e.g., 'indexation', 'search_analytics'). Part of UNIQUE constraint."
- name: rawSourcePayload
type: JSON
required: true
description: "Full JSONB payload — structure varies by action. See JSONB schema below."
- name: fetchedAt
type: DateTime
required: false
description: When the data was fetched from the source API
- name: createdAt
type: DateTime
required: true
description: Auto-generated creation timestamp
- name: updatedAt
type: DateTime
required: true
description: Auto-generated last update timestamp
badges:
- content: TypeORM
backgroundColor: blue
textColor: blue
- content: Core Table
backgroundColor: red
textColor: red
- content: JSONB
backgroundColor: green
textColor: green
---
## Overview
PageVisibilityState is the **core data table** of the visibility domain. Each row records one page's visibility status as reported by one data source. The `metadata` JSONB column stores action-specific data that varies by source type — this is the "full JSONB commitment" from D006.
## Table: `page_visibility_states`
| Column | Type | Constraints |
|--------|------|------------|
| `id` | `bigserial` | PK, auto-increment |
| `page_id` | `uuid` | NOT NULL, FK → `pages.id` |
| `source_id` | `uuid` | NOT NULL, FK → `sources.id` |
| `tenant_id` | `uuid` | NOT NULL |
| `action` | `text` | NOT NULL |
| `raw_source_payload` | `jsonb` | NOT NULL |
| `fetched_at` | `timestamptz` | NULLABLE |
| `created_at` | `timestamp` | NOT NULL, default now() |
| `updated_at` | `timestamp` | NOT NULL, auto-update |
**Constraints**: `UNIQUE(page_id, source_id, action)` — enables `INSERT ... ON CONFLICT DO UPDATE` for upserts.
**Sync-job lookup** (CEN-318, D058): `idx_pvs_operation ("operationId", "sourceId", action) WHERE "operationId" IS NOT NULL`, one attached copy per partition. Read by the history outbox promote; nothing reads it before that.
## Relationships
- **belongs to Page** — the tracked URL via `pageId`
- **belongs to Source** — the data source that reported this state via `sourceId`
- Unique constraint: `(pageId, sourceId, action)` — one row per page per source per action
## JSONB Schema: `rawSourcePayload`
The `rawSourcePayload` column uses an action-based model (D006). The structure depends on which connector action produced the data:
### GSC Indexation Action (`action = 'indexation'`)
```typescript
{
indexing_status: string; // 'Submitted and indexed', 'Crawled - currently not indexed', etc.
non_index_reason: string; // Detailed reason code
last_crawl_time: string; // ISO 8601 timestamp
crawl_status: string; // 'OK', 'SERVER_ERROR', 'REDIRECT', etc.
robots_txt_state: string; // 'ALLOWED', 'DISALLOWED'
page_fetch_state: string; // 'SUCCESSFUL', 'SOFT_404', etc.
}
```
### GSC Search Analytics Action (`action = 'search_analytics'`)
```typescript
{
impressions: number; // Search impressions in period
clicks: number; // Search clicks in period
ctr: number; // Click-through rate (0.0–1.0)
position: number; // Average search position
date: string; // Date of the metrics (ISO 8601)
}
```
### Generic / Legacy
```typescript
{
lastHttpStatus?: number;
crawlFrequency?: string;
mobileUsability?: string;
richResultsStatus?: string;
[key: string]: unknown; // Extensible
}
```
## Materialized Views (D007 — Phase 2)
Raw JSONB queries are slow at scale. Connectors declare materialized views via `SchemaContribution` that pre-compute optimized read paths:
| View | Source | Ticket | Purpose |
|------|--------|--------|---------|
| `cur_indexation` (VIEW) + `cur_indexation_summary` | any (core-owned) | CEN-340 (was `mv_gsc_indexation`, CEN-37) | Latest indexation verdict + coverage state per page and source |
| `mv_gsc_search_metrics` | GSC | F.8b (CEN-38) | Time-series search metrics for trends |
Views are refreshed after each sync or on schedule. The API layer queries views (not raw JSONB) for production reads.
## Indexed JSONB Paths (Planned)
| Path | Type | Source | Purpose |
|------|------|--------|---------|
| `metadata->'indexing_status'` | text | GSC | Filter by index status |
| `metadata->'non_index_reason'` | text | GSC | Filter by exclusion reason |
| `metadata->'impressions'` | int | GSC | Sort/filter by traffic |
| `metadata->'clicks'` | int | GSC | Sort/filter by clicks |
| `metadata->'ctr'` | float | GSC | Sort/filter by CTR |
| `metadata->'position'` | float | GSC | Sort/filter by position |
| `metadata->'cluster_label'` | text | GSC | Group by content cluster |
## Expected Scale
| Metric | Estimate |
|--------|----------|
| Rows per page | 1 per enabled source (typically 1–3) |
| Rows per domain | 100K–1.5M (pages x sources) |
| Growth rate | Grows with page discovery, updated on each sync |
| Write pattern | Upsert on `(pageId, sourceId)` during sync |
| Read pattern | Joins with Page for API queries, materialized views for aggregation |
## Notes
- This is the **highest volume table** in the system
- JSONB `metadata` column is the single source of truth for all source-specific data (D006)
- Optimization happens via materialized views (D007), not by adding typed columns
- Every query **must** include `tenantId`
---
id: Project
name: Project
version: 1.0.0
identifier: id
aggregateRoot: true
summary: Top-level tenant-scoped container representing a web property being monitored for SEO visibility.
properties:
- name: id
type: UUID
required: true
description: Primary key, auto-generated
- name: tenantId
type: UUID
required: true
description: Multi-tenant isolation key — every query MUST include this in WHERE clause
- name: name
type: string
required: true
description: Human-readable project name (max 255 chars)
- name: createdAt
type: DateTime
required: true
description: Auto-generated creation timestamp
- name: updatedAt
type: DateTime
required: true
description: Auto-generated last update timestamp
- name: domains
type: array
items:
type: Domain
required: false
description: Web domains belonging to this project
references: Domain
referencesIdentifier: projectId
relationType: hasMany
badges:
- content: TypeORM
backgroundColor: blue
textColor: blue
- content: Aggregate Root
backgroundColor: purple
textColor: purple
---
## Overview
Project is the aggregate root of the Visibility domain. Each project represents a web property (e.g., "Prerender Marketing Site") being monitored for SEO visibility. All data access flows through Project — it is the entry point for tenant-isolated queries.
## Table: `projects`
| Column | Type | Constraints |
|--------|------|------------|
| `id` | `uuid` | PK, auto-generated |
| `tenant_id` | `uuid` | NOT NULL |
| `name` | `varchar(255)` | NOT NULL |
| `created_at` | `timestamp` | NOT NULL, default now() |
| `updated_at` | `timestamp` | NOT NULL, default now(), auto-update |
## Relationships
- **has many Domains** — a project owns one or more web domains. Cascading: deleting a project removes all downstream data.
## Multi-Tenant Isolation
Every repository query on Project (and all child entities) **must** include `tenantId` in the WHERE clause:
```typescript
{ where: { id: projectId, tenantId } }
```
This is a critical security requirement — missing `tenantId` exposes cross-tenant data.
## Expected Scale
| Metric | Estimate |
|--------|----------|
| Rows per tenant | 1–10 |
| Growth rate | Near-static (manual creation) |
| Query pattern | Lookup by `(id, tenantId)` |
---
id: Projection
name: Connector Projection
version: 1.0.0
identifier: pageId
summary: "Connector-declared per-day history table (CEN-326, D059): one row per (tenant, page, source, day) of one action, folded from history by the promote. One table per declaration, named proj___v; the columns after the core ones come from the declaration."
properties:
- name: tenantId
type: UUID
required: true
description: Multi-tenant isolation key; first column of the primary key (`tenant_id`)
- name: pageId
type: UUID
required: true
description: "Foreign key to Page (`page_id`), ON DELETE CASCADE"
references: Page
referencesIdentifier: id
relationType: hasOne
- name: sourceId
type: UUID
required: true
description: Foreign key to Source (`source_id`)
references: Source
referencesIdentifier: id
relationType: hasOne
- name: projectId
type: UUID
required: true
description: Project of the page (`project_id`)
- name: day
type: Date
required: true
description: "The declaration's `day.from` (metrics or payload key), optionally falling back to ingestDate"
- name: rowId
type: bigint
required: true
description: Highest history row id folded into the day (`row_id`)
- name: fetchedAt
type: DateTime
required: false
description: Freshest fetchedAt of the winning run's rows
- name: winOp
type: UUID
required: false
description: Operation of the run that owns the day
- name: winCompleted
type: boolean
required: true
description: Whether that run's job COMPLETED; first element of the winner tuple
- name: winAt
type: DateTime
required: true
description: "max(COALESCE(fetchedAt, ingestDate)) of the winning run's rows"
- name: winId
type: bigint
required: true
description: Id of the winning run's freshest row; tie-break
badges:
- content: Connector-declared
backgroundColor: purple
textColor: purple
- content: History outbox
backgroundColor: orange
textColor: orange
---
## Overview
Connectors declare per-day projections in `schemaContribution.projections` (SDK
`ProjectionDeclaration`); core never names one. On registration (and on boot) the
`ProjectionRegistry` records them and the `ProjectionReconciler` creates each table
(`CREATE TABLE IF NOT EXISTS`, per-table advisory lock, 5 s lock timeout). The promote folds every
terminal job of the declared action into the tables of its source's type, in the same transaction
as `page_visibility_current`. Spec: `docs/specs/CEN-326-connector-projections.md`.
Replaces the hard-wired `gsc_search_metrics_daily` and `prerender_crawl_stats_daily` (CEN-321),
dropped by migration `DropHardWiredOutboxDailyTables1720483200000`.
Today's declarations: `proj_gsc_search_daily_v1` (GSC `search_analytics`) and
`proj_prerender_crawl_daily_v1` (Prerender `crawl_stats`).
## Table: `proj___v`
| Column | Type | Constraints |
| --------------- | ------------- | --------------------------- |
| `tenant_id` | `uuid` | PK (first) |
| `page_id` | `uuid` | PK, FK → `pages.id` cascade |
| `source_id` | `uuid` | PK |
| `project_id` | `uuid` | NOT NULL |
| `day` | `date` | PK |
| `row_id` | `bigint` | NOT NULL |
| `fetched_at` | `timestamptz` | |
| `win_op` | `uuid` | |
| `win_completed` | `boolean` | NOT NULL, default false |
| `win_at` | `timestamptz` | NOT NULL |
| `win_id` | `bigint` | NOT NULL |
| declared … | per `type` | `__w`, `__n` per `weightedAvg` |
Indexes: primary key `(tenant_id, page_id, source_id, day)`; `(page_id)` for the cascade.
`fillfactor = 90`.
---
id: Source
name: Source
version: 1.0.0
identifier: id
summary: A configured data source (GSC, Bing, GA4, Cloudflare, Prerender) with capabilities, enabled state, and connection configuration.
properties:
- name: id
type: UUID
required: true
description: Primary key, auto-generated
- name: tenantId
type: UUID
required: true
description: Multi-tenant isolation key
- name: type
type: string
required: true
description: Source type enum
enum: ['GSC', 'BING', 'GA4', 'CLOUDFLARE', 'PRERENDER']
- name: name
type: string
required: true
description: Human-readable display name (max 255 chars)
- name: capabilities
type: JSON
required: false
description: "Feature support flags — determines which pipelines activate for this source"
- name: isEnabled
type: boolean
required: true
description: Whether this source is active (default true)
- name: status
type: string
required: true
description: "Connection lifecycle status"
enum: ['PENDING', 'ACTIVE', 'ERROR', 'DISCONNECTED']
- name: propertyUrl
type: string
required: false
description: "GSC property URL (e.g., sc-domain:example.com). Set during OAuth activation."
- name: statusMessage
type: string
required: false
description: Error details when status is ERROR
- name: connectedAt
type: DateTime
required: false
description: When OAuth was completed and source activated
- name: encryptedCredentials
type: string
required: false
description: "AES-256-GCM encrypted OAuth tokens (D011). Format: iv:authTag:ciphertext (base64)"
- name: createdAt
type: DateTime
required: true
description: Auto-generated creation timestamp
- name: visibilityStates
type: array
items:
type: PageVisibilityState
required: false
description: Visibility records from this source
references: PageVisibilityState
referencesIdentifier: sourceId
relationType: hasMany
- name: syncJobs
type: array
items:
type: SyncJob
required: false
description: Synchronization jobs for this source
references: SyncJob
referencesIdentifier: sourceId
relationType: hasMany
badges:
- content: TypeORM
backgroundColor: blue
textColor: blue
- content: Immutable
backgroundColor: orange
textColor: orange
---
## Overview
Source represents a configured data source (e.g. Google Search Console) with declared capabilities and an enabled state. Each source type provides different signals about page visibility and drives different sync pipelines.
## Table: `sources`
| Column | Type | Constraints |
|--------|------|------------|
| `id` | `uuid` | PK, auto-generated |
| `tenant_id` | `uuid` | NOT NULL |
| `type` | `varchar(50)` | NOT NULL, enum |
| `name` | `varchar(255)` | NOT NULL |
| `capabilities` | `jsonb` | NULLABLE |
| `is_enabled` | `boolean` | NOT NULL, default true |
| `status` | `varchar(20)` | NOT NULL, default `'PENDING'` |
| `property_url` | `varchar(500)` | NULLABLE |
| `status_message` | `text` | NULLABLE |
| `connected_at` | `timestamp` | NULLABLE |
| `encrypted_credentials` | `text` | NULLABLE |
| `created_at` | `timestamp` | NOT NULL, default now() |
## Connection Status Machine
```
PENDING → (OAuth activate) → ACTIVE
ACTIVE → (disconnect) → DISCONNECTED
ACTIVE → (token revoked / error) → ERROR
ERROR → (re-connect) → PENDING → ...
```
Managed by `GscOAuthService`. See [GscOAuthService](/docs/services/GscOAuthService) for the full flow.
## Relationships
- **has many PageVisibilityStates** — produces visibility records for pages
- **has many SyncJobs** — owns synchronization job history
## JSONB Schema: `capabilities`
```typescript
type SourceCapabilities = {
supportsIndexStatus: boolean; // Can report whether URLs are indexed
supportsCrawlData: boolean; // Can report crawl metadata (status, frequency)
supportsTrafficData: boolean; // Can report search traffic metrics
supportsHistoricalData: boolean; // Can backfill historical data
dataRetentionDays: number; // How far back data is available (e.g., 480 for GSC)
};
```
## Source Types and Their Capabilities
| Source | Index Status | Crawl Data | Traffic Data | Historical | Retention |
|--------|:-----------:|:----------:|:------------:|:----------:|:---------:|
| **GSC** | Yes | Yes | No | Yes | 480 days |
| **BING** | Yes | No | No | No | — |
| **GA4** | No | No | Yes | Yes | — |
| **CLOUDFLARE** | No | No | No | No | — |
| **PRERENDER** | Yes | Yes | No | No | — |
## Connection & Authentication (CEN-27 — Pending)
OAuth credentials and connection configuration will be stored in a separate encrypted column (or external secrets manager). Not yet implemented:
| Source | Auth Method | Status |
|--------|------------|--------|
| GSC | OAuth2 (Google API) | CEN-27 (TODO) |
| BING | API Key | Future |
| GA4 | OAuth2 (Google API) | Future |
## Expected Scale
| Metric | Estimate |
|--------|----------|
| Rows per tenant | 1–5 |
| Growth rate | Near-static |
| Query pattern | By `(tenantId, isEnabled)`, by `(id, tenantId)` |
## Notes
- **Immutable** — no `updatedAt` column. Changes require creating a new source.
- Capabilities enable runtime feature detection — determines which sync actions to run.
---
id: SyncJob
name: Sync Job
version: 1.0.0
identifier: id
summary: Tracks data synchronization jobs per source. Records job lifecycle with timing and error metadata.
properties:
- name: id
type: UUID
required: true
description: Primary key, auto-generated
- name: sourceId
type: UUID
required: true
description: Foreign key to Source
references: Source
referencesIdentifier: id
relationType: hasOne
- name: tenantId
type: UUID
required: true
description: Multi-tenant isolation key
- name: action
type: string
required: true
description: "The connector action being synced (e.g., 'indexation', 'search_analytics')"
- name: jobType
type: string
required: true
description: "Job trigger type: 'manual', 'scheduled', or 'retry'"
- name: status
type: string
required: true
description: Job lifecycle status
enum: ['PENDING', 'RUNNING', 'COMPLETED', 'FAILED']
- name: checkpoint
type: JSON
required: false
description: Opaque checkpoint for incremental sync — stores connector-specific cursor/offset
- name: recordsProcessed
type: integer
required: true
description: Count of records processed so far (updated during fetch loop)
- name: startedAt
type: DateTime
required: false
description: When the job started running
- name: completedAt
type: DateTime
required: false
description: When the job finished (success or failure)
- name: error
type: string
required: false
description: Error message if the job failed
- name: metadata
type: JSON
required: false
description: |
Per-action observability aggregates written by SyncJobAggregator on COMPLETED (CEN-59). Shape varies by action — indexation { indexed, notIndexed, excluded, unknown, pagesProcessed }; search_analytics { totalClicks, totalImpressions, avgCtr, avgPosition, pagesProcessed }; rendering { rendered, failed, pagesProcessed }; other { pagesProcessed }. FAILED jobs carry { pagesProcessed: }.
- name: createdAt
type: DateTime
required: true
description: Auto-generated creation timestamp
badges:
- content: TypeORM
backgroundColor: blue
textColor: blue
---
## Overview
SyncJob tracks the lifecycle of a data synchronization run for a given source. Each job records timing, status transitions, and outcome metadata, providing an audit trail and operational visibility into the ingestion pipeline.
## Table
`sync_jobs`
## Relationships
- **belongs to Source** — every sync job is scoped to exactly one source via `sourceId`.
## State Machine
```
PENDING → RUNNING → COMPLETED
→ FAILED
```
Transitions enforced by `SyncJobRepository` — invalid transitions return `SyncJobTransitionFailure`.
## Concurrency
`SyncJobRepository.createExclusive()` uses `SELECT ... FOR UPDATE` to prevent concurrent runs for the same `(sourceId, action)`. Only one PENDING/RUNNING job per (source, action) at a time.
## Chunks and the persist fence
A chunked sync job runs as rows of `sync_job_chunks`. A worker claims a chunk by bumping its `attempt`; every later write is fenced on that attempt. `persistedAttempt` (nullable integer, CEN-320) is the attempt whose rows reached `page_visibility_states`. With `CHUNK_PERSIST_FENCE_ENABLED` the chunk's rows and `UPDATE sync_job_chunks SET "persistedAttempt" = attempt WHERE id, "tenantId", attempt, status = 'RUNNING'` commit in one transaction; a stale worker or a replay of a persisted chunk commits nothing.
## Checkpoint Pattern
The `checkpoint` column is an opaque JSONB value that connectors use to store pagination cursors, offsets, or timestamps for incremental sync. `SyncJobTracker.getLastCheckpoint()` retrieves the most recent checkpoint from the last completed job.
## Notes
- Immutable record — there is no `updatedAt` column. Job status is tracked via dedicated timestamp fields (`startedAt`, `completedAt`).
- The `status` enum represents a one-way state machine — jobs never revert to a prior status.
- `recordsProcessed` is updated mid-run during the fetch loop, providing live progress tracking.
---
id: "ConnectorRegistrationCascade"
name: "Connector Registration Cascade"
version: "1.0.0"
summary: "How authenticated worker registration cascades through ConnectorRegistryService to populate SchemaDictionaryService and ViewRegistryService."
steps:
- id: "worker_registers"
title: "Worker Sends Registration"
summary: "A connector worker POSTs /visibility/connectors/register with x-prerender-connector-registration-secret plus workerName, workerURL, capabilities, supportedActions, and full schemaContribution."
service:
id: "WorkerRegistrationService"
version: "1.0.0"
next_step:
id: "api_receives"
label: "POST /visibility/connectors/register"
- id: "api_receives"
title: "Visibility API Receives"
summary: "ConnectorController verifies the shared registration secret, validates the payload with Zod schemas, then delegates ConnectorRegistryService.register()."
service:
id: "VisibilityAPI"
version: "1.0.0"
next_step:
id: "registry_stores"
label: "Delegate registry"
- id: "registry_stores"
title: "ConnectorRegistry Stores Worker"
summary: "Persists ConnectorRegistration in connector_registrations and refreshes the hot in-memory Map keyed by workerName."
service:
id: "ConnectorRegistryService"
version: "1.0.0"
next_steps:
- id: "cascade_schema"
label: "Cascade field metadata"
- id: "cascade_views"
label: "Cascade view definitions"
- id: "cascade_schema"
title: "Populate Schema Dictionary"
summary: "Calls SchemaDictionaryService.registerSource() with connector field metadata. Fields become discoverable by schema endpoints."
service:
id: "SchemaDictionaryService"
version: "1.0.0"
next_step:
id: "complete"
label: "Schema registered"
- id: "cascade_views"
title: "Register Materialized Views"
summary: "Calls ViewRegistryService.registerSourceViews() with connector materialized view definitions. Views become queryable through QueryRouterService.resolve()."
service:
id: "ViewRegistryService"
version: "1.0.0"
next_step:
id: "complete"
label: "Views registered"
- id: "complete"
title: "Connector Fully Registered"
summary: "Worker is stored in registry, fields are discoverable, views are queryable, and sync jobs can route to the worker."
custom:
title: "Registration Complete"
type: "success"
summary: "Source type is fully discoverable — fields, views, worker routing all active"
---
## Connector Registration Cascade
This flow documents what happens after an authenticated connector worker registers with Visibility API.
A single `POST /visibility/connectors/register` triggers worker routing, field discovery, and view registration.
## Why Cascade?
Before Phase 3, field metadata and materialized views were hardcoded in the visibility package.
The cascade pattern (D014 + D015) makes connector rollout zero-code-change for API feature code: deploy a worker, let it register, then API knows its capabilities, fields, and views.
```mermaid
sequenceDiagram
participant Worker as Connector Worker
participant API as Visibility API
participant Registry as ConnectorRegistryService
participant Schema as SchemaDictionaryService
participant Views as ViewRegistryService
Worker->>API: POST /visibility/connectors/register + secret header
API->>Registry: register(params)
Registry->>Registry: persist row + refresh Map
Registry->>Schema: registerSource(sourceType, fields)
Registry->>Views: registerSourceViews(sourceType, viewDefs)
API-->>Worker: { registered: true }
```
## Security Boundary
Registration integrity is protected by `CONNECTOR_REGISTRATION_SECRET`.
The registry is durable, but it is not the only SSRF boundary.
`RemoteConnectorDispatcher` also blocks dispatch unless the stored `workerURL` host is the single-label in-cluster service name equal to `workerName`.
The remaining defense-in-depth item is Kubernetes NetworkPolicy egress allow-listing for the API pod.
---
id: "DailySyncCycle"
name: "Daily Sync Cycle"
version: "1.0.0"
summary: "How the automated daily sync orchestrates across all active sources — from trigger through search analytics import, URL inspection, to materialized view refresh."
steps:
- id: "trigger"
title: "Trigger Daily Sync"
summary: "Cron schedule (02:00 UTC) via Trigger.dev, or manual POST /visibility/sync/daily"
actor:
name: "Scheduler / Operator"
next_step:
id: "orchestrator"
label: "Start daily cycle"
- id: "orchestrator"
title: "Multi-Source Orchestrator"
summary: "Discovers all registered sources via ConnectorRegistryService, builds the SyncDAG, runs each stage. Per-source views refresh after each stage; cross-source views refresh after all stages complete."
service:
id: "MultiSourceOrchestrator"
version: "1.0.0"
next_step:
id: "find_sources"
label: "Query active sources"
- id: "find_sources"
title: "Find Active Sources"
summary: "SELECT * FROM sources WHERE status='ACTIVE' AND is_enabled=true AND tenant_id=:tenantId"
custom:
title: "Find Active Sources"
type: "database"
summary: "PostgreSQL — sources table"
next_step:
id: "per_source"
label: "For each active source"
- id: "per_source"
title: "Per-Source Sync Cycle"
summary: "For each source: run search_analytics → indexation → refresh views. Error isolation: one action failing doesn't block others."
service:
id: "SyncJobRunner"
version: "1.0.0"
next_steps:
- id: "search_analytics"
label: "1. Search Analytics"
- id: "indexation"
label: "2. Indexation"
- id: "search_analytics"
title: "Sync Search Analytics"
summary: "Fetch clicks, impressions, CTR, position for all URLs. Discovers new URLs. 25K rows/batch with pagination."
service:
id: "GscConnector"
version: "1.0.0"
next_steps:
- id: "page_discovery"
label: "New URLs found"
- id: "indexation"
label: "Complete → run indexation"
- id: "sa_failed"
label: "Failed (doesn't block indexation)"
- id: "page_discovery"
title: "Page Discovery"
summary: "Find-or-create PageEntity for new URLs. Match by LOWER(url), create with section from URLNormalizerService."
service:
id: "PageDiscoveryService"
version: "1.0.0"
next_step:
id: "indexation"
label: "Pages ready for inspection"
- id: "sa_failed"
title: "Search Analytics Failed"
summary: "Job marked FAILED. Error logged. Indexation still runs independently."
custom:
title: "Search Analytics Failed"
type: "error"
summary: "Error isolated — other actions continue"
- id: "indexation"
title: "Sync Indexation"
summary: "Inspect URLs via GSC URL Inspection API. Sequential, one URL at a time. Checkpoint per URL for resume."
service:
id: "GscConnector"
version: "1.0.0"
next_steps:
- id: "quota_check"
label: "Check quota budget"
- id: "refresh_views"
label: "Complete → refresh views"
- id: "quota_check"
title: "Quota Check"
summary: "QuotaTrackerService tracks daily usage per (source, action). Indexation limit: 2,000/day. Alert at 90%."
service:
id: "QuotaTrackerService"
version: "1.0.0"
next_step:
id: "refresh_views"
label: "Budget exhausted or all URLs inspected"
- id: "refresh_views"
title: "Refresh Materialized Views"
summary: "REFRESH MATERIALIZED VIEW CONCURRENTLY for both indexation and search metrics views. Non-blocking reads."
service:
id: "ViewRefreshService"
version: "1.0.0"
next_step:
id: "cycle_complete"
label: "Views updated"
- id: "cycle_complete"
title: "Cycle Complete"
summary: "Per-source results returned: search_analytics success/fail, indexation success/fail, viewsRefreshed. Freshness metadata updated."
actor:
name: "Scheduler / Operator"
---
## Daily Sync Cycle
This flow documents the full automated daily sync — the main operational loop of the Visibility platform. Runs once per day per tenant, processing all active sources.
## Cycle Order (per source)
```
1. search_analytics sync (F.1)
→ Fetches clicks/impressions/CTR/position
→ Discovers new URLs via PageDiscoveryService
→ Writes action='search_analytics' to JSONB
2. indexation sync (F.2)
→ Inspects URLs sequentially via GSC API
→ Quota: 2,000 inspections/day/property
→ Writes action='indexation' to JSONB
3. Refresh materialized views (F.8a + F.8b)
→ cur_indexation_summary (cur_indexation is a plain VIEW, live)
→ day_search_analytics
→ CONCURRENT refresh (no read blocking)
```
## Error Isolation
| Scenario | Behavior |
|----------|----------|
| search_analytics fails | indexation still runs |
| indexation fails | views still refresh (with existing data) |
| View refresh fails | Non-fatal — data in base table, views refresh next cycle |
| OAuth token expired | Source transitions to ERROR, skipped next cycle |
## Trigger Options
| Method | How |
|--------|-----|
| **Trigger.dev cron** | Scheduled task at 02:00 UTC daily |
| **Manual HTTP** | `POST /visibility/sync/daily` with `x-tenant-id` header |
| **Per-source manual** | `POST /visibility/sources/:id/sync` with optional `?action=` |
---
id: "OAuthConnection"
name: "GSC OAuth Connection Flow"
version: "1.0.0"
summary: "How a customer connects their Google Search Console property — from OAuth consent through token exchange, property selection, and source activation."
steps:
- id: "user_initiate"
title: "Customer Initiates Connection"
summary: "Customer clicks 'Connect GSC' in the UI"
actor:
name: "Customer"
next_step:
id: "authorize_endpoint"
label: "GET /oauth/gsc/authorize?source_id=X"
- id: "authorize_endpoint"
title: "OAuth Controller"
summary: "Validates source is PENDING, generates HMAC-signed state, returns Google consent URL"
service:
id: "GscOAuthService"
version: "1.0.0"
next_step:
id: "google_consent"
label: "Redirect to Google"
- id: "google_consent"
title: "Google OAuth Consent"
summary: "Customer grants read-only access to their GSC data"
externalSystem:
name: "Google OAuth2"
summary: "Google's authorization server — consent screen + code grant"
url: "https://accounts.google.com"
next_step:
id: "callback_endpoint"
label: "Redirect with authorization code"
- id: "callback_endpoint"
title: "Handle Callback"
summary: "Verify HMAC state, exchange code for tokens, encrypt and store, list available properties"
service:
id: "GscOAuthService"
version: "1.0.0"
next_steps:
- id: "store_tokens"
label: "Encrypt + store tokens"
- id: "list_properties"
label: "List GSC properties"
- id: "store_tokens"
title: "Encrypt & Store Credentials"
summary: "AES-256-GCM encrypt tokens, store in SourceEntity.encryptedCredentials (D011)"
custom:
title: "Encrypt & Store Credentials"
type: "database"
summary: "PostgreSQL — sources.encrypted_credentials"
next_step:
id: "list_properties"
label: "Tokens secured"
- id: "list_properties"
title: "List GSC Properties"
summary: "Call GSC API to discover available properties for the authenticated Google account"
externalSystem:
name: "Google Search Console API"
summary: "searchconsole.sites.list() — returns properties the user has access to"
url: "https://developers.google.com/webmaster-tools"
next_step:
id: "user_selects"
label: "Return property list to customer"
- id: "user_selects"
title: "Customer Selects Property"
summary: "Customer picks which GSC property to connect (e.g., sc-domain:example.com)"
actor:
name: "Customer"
next_step:
id: "activate_endpoint"
label: "POST /oauth/gsc/activate { sourceId, propertyUrl }"
- id: "activate_endpoint"
title: "Activate Source"
summary: "Test API access to selected property, set status=ACTIVE, store capabilities"
service:
id: "GscOAuthService"
version: "1.0.0"
next_steps:
- id: "test_access"
label: "Verify property access"
- id: "activation_failed"
label: "Access denied"
- id: "test_access"
title: "Test GSC API Access"
summary: "Verify the OAuth tokens have access to the selected property"
externalSystem:
name: "Google Search Console API"
summary: "searchconsole.sites.get() — verify property access"
url: "https://developers.google.com/webmaster-tools"
next_step:
id: "source_active"
label: "Access confirmed"
- id: "activation_failed"
title: "Activation Failed"
summary: "Source set to ERROR with descriptive message. Customer can retry."
custom:
title: "Activation Failed"
type: "error"
summary: "HTTP 403 — PROPERTY_ACCESS_DENIED"
- id: "source_active"
title: "Source ACTIVE"
summary: "Source status=ACTIVE, propertyUrl stored, capabilities set from GSC config, connectedAt timestamped"
custom:
title: "Source ACTIVE"
type: "database"
summary: "PostgreSQL — sources table updated"
---
## GSC OAuth Connection Flow
This flow documents how a customer connects their Google Search Console property to the Visibility platform. It covers the full OAuth2 authorization code grant flow with encrypted credential storage.
## Security
| Concern | Mitigation |
|---------|-----------|
| OAuth CSRF | HMAC-signed state parameter (SHA-256) |
| Token at rest | AES-256-GCM encryption in database (D011) |
| Token in transit | HTTPS only (Google requirement) |
| Scope | `webmasters.readonly` — minimum privilege |
| Multi-tenant | `tenantId` checked at every step |
## Mock Mode
When `GSC_OAUTH_MOCK=true`, the entire flow uses mock adapters:
- Authorization URL redirects straight to callback with `code=mock-auth-code`
- Token exchange returns deterministic fake tokens
- Property list returns `[{ siteUrl: 'sc-domain:example.com' }]`
- Access test always succeeds
Enables full end-to-end testing without Google credentials.
---
id: "OverviewDashboard"
name: "Overview Dashboard Query"
version: "1.0.0"
summary: "How the visibility overview endpoint aggregates indexation data — 4 parallel queries from JSONB, section breakdown, coverage calculation."
steps:
- id: "user"
title: "User / Dashboard"
summary: "Requests visibility overview for a project"
actor:
name: "User"
next_step:
id: "api"
label: "GET /visibility/overview?project_id=..."
- id: "api"
title: "Visibility API"
summary: "Validates params via ZodValidationPipe, extracts tenantId from x-tenant-id header"
service:
id: "VisibilityAPI"
version: "1.0.0"
next_step:
id: "overview_service"
label: "Delegate to OverviewService"
- id: "overview_service"
title: "Overview Service"
summary: "Verify project, then fire 4 independent queries in parallel via Promise.all()"
service:
id: "OverviewService"
version: "1.0.0"
next_steps:
- id: "verify_project"
label: "1. Verify project"
- id: "parallel_queries"
label: "2. Promise.all(4 queries)"
- id: "verify_project"
title: "Verify Project"
summary: "Lookup by (project_id, tenantId) — multi-tenant security gate"
custom:
title: "Verify Project"
type: "database"
summary: "PostgreSQL — projects table"
next_steps:
- id: "project_not_found"
label: "Not found → 404"
- id: "parallel_queries"
label: "Found → parallel queries"
- id: "project_not_found"
title: "Project Not Found"
summary: "Returns 404 ProjectNotFoundFailure"
custom:
title: "Project Not Found"
type: "error"
summary: "HTTP 404 — PROJECT_NOT_FOUND"
- id: "parallel_queries"
title: "4 Parallel Queries"
summary: "Promise.all() fires simultaneously: domain lookup, total URL count, visibility aggregation (JSONB), section breakdown (JSONB)"
custom:
title: "4 Parallel Queries"
type: "database"
summary: "PostgreSQL — 4 concurrent queries"
next_steps:
- id: "jsonb_aggregation"
label: "Visibility aggregation"
- id: "section_breakdown"
label: "Section breakdown"
- id: "jsonb_aggregation"
title: "JSONB Visibility Aggregation"
summary: "SUM(CASE WHEN rawSourcePayload->>'indexing_status' = 'INDEXED' ...) — counts INDEXED, NOT_INDEXED, EXCLUDED, UNKNOWN from action='indexation' rows"
custom:
title: "JSONB Visibility Aggregation"
type: "database"
summary: "PostgreSQL — page_visibility_states WHERE action='indexation'"
next_step:
id: "calculate"
label: "Aggregation counts"
- id: "section_breakdown"
title: "Section Breakdown"
summary: "GROUP BY page.section with JSONB indexing_status counts — max 20 sections, ordered by total descending"
custom:
title: "Section Breakdown"
type: "database"
summary: "PostgreSQL — JOIN pages, GROUP BY section"
next_step:
id: "calculate"
label: "Per-section totals"
- id: "calculate"
title: "Calculate Totals + Percentages"
summary: "Compute indexed_percent, coverage from source count. All in-memory — no additional queries."
service:
id: "CoverageService"
version: "1.0.0"
next_step:
id: "response"
label: "Build response"
- id: "response"
title: "API Response"
summary: "200 OK — domain, totals, percentages, by_section (max 20), coverage"
actor:
name: "User"
---
## Overview Dashboard Query
This flow documents how the Overview endpoint aggregates visibility data from the D006 JSONB schema. After CEN-30, this queries real data — no more mock/seed.
## Query Pattern (D006 → interim JSONB, OP-020)
The aggregation queries use JSONB path operators directly on `rawSourcePayload`:
```sql
-- Visibility aggregation (one of 4 parallel queries)
SELECT
SUM(CASE WHEN rawSourcePayload->>'indexing_status' = 'INDEXED' THEN 1 ELSE 0 END) AS indexed,
SUM(CASE WHEN rawSourcePayload->>'indexing_status' = 'NOT_INDEXED' THEN 1 ELSE 0 END) AS not_indexed,
SUM(CASE WHEN rawSourcePayload->>'indexing_status' = 'EXCLUDED' THEN 1 ELSE 0 END) AS excluded,
SUM(CASE WHEN rawSourcePayload->>'indexing_status' = 'UNKNOWN' THEN 1 ELSE 0 END) AS unknown
FROM page_visibility_states
WHERE action = 'indexation' AND tenant_id = :tenantId
```
**Performance note (OP-020):** These are direct JSONB queries — acceptable for dev volumes. F.8a (materialized views) will replace with pre-computed view-backed queries for production.
## Improvements Made in CEN-30
| Before (Phase 1) | After (CEN-30) |
|-------------------|-----------------|
| 6 sequential queries | 4 parallel via `Promise.all()` |
| `isIndexed = true` boolean | `rawSourcePayload->>'indexing_status' = 'INDEXED'` |
| `LIKE '%excluded%'` (full table scan) | Direct enum: `= 'EXCLUDED'` |
| `lastSeenAt` for date filtering | `fetchedAt` |
| Mock/seed data only | Real GSC data after import |
---
id: "SchemaDiscovery"
name: "Schema Discovery"
version: "1.0.0"
summary: "How the frontend discovers available source types, actions, and field metadata — the API surface that makes JSONB payloads self-describing without hardcoded schemas."
steps:
- id: "frontend_requests"
title: "Frontend Requests Sources"
summary: "The dashboard calls GET /visibility/schema/sources to discover which source types have registered connectors."
actor:
name: "Frontend"
next_step:
id: "api_sources"
label: "GET /visibility/schema/sources"
- id: "api_sources"
title: "List Source Types"
summary: "SchemaController delegates to SchemaDictionaryService.getSources(). Returns an array of registered source types (e.g., GSC, PRERENDER) with their action counts."
service:
id: "SchemaDictionaryService"
version: "1.0.0"
next_step:
id: "frontend_picks_source"
label: "Return source list"
- id: "frontend_picks_source"
title: "Frontend Picks Source"
summary: "User selects a source type (e.g., GSC). Frontend calls GET /visibility/schema/sources/:sourceType/actions to discover available actions."
actor:
name: "Frontend"
next_step:
id: "api_actions"
label: "GET /visibility/schema/sources/GSC/actions"
- id: "api_actions"
title: "List Actions"
summary: "Returns available actions for the source type (e.g., indexation, search_analytics) with field counts per action."
service:
id: "SchemaDictionaryService"
version: "1.0.0"
next_step:
id: "frontend_picks_action"
label: "Return action list"
- id: "frontend_picks_action"
title: "Frontend Picks Action"
summary: "User selects an action (e.g., indexation). Frontend calls GET /visibility/schema/sources/:sourceType/actions/:action/fields to get the full field metadata."
actor:
name: "Frontend"
next_step:
id: "api_fields"
label: "GET /visibility/schema/sources/GSC/actions/indexation/fields"
- id: "api_fields"
title: "Return Field Metadata"
summary: "Returns field definitions: path, type, label, description, filterable, sortable flags. Frontend uses these to dynamically render table columns, filter dropdowns, and sort controls."
service:
id: "SchemaDictionaryService"
version: "1.0.0"
next_step:
id: "frontend_renders"
label: "Field list with metadata"
- id: "frontend_renders"
title: "Frontend Renders Dynamic UI"
summary: "Dashboard renders table columns, filter dropdowns, and sort controls based on field metadata. No hardcoded schema knowledge needed — adding a connector automatically adds its fields to the UI."
custom:
title: "Dynamic UI"
type: "success"
summary: "Columns, filters, and sorts rendered from live field metadata"
---
## Schema Discovery
This flow documents how the frontend discovers the shape of data in the system — without any hardcoded schema knowledge. The `/visibility/schema/` endpoints expose field metadata that connectors registered at startup via the [Connector Registration Cascade](/docs/flows/ConnectorRegistrationCascade).
## Architecture Context (D014)
The Schema Dictionary (Decision D014) solves the challenge of dynamic JSONB payloads. Each connector stores different fields in `PageVisibilityState.rawSourcePayload`, and the frontend needs to know what columns are available for display, filtering, and sorting.
Instead of hardcoding a schema per connector, connectors **declare their fields at registration time**. The `SchemaDictionaryService` aggregates these declarations and exposes them via REST.
```mermaid
sequenceDiagram
participant FE as Frontend
participant API as Visibility API
participant Schema as SchemaDictionaryService
FE->>API: GET /visibility/schema/sources
API->>Schema: getSources()
Schema-->>API: [GSC, PRERENDER]
API-->>FE: sources with action counts
FE->>API: GET /visibility/schema/sources/GSC/actions
API->>Schema: getActions('GSC')
Schema-->>API: [indexation (2 fields), search_analytics (4 fields)]
API-->>FE: actions with field counts
FE->>API: GET /visibility/schema/sources/GSC/actions/indexation/fields
API->>Schema: getFields('GSC', 'indexation')
Schema-->>API: [indexing_status, non_index_reason]
API-->>FE: field metadata (path, type, label, filterable, sortable)
```
## Example Response
```json
{
"fields": [
{
"path": "indexing_status",
"type": "text",
"label": "Indexing Status",
"description": "Google indexation verdict: INDEXED, NOT_INDEXED, or EXCLUDED",
"filterable": true,
"sortable": true
},
{
"path": "non_index_reason",
"type": "text",
"label": "Non-Index Reason",
"description": "Reason a URL is not indexed (e.g., noindex, redirect, crawl anomaly)",
"filterable": true,
"sortable": false
}
]
}
```
---
id: "SourceManagement"
name: "Source Management Lifecycle"
version: "1.0.0"
summary: "How sources are managed through their full lifecycle — from OAuth connection through monitoring, manual sync, and disconnection."
steps:
- id: "list_sources"
title: "List Sources"
summary: "GET /visibility/sources — view all sources with status, supported actions, last sync"
service:
id: "SourceManagementService"
version: "1.0.0"
next_steps:
- id: "connect_new"
label: "No sources → connect"
- id: "view_detail"
label: "Select source"
- id: "connect_new"
title: "Connect GSC Property"
summary: "OAuth flow: authorize → Google consent → callback → select property → activate"
service:
id: "GscOAuthService"
version: "1.0.0"
next_step:
id: "source_active"
label: "Source now ACTIVE"
- id: "source_active"
title: "Source ACTIVE"
summary: "Source connected with encrypted credentials, propertyUrl set, capabilities configured from GSC config"
custom:
title: "Source ACTIVE"
type: "database"
summary: "PostgreSQL — sources.status = 'ACTIVE'"
next_steps:
- id: "view_detail"
label: "Monitor source"
- id: "trigger_sync"
label: "Trigger sync"
- id: "disconnect"
label: "Disconnect"
- id: "view_detail"
title: "View Source Detail"
summary: "GET /visibility/sources/:id — capabilities, supported actions, recent jobs, last sync timestamp"
service:
id: "SourceManagementService"
version: "1.0.0"
next_steps:
- id: "view_jobs"
label: "View job history"
- id: "trigger_sync"
label: "Trigger sync"
- id: "disconnect"
label: "Disconnect"
- id: "view_jobs"
title: "View Job History"
summary: "GET /visibility/sources/:id/jobs?action=indexation — filterable by action, ordered by date"
service:
id: "SourceManagementService"
version: "1.0.0"
next_step:
id: "view_detail"
label: "Back to detail"
- id: "trigger_sync"
title: "Trigger Manual Sync"
summary: "POST /visibility/sources/:id/sync?action=indexation — runs sync for specific action or all actions"
service:
id: "SyncJobRunner"
version: "1.0.0"
next_steps:
- id: "sync_running"
label: "Job created"
- id: "sync_rejected"
label: "Already running"
- id: "sync_running"
title: "Sync Running"
summary: "Job transitions PENDING → RUNNING. Connector fetches data, checkpoints progress."
service:
id: "GscConnector"
version: "1.0.0"
next_step:
id: "view_jobs"
label: "Monitor progress in job history"
- id: "sync_rejected"
title: "Sync Rejected"
summary: "SyncJobAlreadyRunningFailure — a job for this (source, action) is already in progress"
custom:
title: "Sync Rejected"
type: "error"
summary: "409 — SYNC_JOB_ALREADY_RUNNING"
- id: "disconnect"
title: "Disconnect Source"
summary: "DELETE /visibility/sources/:id — clears credentials, removes visibility states, sets DISCONNECTED"
service:
id: "SourceManagementService"
version: "1.0.0"
next_step:
id: "source_disconnected"
label: "Source disconnected"
- id: "source_disconnected"
title: "Source DISCONNECTED"
summary: "Credentials cleared, visibility states deleted, source deactivated. Pages preserved (may have data from other sources)."
custom:
title: "Source DISCONNECTED"
type: "database"
summary: "PostgreSQL — sources.status = 'DISCONNECTED'"
---
## Source Management Lifecycle
This flow documents how sources are managed through their full lifecycle — from initial connection through daily operations to disconnection.
## Source Status Machine
```
PENDING → (OAuth activate) → ACTIVE
ACTIVE → (disconnect) → DISCONNECTED
ACTIVE → (token revoked / error) → ERROR
ERROR → (re-connect) → PENDING → ...
```
## Endpoints
| Method | Path | Purpose |
|--------|------|---------|
| `GET` | `/visibility/sources` | List all sources |
| `GET` | `/visibility/sources/:id` | Source detail + recent jobs |
| `GET` | `/visibility/sources/:id/jobs` | Job history (filter by `?action=`) |
| `POST` | `/visibility/sources/:id/sync` | Manual sync (optional `?action=`) |
| `DELETE` | `/visibility/sources/:id` | Disconnect + cleanup |
## What Disconnect Deletes
| Data | Deleted? |
|------|----------|
| Encrypted OAuth credentials | Yes |
| PageVisibilityState rows for this source | Yes |
| Pages | No — may have data from other sources |
| SyncJob history | No — preserved for audit |
---
id: "SyncDataIngestion"
name: "Sync Data Ingestion Pipeline"
version: "1.1.0"
summary: "How GSC search analytics data flows from Google's API into the visibility domain — implemented in CEN-30 with pagination, URL normalization, and JSONB upsert."
steps:
- id: "trigger"
title: "Trigger Sync"
summary: "Manual trigger or scheduled cron via Trigger.dev"
actor:
name: "Operator / Scheduler"
next_step:
id: "sync_job_runner"
label: "Start sync for (source, 'search_analytics')"
- id: "sync_job_runner"
title: "Sync Job Runner"
summary: "Validates source exists and belongs to tenant. Creates exclusive job via SELECT ... FOR UPDATE to prevent concurrent runs for same (source, action)."
service:
id: "SyncJobRunner"
version: "1.0.0"
next_steps:
- id: "connector_factory"
label: "Create connector"
- id: "job_rejected"
label: "Duplicate job exists"
- id: "job_rejected"
title: "Job Rejected"
summary: "SyncJobAlreadyRunningFailure — a job for this (source, action) pair is already PENDING or RUNNING"
custom:
title: "Job Rejected"
type: "error"
summary: "409 — SYNC_JOB_ALREADY_RUNNING"
- id: "connector_factory"
title: "Connector Factory"
summary: "Resolves GSC SourceType → GscConnector with injected OAuth service, API port, URL normalizer, and repositories"
service:
id: "ConnectorFactory"
version: "1.0.0"
next_step:
id: "refresh_credentials"
label: "GscConnector.fetchAction('search_analytics')"
- id: "refresh_credentials"
title: "Refresh OAuth Credentials"
summary: "Check token expiry (5-min buffer). Refresh via Google if expired. Decrypt from SourceEntity.encryptedCredentials (D011)."
service:
id: "GscOAuthService"
version: "1.0.0"
next_step:
id: "gsc_api"
label: "Valid access token"
- id: "gsc_api"
title: "Google Search Console API"
summary: "searchanalytics.query() — dimensions: [page], rowLimit: 25,000, startRow from checkpoint. Returns clicks, impressions, CTR, position per URL."
externalSystem:
name: "Google Search Console"
summary: "webmasters/v3/sites/{siteUrl}/searchAnalytics/query"
url: "https://developers.google.com/webmaster-tools"
next_step:
id: "mapper"
label: "Paginated rows (up to 25K)"
- id: "mapper"
title: "GscAnalyticsMapper"
summary: "Pure function: extract URL from keys[0], normalize via URLNormalizerService (D010), build JSONB payload with clicks/impressions/ctr/position/date_range"
service:
id: "URLNormalizerService"
version: "1.0.0"
next_step:
id: "find_or_create_page"
label: "For each mapped row"
- id: "find_or_create_page"
title: "Find or Create Page"
summary: "Match by LOWER(url) using functional index. If no match, create new PageEntity under the tenant's domain with section_key from URLNormalizerService."
custom:
title: "Find or Create Page"
type: "database"
summary: "PostgreSQL — pages table (idx_pages_url_lower)"
next_step:
id: "upsert_visibility"
label: "Page resolved"
- id: "upsert_visibility"
title: "Upsert Visibility State"
summary: "INSERT or UPDATE PageVisibilityState with action='search_analytics'. Uses UNIQUE(page_id, source_id, action) constraint. Full JSONB payload in rawSourcePayload."
custom:
title: "Upsert Visibility State"
type: "database"
summary: "PostgreSQL — page_visibility_states (bigserial PK, D006 schema)"
next_step:
id: "checkpoint"
label: "Row persisted"
- id: "checkpoint"
title: "Update Checkpoint"
summary: "Save { startRow: currentRow + batchSize } to SyncJob. If rows.length >= 25,000, there's more data."
service:
id: "SyncJobRepository"
version: "1.0.0"
next_steps:
- id: "gsc_api"
label: "hasMore=true → fetch next 25K"
- id: "complete"
label: "hasMore=false → done"
- id: "complete"
title: "Mark Job Completed"
summary: "Transition RUNNING → COMPLETED. Materialized view refresh deferred to F.8a."
service:
id: "SyncJobRepository"
version: "1.0.0"
---
## Sync Data Ingestion Pipeline
This flow documents how GSC Search Analytics data moves from Google's API into the Visibility domain. Implemented in CEN-30 with 9 atomic commits.
## Implementation Details
| Aspect | Value |
|--------|-------|
| **Batch size** | 25,000 rows per API call |
| **Pagination** | startRow checkpoint, resume on failure |
| **Date range** | Last 28 days (GSC has ~3 day data delay) |
| **Normalization** | URLNormalizerService (D010) — 10 configurable rules |
| **Storage** | rawSourcePayload JSONB, action='search_analytics' |
| **PK** | bigserial (OP-018) |
| **Upsert** | UNIQUE(page_id, source_id, action) constraint |
| **Credentials** | AES-256-GCM encrypted, auto-refresh (D011) |
## JSONB Payload Shape
```json
{
"clicks": 42,
"impressions": 150,
"ctr": 0.28,
"position": 3.5,
"date_range": { "start": "2026-02-24", "end": "2026-03-23" }
}
```
## Error Paths
| Failure | When | Effect |
|---------|------|--------|
| `SourceNotFoundFailure` | Source doesn't exist or wrong tenant | Job not created |
| `SyncJobAlreadyRunningFailure` | Concurrent job for same (source, action) | Job rejected |
| `ConnectorNotFoundFailure` | Missing OAuth or API dependencies | Job not started |
| Token refresh failure | OAuth tokens expired/revoked | Job marked FAILED, checkpoint preserved |
| API error (rate limit, 500) | During fetch loop | Job marked FAILED, checkpoint preserved for retry |
| No domain for tenant | During page creation | Error thrown, job fails |
---
id: "URLInspect"
name: "URL Inspect Query"
version: "1.0.0"
summary: "How a single URL deep-dive query flows through the system — from API request through normalization, page lookup, and visibility state aggregation."
steps:
- id: "user"
title: "User / Frontend"
summary: "Requests visibility details for a specific URL"
actor:
name: "User"
next_step:
id: "api"
label: "GET /visibility/inspect?project_id=...&url=..."
- id: "api"
title: "Visibility API"
summary: "Validates request params via ZodValidationPipe, extracts tenantId from header"
service:
id: "VisibilityAPI"
version: "1.0.0"
next_step:
id: "inspect_service"
label: "Delegate to InspectService"
- id: "inspect_service"
title: "Inspect Service"
summary: "Orchestrates the URL inspection — project validation, URL lookup, visibility aggregation"
service:
id: "InspectService"
version: "1.0.0"
next_steps:
- id: "verify_project"
label: "1. Verify project exists"
- id: "normalize_url"
label: "2. Normalize URL"
- id: "verify_project"
title: "Verify Project"
summary: "Lookup by (project_id, tenantId) — multi-tenant security"
custom:
title: "Verify Project"
type: "database"
summary: "PostgreSQL — projects table"
next_steps:
- id: "project_not_found"
label: "Not found"
- id: "normalize_url"
label: "Found → continue"
- id: "project_not_found"
title: "Project Not Found"
summary: "Returns 404 ProjectNotFoundFailure"
custom:
title: "Project Not Found"
type: "error"
summary: "HTTP 404 — PROJECT_NOT_FOUND"
- id: "normalize_url"
title: "Normalize URL"
summary: "Apply per-domain normalization rules (D010): strip www, lowercase hostname, strip query params, extract section key"
service:
id: "URLNormalizerService"
version: "1.0.0"
next_step:
id: "find_page"
label: "Use normalized URL for matching"
- id: "find_page"
title: "Find Page"
summary: "Two-step lookup: exact match on url, then case-insensitive fallback on normalized URL"
custom:
title: "Find Page"
type: "database"
summary: "PostgreSQL — pages table (JOIN domains)"
next_steps:
- id: "url_not_found"
label: "No match"
- id: "get_visibility"
label: "Page found → get states"
- id: "url_not_found"
title: "URL Not Found"
summary: "Returns 400 InvalidURLFailure"
custom:
title: "URL Not Found"
type: "error"
summary: "HTTP 400 — INVALID_URL"
- id: "get_visibility"
title: "Get Visibility States"
summary: "Join page_visibility_states with sources for all sources that have data on this page"
custom:
title: "Get Visibility States"
type: "database"
summary: "PostgreSQL — page_visibility_states JOIN sources"
next_step:
id: "build_response"
label: "Aggregate per-source data"
- id: "build_response"
title: "Build Response"
summary: "Assemble per-source visibility, extract Prerender state, calculate coverage"
service:
id: "InspectService"
version: "1.0.0"
next_steps:
- id: "coverage"
label: "Calculate coverage"
- id: "response_builder"
label: "Wrap in ApiResponse"
- id: "coverage"
title: "Coverage Service"
summary: "Computes (active sources / total sources) × 100"
service:
id: "CoverageService"
version: "1.0.0"
next_step:
id: "response_builder"
label: "Coverage metrics"
- id: "response_builder"
title: "Response Builder"
summary: "Wraps data in ApiResponse envelope with metadata (requestId, timestamp, freshness, coverage)"
service:
id: "ResponseBuilderService"
version: "1.0.0"
next_step:
id: "api_response"
label: "Return to client"
- id: "api_response"
title: "API Response"
summary: "200 OK with InspectData — url, normalized_url, section_key, sources[], prerender state, coverage"
actor:
name: "User"
---
## URL Inspect Query Flow
This flow documents how a single URL deep-dive query traverses the system — from the HTTP request through URL normalization, page resolution, and multi-source visibility aggregation.
## Response Shape
```typescript
{
url: string; // Raw URL as stored
normalized_url: string; // After URLNormalizerService (D010)
section_key: string; // First path segment or 'root'
sources: SourceVisibility[]; // Per-source: is_indexed, reason, timestamps, raw_payload
prerender: PrerenderState; // Rendering-specific: last_render_at, http_status, is_cached
coverage: CoverageInfo; // totalSources, activeSources, coveragePercent
}
```
## URL Resolution Strategy
1. **Exact match** on `page.url = :rawUrl` — fastest path, no normalization needed
2. **Normalized fallback** — `LOWER(page.url) = LOWER(:normalizedUrl)` — handles case differences, www prefix, trailing slashes
This two-step approach avoids normalizing every URL in the database at query time.
## Error Paths
| Step | Failure | HTTP | Code |
|------|---------|------|------|
| Verify Project | `ProjectNotFoundFailure` | 404 | `PROJECT_NOT_FOUND` |
| Find Page | `InvalidURLFailure` | 400 | `INVALID_URL` |
---
id: "WorkerRegistration"
name: "Connector Worker Registration"
version: "1.0.0"
summary: "How a connector worker authenticates and registers with Visibility API on startup — the handshake that makes the worker discoverable and ready to receive sync tasks."
steps:
- id: "pod_start"
title: "Worker Pod Starts"
summary: "K8s starts connector worker pod. NestJS bootstraps application and loads environment variables."
actor:
name: "Kubernetes"
next_step:
id: "module_init"
label: "NestJS app ready"
- id: "module_init"
title: "Module Init"
summary: "NestJS calls onModuleInit on WorkerRegistrationService. The service builds registration payload from workerName, workerURL, supportedSourceTypes, supportedActions, and registration secret."
service:
id: "WorkerRegistrationService"
version: "1.0.0"
next_step:
id: "register_call"
label: "POST registration"
- id: "register_call"
title: "Register with Visibility API"
summary: "POST /visibility/connectors/register with worker metadata and x-prerender-connector-registration-secret. API records worker URL and capabilities for future sync dispatch only after the shared secret matches."
externalSystem:
name: "Visibility API"
summary: "Receives authenticated worker registration and stores worker metadata for connector routing"
url: "http://visibility-api:3001"
next_steps:
- id: "registered"
label: "200 OK"
- id: "retry"
label: "Error / non-200"
- id: "retry"
title: "Retry Backoff"
summary: "Exponential backoff: 1s -> 2s -> 4s. Up to 3 attempts total. Common during rolling deploys when API is not ready yet. Repeated 401 or 503 means the registration secret is wrong or missing."
service:
id: "WorkerRegistrationService"
version: "1.0.0"
next_steps:
- id: "register_call"
label: "Retry"
- id: "unregistered"
label: "All retries exhausted"
- id: "registered"
title: "Worker Ready"
summary: "Registration successful. Readiness flag is set true. K8s readiness probe (GET /readyz) starts returning 200. Worker can receive traffic."
custom:
title: "Worker Ready"
type: "success"
summary: "Readiness probe passes — pod enters service rotation"
- id: "unregistered"
title: "Worker Started Unregistered"
summary: "All retry attempts failed. Worker runs but readiness probe returns not_ready. K8s does not route traffic. It will retry on next pod restart."
custom:
title: "Started Unregistered"
type: "error"
summary: "Pod alive but not ready — no traffic routed"
---
## Connector Worker Registration
This flow documents the startup handshake between a connector worker pod and Visibility API.
Every connector worker follows this protocol to announce itself and become discoverable for sync dispatch.
The handshake is authenticated with `x-prerender-connector-registration-secret`.
## Registration Payload
```json
{
"workerName": "connector-prerender",
"workerURL": "http://connector-prerender:3003",
"supportedSourceTypes": ["PRERENDER"],
"supportedActions": ["cache_status", "rendering", "crawl_stats"]
}
```
The secret is sent as an HTTP header, not in the JSON body:
```http
x-prerender-connector-registration-secret:
```
| Field | Source | Purpose |
|-------|--------|---------|
| `workerName` | `WORKER_NAME` env var | Unique identifier, also the trusted K8s service name |
| `workerURL` | Derived from worker name + port | How API reaches worker |
| `supportedSourceTypes` | `SUPPORTED_SOURCE_TYPES` env var | Which `SourceType` values worker handles |
| `supportedActions` | `SUPPORTED_ACTIONS` env var | Which actions worker can fetch |
## Security Contract
Registration and deregistration require `x-prerender-connector-registration-secret`.
Visibility API returns:
- `401` when the worker omits the header or sends the wrong secret.
- `503` when API has no configured `CONNECTOR_REGISTRATION_SECRET`.
The worker URL must use the in-cluster short service name:
```text
http://:
```
Dispatch is blocked unless `workerURL.hostname` is a single-label host equal to `workerName`.
External hosts, IP literals, userinfo-smuggled URLs, and dotted cluster FQDNs are not trusted by `RemoteConnectorDispatcher`.
## Health Probes
| Probe | Path | Meaning |
|-------|------|---------|
| **Liveness** | `GET /healthz` | Process is running |
| **Readiness** | `GET /readyz` | Registration succeeded |
K8s uses readiness to gate traffic.
A worker that fails registration stays alive but receives no sync requests.
## Retry Strategy
| Attempt | Delay | Total Elapsed |
|---------|-------|---------------|
| 1 | - | 0s |
| 2 | 1s | 1s |
| 3 | 2s | 3s |
After 3 failed attempts, the worker starts unregistered and logs an error.
The next pod restart re-attempts registration.
## Architecture Context (D013)
Each connector runs as a separate K8s pod.
This registration protocol is how Visibility API discovers which connectors are available and what capabilities they expose.
- **Independent scaling** — Prerender connector can scale separately from GSC.
- **Fault isolation** — a crashing connector does not take down API or other connectors.
- **Independent deployment** — update one connector without redeploying others.