Skip to content

refactor: changes LeaseHttpService to accept http client#1888

Merged
stalniy merged 1 commit intomainfrom
fix/lease-http
Sep 5, 2025
Merged

refactor: changes LeaseHttpService to accept http client#1888
stalniy merged 1 commit intomainfrom
fix/lease-http

Conversation

@stalniy
Copy link
Contributor

@stalniy stalniy commented Sep 4, 2025

Why

Default http client is retriable. It makes it easier to make this service a retry on network or server error. ref #1424

Summary by CodeRabbit

  • Refactor

    • Standardized HTTP client usage across multiple backend services for improved consistency and maintainability.
    • Consolidated service registration to reduce duplication and simplify configuration.
    • Updated lease and related services to accept a shared HTTP client instance rather than creating their own.
  • Impact

    • No UI or functional changes for end-users.
    • Developers integrating the SDK may need minor adjustments to service instantiation.

@stalniy stalniy requested a review from a team as a code owner September 4, 2025 04:52
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 4, 2025

Walkthrough

Refactors HTTP SDK wiring to construct Deployment/Cosmos/Lease services with a shared injected HttpClient (CHAIN_API_HTTP_CLIENT) via a consolidated NON_AXIOS_SERVICES factory; rewrites LeaseHttpService to accept HttpClient and use extractData/httpClient calls; notifications provider added token and providers for the shared client and services.

Changes

Cohort / File(s) Summary
API provider — consolidated non-Axios registrations
apps/api/src/core/providers/http-sdk.provider.ts
Adds NON_AXIOS_SERVICES (DeploymentHttpService, LeaseHttpService, CosmosHttpService) and registers them via a shared useFactory resolving CHAIN_API_HTTP_CLIENT; removes prior per-service factories; retains useValue registrations for remaining services and leaves Node/GitHub/CoinGecko registrations unchanged.
Lease service — DI and implementation rewrite
packages/http-sdk/src/lease/lease-http.service.ts
Removes inheritance from HttpService; makes LeaseHttpService a plain class that accepts HttpClient in its constructor; replaces this.get/this.extractData with httpClient.get and the standalone extractData; updates imports and signature.
Notifications provider — shared HttpClient token wiring
apps/notifications/src/modules/alert/providers/http-sdk.provider.ts
Adds CHAIN_API_HTTP_CLIENT_TOKEN: InjectionToken<HttpClient> and a provider that creates a HttpClient for the alert API; registers DeploymentHttpService and LeaseHttpService by injecting that token and constructing services with the shared HttpClient.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Caller
  participant Container
  participant CHAIN_API_HTTP_CLIENT as HttpClient
  participant LeaseHttpService
  participant ChainAPI

  Note over Container,CHAIN_API_HTTP_CLIENT: Registration phase
  Container->>Container: register(CHAIN_API_HTTP_CLIENT, useFactory -> createHttpClient(...))
  Container->>Container: NON_AXIOS_SERVICES.forEach(Service => register(Service, useFactory -> new Service(resolve(CHAIN_API_HTTP_CLIENT))))

  Caller->>Container: resolve(LeaseHttpService)
  Container->>CHAIN_API_HTTP_CLIENT: resolve token -> HttpClient instance
  Container->>LeaseHttpService: construct LeaseHttpService(HttpClient)

  Caller->>LeaseHttpService: list(params)
  LeaseHttpService->>CHAIN_API_HTTP_CLIENT: GET /v1/lease?params
  CHAIN_API_HTTP_CLIENT->>ChainAPI: HTTP GET
  ChainAPI-->>CHAIN_API_HTTP_CLIENT: Response
  CHAIN_API_HTTP_CLIENT-->>LeaseHttpService: Raw response
  LeaseHttpService-->>Caller: extractData(response)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • ygrishajev
  • baktun14

Poem

I hop through code with whiskered cheer,
One client shared, the paths grow clear.
Factories stitch services in a row,
Leases call out, responses flow.
Tiny rabbit, big refactor — hooray! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 50329ff and edc13d3.

