Skip to content

✅ Add scope middleware test suite for context-api#201

Merged
taras merged 3 commits intomainfrom
tm/scope-middleware-tests
Mar 29, 2026
Merged

✅ Add scope middleware test suite for context-api#201
taras merged 3 commits intomainfrom
tm/scope-middleware-tests

Conversation

@taras
Copy link
Copy Markdown
Member

@taras taras commented Mar 26, 2026

Motivation

Effection 4.1 will introduce a new way to provide APIs with middleware built in. We @effectionx/context-api to serve as an upgrade path from Effection 3 to 4.1. The current implementation of @effectionx/context-api already provides most of the compatibility except for one specific use case: once a child scope called around(), it captured a merged snapshot of middleware state. If the parent added middleware afterward, the child did not observe that update.

Effection internals (v3 frame.context, v4 scope.contexts) model contexts as prototype chains, where descendant scopes should continue to see ancestor updates unless they intentionally override the same key locally. We want createApi().around() to match that behavior across both v3 and v4.

Approach

  • Added deterministic regression coverage in context-api/scope-middleware.test.ts for the missing scenario: child extends middleware first, then parent adds more middleware, and child must see both inherited and local layers.
  • Refactored context-api/mod.ts to stop storing pre-composed per-field snapshots in context.
  • around() now stores only per-scope middleware layers (max/min) on the current scope.
  • Operation invocation now computes middleware dynamically by reducing the scope context prototype chain at call time.
  • Added a cross-version internal adapter for scope context windows:
    • v4: scope.contexts
    • v3: scope.frame.context
  • Preserved existing ordering semantics (max outermost, min closest to core) and scope isolation guarantees.

Validation

  • node --env-file=.env --test context-api/scope-middleware.test.ts
  • node --env-file=.env --test context-api/context-api.test.ts
  • pnpm test:matrix (passes with effection 3.0.0 and 4.0.2 matrix entries)

Summary by CodeRabbit

  • Tests

    • Added comprehensive test suite validating middleware registration, inheritance, isolation, and composition across scoped and spawned execution contexts.
  • Refactor

    • Internal middleware registry restructured for improved scope-aware context handling and dynamic middleware aggregation.

Comprehensive cross-scope middleware behavior coverage with 14 tests:
inheritance, ordering, isolation, spawn semantics, arg/result
transformation, and handler-shape coverage across scopes.
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 26, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 1abf0227-a2ba-4f95-b2b5-8a789e262369

📥 Commits

Reviewing files that changed from the base of the PR and between ff8f8e4 and 7738358.

📒 Files selected for processing (1)
  • context-api/mod.ts

📝 Walkthrough

Walkthrough

Replaces per-field pre-composed middleware with runtime scope-based middleware collection/composition and adds a comprehensive BDD test suite validating scope middleware registration, inheritance, min/max ordering, isolation, spawn semantics, and cumulative transformations.

Changes

Cohort / File(s) Summary
Scope Middleware Tests
context-api/scope-middleware.test.ts
Adds an extensive BDD test suite covering api.around behavior: parent→child inheritance, min/max composition and ordering, enter/exit sequencing, scope isolation, spawn semantics (live updates & nested composition), and argument/result transformations across handler shapes.
Context API implementation
context-api/mod.ts
Reworks middleware storage to a scope-level { max, min }, removes pre-composed function, dynamically collects middleware per invocation via collectMiddleware(...), composes with combine([...max, ...min]), and makes around(...) scope-aware. Adds helpers: collectMiddleware, reducePrototypeChain, contextName, contextWindow, isRecord.

Sequence Diagram(s)

sequenceDiagram
participant Caller
participant Scope as Scope (current)
participant Collector as collectMiddleware
participant Composer as combine(...)
participant Middleware as MiddlewareStack
participant Handler

Caller->>Scope: request API field (useScope()/invoke)
Scope->>Collector: collectMiddleware(contextKey, field)
Collector->>Scope: traverse prototype chain, gather {max,min}
Collector->>Composer: return arrays
Composer->>Middleware: compose([...max, ...min])
Caller->>Middleware: invoke wrapper chain (enter)
Middleware->>Handler: call underlying handler (may spawn)
Handler-->>Middleware: return/result
Middleware->>Caller: unwind wrappers (exit)
note right of Handler: spawned tasks consult live Scope for middleware updates
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • cowboyd
  • jbolda

Important

Pre-merge checks failed

Please resolve all errors before merging. Addressing warnings is optional.

❌ Failed checks (1 error, 1 warning)

Check name Status Explanation Resolution
Policy Compliance ❌ Error PR modifies context-api/mod.ts with significant changes but does not include version bump in package.json, violating the Version Bump policy. Update context-api/package.json to bump version from 0.5.2 to 0.5.3 for the backward-compatible middleware refactor changes.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: adding a scope middleware test suite for context-api, which is the primary addition in the changeset.
Description check ✅ Passed The description includes both required sections (Motivation and Approach) with comprehensive detail on the problem, solution, and validation steps performed.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch tm/scope-middleware-tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@pkg-pr-new
Copy link
Copy Markdown

pkg-pr-new Bot commented Mar 26, 2026

Open in StackBlitz

npm i https://pkg.pr.new/@effectionx/context-api@201

commit: 7738358

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@context-api/mod.ts`:
- Around line 175-191: The contextWindow function currently reads undocumented
internals (scope.contexts and scope.frame.context); replace this with a safe
approach: first attempt to use any public Effection API for context
introspection (call the public getter if available), otherwise add explicit
runtime version/feature guards in contextWindow by detecting known Effection
versions or feature flags (e.g., check process.env or a runtime
Effection.version property) and then branch to the existing internal-path logic
only when the detected version matches a supported internal shape, returning a
clear, descriptive Error that names contextWindow and the detected version/shape
when unsupported; also add an integration test covering both v3(via
frame.context) and v4(via contexts) code paths and add a short doc note and an
issue in the repo to request a public API if missing.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 9ca3fedb-7a76-48b9-bbb5-e5ceb8786a14

📥 Commits

Reviewing files that changed from the base of the PR and between 7ee4d82 and ff8f8e4.

📒 Files selected for processing (2)
  • context-api/mod.ts
  • context-api/scope-middleware.test.ts

Comment thread context-api/mod.ts
@taras taras merged commit 6ba3546 into main Mar 29, 2026
7 checks passed
taras added a commit that referenced this pull request Mar 29, 2026
Version bump for scope middleware changes merged in #201.
taras added a commit that referenced this pull request Mar 29, 2026
Version bump for scope middleware changes merged in #201.
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.

1 participant