Skip to content

feat: add id config and pagination helpers - #676

Merged
uniqueg merged 7 commits into
devfrom
feat/623-id-config-pagination
Nov 4, 2026
Merged

uniqueg merged 7 commits into
devfrom
feat/623-id-config-pagination

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Generalizes what cloud-registry does:

  • foca.models.config.IdConfig: character set and length of identifiers, for the custom config of apps, with the validator of cloud-registry; for foca.utils.misc.generate_id().
  • foca.utils.pagination: get_page() checks offset and limit (400 for invalid ones, larger limits are reduced to max_limit), get_page_links() builds first, prev, next and last from server.public_url, not the Host header, keeping the path and other query parameters, and get_link_header() formats them as per RFC 8288.
  • service_info.locked_fields: fields that only runtime_fields may set. Refused in service at startup, and the service info fails if the function doesn't return them.
  • Docs: docs/utilities.md, docs/configuration/service-info.md, docs/reference.md.

Closes #623

For the maintainer

  • POST /service-info from the issue doesn't exist in FOCA, so nothing to lock there.
  • The config taking precedence over the runtime function is documented behaviour, as overlays rely on it, so changing it would break apps. Hence the opt-in locked_fields, off by default.

Verification

  • ruff check, ruff format --check, mypy, mkdocs build --strict: pass.
  • pytest with coverage: 100 %. Locally, tests/factories/test_celery_worker_fork.py::test_no_client_opened_before_fork depends on which checkout the shared virtual environment has installed; see CI for the run on this branch.
  • The reviewer checked skip() at the upper bound on MongoDB 7.0, not 8.
  • Both reviewer subagents, two rounds.

Declined review findings

  • . in IdConfig.charset with short lengths can generate dot segments: cloud-registry's validator accepts the same, and such a configuration is deliberate; get_public_url() refuses those identifiers.
  • A shared constant with access control's DEFAULT_PAGE_SIZE: foca.utils doesn't depend on foca.security, and the two defaults mean different lists.

🤖 Generated with Claude Code

Summary by Sourcery

Add reusable identifier, pagination, and runtime service-info configuration helpers.

New Features:

  • Add configurable identifier generation settings through IdConfig, including validation for URL-safe character sets.
  • Add offset-based pagination helpers for validating page parameters, generating public page links, and formatting RFC 8288 Link headers.

Enhancements:

  • Allow service-info fields to be marked as locked so runtime-generated values cannot be overridden by static configuration.

Documentation:

  • Document identifier configuration, pagination utilities, and locked service-info fields.

Tests:

  • Add coverage for identifier validation, pagination behavior, and locked service-info fields.

uniqueg and others added 4 commits November 4, 2026 06:10
Generalize what cloud-registry does: IdConfig for the custom config of
apps, foca.utils.pagination for offset-based lists with links from the
public URL, and opt-in service_info.locked_fields for fields that only
the runtime function may set, as config takes precedence otherwise.

Closes #623

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reject offsets beyond 8 bytes, which MongoDB refuses, and limits of the
app below 1. Keep trailing slashes in links, and let prev point to a
page with items. Count locked fields returned as null as missing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.21.0 milestone Nov 4, 2026
@uniqueg
uniqueg marked this pull request as ready for review November 4, 2026 05:29
@sourcery-ai

sourcery-ai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR adds reusable identifier configuration and offset-pagination utilities, including safe public URL link generation and RFC 8288 headers, and introduces opt-in protection for service-info fields that must be supplied by runtime code.

Sequence diagram for paginated resource links

sequenceDiagram
    participant Client
    participant Controller
    participant Pagination as foca.utils.pagination
    participant Server as server.public_url
    participant Collection

    Client->>Controller: GET collection?offset&limit
    Controller->>Pagination: get_page(offset, limit)
    Pagination-->>Controller: Page(offset, limit)
    Controller->>Collection: Fetch page using Page
    Collection-->>Controller: Items and total
    Controller->>Pagination: get_page_links(page, total)
    Pagination->>Server: get_public_url(request.path)
    Server-->>Pagination: Public page URL
    Pagination-->>Controller: first, prev, next, last links
    Controller->>Pagination: get_link_header(links)
    Pagination-->>Controller: RFC 8288 Link value
    Controller-->>Client: Items, links, Link header
Loading

Sequence diagram for locked runtime service-info fields