📒 Files selected for processing (3)
  • apps/api/src/core/providers/http-sdk.provider.ts (1 hunks)
  • apps/notifications/src/modules/alert/providers/http-sdk.provider.ts (1 hunks)
  • packages/http-sdk/src/lease/lease-http.service.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/notifications/src/modules/alert/providers/http-sdk.provider.ts
  • apps/api/src/core/providers/http-sdk.provider.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Never use type any or cast to type any. Always define the proper TypeScript types.

Files:

  • packages/http-sdk/src/lease/lease-http.service.ts
**/*.{js,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

**/*.{js,ts,tsx}: Never use deprecated methods from libraries.
Don't add unnecessary comments to the code

Files:

  • packages/http-sdk/src/lease/lease-http.service.ts
🧠 Learnings (1)
📓 Common learnings
Learnt from: jzsfkzm
PR: akash-network/console#1372
File: apps/api/src/dashboard/services/stats/stats.service.ts:0-0
Timestamp: 2025-05-28T20:42:58.200Z
Learning: The user successfully implemented CosmosHttpService with retry logic using axiosRetry, exponential backoff, and proper error handling for Cosmos API calls, replacing direct axios usage in StatsService.
🧬 Code graph analysis (1)
packages/http-sdk/src/lease/lease-http.service.ts (1)
packages/http-sdk/src/index.ts (1)
  • HttpClient (26-26)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: validate / validate-app
  • GitHub Check: test-build
  • GitHub Check: validate / validate-app
  • GitHub Check: test-build
  • GitHub Check: validate / validate-app
  • GitHub Check: test-build
  • GitHub Check: Validate local packages
🔇 Additional comments (2)
packages/http-sdk/src/lease/lease-http.service.ts (2)

1-2: No action needed – HttpClient.get() returns AxiosResponse, matching extractData’s expected input
extractData(response: AxiosResponse) returns the data: T field, and HttpClient is simply an AxiosInstance whose get<T>() resolves to Promise<AxiosResponse<T>>, so the contract already holds.


56-57: All callers updated; no direct instantiations or subclassing remain
The only new LeaseHttpService(...) is in the DI provider’s useFactory (apps/notifications/src/modules/alert/providers/http-sdk.provider.ts), and LeaseHttpService no longer extends HttpService.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/lease-http

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@codecov
Copy link

codecov bot commented Sep 4, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 44.49%. Comparing base (3343c6a) to head (edc13d3).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #1888   +/-   ##
=======================================
  Coverage   44.49%   44.49%           
=======================================
  Files         973      973           
  Lines       27349    27349           
  Branches     7073     7073           
=======================================
+ Hits        12168    12169    +1     
+ Misses      14078    14001   -77     
- Partials     1103     1179   +76     
Flag Coverage Δ *Carryforward flag
api 81.28% <100.00%> (-0.01%) ⬇️
deploy-web 22.65% <ø> (+<0.01%) ⬆️
log-collector 75.35% <ø> (ø)
notifications 87.94% <100.00%> (+0.01%) ⬆️
provider-console 81.48% <ø> (ø) Carriedforward from 3343c6a
provider-proxy 84.47% <ø> (ø) Carriedforward from 3343c6a

*This pull request uses carry forward flags. Click here to find out more.

Files with missing lines Coverage Δ
apps/api/src/core/providers/http-sdk.provider.ts 100.00% <100.00%> (ø)
...s/src/modules/alert/providers/http-sdk.provider.ts 100.00% <100.00%> (ø)

... and 33 files with indirect coverage changes

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Contributor

@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: 0

🧹 Nitpick comments (4)
apps/api/src/core/providers/http-sdk.provider.ts (2)

30-32: Prefer a singleton HttpClient to avoid per-resolution instances.

Without a lifecycle, each service resolution creates a fresh client, fragmenting interceptors/retry state and wasting sockets.

Apply:

-import { container } from "tsyringe";
+import { container, Lifecycle } from "tsyringe";
...
-container.register(CHAIN_API_HTTP_CLIENT, {
-  useFactory: () => createHttpClient({ baseURL: apiNodeUrl })
-});
+container.register(CHAIN_API_HTTP_CLIENT, {
+  useFactory: () => createHttpClient({ baseURL: apiNodeUrl }),
+  lifecycle: Lifecycle.Singleton
+});

