Api filters

From openmeterio/openmeter · View interactive version

Api filters is an AI agent skill from the GitHub repository openmeterio/openmeter. Add, modify, or convert AIP-style query-parameter filters on v3 list endpoints. Use when adding filterable fields to a list API, wiring filter parsing into a handler, converting API filters into pkg/filter predicates, or debugging filter parsing/validation behavior.

How to use this skill

Skill file

v3 API Filter Parsing

You are helping the user add or modify AIP-style query-parameter filters on an OpenMeter v3 list endpoint.

OpenMeter follows the Kong AIP filter spec (NOT Google AIP-160 expression syntax). Filters use the deepObject query-parameter encoding ?filter[field][op]=value. The implementation is split across three layers:

Relationship to other skills

Filtering straddles two layers that the repo skill set keeps separate:

If you are adding a brand-new filterable endpoint, invoke /api first to wire up the TypeSpec + handler shell, then come back here for the conversion + adapter code. If you are only adding/modifying filters on an existing endpoint, this skill is enough on its own.

Context

Architecture: three-layer conversion

TypeSpec Common.*FieldFilter
        │  (make gen-api)
        ▼
api.Filter* (generated OAS types)        ─┐
        │                                  │ handler decode layer
api/v3/filters.Filter*  (API-layer types)  │  calls filters.FromAPIFilter*(...)
        │                                  │
pkg/filter.Filter*      (predicate model) ─┘  stored on service input struct
        │
        ▼                                    adapter layer
filter.ApplyToQuery(query, input.Field, dbField)

Rules:

Filter Grammar (Kong AIP)

Encoding: deepObject query parameters. Two-level brackets identify field and operator:

filter[field]=value              # shorthand → eq
filter[field][eq]=value          # exact match
filter[field][neq]=value         # not equal (also returns NULLs)
filter[field][contains]=value    # substring match (case-insensitive on strings)
filter[field][oeq]=a,b,c         # one-of-equal (comma-separated, max 50 items)
filter[field][ocontains]=a,b     # one-of-contains
filter[field][gt]=value          # greater than
filter[field][gte]=value         # greater than or equal
filter[field][lt]=value          # less than
filter[field][lte]=value         # less than or equal
filter[field]                    # bare key → exists=true (presence check)
filter[field][exists]            # explicit existence check
filter[field][nexists]           # absence check (only for additionalProperties maps like labels)
filter[labels.key_1][eq]=val     # dot-notation: only the FIRST dot is a delimiter

Operator constants live in api/v3/filters/parse.go as OpEq, OpNeq, OpGt, OpGte, OpLt, OpLte, OpContains, OpOeq, OpOcontains, OpExists, OpNexists.

API-layer filter types (`api/v3/filters/filter.go`)

| Go type | Fields |

| ------------------- | ------------------------------------------------------------------------------ |

| FilterBoolean | Eq |

| FilterNumeric | Eq, Neq, Oeq, Gt, Gte, Lt, Lte |

| FilterDateTime | Eq, Gt, Gte, Lt, Lte (all *time.Time; no Neq/Oeq) |

| FilterString | Eq, Neq, Gt, Gte, Lt, Lte, Contains, Oeq, Ocontains, Exists |

| FilterULID | Eq, Neq, Contains, Oeq, Ocontains, Exists (no range ops) |

| FilterStringExact | Eq, Neq, Oeq (no Exists, no Contains) |

| FilterLabel | Eq, Neq, Contains, Oeq, Ocontains (label map value predicates) |

| FilterLabels | type alias: map[string]FilterLabel |

The wire operator for Exists is plain exists (see OpExists in api/v3/filters/parse.go), matching its json:"exists,omitempty" tag. The v1 filter models in api/models/models.gen.go use $-prefixed JSON tags.

Important: the API-layer types do NOT have Validate() methods. Validation (mutual exclusivity, complexity bounds, format checks) happens on the internal pkg/filter.* predicates — typically from the service input struct's own Validate(), calling f.Validate() on each non-nil filter.

`pkg/filter` predicates

| Predicate | Produced by converter | Notes |

| ------------------------ | ----------------------------- | -------------------------------- |

| *filter.FilterString | FromAPIFilterString | Also used by FromAPIFilterLabel, FromAPIFilterStringExact |

