Skip to content

Conversation

@MohamedBassem
Copy link
Collaborator

No description provided.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 29, 2025

Walkthrough

This pull request refactors network operations in apps/workers/network.ts from ad-hoc promise-based patterns to Effect-based functional programming. The refactor introduces DNS caching with TTL, structured error types, and staged effect composition for URL validation, proxy agent resolution, and HTTP fetching. Supporting changes add the Effect library dependency and update worker files to consume the new Either-based validation API.

Changes

Cohort / File(s) Change Summary
Effect library integration
package.json, apps/workers/package.json
Added @effect/language-service dev dependency and prepare script to root; added effect dependency to workers package.
TypeScript compiler configuration
tooling/typescript/base.json
Registered @effect/language-service plugin in TypeScript compiler options.
Network module refactor
apps/workers/network.ts
Rewrote DNS resolution, URL validation, and proxy handling using Effect system; introduced DnsResolverService, DnsCache, and structured error classes (FetchError, UrlParseError, UrlValidationError, HostAddressResolutionError); converted validateUrl, getProxyAgent, matchesNoProxy, and fetchWithProxy to effect-based implementations.
Worker adapters
apps/workers/workers/crawlerWorker.ts, apps/workers/workers/videoWorker.ts
Updated URL validation result handling from ok/reason flags to Either-based structure; adjusted error message extraction to use validation.left.message and value extraction to use validation.right.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • apps/workers/network.ts: Dense refactor introducing new Error taxonomy, service layers (DnsResolverService, DnsCache, DnsResolverLive), staged Effect.gen composition, and API signature changes; requires understanding of Effect patterns and error propagation.
  • Worker files: Propagated API changes from network.ts; Either-based validation logic and error extraction paths need verification for correctness across both files.
  • Dependency and tooling changes: New library integration and build tooling require verification of compatibility and proper setup.

Possibly related PRs

  • #2082: Directly modifies the same network.ts module with validateUrl, DNS caching, proxy logic, and fetchWithProxy implementations that this PR refactors to use the Effect system.

Pre-merge checks

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description check ❓ Inconclusive No pull request description was provided by the author, making it impossible to assess whether the description relates to the changeset. Add a description explaining the refactoring motivation, key changes made, and any migration implications for consumers of the affected modules.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title 'refactor: Effect-ify the workers' clearly and specifically describes the main change: converting the worker modules to use the Effect library for handling promises and error management.

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.

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 (6)
apps/workers/workers/videoWorker.ts (1)

4-4: Video worker’s migration to Either-based URL validation looks correct

Importing Either and switching to Either.isRight(validation) with validation.right.toString() for the normalized URL aligns with the new validateUrl return type; logging validation.left.message on failure keeps behavior clear while honoring the new error model.

If you want more diagnostic detail when debugging URL issues, you could also log validation.left._tag (error type) alongside message.

Also applies to: 111-118

apps/workers/workers/crawlerWorker.ts (1)

13-13: Crawler worker’s switch to Either-based URL validation is sound

The new Either import and usage (Either.isRight, .left.message, .right.toString()) for both sub-request blocking and main navigation correctly match the refactored validateUrl contract and preserve the intended control flow (block disallowed URLs, throw on invalid navigation targets).

If you need to distinguish parse/DNS/validation failures operationally, consider also logging validation.left._tag in addition to .message.

Also applies to: 511-518, 525-535

apps/workers/network.ts (4)

70-90: DNS resolver service and cache logic look correct and safe

The DnsResolverService Context tag, DnsResolverLive layer, and DnsCache (5‑minute TTL, capacity 1000, dual A/AAAA lookup via Effect.all + Either) form a reasonable, side‑effect‑controlled DNS resolution path, and the code correctly fails with HostAddressResolutionError when no addresses are resolved.

If DNS resolution becomes a bottleneck, consider tightening capacity/TTL or adding simple metrics around cache hit/miss rates for observability.

Also applies to: 92-140


268-277: matchesNoProxy and getProxyAgent correctly wrap the new Effect-based helpers

The effectful implementations—matchesNoProxyEffect (with graceful fallback on UrlParseError) and getProxyAgentEffect (respecting noProxy and protocol-specific proxy lists)—mirror prior behavior while centralizing parsing and validation; the exported wrappers using Effect.runSync keep the public API synchronous for existing callers.

You might later consolidate the proxy-selection logic (HTTP vs HTTPS vs fallback) into a small helper to ease testing, but it’s fine as-is.

Also applies to: 278-310


414-483: fetchWithProxy Effect-based redirect loop appears correct and bounded

The new fetchWithProxy uses prepareFetchOptions + buildFetchOptions, resolves an agent via getProxyAgentEffect, validates each hop via validateUrlEffect, and handles redirects manually with a clear maxRedirects limit and a FetchError on exhaustion; non-redirect responses or missing Location headers correctly terminate the loop.

If you expect many redirects, you might consider logging when maxRedirects is hit to distinguish “too many redirects” from other FetchError cases in your metrics.


157-160: UrlValidationResult type is unused and should be removed