30-32: Minor typing cleanup for readability.

Alias the constructor shape instead of repeating the newable type.

-const NON_AXIOS_SERVICES: Array<new (httpClient: HttpClient) => unknown> = [DeploymentHttpService, LeaseHttpService, CosmosHttpService];
+type HttpClientCtor<T = unknown> = new (httpClient: HttpClient) => T;
+const NON_AXIOS_SERVICES: HttpClientCtor[] = [DeploymentHttpService, LeaseHttpService, CosmosHttpService];
packages/http-sdk/src/lease/lease-http.service.ts (2)

60-62: Guard against undefined params across serializers.

Axios typically drops undefined, but being explicit avoids surprises if serializers change.

-    return extractData(
-      await this.httpClient.get<RestAkashLeaseListResponse>("/akash/market/v1beta4/leases/list", {
-        params: {
-          "filters.owner": owner,
-          "filters.dseq": dseq,
-          "filters.state": state
-        }
-      })
-    );
+    return extractData(
+      await this.httpClient.get<RestAkashLeaseListResponse>("/akash/market/v1beta4/leases/list", {
+        params: {
+          "filters.owner": owner,
+          ...(dseq ? { "filters.dseq": dseq } : {}),
+          ...(state ? { "filters.state": state } : {})
+        }
+      })
+    );

50-54: Consider exporting LeaseListParams (and re-exporting from the package index).

Helps consumers import the type directly instead of relying on d.ts inference.

