Repository navigation
feat: add id config and pagination helpers - #676
Conversation
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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideThe 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 linkssequenceDiagram
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
Sequence diagram for locked runtime service-info fieldssequenceDiagram
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
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
Also describe the limits of offset pagination and of the default identifiers in the docs. Co-Authored-By: Claude Opus 5.5 <[email protected]>
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; forfoca.utils.misc.generate_id().foca.utils.pagination:get_page()checks offset and limit (400for invalid ones, larger limits are reduced tomax_limit),get_page_links()buildsfirst,prev,nextandlastfromserver.public_url, not theHostheader, keeping the path and other query parameters, andget_link_header()formats them as per RFC 8288.service_info.locked_fields: fields that onlyruntime_fieldsmay set. Refused inserviceat startup, and the service info fails if the function doesn't return them.docs/utilities.md,docs/configuration/service-info.md,docs/reference.md.Closes #623
For the maintainer
POST /service-infofrom the issue doesn't exist in FOCA, so nothing to lock there.locked_fields, off by default.Verification
ruff check,ruff format --check,mypy,mkdocs build --strict: pass.pytestwith coverage: 100 %. Locally,tests/factories/test_celery_worker_fork.py::test_no_client_opened_before_forkdepends on which checkout the shared virtual environment has installed; see CI for the run on this branch.skip()at the upper bound on MongoDB 7.0, not 8.Declined review findings
.inIdConfig.charsetwith 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.DEFAULT_PAGE_SIZE:foca.utilsdoesn't depend onfoca.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:
IdConfig, including validation for URL-safe character sets.Enhancements:
Documentation:
Tests: