Skip to content

refactor: remove legacy DI wrapper signatures (#656 PR A) - #663

Merged
grunch merged 5 commits into
mainfrom
cleanup/remove-legacy-wrappers-656
Mar 17, 2026
Merged

refactor: remove legacy DI wrapper signatures (#656 PR A)#663
grunch merged 5 commits into
mainfrom
cleanup/remove-legacy-wrappers-656

Conversation

@mostronatorcoder

@mostronatorcoder mostronatorcoder Bot commented Mar 13, 2026

Copy link
Copy Markdown
Contributor

Context

Issue #656 tracks cleanup tasks after phase-5 DI migration (#639) is complete.

This PR implements PR A from the #656 checklist: removal of legacy entrypoints.

Changes

After phase 5, all handlers have two signatures:

  • *_action_with_ctx(ctx, ...) — DI entrypoint ✅
  • *_action(pool, ...) — legacy wrapper ❌

This PR:

  • ✅ Deletes all *_action(pool, ...) wrappers that only delegate
  • ✅ Renames *_action_with_ctx*_action (removes _with_ctx suffix)
  • ✅ Updates dispatcher imports and call sites
  • ✅ Fixes test signatures to use AppContext instead of raw pool
  • ✅ Updates RPC service to construct AppContext via from_globals()

Files Modified (19 total)

Handlers (16):

  • src/app/add_invoice.rs
  • src/app/admin_add_solver.rs
  • src/app/admin_cancel.rs
  • src/app/admin_settle.rs
  • src/app/admin_take_dispute.rs
  • src/app/cancel.rs
  • src/app/dispute.rs
  • src/app/fiat_sent.rs
  • src/app/last_trade_index.rs
  • src/app/order.rs
  • src/app/orders.rs
  • src/app/rate_user.rs
  • src/app/release.rs
  • src/app/restore_session.rs
  • src/app/take_buy.rs
  • src/app/take_sell.rs
  • src/app/trade_pubkey.rs

Dispatcher + RPC (2):

  • src/app.rs (dispatcher imports and routing)
  • src/rpc/service.rs (admin RPC handlers)

Auxiliary:

  • Added use sqlx::{Pool, Sqlite}; to internal helper functions where needed

Impact

Before:

pub async fn order_action_with_ctx(ctx: &AppContext, ...) { ... }
pub async fn order_action(pool: &Pool<Sqlite>, ...) { ... }  // wrapper

After:

pub async fn order_action(ctx: &AppContext, ...) { ... }
// no wrapper

Diff stats:

  • 19 files changed
  • +145 / -263 lines
  • Net: -118 lines (removed scaffolding)

Validation

cargo fmt
cargo clippy --all-targets --all-features -- -D warnings (0 warnings)
cargo test --bin mostrod (189 passed, 0 failed)

Related

Next Steps

After merge:

  • PR B: simplify dispatcher (remove pool parameter)
  • PR C: eliminate remaining global accesses in handlers
  • PR D (optional): finalize AppContext::from_globals()

Summary by CodeRabbit

Release Notes

  • Refactor
    • Internal consolidation of application context handling. Database pool management has been optimized to use a centralized context mechanism, streamlining action handler signatures across the platform. These changes improve code consistency and maintainability without affecting user-facing functionality.

Remove migration scaffolding after phase-5 DI completion:

- Delete all `*_action(pool, ...)` wrappers that only delegate to ctx
- Rename `*_action_with_ctx(ctx, ...)` → `*_action(ctx, ...)`
- Update dispatcher imports and call sites in src/app.rs
- Fix test call sites to use AppContext instead of raw pool
- Update RPC service to build AppContext via from_globals()
- Add required Pool/Sqlite imports for internal helper functions

Files modified (18 total):
- 16 handler modules (add_invoice, admin_*, cancel, dispute, etc.)
- src/app.rs (dispatcher)
- src/rpc/service.rs (admin RPC handlers)

All handlers now accept `&AppContext` as first parameter with no
legacy pool-based wrappers remaining.

Related: #656 (cleanup after #639 phase 5)

Validation:
- cargo fmt ✅
- cargo clippy --all-targets --all-features -- -D warnings ✅
- cargo test --bin mostrod ✅ (189 passed, 0 failed)
@grunch
grunch requested review from Catrya, arkanoider and grunch and removed request for grunch March 13, 2026 14:00
@grunch

grunch commented Mar 13, 2026

Copy link
Copy Markdown
Member

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Mar 13, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai

coderabbitai Bot commented Mar 13, 2026

Copy link
Copy Markdown
Contributor

Important

Review skipped

Bot user detected.

To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e5780505-a3c5-40f9-8486-b8e25f6be598

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Walkthrough

This PR refactors public action handler signatures across the application to remove explicit pool parameters and eliminate _with_ctx wrapper functions. Handlers now derive the database pool internally from AppContext via ctx.pool(), consolidating pool acquisition and simplifying the public API surface.

Changes

Cohort / File(s) Summary
Main Application Routing
src/app.rs
Updated action routing to call non-ctx handler variants (e.g., order_action instead of order_action_with_ctx). Routes unchanged for NewOrder, TakeSell, TakeBuy, FiatSent, AddInvoice, and other actions; now delegates to refactored handlers without explicit pool parameter.
Admin Action Handlers
src/app/admin_add_solver.rs, src/app/admin_cancel.rs, src/app/admin_settle.rs, src/app/admin_take_dispute.rs
Removed wrapper functions and updated public signatures to remove pool parameter. Handlers now obtain pool via ctx.pool() internally; control flow preserved.
User-Facing Action Handlers
src/app/add_invoice.rs, src/app/dispute.rs, src/app/fiat_sent.rs, src/app/order.rs, src/app/orders.rs, src/app/restore_session.rs, src/app/trade_pubkey.rs
Removed _with_ctx wrappers and eliminated explicit pool parameters from public function signatures. Pool now derived from context within each handler.
Trading Action Handlers
src/app/take_buy.rs, src/app/take_sell.rs, src/app/cancel.rs, src/app/release.rs
Removed wrapper functions; updated signatures to drop pool parameter and obtain it from ctx.pool() internally. Tests migrated to use AppContext.
Utility Handlers
src/app/last_trade_index.rs, src/app/rate_user.rs
Refactored to accept AppContext and derive pool internally. Removed _with_ctx wrappers; tests updated to use context-based calls.
RPC Service Integration
src/rpc/service.rs
Updated admin action call sites to construct AppContext per-call and pass context to handlers instead of passing self.pool directly. Added #[allow(dead_code)] on pool field in AdminServiceImpl.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • arkanoider
  • Catrya

Poem

🐰 Wrapper functions fade away,
Pool flows from context, here to stay,
Cleaner signatures, less to pass,
AppContext reigns—refactoring class!
No more _with_ctx, just pure and true,
Mostro's API shines anew! ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'refactor: remove legacy DI wrapper signatures' directly and clearly describes the primary change in this PR: systematically removing legacy wrapper functions and renaming DI entrypoints by dropping the _with_ctx suffix.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch cleanup/remove-legacy-wrappers-656
📝 Coding Plan
  • Generate coding plan for human review comments

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (6)
src/app/release.rs (1)

112-119: ⚠️ Potential issue | 🟡 Minor

Update the release_action docs to match the new parameters.

The signature now takes ctx and no longer takes pool, but the /// # Arguments block above still documents pool and omits ctx.

📝 Suggested doc update
-/// * `msg` - The message containing the release request and associated metadata
-/// * `event` - The unwrapped gift event containing the seller's signature and verification data
-/// * `my_keys` - Mostro node's keys used for signing events and messages
-/// * `pool` - Database connection pool for order updates
+/// * `ctx` - Application context used to resolve shared dependencies like the database pool
+/// * `msg` - The message containing the release request and associated metadata
+/// * `event` - The unwrapped gift event containing the seller's signature and verification data
+/// * `my_keys` - Mostro node's keys used for signing events and messages
 /// * `ln_client` - Lightning network client for invoice settlement

As per coding guidelines, "Document non-obvious public APIs with /// doc comments".

Also applies to: 160-167

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/app/release.rs` around lines 112 - 119, Update the doc comment for the
release_action function to reflect the new parameter list: remove the outdated
`pool` entry and add a description for the `ctx` parameter (the
execution/context object now passed into release_action); update both `/// #
Arguments` blocks that describe release_action (the earlier block and the later
block around the other occurrence) so they list `msg`, `event`, `my_keys`,
`ctx`, and `ln_client` with brief descriptions matching their roles.
src/app/order.rs (1)

56-84: ⚠️ Potential issue | 🟡 Minor

Update the order_action docs to the ctx-based API.

The /// above still lists a pool argument and the example calls the removed order_action(..., &pool) form. Please sync the parameter docs and example with order_action(&ctx, msg, &event, &my_keys).

As per coding guidelines, "Document non-obvious public APIs with /// doc comments".

Also applies to: 85-91

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/app/order.rs` around lines 56 - 84, Update the order_action documentation
and example to reflect the ctx-based API: replace the parameter list and
narrative that mention `pool` with the new signature `order_action(&ctx, msg,
&event, &my_keys)`, update the parameter section to describe `ctx` instead of
`pool`, and modify the example invocation to call `order_action(&ctx, msg,
&event, &my_keys).await?`; ensure references to `msg`, `event`, and `my_keys`
remain correct and adjust any surrounding text that described `pool` to refer to
`ctx` semantics (e.g., database access via ctx).
src/app/rate_user.rs (1)

48-58: ⚠️ Potential issue | 🟡 Minor

Sync the doc comment with the new signature.

The public docs still advertise a pool parameter, but callers now provide ctx: &AppContext. Leaving the old parameter list here points integrators to the removed API.

As per coding guidelines, "Document non-obvious public APIs with /// doc comments".

Also applies to: 71-77

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/app/rate_user.rs` around lines 48 - 58, The doc comment for the public
function rate_user is out of sync: it still documents a removed pool parameter
instead of the current ctx: &AppContext signature; update the triple-slash docs
above rate_user (and the subsequent doc block that mirrors it) to list the
correct parameters (msg, event, my_keys, ctx: &AppContext) and their meanings
and update the Returns section if the return type changed, ensuring the public
API docs accurately reflect the new function signature and not the old pool
parameter.
src/app/last_trade_index.rs (1)

14-29: ⚠️ Potential issue | 🟡 Minor

Update the parameter docs for last_trade_index.

The doc block still documents pool, but this entry point now pulls it from ctx. The public API docs are out of sync with the implementation.

As per coding guidelines, "Document non-obvious public APIs with /// doc comments".

Also applies to: 44-50

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/app/last_trade_index.rs` around lines 14 - 29, The doc comment for the
public function last_trade_index is out of sync: it still documents a `pool`
parameter though the function now obtains the DB pool from `ctx`; update the
`///` parameter docs to remove `pool`, add an entry describing `ctx` (what it
contains, e.g., DB pool and other contextual data), and ensure any other
parameter docs (e.g., `msg`, `event`, `my_keys`) remain accurate; also apply the
same update to the duplicate doc block later (the one covering lines noted in
the review) so the public API docs reflect the current function signature and
data flow.
src/app/cancel.rs (1)

348-360: ⚠️ Potential issue | 🟡 Minor

Remove the stale legacy-wrapper note.

The /// above cancel_action still says callers can use a pool-based legacy wrapper, but this PR deletes that path. That note now points readers to an API that no longer exists.

As per coding guidelines, "Document non-obvious public APIs with /// doc comments".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/app/cancel.rs` around lines 348 - 360, The doc comment for cancel_action
is outdated: remove the sentence saying callers can use the legacy
[`cancel_action`] wrapper and any mention of passing `pool` directly (that API
no longer exists) and instead leave a short, accurate note that this is the
preferred entry point and that the connection pool is extracted from AppContext;
keep the reference to the internal helper cancel_action_generic if desired but
delete the stale legacy-wrapper note.
src/app/trade_pubkey.rs (1)

25-46: ⚠️ Potential issue | 🟠 Major

Stop decrypting master_*_pubkey here.

After the phase-3/4 migration those columns are already stored in plaintext, so CryptoUtils::decrypt_data(...) will reject valid rows or compare against the wrong value. This flow should compare the stored master key directly to event.sender.

🛠️ Proposed fix
-    // Get master keys decrypted
+    // Master keys are stored in plaintext after the phase-3/4 migration.
     let (master_buyer_key, master_seller_key) = if order.master_buyer_pubkey.is_some() {
-        let master_buyer_key = CryptoUtils::decrypt_data(
-            order
-                .get_master_buyer_pubkey(None)
-                .map_err(MostroInternalErr)?
-                .to_string(),
-            None,
-        )
-        .map_err(MostroInternalErr)?;
+        let master_buyer_key = order
+            .get_master_buyer_pubkey(None)
+            .map_err(MostroInternalErr)?
+            .to_string();
         (Some(master_buyer_key), None)
     } else {
-        let master_seller_key = CryptoUtils::decrypt_data(
-            order
-                .get_master_seller_pubkey(None)
-                .map_err(MostroInternalErr)?
-                .to_string(),
-            None,
-        )
-        .map_err(MostroInternalErr)?;
+        let master_seller_key = order
+            .get_master_seller_pubkey(None)
+            .map_err(MostroInternalErr)?
+            .to_string();
         (None, Some(master_seller_key))
     };
Based on learnings, "After Phase 3 is applied, no in-memory decryption fallback is needed for these columns; direct comparison is correct."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/app/trade_pubkey.rs` around lines 25 - 46, The current code decrypts
master_buyer_pubkey/master_seller_pubkey using CryptoUtils::decrypt_data which
is no longer correct after phase-3/4; instead, remove the decryption calls and
simply read order.get_master_buyer_pubkey(None) and
order.get_master_seller_pubkey(None) (handling the Option via map or pattern
match) and assign those plaintext values to master_buyer_key/master_seller_key
(Some(value) or None) so you can directly compare them to event.sender;
eliminate any use of CryptoUtils::decrypt_data in this flow and keep the
existing MostroInternalErr mapping around the get_master_* calls.
🧹 Nitpick comments (2)
src/app/take_sell.rs (1)

206-210: Extract the repeated test-context fixture.

The same TestContextBuilder setup is copied into each async test, so any future pool/settings tweak now needs multiple edits. A small helper would keep these structural tests easier to maintain.

Also applies to: 219-219, 227-231, 239-239, 246-250, 258-258, 267-267, 273-273, 280-284, 292-292, 299-303, 309-309, 314-314

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/app/take_sell.rs` around lines 206 - 210, Extract the repeated
TestContextBuilder setup into a single helper function (e.g., new_test_context
or build_test_context) that accepts the pool (or Arc<Pool>) and returns the
built context; replace each duplicated block that calls
TestContextBuilder::new().with_pool(...).with_settings(test_settings()).build()
with a call to this helper; ensure the helper references TestContextBuilder,
test_settings, and takes/uses the same pool type (std::sync::Arc and
pool.clone() where needed) so all tests use the centralized fixture.
src/app/admin_cancel.rs (1)

16-23: Document the new AppContext-based entrypoint.

This public handler's contract changed substantially, but it still has no /// docs explaining what the caller must provide in ctx or that it mutates DB, LN, and DM state.

📝 Suggested doc stub
+/// Cancels an order from the admin dispute flow using dependencies provided by `ctx`.
+/// The caller must supply an initialized `AppContext`; this handler updates DB state,
+/// may cancel the hold invoice, and notifies the affected peers.
 pub async fn admin_cancel_action(
As per coding guidelines, "Document non-obvious public APIs with `///` doc comments".
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/app/admin_cancel.rs` around lines 16 - 23, Add a concise /// doc comment
for the public handler function admin_cancel_action describing the expected
contract: that ctx: &AppContext must provide a populated DB pool/connection and
any needed config/state (e.g., authenticated user/session), what each parameter
represents (msg: Message, event: &UnwrappedGift, my_keys: &Keys, ln_client: &mut
LndConnector), that the function mutates persistent state (database), interacts
with the Lightning node (LN) and the direct message system (DM), the kinds of
side effects performed (cancelling gifts, updating DB rows, sending DM/LN
calls), and the error behavior/return type (Result<(), MostroError>) so callers
know to handle failures and any transactional expectations.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/rpc/service.rs`:
- Around line 22-23: The AdminServiceImpl is ignoring its injected DB pool by
calling AppContext::from_globals()/get_db_pool(); update the code to construct
the AppContext using the instance field pool (Arc<Pool<Sqlite>>) held on self
instead of using AppContext::from_globals(), or alternatively remove the pool
parameter/field from AdminServiceImpl::new and the struct if you intend to rely
on globals; make the same change for all sites that build AppContext (the
occurrences that currently call AppContext::from_globals()/get_db_pool()), so
the admin paths use the injected pool rather than the global.

---

Outside diff comments:
In `@src/app/cancel.rs`:
- Around line 348-360: The doc comment for cancel_action is outdated: remove the
sentence saying callers can use the legacy [`cancel_action`] wrapper and any
mention of passing `pool` directly (that API no longer exists) and instead leave
a short, accurate note that this is the preferred entry point and that the
connection pool is extracted from AppContext; keep the reference to the internal
helper cancel_action_generic if desired but delete the stale legacy-wrapper
note.

In `@src/app/last_trade_index.rs`:
- Around line 14-29: The doc comment for the public function last_trade_index is
out of sync: it still documents a `pool` parameter though the function now
obtains the DB pool from `ctx`; update the `///` parameter docs to remove
`pool`, add an entry describing `ctx` (what it contains, e.g., DB pool and other
contextual data), and ensure any other parameter docs (e.g., `msg`, `event`,
`my_keys`) remain accurate; also apply the same update to the duplicate doc
block later (the one covering lines noted in the review) so the public API docs
reflect the current function signature and data flow.

In `@src/app/order.rs`:
- Around line 56-84: Update the order_action documentation and example to
reflect the ctx-based API: replace the parameter list and narrative that mention
`pool` with the new signature `order_action(&ctx, msg, &event, &my_keys)`,
update the parameter section to describe `ctx` instead of `pool`, and modify the
example invocation to call `order_action(&ctx, msg, &event, &my_keys).await?`;
ensure references to `msg`, `event`, and `my_keys` remain correct and adjust any
surrounding text that described `pool` to refer to `ctx` semantics (e.g.,
database access via ctx).

In `@src/app/rate_user.rs`:
- Around line 48-58: The doc comment for the public function rate_user is out of
sync: it still documents a removed pool parameter instead of the current ctx:
&AppContext signature; update the triple-slash docs above rate_user (and the
subsequent doc block that mirrors it) to list the correct parameters (msg,
event, my_keys, ctx: &AppContext) and their meanings and update the Returns
section if the return type changed, ensuring the public API docs accurately
reflect the new function signature and not the old pool parameter.

In `@src/app/release.rs`:
- Around line 112-119: Update the doc comment for the release_action function to
reflect the new parameter list: remove the outdated `pool` entry and add a
description for the `ctx` parameter (the execution/context object now passed
into release_action); update both `/// # Arguments` blocks that describe
release_action (the earlier block and the later block around the other
occurrence) so they list `msg`, `event`, `my_keys`, `ctx`, and `ln_client` with
brief descriptions matching their roles.

In `@src/app/trade_pubkey.rs`:
- Around line 25-46: The current code decrypts
master_buyer_pubkey/master_seller_pubkey using CryptoUtils::decrypt_data which
is no longer correct after phase-3/4; instead, remove the decryption calls and
simply read order.get_master_buyer_pubkey(None) and
order.get_master_seller_pubkey(None) (handling the Option via map or pattern
match) and assign those plaintext values to master_buyer_key/master_seller_key
(Some(value) or None) so you can directly compare them to event.sender;
eliminate any use of CryptoUtils::decrypt_data in this flow and keep the
existing MostroInternalErr mapping around the get_master_* calls.

---

Nitpick comments:
In `@src/app/admin_cancel.rs`:
- Around line 16-23: Add a concise /// doc comment for the public handler
function admin_cancel_action describing the expected contract: that ctx:
&AppContext must provide a populated DB pool/connection and any needed
config/state (e.g., authenticated user/session), what each parameter represents
(msg: Message, event: &UnwrappedGift, my_keys: &Keys, ln_client: &mut
LndConnector), that the function mutates persistent state (database), interacts
with the Lightning node (LN) and the direct message system (DM), the kinds of
side effects performed (cancelling gifts, updating DB rows, sending DM/LN
calls), and the error behavior/return type (Result<(), MostroError>) so callers
know to handle failures and any transactional expectations.

In `@src/app/take_sell.rs`:
- Around line 206-210: Extract the repeated TestContextBuilder setup into a
single helper function (e.g., new_test_context or build_test_context) that
accepts the pool (or Arc<Pool>) and returns the built context; replace each
duplicated block that calls
TestContextBuilder::new().with_pool(...).with_settings(test_settings()).build()
with a call to this helper; ensure the helper references TestContextBuilder,
test_settings, and takes/uses the same pool type (std::sync::Arc and
pool.clone() where needed) so all tests use the centralized fixture.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 196969f8-9193-4cbe-bf4a-6b4471e0e3da

📥 Commits

Reviewing files that changed from the base of the PR and between 54d053b and 35e3f13.

📒 Files selected for processing (19)
  • src/app.rs
  • src/app/add_invoice.rs
  • src/app/admin_add_solver.rs
  • src/app/admin_cancel.rs
  • src/app/admin_settle.rs
  • src/app/admin_take_dispute.rs
  • src/app/cancel.rs
  • src/app/dispute.rs
  • src/app/fiat_sent.rs
  • src/app/last_trade_index.rs
  • src/app/order.rs
  • src/app/orders.rs
  • src/app/rate_user.rs
  • src/app/release.rs
  • src/app/restore_session.rs
  • src/app/take_buy.rs
  • src/app/take_sell.rs
  • src/app/trade_pubkey.rs
  • src/rpc/service.rs

Comment thread src/rpc/service.rs Outdated
- RPC service now uses injected pool instead of from_globals()
  - Construct AppContext explicitly with self.pool in all admin methods
  - Remove #[allow(dead_code)] from pool field (now used)

- Update outdated doc comments to reflect ctx-based signatures:
  - cancel.rs: remove legacy wrapper mention
  - last_trade_index.rs: document ctx parameter instead of pool
  - order.rs: update params list and example to use ctx
  - rate_user.rs: document ctx instead of pool
  - release.rs: document ctx parameter

All documentation now accurately reflects the current API.
@mostronatorcoder

Copy link
Copy Markdown
Contributor Author

Addressed all CodeRabbit feedback in a58682c:

RPC service fix

  • AdminServiceImpl now constructs AppContext using the injected self.pool instead of calling from_globals()
  • ✅ Removed #[allow(dead_code)] from pool field (now actively used)
  • Applied to all 4 admin methods: call_admin_cancel, call_admin_settle, call_admin_add_solver, call_admin_take_dispute

Documentation updates

Fixed outdated doc comments to reflect current ctx-based API:

  • cancel.rs: removed stale legacy wrapper mention
  • last_trade_index.rs: documented ctx parameter instead of removed pool
  • order.rs: updated params list and example to use &ctx
  • rate_user.rs: documented ctx instead of pool
  • release.rs: documented ctx parameter

All documentation now accurately reflects the current function signatures.


Validation:

  • cargo clippy --all-targets --all-features -- -D warnings → ✅ 0 warnings

- trade_pubkey.rs: remove incorrect decrypt_data calls
  - Master keys are already plaintext after phase-3/4 encryption migration
  - Read directly from get_master_buyer_pubkey/get_master_seller_pubkey

- admin_cancel.rs: add comprehensive doc comment
  - Document parameters, side effects, and error conditions

- take_sell.rs: extract test context helper
  - Created build_test_context() to reduce duplication
  - Replaced 5 verbose TestContextBuilder setups with helper calls
@mostronatorcoder

Copy link
Copy Markdown
Contributor Author

Addressed second round of CodeRabbit feedback in ddf3e23:

🐛 Bug fix: trade_pubkey.rs

  • ✅ Removed incorrect CryptoUtils::decrypt_data() calls
  • ✅ Master keys are already plaintext after phase-3/4 encryption migration
  • ✅ Now reads directly from get_master_buyer_pubkey(None) / get_master_seller_pubkey(None)

📝 Nitpick: admin_cancel.rs

  • ✅ Added comprehensive doc comment for admin_cancel_action
  • Documents parameters, side effects (DB/LN/DM), and error conditions

🧹 Nitpick: take_sell.rs

  • ✅ Extracted build_test_context() helper function
  • ✅ Replaced 5 duplicated TestContextBuilder setups with helper calls
  • Cleaner test code, single source of truth for test context construction

Validation:

  • cargo clippy --all-targets --all-features -- -D warnings → ✅ 0 warnings

grunch
grunch previously approved these changes Mar 13, 2026
@grunch
grunch dismissed their stale review March 13, 2026 18:52

found a bug

@grunch grunch left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

tACK

@grunch
grunch merged commit 886f80f into main Mar 17, 2026
8 checks passed
@grunch
grunch deleted the cleanup/remove-legacy-wrappers-656 branch March 17, 2026 17:02
mostronatorcoder Bot pushed a commit that referenced this pull request Mar 17, 2026
## Context

Issue #656 tracks cleanup tasks after phase-5 DI migration (#639).
This PR implements **PR B**: simplify dispatcher and remove `pool` parameter.

## Changes

After PR A (#663), all handlers use `AppContext` for dependencies.
This PR completes the dispatcher simplification:

### 1. Remove `pool` from main event loop
- Deleted: `let pool = get_db_pool();`
- Removed: `use crate::config::settings::get_db_pool;`
- Removed: `use sqlx::{Pool, Sqlite};`

### 2. Update `check_trade_index` signature
- Before: `check_trade_index(pool: &Pool<Sqlite>, ...)`
- After: `check_trade_index(ctx: &AppContext, ...)`
- Internally extracts pool via `ctx.pool()`

### 3. Remove migration comments
- Deleted references to "gradually migrate from using pool directly"
- Removed outdated docstring parameters (`pool`, `rate_list`)

### 4. Update tests to use `AppContext`
- `check_trade_index_tests` now use `TestContextBuilder`
- Tests create `AppContext` instead of raw pool

## Impact

**Before:**
```rust
let pool = get_db_pool();
let ctx = AppContext::from_globals()?;
check_trade_index(&pool, &event, &message).await?;
```

**After:**
```rust
let ctx = AppContext::from_globals()?;
check_trade_index(&ctx, &event, &message).await?;
```

**Diff stats:**
- 1 file changed
- +19 / -21 lines
- **Net: -2 lines**

## Validation

✅ `cargo fmt`
✅ `cargo clippy --all-targets --all-features -- -D warnings` (0 warnings)
✅ `cargo test --bin mostrod` (189 passed, 0 failed)

## Debt grep checks

```bash
grep -R "get_db_pool" src/app.rs  # 0 matches ✅
grep -R "Pool<Sqlite>" src/app.rs  # 0 matches ✅
```

## Related

- Parent cleanup issue: #656
- PR A (legacy wrappers): #663
- Original DI migration: #639
grunch pushed a commit that referenced this pull request Mar 17, 2026
…665)

## Context

Issue #656 tracks cleanup tasks after phase-5 DI migration (#639).
This PR implements **PR B**: simplify dispatcher and remove `pool` parameter.

## Changes

After PR A (#663), all handlers use `AppContext` for dependencies.
This PR completes the dispatcher simplification:

### 1. Remove `pool` from main event loop
- Deleted: `let pool = get_db_pool();`
- Removed: `use crate::config::settings::get_db_pool;`
- Removed: `use sqlx::{Pool, Sqlite};`

### 2. Update `check_trade_index` signature
- Before: `check_trade_index(pool: &Pool<Sqlite>, ...)`
- After: `check_trade_index(ctx: &AppContext, ...)`
- Internally extracts pool via `ctx.pool()`

### 3. Remove migration comments
- Deleted references to "gradually migrate from using pool directly"
- Removed outdated docstring parameters (`pool`, `rate_list`)

### 4. Update tests to use `AppContext`
- `check_trade_index_tests` now use `TestContextBuilder`
- Tests create `AppContext` instead of raw pool

## Impact

**Before:**
```rust
let pool = get_db_pool();
let ctx = AppContext::from_globals()?;
check_trade_index(&pool, &event, &message).await?;
```

**After:**
```rust
let ctx = AppContext::from_globals()?;
check_trade_index(&ctx, &event, &message).await?;
```

**Diff stats:**
- 1 file changed
- +19 / -21 lines
- **Net: -2 lines**

## Validation

✅ `cargo fmt`
✅ `cargo clippy --all-targets --all-features -- -D warnings` (0 warnings)
✅ `cargo test --bin mostrod` (189 passed, 0 failed)

## Debt grep checks

```bash
grep -R "get_db_pool" src/app.rs  # 0 matches ✅
grep -R "Pool<Sqlite>" src/app.rs  # 0 matches ✅
```

## Related

- Parent cleanup issue: #656
- PR A (legacy wrappers): #663
- Original DI migration: #639

Co-authored-by: MostronatorCoder[bot] <182182091+MostronatorCoder[bot]@users.noreply.github.com>
mostronatorcoder Bot pushed a commit that referenced this pull request Mar 17, 2026
## Context

Issue #656 tracks cleanup tasks after phase-5 DI migration (#639).
This PR implements **PR C**: remove global accesses from handler paths.

## Changes

Replaced direct global function calls with `ctx` accessors in handlers:

### Settings access
- `Settings::get_mostro()` → `ctx.settings().mostro`
- `Settings::get_ln()` → `ctx.settings().lightning` (where applicable)

### Nostr client access
- `get_nostr_client()?` → `ctx.nostr_client()`
- Removed fallible Result handling (ctx always has valid client)

### Database pool access
- `pool` parameters in internal functions → `ctx: &AppContext`
- Extract pool internally: `let pool = ctx.pool();`

## Files Modified (8 total)

**Handlers:**
- `src/app/admin_cancel.rs` - Settings + nostr_client
- `src/app/admin_settle.rs` - Settings + nostr_client
- `src/app/admin_take_dispute.rs` - Settings + nostr_client
- `src/app/cancel.rs` - Propagate ctx to internal helpers
- `src/app/dispute.rs` - Settings + nostr_client + close_dispute_after_user_resolution
- `src/app/order.rs` - Settings (calculate_and_check_quote)
- `src/app/orders.rs` - Settings
- `src/app/release.rs` - nostr_client

## Breaking Changes

- `close_dispute_after_user_resolution()` signature changed:
  - Before: `(pool, order, status, keys, context)`
  - After: `(ctx, order, status, keys, context)`

## What Remains Global

The following still use globals (tracked for future PRs):

**In `src/app/release.rs`:**
- `check_failure_retries()` - uses `get_db_pool()`, `Settings::get_ln()`
- `do_payment()` - uses `get_db_pool()`
- `retry_failed_payments()` - uses `get_db_pool()`

**Reason:** These are called from `src/scheduler.rs` which doesn't have
`AppContext`. Migrating scheduler requires a larger refactor.

**In `src/app/context.rs`:**
- `AppContext::from_globals()` - by design (bridges old → new architecture)

## Diff Stats

- 8 files changed
- +59 / -91 lines
- **Net: -32 lines**

## Validation

✅ `cargo fmt`
✅ `cargo clippy --all-targets --all-features -- -D warnings`
✅ `cargo test --bin mostrod` (189 passed, 0 failed)

## Debt Grep Checks

```bash
# Remaining globals in src/app (excluding context.rs):
$ grep -R "Settings::get_" src/app --include="*.rs" | grep -v context.rs
src/app/release.rs:39:    let ln_settings = Settings::get_ln();

$ grep -R "get_db_pool\|get_nostr_client" src/app --include="*.rs" | grep -v context.rs
src/app/release.rs:36:    let pool = get_db_pool();
src/app/release.rs:537:    let pool = get_db_pool();
src/app/release.rs:622:    let pool = get_db_pool();
```

All remaining globals are in scheduler-called functions (documented above).

## Related

- Parent cleanup issue: #656
- PR A (legacy wrappers): #663 ✅ merged
- PR B (dispatcher pool): #665 ✅ merged
- Original DI migration: #639

## Next Steps

- PR D (optional): Migrate scheduler to use AppContext
- PR E (optional): Finalize AppContext::from_globals()
grunch pushed a commit that referenced this pull request Mar 17, 2026
## Context

Issue #656 tracks cleanup tasks after phase-5 DI migration (#639).
This PR implements **PR C**: remove global accesses from handler paths.

## Changes

Replaced direct global function calls with `ctx` accessors in handlers:

### Settings access
- `Settings::get_mostro()` → `ctx.settings().mostro`
- `Settings::get_ln()` → `ctx.settings().lightning` (where applicable)

### Nostr client access
- `get_nostr_client()?` → `ctx.nostr_client()`
- Removed fallible Result handling (ctx always has valid client)

### Database pool access
- `pool` parameters in internal functions → `ctx: &AppContext`
- Extract pool internally: `let pool = ctx.pool();`

## Files Modified (8 total)

**Handlers:**
- `src/app/admin_cancel.rs` - Settings + nostr_client
- `src/app/admin_settle.rs` - Settings + nostr_client
- `src/app/admin_take_dispute.rs` - Settings + nostr_client
- `src/app/cancel.rs` - Propagate ctx to internal helpers
- `src/app/dispute.rs` - Settings + nostr_client + close_dispute_after_user_resolution
- `src/app/order.rs` - Settings (calculate_and_check_quote)
- `src/app/orders.rs` - Settings
- `src/app/release.rs` - nostr_client

## Breaking Changes

- `close_dispute_after_user_resolution()` signature changed:
  - Before: `(pool, order, status, keys, context)`
  - After: `(ctx, order, status, keys, context)`

## What Remains Global

The following still use globals (tracked for future PRs):

**In `src/app/release.rs`:**
- `check_failure_retries()` - uses `get_db_pool()`, `Settings::get_ln()`
- `do_payment()` - uses `get_db_pool()`
- `retry_failed_payments()` - uses `get_db_pool()`

**Reason:** These are called from `src/scheduler.rs` which doesn't have
`AppContext`. Migrating scheduler requires a larger refactor.

**In `src/app/context.rs`:**
- `AppContext::from_globals()` - by design (bridges old → new architecture)

## Diff Stats

- 8 files changed
- +59 / -91 lines
- **Net: -32 lines**

## Validation

✅ `cargo fmt`
✅ `cargo clippy --all-targets --all-features -- -D warnings`
✅ `cargo test --bin mostrod` (189 passed, 0 failed)

## Debt Grep Checks

```bash
# Remaining globals in src/app (excluding context.rs):
$ grep -R "Settings::get_" src/app --include="*.rs" | grep -v context.rs
src/app/release.rs:39:    let ln_settings = Settings::get_ln();

$ grep -R "get_db_pool\|get_nostr_client" src/app --include="*.rs" | grep -v context.rs
src/app/release.rs:36:    let pool = get_db_pool();
src/app/release.rs:537:    let pool = get_db_pool();
src/app/release.rs:622:    let pool = get_db_pool();
```

All remaining globals are in scheduler-called functions (documented above).

## Related

- Parent cleanup issue: #656
- PR A (legacy wrappers): #663 ✅ merged
- PR B (dispatcher pool): #665 ✅ merged
- Original DI migration: #639

## Next Steps

- PR D (optional): Migrate scheduler to use AppContext
- PR E (optional): Finalize AppContext::from_globals()

Co-authored-by: MostronatorCoder[bot] <182182091+MostronatorCoder[bot]@users.noreply.github.com>
mostronatorcoder Bot pushed a commit that referenced this pull request Mar 17, 2026
## Context

Issue #656 tracks cleanup tasks after phase-5 DI migration (#639).
This PR implements **PR D**: migrate scheduler to use AppContext.

## Changes

### scheduler.rs
- `start_scheduler()` now receives `AppContext` as parameter
- All job functions updated to receive and use `ctx`:
  - `job_expire_pending_older_orders(ctx)`
  - `job_update_rate_events(ctx)`
  - `job_cancel_orders(ctx)`
  - `job_retry_failed_payments(ctx)`
  - `job_process_dev_fee_payment(ctx)`
  - `job_info_event_send(ctx)`
  - `job_relay_list(ctx)`
- Removed all `get_db_pool()` calls → use `ctx.pool()`
- Removed all `get_nostr_client()` calls → use `ctx.nostr_client()`
- Removed all `Settings::get_*()` calls → use `ctx.settings()`

### main.rs
- Build `AppContext` before starting scheduler
- Pass `ctx` to `start_scheduler()`

### release.rs
- `do_payment()` now receives `&AppContext`
- `check_failure_retries()` now receives `&AppContext`
- `payment_success()` now receives `&AppContext`
- `get_child_order()` now receives `&AppContext`
- `create_order_event()` now receives `&AppContext`
- `order_for_equal()` and `order_for_greater()` now receive `&AppContext`
- Removed unused `use crate::config`

### admin_settle.rs
- Updated `do_payment()` call to pass `ctx`

## Breaking Changes

### Public API changes:
- `start_scheduler()`: `() -> (ctx: AppContext)`
- `do_payment()`: `(order, request_id) -> (ctx, order, request_id)`
- `check_failure_retries()`: `(order, request_id) -> (ctx, order, request_id)`
- `get_child_order()`: `(order, keys) -> (ctx, order, keys)`

## Global Access Elimination

After this PR, the following globals are **no longer used anywhere** in handler/scheduler paths:
- `get_db_pool()` ❌
- `get_nostr_client()` ❌ (except initial setup in main.rs)
- `Settings::get_mostro()` ❌
- `Settings::get_ln()` ❌

The only remaining global access is:
- `AppContext::from_globals()` in main.rs (by design - bridges initialization)

## Diff Stats

- 4 files changed
- +89 / -84 lines
- **Net: +5 lines** (mostly signature changes)

## Validation

✅ `cargo fmt`
✅ `cargo clippy --all-targets --all-features -- -D warnings`
✅ `cargo test --bin mostrod` (189 passed, 0 failed)

## Related

- Parent cleanup issue: #656
- PR A (legacy wrappers): #663 ✅ merged
- PR B (dispatcher pool): #665 ✅ merged
- PR C (handler paths): #666 ✅ merged
- Original DI migration: #639
grunch pushed a commit that referenced this pull request Mar 18, 2026
## Context

Issue #656 tracks cleanup tasks after phase-5 DI migration (#639).
This PR implements **PR D**: migrate scheduler to use AppContext.

## Changes

### scheduler.rs
- `start_scheduler()` now receives `AppContext` as parameter
- All job functions updated to receive and use `ctx`:
  - `job_expire_pending_older_orders(ctx)`
  - `job_update_rate_events(ctx)`
  - `job_cancel_orders(ctx)`
  - `job_retry_failed_payments(ctx)`
  - `job_process_dev_fee_payment(ctx)`
  - `job_info_event_send(ctx)`
  - `job_relay_list(ctx)`
- Removed all `get_db_pool()` calls → use `ctx.pool()`
- Removed all `get_nostr_client()` calls → use `ctx.nostr_client()`
- Removed all `Settings::get_*()` calls → use `ctx.settings()`

### main.rs
- Build `AppContext` before starting scheduler
- Pass `ctx` to `start_scheduler()`

### release.rs
- `do_payment()` now receives `&AppContext`
- `check_failure_retries()` now receives `&AppContext`
- `payment_success()` now receives `&AppContext`
- `get_child_order()` now receives `&AppContext`
- `create_order_event()` now receives `&AppContext`
- `order_for_equal()` and `order_for_greater()` now receive `&AppContext`
- Removed unused `use crate::config`

### admin_settle.rs
- Updated `do_payment()` call to pass `ctx`

## Breaking Changes

### Public API changes:
- `start_scheduler()`: `() -> (ctx: AppContext)`
- `do_payment()`: `(order, request_id) -> (ctx, order, request_id)`
- `check_failure_retries()`: `(order, request_id) -> (ctx, order, request_id)`
- `get_child_order()`: `(order, keys) -> (ctx, order, keys)`

## Global Access Elimination

After this PR, the following globals are **no longer used anywhere** in handler/scheduler paths:
- `get_db_pool()` ❌
- `get_nostr_client()` ❌ (except initial setup in main.rs)
- `Settings::get_mostro()` ❌
- `Settings::get_ln()` ❌

The only remaining global access is:
- `AppContext::from_globals()` in main.rs (by design - bridges initialization)

## Diff Stats

- 4 files changed
- +89 / -84 lines
- **Net: +5 lines** (mostly signature changes)

## Validation

✅ `cargo fmt`
✅ `cargo clippy --all-targets --all-features -- -D warnings`
✅ `cargo test --bin mostrod` (189 passed, 0 failed)

## Related

- Parent cleanup issue: #656
- PR A (legacy wrappers): #663 ✅ merged
- PR B (dispatcher pool): #665 ✅ merged
- PR C (handler paths): #666 ✅ merged
- Original DI migration: #639

Co-authored-by: MostronatorCoder[bot] <182182091+MostronatorCoder[bot]@users.noreply.github.com>
mostronatorcoder Bot pushed a commit that referenced this pull request Mar 18, 2026
## Context

Issue #656 tracks cleanup tasks after phase-5 DI migration (#639).
This PR implements **PR E**: add Mostro's signing keys to AppContext.

## Problem

`get_keys()` was called 10+ times across the codebase, re-parsing
the nsec on every call. This was inefficient and spread error handling
across multiple call sites.

## Solution

Add `keys: Keys` field to `AppContext`:
- Parse nsec once at startup in `from_globals()`
- Early error detection for invalid nsec
- Access via `ctx.keys()` instead of `get_keys()?`

## Changes

### AppContext (src/app/context.rs)
- Added `keys: Keys` field to struct
- Updated `new()` to accept `keys` parameter
- Updated `from_globals()` to parse keys at construction
- Added `keys(&self) -> &Keys` accessor
- Updated `TestContextBuilder` with `with_keys()` method

### Scheduler (src/scheduler.rs)
- Replaced all `get_keys()?` calls with `ctx.keys().clone()`
- Updated jobs: flush_messages_queue, relay_list, info_event_send,
  cancel_orders, expire_pending_older_orders
- Removed `get_keys` import

### Handlers
- `release.rs`: Use `ctx.keys().clone()` in `do_payment()`
- `admin_take_dispute.rs`: Pass `keys` to `pubkey_event_can_solve()`
- `admin_cancel.rs`, `admin_settle.rs`: Pass admin pubkey to
  `is_dispute_taken_by_admin()`

### Database (src/db.rs)
- `is_dispute_taken_by_admin()`: Now takes `admin_pubkey: &str`
  parameter instead of calling `get_keys()` internally

### Flow (src/flow.rs)
- `hold_invoice_paid()`: Now takes `my_keys: &Keys` parameter

### RPC Service (src/rpc/service.rs)
- Updated all `AppContext::new()` calls to include `self.keys.clone()`

## What Still Uses `get_keys()`

The following still call `get_keys()` (documented for future cleanup):

- `src/util.rs`: `publish_dev_fee_audit_event()` - called from dev_fee
  flow which doesn't have ctx
- `src/util.rs`: `invoice_subscribe()` - invoice subscription flow
- `src/main.rs`: Initial key loading at startup (by design)

## Diff Stats

- 10 files changed
- +88 / -59 lines
- **Net: +29 lines** (mostly accessor and parameter additions)

## Validation

✅ `cargo fmt`
✅ `cargo clippy --all-targets --all-features -- -D warnings`
✅ `cargo test --bin mostrod` (189 passed, 0 failed)

## Related

- Parent cleanup issue: #656
- PR A (legacy wrappers): #663 ✅ merged
- PR B (dispatcher pool): #665 ✅ merged
- PR C (handler paths): #666 ✅ merged
- PR D (scheduler): #667 ✅ merged
- PR F (remove from_globals): 📋 planned
grunch pushed a commit that referenced this pull request Mar 18, 2026
## Context

Issue #656 tracks cleanup tasks after phase-5 DI migration (#639).
This PR implements **PR E**: add Mostro's signing keys to AppContext.

## Problem

`get_keys()` was called 10+ times across the codebase, re-parsing
the nsec on every call. This was inefficient and spread error handling
across multiple call sites.

## Solution

Add `keys: Keys` field to `AppContext`:
- Parse nsec once at startup in `from_globals()`
- Early error detection for invalid nsec
- Access via `ctx.keys()` instead of `get_keys()?`

## Changes

### AppContext (src/app/context.rs)
- Added `keys: Keys` field to struct
- Updated `new()` to accept `keys` parameter
- Updated `from_globals()` to parse keys at construction
- Added `keys(&self) -> &Keys` accessor
- Updated `TestContextBuilder` with `with_keys()` method

### Scheduler (src/scheduler.rs)
- Replaced all `get_keys()?` calls with `ctx.keys().clone()`
- Updated jobs: flush_messages_queue, relay_list, info_event_send,
  cancel_orders, expire_pending_older_orders
- Removed `get_keys` import

### Handlers
- `release.rs`: Use `ctx.keys().clone()` in `do_payment()`
- `admin_take_dispute.rs`: Pass `keys` to `pubkey_event_can_solve()`
- `admin_cancel.rs`, `admin_settle.rs`: Pass admin pubkey to
  `is_dispute_taken_by_admin()`

### Database (src/db.rs)
- `is_dispute_taken_by_admin()`: Now takes `admin_pubkey: &str`
  parameter instead of calling `get_keys()` internally

### Flow (src/flow.rs)
- `hold_invoice_paid()`: Now takes `my_keys: &Keys` parameter

### RPC Service (src/rpc/service.rs)
- Updated all `AppContext::new()` calls to include `self.keys.clone()`

## What Still Uses `get_keys()`

The following still call `get_keys()` (documented for future cleanup):

- `src/util.rs`: `publish_dev_fee_audit_event()` - called from dev_fee
  flow which doesn't have ctx
- `src/util.rs`: `invoice_subscribe()` - invoice subscription flow
- `src/main.rs`: Initial key loading at startup (by design)

## Diff Stats

- 10 files changed
- +88 / -59 lines
- **Net: +29 lines** (mostly accessor and parameter additions)

## Validation

✅ `cargo fmt`
✅ `cargo clippy --all-targets --all-features -- -D warnings`
✅ `cargo test --bin mostrod` (189 passed, 0 failed)

## Related

- Parent cleanup issue: #656
- PR A (legacy wrappers): #663 ✅ merged
- PR B (dispatcher pool): #665 ✅ merged
- PR C (handler paths): #666 ✅ merged
- PR D (scheduler): #667 ✅ merged
- PR F (remove from_globals): 📋 planned

Co-authored-by: MostronatorCoder[bot] <182182091+MostronatorCoder[bot]@users.noreply.github.com>
mostronatorcoder Bot pushed a commit that referenced this pull request Mar 18, 2026
…656 PR F)

## Context

Issue #656 tracks cleanup tasks after phase-5 DI migration (#639).
This PR implements **PR F**: remove the `from_globals()` bridge and
construct `AppContext` explicitly at bootstrap.

## Problem

`AppContext::from_globals()` was a transitional bridge between the old
global-based architecture and the new DI pattern. Now that all handlers
and scheduler use `AppContext`, we can eliminate this bridge.

## Solution

Construct `AppContext` explicitly in `main.rs` using values already
available at that point:
- `get_db_pool()` — database pool
- `client` — Nostr client
- `MOSTRO_CONFIG` — settings
- `MESSAGE_QUEUES.queue_order_msg` — message queue
- `mostro_keys` — signing keys

## Changes

### main.rs
- Construct `AppContext::new()` explicitly with all dependencies
- Pass `ctx` to `run()` instead of `my_keys` and `client`
- Import `MESSAGE_QUEUES` and `MOSTRO_CONFIG`

### app.rs
- `run()` signature changed: `(my_keys, client, ln_client)` → `(ctx, ln_client)`
- Extract `my_keys`, `client`, and `pow` from `ctx` at function start
- Remove `AppContext::from_globals()` call from event loop
- Remove unused `Settings` import

### context.rs
- **Removed `from_globals()` method entirely**
- Removed unused `MESSAGE_QUEUES` import

## Breaking Changes

`run()` function signature changed:
- **Before:** `run(my_keys: Keys, client: &Client, ln_client: &mut LndConnector)`
- **After:** `run(ctx: AppContext, ln_client: &mut LndConnector)`

## Benefits

1. **No more bridge code** — cleaner architecture
2. **Single construction point** — `AppContext` built once in main
3. **Explicit dependencies** — all deps visible at construction
4. **Testability** — easier to mock in tests

## Diff Stats

- 3 files changed
- +26 / -61 lines
- **Net: -35 lines** 🧹

## Validation

✅ `cargo fmt`
✅ `cargo clippy --all-targets --all-features -- -D warnings`
✅ `cargo test --bin mostrod` (189 passed, 0 failed)

## DI Migration Complete! 🎉

With this PR, the dependency injection migration from #639 is **complete**:

| PR | Description | Status |
|----|-------------|--------|
| PR A | Remove legacy wrappers | ✅ #663 |
| PR B | Simplify dispatcher | ✅ #665 |
| PR C | Remove global accesses | ✅ #666 |
| PR D | Migrate scheduler | ✅ #667 |
| PR E | Add keys to AppContext | ✅ #670 |
| **PR F** | Remove from_globals() | ✅ This PR |

## Related

- Parent cleanup issue: #656
- Suggested by @codaMW in #667 review
grunch pushed a commit that referenced this pull request Mar 18, 2026
…656 PR F) (#671)

## Context

Issue #656 tracks cleanup tasks after phase-5 DI migration (#639).
This PR implements **PR F**: remove the `from_globals()` bridge and
construct `AppContext` explicitly at bootstrap.

## Problem

`AppContext::from_globals()` was a transitional bridge between the old
global-based architecture and the new DI pattern. Now that all handlers
and scheduler use `AppContext`, we can eliminate this bridge.

## Solution

Construct `AppContext` explicitly in `main.rs` using values already
available at that point:
- `get_db_pool()` — database pool
- `client` — Nostr client
- `MOSTRO_CONFIG` — settings
- `MESSAGE_QUEUES.queue_order_msg` — message queue
- `mostro_keys` — signing keys

## Changes

### main.rs
- Construct `AppContext::new()` explicitly with all dependencies
- Pass `ctx` to `run()` instead of `my_keys` and `client`
- Import `MESSAGE_QUEUES` and `MOSTRO_CONFIG`

### app.rs
- `run()` signature changed: `(my_keys, client, ln_client)` → `(ctx, ln_client)`
- Extract `my_keys`, `client`, and `pow` from `ctx` at function start
- Remove `AppContext::from_globals()` call from event loop
- Remove unused `Settings` import

### context.rs
- **Removed `from_globals()` method entirely**
- Removed unused `MESSAGE_QUEUES` import

## Breaking Changes

`run()` function signature changed:
- **Before:** `run(my_keys: Keys, client: &Client, ln_client: &mut LndConnector)`
- **After:** `run(ctx: AppContext, ln_client: &mut LndConnector)`

## Benefits

1. **No more bridge code** — cleaner architecture
2. **Single construction point** — `AppContext` built once in main
3. **Explicit dependencies** — all deps visible at construction
4. **Testability** — easier to mock in tests

## Diff Stats

- 3 files changed
- +26 / -61 lines
- **Net: -35 lines** 🧹

## Validation

✅ `cargo fmt`
✅ `cargo clippy --all-targets --all-features -- -D warnings`
✅ `cargo test --bin mostrod` (189 passed, 0 failed)

## DI Migration Complete! 🎉

With this PR, the dependency injection migration from #639 is **complete**:

| PR | Description | Status |
|----|-------------|--------|
| PR A | Remove legacy wrappers | ✅ #663 |
| PR B | Simplify dispatcher | ✅ #665 |
| PR C | Remove global accesses | ✅ #666 |
| PR D | Migrate scheduler | ✅ #667 |
| PR E | Add keys to AppContext | ✅ #670 |
| **PR F** | Remove from_globals() | ✅ This PR |

## Related

- Parent cleanup issue: #656
- Suggested by @codaMW in #667 review

Co-authored-by: MostronatorCoder[bot] <182182091+MostronatorCoder[bot]@users.noreply.github.com>
mostronatorcoder Bot added a commit that referenced this pull request Mar 18, 2026
…656 PR F) (#671)

## Context

Issue #656 tracks cleanup tasks after phase-5 DI migration (#639).
This PR implements **PR F**: remove the `from_globals()` bridge and
construct `AppContext` explicitly at bootstrap.

## Problem

`AppContext::from_globals()` was a transitional bridge between the old
global-based architecture and the new DI pattern. Now that all handlers
and scheduler use `AppContext`, we can eliminate this bridge.

## Solution

Construct `AppContext` explicitly in `main.rs` using values already
available at that point:
- `get_db_pool()` — database pool
- `client` — Nostr client
- `MOSTRO_CONFIG` — settings
- `MESSAGE_QUEUES.queue_order_msg` — message queue
- `mostro_keys` — signing keys

## Changes

### main.rs
- Construct `AppContext::new()` explicitly with all dependencies
- Pass `ctx` to `run()` instead of `my_keys` and `client`
- Import `MESSAGE_QUEUES` and `MOSTRO_CONFIG`

### app.rs
- `run()` signature changed: `(my_keys, client, ln_client)` → `(ctx, ln_client)`
- Extract `my_keys`, `client`, and `pow` from `ctx` at function start
- Remove `AppContext::from_globals()` call from event loop
- Remove unused `Settings` import

### context.rs
- **Removed `from_globals()` method entirely**
- Removed unused `MESSAGE_QUEUES` import

## Breaking Changes

`run()` function signature changed:
- **Before:** `run(my_keys: Keys, client: &Client, ln_client: &mut LndConnector)`
- **After:** `run(ctx: AppContext, ln_client: &mut LndConnector)`

## Benefits

1. **No more bridge code** — cleaner architecture
2. **Single construction point** — `AppContext` built once in main
3. **Explicit dependencies** — all deps visible at construction
4. **Testability** — easier to mock in tests

## Diff Stats

- 3 files changed
- +26 / -61 lines
- **Net: -35 lines** 🧹

## Validation

✅ `cargo fmt`
✅ `cargo clippy --all-targets --all-features -- -D warnings`
✅ `cargo test --bin mostrod` (189 passed, 0 failed)

## DI Migration Complete! 🎉

With this PR, the dependency injection migration from #639 is **complete**:

| PR | Description | Status |
|----|-------------|--------|
| PR A | Remove legacy wrappers | ✅ #663 |
| PR B | Simplify dispatcher | ✅ #665 |
| PR C | Remove global accesses | ✅ #666 |
| PR D | Migrate scheduler | ✅ #667 |
| PR E | Add keys to AppContext | ✅ #670 |
| **PR F** | Remove from_globals() | ✅ This PR |

## Related

- Parent cleanup issue: #656
- Suggested by @codaMW in #667 review

Co-authored-by: MostronatorCoder[bot] <182182091+MostronatorCoder[bot]@users.noreply.github.com>
grunch pushed a commit that referenced this pull request Mar 18, 2026
…656 PR F) (#671) (#672)

## Context

Issue #656 tracks cleanup tasks after phase-5 DI migration (#639).
This PR implements **PR F**: remove the `from_globals()` bridge and
construct `AppContext` explicitly at bootstrap.

## Problem

`AppContext::from_globals()` was a transitional bridge between the old
global-based architecture and the new DI pattern. Now that all handlers
and scheduler use `AppContext`, we can eliminate this bridge.

## Solution

Construct `AppContext` explicitly in `main.rs` using values already
available at that point:
- `get_db_pool()` — database pool
- `client` — Nostr client
- `MOSTRO_CONFIG` — settings
- `MESSAGE_QUEUES.queue_order_msg` — message queue
- `mostro_keys` — signing keys

## Changes

### main.rs
- Construct `AppContext::new()` explicitly with all dependencies
- Pass `ctx` to `run()` instead of `my_keys` and `client`
- Import `MESSAGE_QUEUES` and `MOSTRO_CONFIG`

### app.rs
- `run()` signature changed: `(my_keys, client, ln_client)` → `(ctx, ln_client)`
- Extract `my_keys`, `client`, and `pow` from `ctx` at function start
- Remove `AppContext::from_globals()` call from event loop
- Remove unused `Settings` import

### context.rs
- **Removed `from_globals()` method entirely**
- Removed unused `MESSAGE_QUEUES` import

## Breaking Changes

`run()` function signature changed:
- **Before:** `run(my_keys: Keys, client: &Client, ln_client: &mut LndConnector)`
- **After:** `run(ctx: AppContext, ln_client: &mut LndConnector)`

## Benefits

1. **No more bridge code** — cleaner architecture
2. **Single construction point** — `AppContext` built once in main
3. **Explicit dependencies** — all deps visible at construction
4. **Testability** — easier to mock in tests

## Diff Stats

- 3 files changed
- +26 / -61 lines
- **Net: -35 lines** 🧹

## Validation

✅ `cargo fmt`
✅ `cargo clippy --all-targets --all-features -- -D warnings`
✅ `cargo test --bin mostrod` (189 passed, 0 failed)

## DI Migration Complete! 🎉

With this PR, the dependency injection migration from #639 is **complete**:

| PR | Description | Status |
|----|-------------|--------|
| PR A | Remove legacy wrappers | ✅ #663 |
| PR B | Simplify dispatcher | ✅ #665 |
| PR C | Remove global accesses | ✅ #666 |
| PR D | Migrate scheduler | ✅ #667 |
| PR E | Add keys to AppContext | ✅ #670 |
| **PR F** | Remove from_globals() | ✅ This PR |

## Related

- Parent cleanup issue: #656
- Suggested by @codaMW in #667 review

Co-authored-by: mostronatorcoder[bot] <263173566+mostronatorcoder[bot]@users.noreply.github.com>
Co-authored-by: MostronatorCoder[bot] <182182091+MostronatorCoder[bot]@users.noreply.github.com>
mostronatorcoder Bot pushed a commit that referenced this pull request Mar 18, 2026
## Context

After completing the DI migration (PRs A-F in #656), the documentation
needed updates to reflect the new architecture.

## Changes

### ARCHITECTURE.md
- Added new section: **Dependency Injection (AppContext)**
  - Documents AppContext fields and accessors
  - Shows construction pattern and testing usage
- Updated startup sequence diagram to show AppContext construction
- Updated module description to mention `src/app/context.rs`
- Changed `run(keys, client, ln)` to `run(ctx, ln)` in diagram

### STARTUP_AND_CONFIG.md
- Updated startup steps 8-10:
  - Step 8: Build AppContext with all dependencies
  - Step 9: `start_scheduler(ctx)` now receives AppContext
  - Step 10: `run(ctx, ln_client)` receives AppContext

### DEV_FEE.md
- Updated code example to show new scheduler pattern:
  - `job_process_dev_fee_payment(ctx: AppContext)`
  - `ctx.pool()` instead of `get_db_pool()`

## Related

- Parent cleanup issue: #656
- DI migration PRs: #663, #665, #666, #667, #670, #672
grunch pushed a commit that referenced this pull request Mar 18, 2026
## Context

After completing the DI migration (PRs A-F in #656), the documentation
needed updates to reflect the new architecture.

## Changes

### ARCHITECTURE.md
- Added new section: **Dependency Injection (AppContext)**
  - Documents AppContext fields and accessors
  - Shows construction pattern and testing usage
- Updated startup sequence diagram to show AppContext construction
- Updated module description to mention `src/app/context.rs`
- Changed `run(keys, client, ln)` to `run(ctx, ln)` in diagram

### STARTUP_AND_CONFIG.md
- Updated startup steps 8-10:
  - Step 8: Build AppContext with all dependencies
  - Step 9: `start_scheduler(ctx)` now receives AppContext
  - Step 10: `run(ctx, ln_client)` receives AppContext

### DEV_FEE.md
- Updated code example to show new scheduler pattern:
  - `job_process_dev_fee_payment(ctx: AppContext)`
  - `ctx.pool()` instead of `get_db_pool()`

## Related

- Parent cleanup issue: #656
- DI migration PRs: #663, #665, #666, #667, #670, #672

Co-authored-by: MostronatorCoder[bot] <182182091+MostronatorCoder[bot]@users.noreply.github.com>
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