Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@ Structure
- Handlers: `src/handlers/` (HandlerApi, HandlerToken, HandlerTopic, HandlerHealth, HandlerStats, HandlerNamedQuery)
- Writers: `src/writers/` (inherit from `Writer` base class)
- Readers: `src/readers/` (read-only database access for stats)
- Named queries: `POST /stats/{topic}/query/{query_name}`; public names are discovered from `src/readers/sql/*.sql` by `src/readers/query_catalog.py`, no Python registry
- `jobs_detail_queries.sql`: `<name>` + `<name>_with_cursor` (paginated)
- `aggregation_queries.sql`: `<name>_summary` + `<name>_timeline_hourly` + `<name>_timeline_daily` (no `cursor`/`limit`)
- Both families accept optional `source_app` and `tenant_id` filters (exact match, `null` = no filter)
- Public names must not clash across families; `stats.sql` queries stay private
- Named queries: `POST /stats/{topic}/query/{query_name}`; `HandlerNamedQuery._query_routes` explicitly exposes `runs_jobs_detail`, `runs_jobs_detail_aggregation`, and `runs_jobs_detail_breakdowns`
- `src/readers/sql/runs.sql` contains four statements: detail, aggregation summary, parameterized timeline, and breakdowns
- Stats and named detail share SQL with optional cursor/source/tenant filters, but retain their separate response formatters
- Aggregation and breakdown routes have no `cursor`/`limit`; all named routes accept optional exact-match `source_app`/`tenant_id` filters (`null` = no filter)
- SQL loading is lazy/cached through `ReaderQueries`; internal SQL statements never become public routes automatically
- Add another topic-oriented SQL file only when another topic is supported
- aiosql methods are dynamic: access with `getattr(queries, "name").sql`
- Config: `conf/config.json`, `conf/access.json`, `conf/topic_schemas/*.json`

Expand All @@ -25,7 +26,7 @@ Python style
- Use built-in generics for type hints
- Use `logging.getLogger(__name__)`, not print
- Structured logging: constant message + data in `extra`: `logger.info("Message accepted.", extra={"writer": name})`
- Do not re-log `topic`, `user`, `resource`, `http_method` or the Lambda context; they are bound per request in `src/utils/observability.py`
- Do not repeat bound request keys (`topic`, `user`, `resource`, `http_method`, or Lambda context) in individual log extras
- `logger.exception()` only inside an `except` block; outside it pass `exc_info=exc` to `logger.error()`
- F-strings in exceptions: `raise ValueError(f"Error {var}")`
- All imports at top of file (never inside functions)
Expand All @@ -39,12 +40,16 @@ Python style
- Levels: TRACE payloads, DEBUG steps, INFO request outcomes, WARNING rejected requests, ERROR actionable failures

