# Paginate by page, range or cursor

Normalize bounded requests and build look-ahead results without mandatory totals.

Status: supplied in **0.15.0**. Version 0.14.0
contains only the existing `PagedResult<T>` numbered-page response; it does not
contain the APIs described below. Consumer adoption remains explicit.

## Contracts and endpoint policy

`Fabricators.Kernel.Common.Pagination` supplies `PaginationInput`, `PaginationPolicy`,
`PaginationParser`, validated immutable requests and result builders. It has
no HTTP, EF, DI or database dependency. The optional
`Fabricators.Kernel.AspNetCore.PaginationQuery.ReadPagination` adapter reads
query parameters and delegates to the same parser.

| Input | Normalized request | Semantics |
| --- | --- | --- |
| `page=2&pageSize=50` | `PageRequest` | One-based pages; offset 50, limit 50. |
| `from=50&to=100` | `RangeRequest` | Zero-based positions, exclusive upper bound; offset 50, limit 50. |
| `after=<opaque>&limit=50` | `CursorRequest` | Continue after an application-decoded position; limit 50. |

An endpoint declares supported modes and a default. With no parameters, the
default Page request starts at page 1; Range starts at `[0, defaultSize)`;
Cursor starts without `after`. A supplied `limit` selects Cursor, while
`pageSize` selects Page. Mixing any fields from different modes fails rather
than silently choosing one. Both `from` and `to` are required for an explicit
range. A range refers to row positions, not dates.

```csharp
var policy = new PaginationPolicy(
    defaultMode: PaginationMode.Cursor,
    supportedModes: PaginationModes.Cursor,
    defaultSize: 50,
    maximumSize: 100);
Result<PaginationRequest> parsed = http.Request.ReadPagination(policy);
if (parsed.IsFailure)
{
    return parsed.ToApiResult();
}
```

The example uses `Fabricators.Kernel.Common`, `Fabricators.Kernel.Common.Pagination` and
`Fabricators.Kernel.AspNetCore`; `http` is an authenticated product endpoint's
`HttpContext`. Pagination itself does not authenticate or authorize callers.

Default policy: page mode, all three modes supported, size 50, maximum size
200, maximum offset 1,000,000 and maximum cursor length 2,048 characters.
Override these per endpoint. Invalid policy configuration throws at startup.
Invalid input returns validation error `Pagination.InvalidRequest` without
clamping or echoing input. Standard `ToApiResult` maps validation to HTTP 422;
products retain their existing HTTP mapping/compatibility policy explicitly.

Page/range calculations use wide arithmetic before conversion to database
offsets. Zero/negative sizes, overflow, excessive offsets and unsupported modes
are rejected. The HTTP adapter also rejects duplicate pagination keys,
empty values, signs, whitespace, non-ASCII decimal digits and integer overflow.
Application filter keys remain application-owned, not rejected by this helper.

## Query and result construction

Every normalized request provides `Limit` and `WindowSize = Limit + 1`. Apply
authorization and filters first, then a deterministic order and a bounded query.
For `OffsetPaginationRequest`, use its validated `Offset` and `WindowSize`.
For Cursor, validate/decode `After` and apply the corresponding keyset predicate.
Foundation does not generate that predicate or execute a COUNT query.

Pass the ordered result window to:

- `OffsetPage<T>.FromWindow(request, window, totalCount: null)` for Page/Range.
- `CursorPage<T>.FromWindow(request, window, createCursor, totalCount: null)`
  for Cursor.

Only `Limit` rows are returned; the extra look-ahead row determines `HasMore`.
The cursor factory receives the **last returned row**, not the extra row, so
continuation does not skip an item. It is not called on the final/empty page.
`NextCursor` is null on those pages. Result item lists are copied and readonly.
Oversized windows, invalid generated cursors and inconsistent supplied counts
fail as caller/programming errors, not silently truncated query mistakes.

Totals are optional nullable `long`; no mandatory COUNT is introduced. Offset
results expose exact `TotalPages` when a total is supplied. A total must describe
the same authorization/filter/snapshot as the rows; omit it if that cannot be
guaranteed. Empty requests beyond the last offset are supported. The existing
`PagedResult<T>` constructor/properties/JSON are unchanged for compatibility;
it remains the legacy int-count response, not the normalized request model.

## Ordering, cursor ownership and freshness

Always include a stable unique tie-breaker: for example `(CreatedAt, Id)`.
A single-field timestamp sort can skip or duplicate equal timestamps. Offset
pagination supports direct page access but can shift when rows are inserted or
deleted. A cursor avoids growing OFFSET work; it does not itself provide a
cross-request snapshot or freeze mutable sort fields.

Treat cursors as opaque, untrusted input. Foundation bounds their length and
rejects whitespace/control characters; it does not interpret, sign or encrypt
application positions. Products must validate their version, order/filter and
tenant/company scope. Use a scoped protected token when those bindings must be
tamper-resistant; include resource/version bounds when promising stable scans.
Recheck current authorization on every page regardless of cursor protection.
Never use an in-memory authorization cache or cursor claim to preserve a
revoked permission, and never expose an unauthorized total count.

An endpoint may support only one mode when appropriate; Foundation supports
all three without imposing all three on every route. Export scans and mutable
feeds must document their stronger consistency/resumption contract separately.

## Verification and adoption

Unit/HTTP tests cover equivalent page/range offsets, exclusive bounds,
conflicting/unsupported inputs, defaults, overflow, cursor/window bounds,
look-ahead continuation without skipping, optional large totals, result
immutability and legacy JSON compatibility. The independently packed pure
consumer exercises these APIs without EF/ASP.NET references.

ERP's current `after=<UUID>`/`nextAfter` workspace API remains an existing local
wire contract until a coordinated release/adoption with its BFF and SDK. This
increment does not silently change a deployed ERP or IC route.

Local acceptance: the complete source/style/layout/semantic-unused-using gate,
Release build, documentation export/determinism and 30 independently packed
package/tool consumers passed. There are 23 new pagination tests (seven kernel
cases and 16 HTTP cases). The full SDK run passes 582 tests; the dedicated
PostgreSQL gate additionally passes all 14 database cases, yielding 596 distinct
passing tests. No production dependency or persistent schema was changed.