| *filter.FilterULID | FromAPIFilterULID | Embeds FilterString |

| *filter.FilterFloat | FromAPIFilterNumeric | (note: not FilterNumeric) |

| *filter.FilterTime | FromAPIFilterDateTime | RFC-3339 already parsed to time.Time by Parse |

| *filter.FilterBoolean | FromAPIFilterBoolean | |

| map[string]filter.FilterString | FromAPIFilterLabels | Label map flatten |

The Filter interface (pkg/filter/filter.go:19) exposes Validate(), ValidateWithComplexity(maxDepth int), Select(field string) func(*sql.Selector), SelectWhereExpr(...), and IsEmpty().

Multi-filter semantics

Validation is done by `pkg/filter`

Mutual-exclusivity and format rules (e.g. "multiple operators on one node", ULID format, complexity depth) are enforced by *filter.FilterX.Validate() — not by the API-layer types. A typical service input Validate() looks like:

if i.Key != nil {
    if err := i.Key.Validate(); err != nil {
        errs = append(errs, models.NewGenericValidationError(fmt.Errorf("invalid key filter: %w", err)))
    }
}

Hard limits (security, `api/v3/filters/parse.go:16-19`)

Workflow

Follow these steps in order. Use the /api skill alongside this one when you also need to touch TypeSpec.

Step 1: Define the filterable fields in TypeSpec

In api/spec/packages/aip/src/<domain>/operations.tsp, define a named filter model for the list operation and expose it as filter with style: "deepObject", explode: true. Use the Common.*FieldFilter types from common/parameters.tsp — do not hand-roll filter models.

The canonical rule for which Common.*FieldFilter type to pick, the Shared.ResourceFilters spread, label dot-notation, and OAS documentation requirements is ../api/rules/aip-160-filtering.md. That rule also includes the TypeSpec type ↔ Go filters.Filter* mapping. Read it once before picking types — this skill is not the source of truth for the TypeSpec side.

The events list endpoint (api/spec/packages/aip/src/events/operations.tsp) and the customer list endpoint are the canonical worked examples.

After editing TypeSpec, run make gen-api. Check the generated filter type in api/v3/models/models.gen.go for the new fields (for example, ListCustomersParamsFilter for ListCustomersParams.Filter).

Step 2: Store `pkg/filter` predicates on the service input struct

In your domain service input type, add fields typed as pkg/filter predicates, not API-layer types. Example from openmeter/customer/customer.go:296:

type ListCustomersInput struct {
    Namespace string
    pagination.Page

    OrderBy string
    Order   sortx.Order

    Key          *filter.FilterString
    Name         *filter.FilterString
    PrimaryEmail *filter.FilterString
    // ...
}

func (i ListCustomersInput) Validate() error {
    var errs []error
    // ...
    if i.Key != nil {
        if err := i.Key.Validate(); err != nil {
            errs = append(errs, models.NewGenericValidationError(fmt.Errorf("invalid key filter: %w", err)))
        }
    }
    // ...
    return models.NewNillableGenericValidationError(errors.Join(errs...))
}

Pick the narrowest predicate: filter.FilterString for strings, filter.FilterULID for ULID columns, filter.FilterFloat for numbers, filter.FilterTime for timestamps, filter.FilterBoolean for bools.

Step 3: Convert API filters in the HTTP handler

In the handler decoder (the first argument to httptransport.NewHandlerWithArgs), call the matching filters.FromAPIFilter* helper against the generated params.Filter.<field> and assign to the request. The canonical pattern is in api/v3/handlers/customers/list.go:

import (
    "github.com/openmeterio/openmeter/api/v3/apierrors"
    "github.com/openmeterio/openmeter/api/v3/filters"
)

if params.Filter != nil {
    key, err := filters.FromAPIFilterString(params.Filter.Key)
    if err != nil {
        return ListCustomersRequest{}, apierrors.NewBadRequestError(ctx, err, apierrors.InvalidParameters{
            {Field: "filter[key]", Reason: err.Error(), Source: apierrors.InvalidParamSourceQuery},
        })
    }
    req.Key = key

    name, err := filters.FromAPIFilterString(params.Filter.Name)
    if err != nil {
        return ListCustomersRequest{}, apierrors.NewBadRequestError(ctx, err, apierrors.InvalidParameters{
            {Field: "filter[name]", Reason: err.Error(), Source: apierrors.InvalidParamSourceQuery},
        })
    }
    req.Name = name
}