sequenceDiagram
    participant App
    participant Config as ServiceInfoConfig
    participant Runtime as runtime_fields
    participant Builder as build_service_info

    App->>Config: Validate locked_fields
    alt locked_fields without runtime_fields
        Config-->>App: Reject configuration
    else service sets a locked field
        Config-->>App: Reject configuration
    else valid configuration
        App->>Builder: build_service_info(conf)
        Builder->>Runtime: call_runtime_function(runtime_fields)
        alt runtime omits or nulls a locked field
            Builder-->>App: InvalidServiceInfo
        else runtime returns locked fields
            Builder-->>App: Merged and validated service info
        end
    end
Loading

File-Level Changes

Change Details Files
Add configurable identifier generation settings with validation for URL-safe character sets and positive lengths.
  • Introduce IdConfig with uppercase-alphanumeric defaults.
  • Reject empty, expression-like, slash-containing, and dots-only character sets.
  • Reuse generate_id() to validate character sets.
foca/models/config.py
docs/utilities.md
tests/models/test_config.py
Add offset-based pagination helpers that validate bounds and generate stable public links and RFC 8288 headers.
  • Parse and validate integer offsets and limits, cap limits at max_limit, and model pages with Page.
  • Build first/previous/next/last links using server.public_url, preserving paths, trailing slashes, and unrelated query parameters while ignoring the request Host header.
  • Format page links as an RFC 8288 Link header.
foca/utils/pagination.py
docs/utilities.md
docs/reference.md
tests/utils/test_pagination.py
Protect runtime-generated service information fields from static configuration overrides.
  • Add opt-in locked_fields configuration and reject locked fields in service or configurations without runtime_fields.
  • Require runtime output to provide every locked field with a non-null value before merging and validating service info.
  • Document locked-field behavior and its startup/runtime failure modes.
foca/models/config.py
foca/api/service_info.py
docs/configuration/service-info.md
tests/api/test_service_info.py
tests/models/test_config.py

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (05c6eab) to head (52793ba).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #676   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           57        58    +1     
  Lines         7431      7499   +68     
=========================================
+ Hits          7431      7499   +68     
Flag Coverage Δ
test_unit 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 6 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="foca/utils/pagination.py" line_range="61" />
<code_context>
+    if (
+        not isinstance(value, int)
+        or isinstance(value, bool)
+        or not minimum <= value <= _MAX_VALUE
+    ):
+        raise BadRequest(f"'{name}' must be an integer from {minimum} to {_MAX_VALUE}.")
</code_context>
<issue_to_address>
**Large offsets exhaust database resources**

When an unauthenticated or low-privilege caller requests a very large offset through a MongoDB list endpoint, `get_page()` accepts offsets up to `_MAX_VALUE`, and the documented MongoDB `skip()` pattern scans and discards preceding records, consuming substantial database resources and potentially denying service to other users.

Impose a practical maximum offset or use pagination that avoids scanning all preceding records.

Also at `docs/utilities.md:60`.
</issue_to_address>

### Comment 2
<location path="foca/utils/pagination.py" line_range="92-93" />
<code_context>
+            `limit` from 1, to the largest one of 8 bytes.
+        ValueError: `default_limit` or `max_limit` is less than 1.
+    """
+    if default_limit < 1 or max_limit < 1:
+        raise ValueError("`default_limit` and `max_limit` must be at least 1")
+    return Page(
+        offset=0 if offset is None else _get_integer(offset, "offset", 0),
</code_context>
<issue_to_address>
**Oversized limits fail MongoDB requests**

When `default_limit` exceeds `_MAX_VALUE` and `max_limit` is at least as large, `get_page()` checks only that the limits are positive, so it returns a page with a limit above MongoDB’s signed 64-bit range and the cursor request fails.

Reject `default_limit` or `max_limit` values above `_MAX_VALUE`.
</issue_to_address>

### Comment 3
<location path="foca/models/config.py" line_range="154-155" />
<code_context>
+        IdConfig(charset='ABC123', length=6)
+    """
+
+    charset: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+    length: PositiveInt = 6
+
+    @field_validator("charset")
</code_context>
<issue_to_address>
**Default identifiers collide at scale**

When an app uses the default `IdConfig` for tens of thousands of stored resources, `generate_id()` independently samples six characters from only 36 possibilities per position, giving about 31 bits of entropy; after roughly 55,000 generated IDs, a collision is about as likely as not, so storing them as unique resource IDs causes inserts to reject or overwrite existing records.

