Skip to content
Merged
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
60 changes: 56 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,16 @@ in-memory tier and a durable storage-backed tier for expensive operations.

> [!IMPORTANT]
> Rate Limit is in early `0.x` development. Its public API is not stable.
> `@pegma/rate-limit@0.1.0` is the first advertised release, published from
> the protected signed `v0.1.0` tag through trusted-publisher OIDC with
> provenance. pegma.dev composes the durable tier in its production Identity
> worker.
> Current source is the **`0.3.0` candidate, not published**. Registry `0.2.0`
> predates the merged [PR #8 hardening](https://github.com/pegma-dev/rate-limit/pull/8)
> and the new bounded maintenance helper. The first advertised `0.1.0`
> release was published from protected signed `v0.1.0` through
> trusted-publisher OIDC with provenance; the historical `0.0.0` name bootstrap
> remains separate under `bootstrap`. pegma.dev composes the durable tier in
> its production Identity worker; this candidate is not a new host deployment.

The source behavior below describes the `0.3.0` candidate. Adoption waits for
its reviewed publication and the host's explicit configuration/storage transition.

## Two tiers, no pretending

Expand Down Expand Up @@ -49,6 +55,52 @@ Conflicting instances fail closed; rolling configuration changes use a
versioned policy name or a coordinated store reset. Sweeps retain ended windows
for a configurable clock-skew grace, 60 seconds by default.

## Bounded global durable maintenance (source candidate)

`sweepDurableWindowsPage` is exported from the package root and
`@pegma/rate-limit/durable`. It takes a Store and a required physical page
`limit`, optional opaque `cursor`, `clock`, and `maxClockSkewMs`, returning
`{ scanned, deleted, nextCursor }`. The
[source definition](packages/rate-limit/src/durable.ts) owns the exact types.
This is maintenance across all policies in that Store's rate-limit collection;
it requires no policy enumeration or live limiter instances.

Each call makes one scan of at most `limit` physical rows, including policy
descriptors, unrelated policies, malformed records, and unknown legacy rows.
It validates the page bound before filtering or keyed work, then makes at most
`limit` fresh descriptor reads and `limit` conditional deletes. Only a valid
new-format expired window whose identity matches its actual scan key, current
policy descriptor, and unchanged opaque version can be deleted. Descriptors,
legacy `0.2.0` rows, malformed rows, and policy mismatches remain stored.
Malformed stored payloads are distinct from invalid adapter page/row envelopes:
invalid envelopes and storage failures reject the call without skipping ahead.

Descriptor reads and deletes run sequentially. The row/call bounds provide no
wall-clock or deadline guarantee. Choose a small page limit that fits the real
provider's storage latency, execution-time and subrequest budgets.

The host persists the returned cursor unchanged after a successful page,
including a page that deletes nothing. On rejection it retains the previous
cursor and retries later; no completed page is reported. A mid-page failure
does not roll back earlier conditional deletions, and retrying from the prior
cursor can repeat work. Pages are not
snapshots, so repeat complete cycles. The helper applies its configured
clock-skew grace across the page, 60 seconds by default; choose a common grace
consistent with the host's peer-clock envelope. The helper itself leaves the
already-merged memory behavior, `allow()`, and per-policy `limiter.sweep()`
unchanged.

## Published `0.2.0` storage and configuration

Published `0.2.0` predates immutable policy descriptors and the new
`kind`/`limit`/`windowMs` counter layout. The candidate does not automatically
convert or clean up those legacy rows. Plan a versioned policy name or a
separate Store namespace, or coordinate a deliberate reset of the affected
policy storage. Do not silently reuse an old layout or overwrite a descriptor
to change limits. A new namespace/reset starts a separate count budget; the
host must plan the transition rather than assume old and new counts combine.
See the [package migration notes](packages/rate-limit/README.md#migrating-storage-and-policy-configuration).

Fixed windows have a documented edge: a burst crossing a boundary can briefly
admit nearly twice the configured limit. This package does not claim to be
DDoS or volumetric protection, and it does not provide HTTP middleware or
Expand Down
50 changes: 46 additions & 4 deletions docs/PROJECT_PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,14 @@
## Status

**Stage:** Phases 1, 2, and 4 are complete; Phase 3 has its first production
consumer. `@pegma/rate-limit@0.1.1` is published, and pegma.dev composes the
durable tier for its Identity surface. `0.2.0` is prepared, aligning
`@pegma/storage-core` at `0.4.0` across the stack. The public API remains
unstable.
consumer. Registry `@pegma/rate-limit@0.2.0` is published, and pegma.dev composes
the durable tier for its Identity surface. Current source is the **`0.3.0`
candidate, not published**, retaining exact Storage Core `0.4.0`. Published
`0.2.0` predates the already-merged [PR #8 hardening](https://github.com/pegma-dev/rate-limit/pull/8)
for immutable policy descriptors, counter kind/configuration bindings, and
clock-skew grace. The candidate includes that hardening plus bounded global
maintenance. The public API remains unstable; source completion is not a
publication or host-adoption receipt.

The exact reviewed `0.0.0` package-name bootstrap remains published under
`bootstrap`. The first advertised `0.1.0` release was published from the
Expand Down Expand Up @@ -183,6 +187,44 @@ collection over an injected Store). The memory tier must remain importable
without a Store — a host wanting only abuse-dampening should not construct
storage. TypeScript, vitest, the ecosystem's standard layout.

## `0.3.0` bounded-maintenance source candidate

`sweepDurableWindowsPage` is a root/durable export over the existing
`rate-limit-windows` collection. One call makes one physical global scan page,
bounded by the required `limit`, with at most that many fresh descriptor reads
and version-conditional deletes. Every returned row counts before filtering;
there is no policy enumeration or unbounded list behind the page API.
Reads and deletes are sequential; these bounds do not guarantee wall-clock
completion or a deadline. Hosts choose a small page limit that fits the real
provider's storage latency, execution-time and subrequest budgets.

Only structurally valid new-format expired windows whose identity matches the
actual scan key and current immutable descriptor are deletion candidates.
The exact captured window version must still match. Descriptors, legacy
`0.2.0` layouts, malformed rows, and unknown/mismatched policy state remain.
Malformed stored payloads are retained; invalid adapter page/row envelopes and
storage failures reject rather than skip/advance.
Grace defaults to 60 seconds and is explicit host configuration across the
global pass. Adding this helper leaves the already-merged memory-tier and
existing `allow()`/per-policy sweep behavior unchanged.

Hosts own cursor retention and scheduling. Preserve the opaque continuation
after each successful page, including no-deletion pages; retain the previous
cursor after an error. Pages are not snapshots, so repeat full cycles. The
earlier conditional deletions from a failed page are not rolled back;
retrying from the previous cursor can repeat work. The
[source API](../packages/rate-limit/src/durable.ts) and
[package contract](../packages/rate-limit/README.md#bounded-global-cleanup)
define the interface; current-head gates, review, exact publication, and host
adoption remain release work.

Upgrading existing durable data is deliberate: use versioned policy names or
an isolated Store namespace, or coordinate a policy-store reset. Immutable
descriptors bind `limit` and `windowMs`; neither conflicting configuration nor
the old published layout is silently rewritten or reused. The global helper
retains legacy rows rather than migrating them. New namespaces/resets do not
carry over or aggregate old counters automatically.

## Delivery phases

### Phase 1 — port and memory tier
Expand Down
89 changes: 86 additions & 3 deletions packages/rate-limit/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,17 @@ Two explicitly named application rate-limit tiers:
abuse-critical operations.

> [!IMPORTANT]
> `0.1.0` is the first advertised release, published through
> Current source is the **`0.3.0` candidate, not published**. Published `0.2.0`
> predates the merged descriptor/configuration hardening and the bounded
> global sweep described here. `0.1.0` was the first advertised release, published through
> trusted-publisher OIDC with provenance. The exact reviewed `0.0.0`
> package-name bootstrap remains isolated under the `bootstrap` dist-tag and
> is never advertised as the current supported release.

The API and storage behavior below describe candidate source. Use an exact
published version only after its release verification and an explicit host
storage/configuration transition.

There is no default tier and no automatic upgrade. This package is application
abuse control, not DDoS protection, HTTP middleware, or billing metering.
Policy names and limiter keys must be primitive, non-blank strings. Whitespace
Expand Down Expand Up @@ -107,14 +113,91 @@ The durable tier uses fixed windows. A burst across a boundary can briefly
admit nearly twice the limit. It also puts shared-storage latency on every
allowed check; do not use it for hot, cheap endpoints.

Sweeps list one policy partition and delete structurally valid expired rows
The existing `limiter.sweep()` lists one policy partition and deletes structurally valid expired rows
only if their versions are unchanged. By default a row remains for 60 seconds
after its window ends; `maxClockSkewMs` can set a different bounded,
non-negative grace for hosts with a known clock envelope. Malformed rows are retained:
storage-core listings do not expose actual row keys, so pairing a malformed
that partition-listing API does not expose actual row keys, so pairing a malformed
row's version with a key reconstructed from its payload could target another
row. Checks against that malformed row still fail closed.

## Bounded global cleanup

The candidate adds this interface at the root and durable subpath, defined in
[the actual source](src/durable.ts):

```ts
export declare function sweepDurableWindowsPage(
store: Store,
options: DurableWindowsSweepOptions,
): Promise<DurableWindowsSweepPage>;
```

`options.limit` is required: a safe integer from 1 through Storage Core's
`MAX_SCAN_PAGE_SIZE` (1,000). Other options are an opaque nonempty `cursor`,
an optional Spine `clock`, and non-negative safe-integer `maxClockSkewMs`.
The result is `{ scanned: number, deleted: number, nextCursor: string | null }`.
This is a source API signature, not an execution example or publication receipt.

One call scans one global physical page of `rate-limit-windows`, without a
policy filter, partition enumeration, `list`, or `listVersioned`. `scanned`
counts every adapter-returned row before filtering, even descriptors, unknown
legacy layouts, malformed stored payloads, and policies the current host no
longer constructs. A nonconforming adapter page/row envelope rejects instead
Comment thread
FlyOverCoderKY marked this conversation as resolved.
Resolved
of being treated as a malformed stored payload to skip. Physical page
validation runs before descriptor reads or deletes. There are at most `limit`
fresh descriptor reads and `limit` `deleteIfUnchanged` calls.

Those calls run sequentially. These are row/call bounds, with no wall-clock or
deadline guarantee. Hosts should choose a small page limit using the real
provider's storage latency, execution-time and subrequest budgets.

Deletion requires a structurally valid new-format `window` with valid hashes,
canonical window ID, aligned start, count within its stored limit, and a safe
expiry. Its decoded partition/ID must match the actual scan key. The current
descriptor is read by that authoritative key for each candidate and must match
the exact policy kind/key/hash, descriptor null fields, `limit`, and `windowMs`.
Only the captured unchanged window version is deleted. This is conditional
maintenance, not an atomic snapshot across descriptors and windows.

Expiry is `windowStartMs + windowMs + maxClockSkewMs <= now`. The clock must
return a canonical timestamp; the sum must be a safe integer. The default
grace is 60,000 ms; explicit zero is supported. The global helper applies its
own grace to every policy it encounters, so the host chooses one that covers
its peer-clock envelope. Descriptors, legacy `0.2.0` rows, malformed windows,
unknown kinds, missing/mismatched descriptors, and changed window versions are
retained.

Persist `nextCursor` unchanged only after success, including pages with no
deletions. Null ends that cycle; it does not prove no concurrent/new rows exist.
Repeat complete cycles for ongoing hygiene. Invalid adapter envelopes and
storage or time failures reject without a completed page or new cursor;
retain the previous cursor on failure. A mid-page failure does not roll back
conditional deletions that already succeeded. Retrying from the prior cursor
can repeat reads and deletion attempts.
The helper itself does not change the already-merged memory behavior,
`allow()` admission, or the existing per-policy sweep.

## Migrating storage and policy configuration

Registry `0.2.0` is older than the descriptor and `kind`/`limit`/`windowMs`
hardening already merged on main. Sharing its version label or policy name
does not make legacy counter rows compatible with this candidate. Neither
the limiter nor global cleanup silently migrates the old layout; unknown
legacy rows remain, and malformed encountered counter state fails closed.

Select versioned policy names or a separate Store namespace for the new
configuration, or coordinate an explicit reset of the affected policy storage.
New names/namespaces and resets start independent count budgets; plan the
cutover and old-data retention rather than assuming counts carry over or add
together across deployments. The package supplies no automatic migration/reset.

Once a descriptor exists, its policy name is bound immutably to `limit` and
`windowMs`. Changing either requires another versioned name or a coordinated
reset; conflicting instances fail closed. Do not edit descriptors in place,
delete arbitrary malformed rows, or mistake the global sweep for a migration
of previously published `0.2.0` data.

## License

MIT
2 changes: 1 addition & 1 deletion packages/rate-limit/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@pegma/rate-limit",
"version": "0.2.0",
"version": "0.3.0",
"description": "Explicit per-instance sliding-window and shared durable fixed-window rate limiters.",
"license": "MIT",
"type": "module",
Expand Down
Loading
Loading