Notes:

Step 4: Apply to the query in the adapter

Adapters use filter.ApplyToQuery(query, input.Field, dbField) — a generic helper that:

  1. Returns the query unchanged when the predicate is nil.
  2. Builds an Ent predicate via pkg/filter.SelectPredicate[P](...).
  3. Calls q.Where(*p) when the predicate is non-empty.

From openmeter/customer/adapter/customer.go:52:

query = filter.ApplyToQuery(query, input.Key, customerdb.FieldKey)
query = filter.ApplyToQuery(query, input.Name, customerdb.FieldName)
query = filter.ApplyToQuery(query, input.PrimaryEmail, customerdb.FieldPrimaryEmail)

Important behaviors baked into the converter + ApplyToQuery pipeline:

Step 5: Service Level Tests

ALWAYS add service level tests for the list function in the domain's service_test.go. These tests should:

  1. Use a table-based test approach (testCases := []struct{...}).
  2. Cover each new filter field (e.g., FilterByID, FilterByKey, FilterByStatus).
  3. Cover the new sort options (e.g., SortByNameDesc).
  4. Assert on the expected number of items and specific item properties in the result.

Step 6: Adapter & Integration Tests

Write tests at three additional layers:

  1. Parser tests (api/v3/filters/parse_test.go): the parse layer is already covered for the generic operator surface; only add cases when introducing a new filter type or operator.
  2. Converter tests (api/v3/filters/convert_test.go): only when adding a new FromAPIFilter* helper.
  3. Adapter tests (adapter_test.go): If you made changes to the adapter (e.g., adding filter.ApplyToQuery for new fields) that are not already covered by existing tests, add specific test cases to verify the Ent query generation for these fields.
  4. Handler/adapter integration tests: the important layer for new endpoints — assert that representative ?filter[...]= query strings produce the expected results. Cover at minimum:

Use httptest.NewRequest and assert on the response body or the captured service input.

Common Patterns and Gotchas

Picking the right filter type

| You want… | API type | Predicate |

| ------------------------------------------------------ | ------------------- | ------------------------ |

| Equality + contains + ranges on a string column | FilterString | *filter.FilterString |

| ULID column (eq/neq/contains/oeq/ocontains/exists) | FilterULID | *filter.FilterULID |

| Equality + neq + IN-list on an enum-like string column | FilterStringExact | *filter.FilterString |

| Numeric column with ranges | FilterNumeric | *filter.FilterFloat |

| Timestamp column with ranges | FilterDateTime | *filter.FilterTime |

| Boolean flag column | FilterBoolean | *filter.FilterBoolean |

| Single label map key | FilterLabel | *filter.FilterString |

| Full labels map | FilterLabels | map[string]filter.FilterString |

Dot notation and label maps

Datetime values

FilterDateTime holds *time.Time and Parse rejects malformed RFC-3339 strings at parse time (via ErrInvalidDateTime). The converter cannot produce format errors; its error return is a forward-compat hook.

Repeated parameters

?filter[f][eq]=a&filter[f][eq]=b is rejected — this is intentional. To express OR semantics use oeq. Do not try to "fix" the parser to merge repeated keys.

Range queries

Multiple range operators on the same field (e.g. gte+lte) are packed into And{gte, lte} by the converter. Validation of pathological combinations (e.g. both gt and gte) lives in pkg/filter.FilterX.Validate(); the service input's own Validate() surfaces those errors.

Case sensitivity

Quantifiers (`any` / `all`) on list fields

The Kong AIP spec allows ?filter[tags][eq][any]=urgent and [all] quantifiers on list-typed fields. The current OpenMeter implementation does NOT support quantifiers. If a request comes in for a list field, raise this with the user before attempting to add it — this is a parser-level extension, not a per-endpoint change.

Things the parser intentionally does NOT support

If a customer asks for any of these, treat it as a feature request, not a bug fix.

Error Handling

Representative error messages from Parse:

Reference Files

Important Reminders

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.