Increase the default identifier entropy and document that callers must enforce uniqueness and retry on collisions at the persistence layer.
</issue_to_address>

### Comment 4
<location path="foca/utils/pagination.py" line_range="144" />
<code_context>
+        previous = max(page.offset - page.limit, 0)
+        # Not an empty page, if the current one starts past the end
+        links["prev"] = link(previous if last is None else min(previous, last))
+    following = page.offset + page.limit
+    if following <= _MAX_VALUE and (total is None or following < total):
+        links["next"] = link(following)
</code_context>
<issue_to_address>
**Concurrent changes duplicate or skip items**

When the collection changes between requests while a client traverses pages, `get_page_links()` advances by the prior page’s fixed offset, so inserted rows shift later pages and clients receive duplicates, while deleted rows cause items to be skipped.

Use cursor- or snapshot-based pagination when a traversal must remain stable, or explicitly document that offset pagination can repeat or skip items under concurrent writes.
</issue_to_address>

### Comment 5
<location path="foca/utils/pagination.py" line_range="145-146" />
<code_context>
+        # Not an empty page, if the current one starts past the end
+        links["prev"] = link(previous if last is None else min(previous, last))
+    following = page.offset + page.limit
+    if following <= _MAX_VALUE and (total is None or following < total):
+        links["next"] = link(following)
+    if last is not None:
+        links["last"] = link(last)
</code_context>
<issue_to_address>
**Next link is omitted at maximum offset**

When a caller requests a page at or near the maximum accepted offset and omits `total`, `get_page_links()` omits `next` when the following offset exceeds `_MAX_VALUE`, so callers do not receive the next link promised by the documentation.

Align the maximum-offset behavior with the documented next-link guarantee.

Also at `docs/utilities.md:75-76`, `foca/utils/pagination.py:112-113`.
</issue_to_address>

### Comment 6
<location path="foca/api/service_info.py" line_range="80-87" />
<code_context>
     path = str(conf.runtime_fields)
     runtime = call_runtime_function(conf.runtime_function, path)
+    # `null` removes a field
+    missing = sorted(
+        name for name in set(conf.locked_fields) if runtime.get(name) is None
+    )
+    if missing:
+        raise InvalidServiceInfo(
</code_context>
<issue_to_address>
**No POST override protection**

The change checks locked fields returned by runtime_fields, but does not protect them from POST /service-info input. The PR notes that FOCA has no such endpoint, so this entry point remains unimplemented.
</issue_to_address>

Linked issues

#623 feat: add IdConfig, locked fields, pagination · 4 of 5 met

# Requirement Status Notes
1 Add a shared IdConfig model for identifier charset and length. ✅ Met IdConfig provides charset and positive length settings, with validation for unusable identifier character sets.
2 Protect runtime-computed service-info fields from overrides by config or POST /service-info. 🟡 Partly met The change rejects locked fields in service configuration and requires runtime_fields to return them; FOCA has no POST /service-info route, so POST overrides are not handled.
3 Add pagination helpers for offset and page handling, with links built from server.public_url. ✅ Met get_page validates and caps pagination parameters; get_page_links builds public-URL links while retaining the request path and other query parameters.
4 Add tests for each feature and achieve 100% coverage. ✅ Met Tests are added for IdConfig, locked fields, and pagination; the PR reports 100% coverage.
5 Document the features with examples. ✅ Met Examples and guidance are added for IdConfig, pagination, and locked service-info fields.

Sourcery assessment

Approval pending. 5 findings to address first.

Blocking findings: foca/utils/pagination.py:61, foca/utils/pagination.py:93, foca/models/config.py:155, foca/utils/pagination.py:144, foca/api/service_info.py:87


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread foca/utils/pagination.py Resolved
Comment thread foca/utils/pagination.py Resolved
Comment thread foca/models/config.py Resolved
Comment thread foca/utils/pagination.py Resolved
Comment thread foca/utils/pagination.py Resolved
Comment thread foca/api/service_info.py Resolved
uniqueg and others added 2 commits November 4, 2026 07:10
Also describe the limits of offset pagination and of the default
identifiers in the docs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery assessment

Approved.

@uniqueg
uniqueg merged commit 3986da8 into dev Nov 4, 2026
56 checks passed
@uniqueg
uniqueg deleted the feat/623-id-config-pagination branch November 4, 2026 06:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: add IdConfig, locked fields, pagination

1 participant