The exported UrlValidationResult type (lines 157–160) is never referenced anywhere in the codebase. The validateUrl function correctly returns Promise<Either<UrlValidationError, URL>> via the Effect pipeline, which is the actual contract being used by callers in videoWorker.ts and crawlerWorker.ts.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e67c33e and 02c1d01.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (6)
  • apps/workers/network.ts (4 hunks)
  • apps/workers/package.json (1 hunks)
  • apps/workers/workers/crawlerWorker.ts (3 hunks)
  • apps/workers/workers/videoWorker.ts (2 hunks)
  • package.json (2 hunks)
  • tooling/typescript/base.json (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx,js,jsx,json,css,md}

📄 CodeRabbit inference engine (AGENTS.md)

Format code using Prettier according to project standards

Files:

  • package.json
  • tooling/typescript/base.json
  • apps/workers/workers/videoWorker.ts
  • apps/workers/workers/crawlerWorker.ts
  • apps/workers/package.json
  • apps/workers/network.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use TypeScript for type safety in all source files

Files:

  • apps/workers/workers/videoWorker.ts
  • apps/workers/workers/crawlerWorker.ts
  • apps/workers/network.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

Lint code using oxlint and fix issues with pnpm lint:fix

Files:

  • apps/workers/workers/videoWorker.ts
  • apps/workers/workers/crawlerWorker.ts
  • apps/workers/network.ts
🧠 Learnings (1)
📚 Learning: 2025-11-27T16:02:47.432Z
Learnt from: CR
Repo: karakeep-app/karakeep PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-11-27T16:02:47.432Z
Learning: Applies to **/*.{ts,tsx,js,jsx} : Lint code using oxlint and fix issues with `pnpm lint:fix`

Applied to files:

  • package.json
🧬 Code graph analysis (1)
apps/workers/network.ts (1)
packages/trpc/index.ts (1)
  • Context (22-28)
🪛 Biome (2.1.2)
package.json

[error] 7-7: The key prepare was already declared.

This where a duplicated key was declared again.

If a key is defined multiple times, only the last definition takes effect. Previous definitions are ignored.

(lint/suspicious/noDuplicateObjectKeys)

⏰ 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). (2)
  • GitHub Check: tests
  • GitHub Check: typecheck
🔇 Additional comments (4)
package.json (1)

30-30: New @effect/language-service devDependency looks appropriate

Adding @effect/language-service here aligns with the new TS plugin configuration and Effect-based code in workers; no issues from this change alone.

Please just confirm locally that pnpm install plus tsserver/IDE pick up the plugin without additional configuration.

tooling/typescript/base.json (1)

18-23: TS config changes for Effect plugin look consistent

Setting noUncheckedIndexedAccess explicitly and wiring @effect/language-service into compilerOptions.plugins is coherent with the new devDependency; no issues from a tooling standpoint.

Please confirm in your environment that tsc --showConfig (or your IDE) reflects the plugin and that diagnostics from the Effect language service work as expected.

apps/workers/package.json (1)

22-22: Adding effect runtime dependency is appropriate

Including effect@^3.19.8 in workers’ dependencies matches the new Effect-based networking and validation code.

After installing, please verify pnpm-lock.yaml (or equivalent) is updated and that pnpm --filter @karakeep/workers test / typecheck run clean against this version.

apps/workers/network.ts (1)

3-13: Error modeling with Schema.TaggedError and parseUrl is well-structured

The introduction of FetchError, UrlValidationError, UrlParseError, and HostAddressResolutionError plus the parseUrl helper gives you a clear, typed error taxonomy around DNS, URL parsing, validation, and fetch failures; the Effect.try usage cleanly wraps new URL(...) into a tagged error path.

Please ensure downstream code (e.g., logging/metrics) treats these tagged errors as expected (e.g., by _tag or message) and doesn’t rely on older string-based reasons.

Also applies to: 20-50

"version": "0.1.0",
"private": true,
"scripts": {
"prepare": "effect-language-service patch",
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Duplicate prepare script means the new command never runs

You now have two prepare keys (lines 7 and 17); only the last one (husky) is honored, so effect-language-service patch is effectively disabled. Consider merging into a single script, e.g.:

-  "scripts": {
-    "prepare": "effect-language-service patch",
+  "scripts": {
+    "prepare": "husky && effect-language-service patch",

(or the opposite order, depending on which you prefer to run first).

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Biome (2.1.2)

[error] 7-7: The key prepare was already declared.

This where a duplicated key was declared again.

If a key is defined multiple times, only the last definition takes effect. Previous definitions are ignored.

(lint/suspicious/noDuplicateObjectKeys)

🤖 Prompt for AI Agents
In package.json around line 7, there are duplicate "prepare" scripts so only the
later husky script is executed and "effect-language-service patch" is skipped;
remove the duplicate key and merge the two commands into a single "prepare"
script that runs both commands in the desired order (e.g., run
effect-language-service patch first, then husky install) by joining them with a
shell operator (&&) or using a task runner, and delete the extra "prepare" entry
so only the combined script remains.

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.

2 participants