Patterns
- Reuse existing helpers before adding new abstractions; prefer simple explicit implementations unless current requirements justify generalization
- In topic-based handlers, use `resolve_request_topic(event)` for topic normalization, missing-topic handling, and request-log binding
- `__init__` methods must not raise exceptions; defer validation and connection to first use (lazy init)
- Writers: inherit from `Writer(ABC)`, implement `write(topic, message) -> (bool, str|None)` and `check_health() -> (bool, str)`
- PostgreSQL: `WriterPostgres` and `ReaderPostgres` cache a single connection per instance
- Finish PostgreSQL reader transactions on both success and failure; multi-SELECT responses requiring a consistent snapshot must share one read-only REPEATABLE READ transaction
- Route dispatch via `ROUTE_MAP` dict mapping routes to handler functions in `event_gate_lambda.py` and `event_stats_lambda.py`
- Separate business logic from environment access (env vars, file I/O, network calls)
- No duplicate validation; centralize parsing in one layer where practical
- Prefer bound parameters to duplicated SQL that differs only in values or optional filters
- Preserve existing formatting and conventions
- Keep API Gateway response structure stable: `{"statusCode": int, "headers": {...}, "body": "..."}`
- Keep error response format stable: `{"success": false, "statusCode": int, "errors": [...]}`
Expand Down
95 changes: 91 additions & 4 deletions api.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,7 @@ paths:
description: >
Runs a curated, server-side named query by name. `runs_jobs_detail` returns paginated
results. `runs_jobs_detail_aggregation` returns window totals and a bucketed timeline.
`runs_jobs_detail_breakdowns` independently returns tenant/source distributions.
security: []
parameters:
- name: topic_name
Expand All @@ -347,12 +348,13 @@ paths:
required: true
schema:
type: string
enum: [runs_jobs_detail, runs_jobs_detail_aggregation]
enum: [runs_jobs_detail, runs_jobs_detail_aggregation, runs_jobs_detail_breakdowns]
description: Identifier of the named query to run
requestBody:
description: >
Query parameters. Shape depends on `query_name`: pagination fields for
`runs_jobs_detail`, time window only for `runs_jobs_detail_aggregation`.
`runs_jobs_detail`, time window and optional exact filters for
`runs_jobs_detail_aggregation` and `runs_jobs_detail_breakdowns`.
required: false
content:
application/json:
Expand All @@ -364,13 +366,15 @@ paths:
'200':
description: >
Named-query result. `runs_jobs_detail` returns a paginated result set;
`runs_jobs_detail_aggregation` returns window-wide aggregations instead.
`runs_jobs_detail_aggregation` returns window-wide totals/timeline;
`runs_jobs_detail_breakdowns` returns tenant/source distributions instead.
content:
application/json:
schema:
anyOf:
- $ref: '#/components/schemas/RunsJobsDetailResponse'
- $ref: '#/components/schemas/RunsJobsDetailAggregationResponse'
- $ref: '#/components/schemas/RunsJobsDetailBreakdownsResponse'
'400':
description: Invalid parameters, unsupported topic, or unknown query_name
content:
Expand Down Expand Up @@ -451,10 +455,13 @@ components:
RunsJobsDetailAggregationQueryBody:
type: object
description: >
Request body for the window-wide `runs_jobs_detail_aggregation` named query.
Request body for the window-wide `runs_jobs_detail_aggregation` and
`runs_jobs_detail_breakdowns` named queries.
`cursor`/`limit` are not accepted here (400 if present) since this query is not paginated.
source_app and tenant_id are optional exact, case-sensitive filters combined with AND.
Omitted or null filters mean all values. Filters do not enforce authorization.
Bounds are inclusive and apply to the parent run's timestamp_start, not job timestamps.
Both filters apply before both breakdown groupings; these are not self-excluding facets.
properties:
timestamp_start:
type: integer
Expand Down Expand Up @@ -626,6 +633,86 @@ components:
type: integer
description: Count of job rows with raw status skipped in this bucket
example: 0
RunsJobsDetailBreakdownsResponse:
type: object
properties:
success:
type: boolean
example: true
statusCode:
type: integer
example: 200
breakdowns:
type: object
required: [window, by_tenant, by_source]
additionalProperties: false
description: >
Complete whole-window distributions at job-row grain, not distinct runs or latest states.
Both arrays are empty when no rows match. Total counts all matching job rows.
Rows serialize the identifier first, then total, succeeded, failed, killed, skipped.
properties:
window:
type: object
required: [timestamp_start, timestamp_end]
properties:
timestamp_start:
type: integer
example: 1704067200000
timestamp_end:
type: integer
example: 1706745600000
by_tenant:
type: array
description: All matching tenant groups, sorted by raw tenant_id ascending with case-sensitive C collation
items:
type: object
required: [tenant_id, total, succeeded, failed, killed, skipped]
additionalProperties: false
properties:
tenant_id:
type: string
example: tenant-a
total:
type: integer
example: 120
succeeded:
type: integer
example: 70
failed:
type: integer
example: 50
killed:
type: integer
example: 0
skipped:
type: integer
example: 0
by_source:
type: array
description: All matching source groups, sorted by raw source_app ascending with case-sensitive C collation
items:
type: object
required: [source_app, total, succeeded, failed, killed, skipped]
additionalProperties: false
properties:
source_app:
type: string
example: app-x
total:
type: integer
example: 200
succeeded:
type: integer
example: 90
failed:
type: integer
example: 110
killed:
type: integer
example: 0
skipped:
type: integer
example: 0
ErrorResponse:
type: object
properties:
Expand Down
Loading