-type LeaseListParams = {
+export type LeaseListParams = {
   owner: string;
   dseq?: string;
   state?: "active" | "insufficient_funds" | "closed";
 };

And ensure the barrel re-exports:

// packages/http-sdk/src/index.ts
export * from "./lease/lease-http.service";
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between fd25b65 and c6b651d.

📒 Files selected for processing (2)
  • apps/api/src/core/providers/http-sdk.provider.ts (1 hunks)
  • packages/http-sdk/src/lease/lease-http.service.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Never use type any or cast to type any. Always define the proper TypeScript types.

Files:

  • apps/api/src/core/providers/http-sdk.provider.ts
  • packages/http-sdk/src/lease/lease-http.service.ts
**/*.{js,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

**/*.{js,ts,tsx}: Never use deprecated methods from libraries.
Don't add unnecessary comments to the code

Files:

  • apps/api/src/core/providers/http-sdk.provider.ts
  • packages/http-sdk/src/lease/lease-http.service.ts
🧬 Code graph analysis (2)
apps/api/src/core/providers/http-sdk.provider.ts (4)
packages/http-sdk/src/utils/httpClient.ts (1)
  • HttpClient (23-23)
packages/http-sdk/src/deployment/deployment-http.service.ts (1)
  • DeploymentHttpService (134-195)
packages/http-sdk/src/lease/lease-http.service.ts (1)
  • LeaseHttpService (56-70)
packages/http-sdk/src/cosmos/cosmos-http.service.ts (1)
  • CosmosHttpService (21-109)
packages/http-sdk/src/lease/lease-http.service.ts (1)
packages/http-sdk/src/index.ts (1)
  • HttpClient (26-26)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: test-build
  • GitHub Check: validate / validate-app
  • GitHub Check: validate / validate-app
  • GitHub Check: test-build
🔇 Additional comments (3)
apps/api/src/core/providers/http-sdk.provider.ts (1)

27-27: Services’ constructors accept Axios config; registration is safe
All listed HTTP services—BalanceHttpService, AuthzHttpService, BlockHttpService, BidHttpService, ProviderHttpService—define constructor(config?: Pick<AxiosRequestConfig, …>) and call super(config), so the SERVICES array registration remains valid at runtime.

packages/http-sdk/src/lease/lease-http.service.ts (2)

1-2: LGTM: decoupled from HttpService and typed HttpClient import is correct.


56-57: LGTM: constructor injection matches provider changes.

@stalniy stalniy force-pushed the fix/lease-http branch 2 times, most recently from a3eade2 to 50329ff Compare September 4, 2025 05:46
Copy link
Contributor

@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

🧹 Nitpick comments (2)
apps/notifications/src/modules/alert/providers/http-sdk.provider.ts (2)

8-9: Good: dedicated, typed DI token

Symbol-based token avoids collisions and preserves typing. If this token must be referenced across multiple packages, consider using Symbol.for to guard against accidental duplication when bundles split.

-export const CHAIN_API_HTTP_CLIENT_TOKEN: InjectionToken<HttpClient> = Symbol("CHAIN_API_HTTP_CLIENT");
+export const CHAIN_API_HTTP_CLIENT_TOKEN: InjectionToken<HttpClient> = Symbol.for("CHAIN_API_HTTP_CLIENT");

16-20: Optional DRY: generate service providers from a typed list

Keeps provider list consistent as services grow without repeating boilerplate.

 export const HTTP_SDK_PROVIDERS: Provider[] = [
   {
     provide: CHAIN_API_HTTP_CLIENT_TOKEN,
     inject: [ConfigService],
     useFactory: (configService: ConfigService<AlertConfig>) => createHttpClient({ baseURL: configService.getOrThrow("alert.API_NODE_ENDPOINT") })
   },
-  {
-    provide: DeploymentHttpService,
-    inject: [CHAIN_API_HTTP_CLIENT_TOKEN],
-    useFactory: (httpClient: HttpClient) => new DeploymentHttpService(httpClient)
-  },
-  {
-    provide: LeaseHttpService,
-    inject: [CHAIN_API_HTTP_CLIENT_TOKEN],
-    useFactory: (httpClient: HttpClient) => new LeaseHttpService(httpClient)
-  }
+  ...([DeploymentHttpService, LeaseHttpService] as const).map((Svc): Provider => ({
+    provide: Svc,
+    inject: [CHAIN_API_HTTP_CLIENT_TOKEN],
+    useFactory: (httpClient: HttpClient) => new Svc(httpClient)
+  }))
 ];

Also applies to: 23-24

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between c6b651d and 50329ff.

📒 Files selected for processing (3)
  • apps/api/src/core/providers/http-sdk.provider.ts (1 hunks)
  • apps/notifications/src/modules/alert/providers/http-sdk.provider.ts (1 hunks)
  • packages/http-sdk/src/lease/lease-http.service.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/http-sdk/src/lease/lease-http.service.ts
  • apps/api/src/core/providers/http-sdk.provider.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

Never use type any or cast to type any. Always define the proper TypeScript types.

Files:

  • apps/notifications/src/modules/alert/providers/http-sdk.provider.ts
**/*.{js,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/general.mdc)

**/*.{js,ts,tsx}: Never use deprecated methods from libraries.
Don't add unnecessary comments to the code

Files:

  • apps/notifications/src/modules/alert/providers/http-sdk.provider.ts
🧬 Code graph analysis (1)
apps/notifications/src/modules/alert/providers/http-sdk.provider.ts (4)
packages/http-sdk/src/utils/httpClient.ts (2)
  • HttpClient (23-23)
  • createHttpClient (5-21)
apps/notifications/src/modules/alert/config/index.ts (1)
  • AlertConfig (9-9)
packages/http-sdk/src/deployment/deployment-http.service.ts (1)
  • DeploymentHttpService (134-195)
packages/http-sdk/src/lease/lease-http.service.ts (1)
  • LeaseHttpService (56-70)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: validate / validate-app
  • GitHub Check: validate / validate-app
  • GitHub Check: test-build
  • GitHub Check: test-build
🔇 Additional comments (1)
apps/notifications/src/modules/alert/providers/http-sdk.provider.ts (1)

1-3: Type-only and Nest DI imports look good

Type-only import for HttpClient and explicit Nest types keep runtime clean and typings precise.

@stalniy stalniy merged commit 4a13f24 into main Sep 5, 2025
63 checks passed
@stalniy stalniy deleted the fix/lease-http branch September 5, 2025 06:04
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.

3 participants

Comments