Skip to content

Conversation

flevi29
Copy link
Collaborator

@flevi29 flevi29 commented Sep 27, 2025

Pull Request

Related issue

Fixes #2001

What does this PR do?

  • adds sharding support
  • adds test

Summary by CodeRabbit

  • New Features

    • Task responses can include network metadata (origin and remote task details).
    • Network updates now accept a flexible UpdatableNetwork options object.
  • Refactor

    • Public API: updateNetwork signature changed to accept UpdatableNetwork.
  • Chores

    • Public type exports reorganized and module export names standardized.
    • Removed legacy exported types and adjusted exported error/network typings.
  • Tests

    • Improved and consolidated test assertion helpers and task/batch validations.

@flevi29 flevi29 added the enhancement New feature or request label Sep 27, 2025
Copy link

coderabbitai bot commented Sep 27, 2025

Walkthrough

Updates network and tasks typings, adds UpdatableNetwork, changes MeiliSearch.updateNetwork to accept UpdatableNetwork (sent as PATCH body), reorganizes type exports (hyphenated task-and-batch), and refactors test assertion utilities and task/batch assertion helpers.

Changes

Cohort / File(s) Summary
Network types & exports
src/types/network.ts, src/types/index.ts, src/types/types.ts
Adds Remote, Network, UpdatableNetwork; re-exports ./network.js; removes older Remote/Network from types.ts; switches task_and_batch.jstask-and-batch.js.
Client API change
src/meilisearch.ts
Changes updateNetwork(network: Partial<Network>)updateNetwork(options: UpdatableNetwork) and uses options as PATCH /network body.
Shared types update
src/types/shared.ts
Replaces NonNullableDeepRecordValues with recursive DeepPartial; adds SafeOmit, OptionStarOr, OptionStarOrList.
Tasks & batches typing
src/types/task-and-batch.ts
Adds Origin, NetworkOrigin, RemoteTask, NetworkRemoteTasks; extends Task with optional network info.
Tests — assertion utilities split
tests/utils/assert.ts, tests/utils/assertions/*.ts, tests/utils/object.ts, tests/utils/meilisearch-test-utils.ts, tests/utils/tasks-and-batches.ts
Introduces modular test assertion helpers (error, promise, tasks-and-batches), merges them via tests/utils/assert.ts; adds objectKeys/objectEntries; removes old tests/utils/tasks-and-batches.ts and inlines/rewires exports in meilisearch-test-utils.ts.
Tests — client & tasks updates
tests/client.test.ts, tests/tasks-and-batches.test.ts
client.test.ts now imports UpdatableNetwork and asserts full network options; tasks-and-batches.test.ts adjusts result variable shapes and assertions to new helpers.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Dev as Client Code
  participant SDK as MeiliSearch SDK
  participant HTTP as HTTP Client
  participant API as Meilisearch Server

  Dev->>SDK: updateNetwork(options: UpdatableNetwork)
  SDK->>HTTP: PATCH /network (body: options)
  HTTP->>API: PATCH /network
  API-->>HTTP: 200 OK (Network)
  HTTP-->>SDK: Network
  SDK-->>Dev: Promise<Network>

  rect rgba(230,250,230,0.4)
    note right of API: Network may include remotes.writeApiKey and sharding flag
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

breaking-change

Suggested reviewers

  • nicolasvienot
  • Strift

Poem

I hop through types and patch the net,
Remotes and shards are placed just yet.
Tests rearranged, assertions new—
Keys and hyphens hop in view.
A rabbit cheers: small change, big set. 🐇✨

Pre-merge checks and finishing touches

❌ Failed checks (3 warnings)
Check name Status Explanation Resolution
Linked Issues Check ⚠️ Warning The pull request updates the Network methods to accept a sharding parameter, includes writeApiKey in network responses, and adds tests for updateNetwork, but it does not implement or verify the inclusion of remotes objects in task responses as required by linked issue #2001. Please extend the Tasks methods to return the remotes objects in task responses and add corresponding test cases to validate this behavior in accordance with issue #2001.
Out of Scope Changes Check ⚠️ Warning The pull request introduces extensive refactoring of shared type utilities, reorganization of test assertion modules, and changes to export patterns across type and test files that are unrelated to the core objectives of adding sharding support and updating network and task APIs. Please separate unrelated type and test utility refactoring into a dedicated pull request and limit this changeset to only the code and tests needed for sharding and task response updates.
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.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title succinctly expresses the primary enhancement by stating that the pull request adds the sharding feature, directly matching the PR objective to support sharding in the SDK and clearly communicating the main change to reviewers.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

@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 (1)
src/types/shared.ts (1)

9-12: Ensure DeepPartial preserves array shapes

When DeepPartial hits an array, it currently turns that array into an object with optional numeric keys, so DeepPartial<string[]> no longer accepts string[]. UpdatableNetwork (and any future callers) will immediately lose type safety as soon as Network gains an array member (e.g., a list of shard names or roles). A small tweak keeps array members as arrays while still recursing into their element type.

-export type DeepPartial<T> = T extends object
-  ? { [TKey in keyof T]?: DeepPartial<T[TKey]> }
-  : T;
+export type DeepPartial<T> = T extends ReadonlyArray<infer U>
+  ? ReadonlyArray<DeepPartial<U>>
+  : T extends Array<infer U>
+    ? Array<DeepPartial<U>>
+    : T extends object
+      ? { [TKey in keyof T]?: DeepPartial<T[TKey]> }
+      : T;
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4f7c885 and 2becefb.

📒 Files selected for processing (7)
  • src/meilisearch.ts (2 hunks)
  • src/types/index.ts (1 hunks)
  • src/types/network.ts (1 hunks)
  • src/types/shared.ts (1 hunks)
  • src/types/task-and-batch.ts (2 hunks)
  • src/types/types.ts (1 hunks)
  • tests/client.test.ts (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (4)
tests/client.test.ts (2)
src/types/network.ts (1)
  • UpdatableNetwork (17-17)
tests/utils/meilisearch-test-utils.ts (1)
  • assert (231-234)
src/types/network.ts (1)
src/types/shared.ts (1)
  • DeepPartial (10-12)
src/types/task-and-batch.ts (1)
src/types/types.ts (1)
  • MeiliSearchErrorResponse (825-832)
src/meilisearch.ts (1)
src/types/network.ts (2)
  • UpdatableNetwork (17-17)
  • Network (11-15)
⏰ 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: integration-tests (Node.js 20)
  • GitHub Check: integration-tests (Node.js 22)
🔇 Additional comments (2)
src/meilisearch.ts (1)

387-389: Deep-partial typing unlocks granular updates

Switching to UpdatableNetwork lets callers patch just the sharding flag or remote write keys without rebuilding full objects, while the request flow stays unchanged. Looks solid.

src/types/network.ts (1)

1-18: Network typings now cover sharding and write keys

The dedicated Remote/Network types model the new API surface, and the DeepPartial alias makes partial network updates ergonomic. Nice addition.

Copy link

codecov bot commented Sep 27, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.83%. Comparing base (4f7c885) to head (b6a39a5).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2037      +/-   ##
==========================================
- Coverage   98.83%   98.83%   -0.01%     
==========================================
  Files          18       18              
  Lines        1549     1547       -2     
  Branches      334      334              
==========================================
- Hits         1531     1529       -2     
  Misses         18       18              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link

@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 (1)
tests/utils/assertions/error.ts (1)

5-10: Relax the key-count assertion to future-proof error checks

Hard-coding assert.lengthOf(..., 4) will break as soon as the API grows an optional field (e.g. details). Dropping that length check keeps the helper resilient while still validating the required properties.

-    assert.lengthOf(Object.keys(error), 4);
     const { message, code, type, link } = error;
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2becefb and b6a39a5.

📒 Files selected for processing (8)
  • tests/tasks-and-batches.test.ts (3 hunks)
  • tests/utils/assert.ts (1 hunks)
  • tests/utils/assertions/error.ts (1 hunks)
  • tests/utils/assertions/promise.ts (1 hunks)
  • tests/utils/assertions/tasks-and-batches.ts (1 hunks)
  • tests/utils/meilisearch-test-utils.ts (2 hunks)
  • tests/utils/object.ts (1 hunks)
  • tests/utils/tasks-and-batches.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • tests/utils/tasks-and-batches.ts
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-09-04T06:44:01.679Z
Learnt from: flevi29
PR: meilisearch/meilisearch-js#2012
File: tests/client.test.ts:13-13
Timestamp: 2025-09-04T06:44:01.679Z
Learning: The meilisearch-js project supports Node.js 20 and above, so JSON imports should use the modern `with { type: "json" }` syntax rather than the deprecated `assert { type: "json" }` syntax.

Applied to files:

  • tests/utils/meilisearch-test-utils.ts
🧬 Code graph analysis (3)
tests/utils/assert.ts (3)
tests/utils/assertions/error.ts (1)
  • errorAssertions (4-12)
tests/utils/assertions/promise.ts (1)
  • promiseAssertions (6-43)
tests/utils/assertions/tasks-and-batches.ts (1)
  • tasksAndBatchesAssertions (38-229)
tests/utils/assertions/error.ts (1)
src/types/types.ts (1)
  • MeiliSearchErrorResponse (825-832)
tests/utils/assertions/tasks-and-batches.ts (3)
tests/utils/object.ts (1)
  • objectKeys (1-3)
src/types/task-and-batch.ts (7)
  • TaskStatus (33-35)
  • TaskType (42-56)
  • EnqueuedTask (97-103)
  • Batch (236-245)
  • TasksResults (194-194)
  • BatchesResults (252-252)
  • Task (156-167)
tests/utils/assertions/error.ts (1)
  • errorAssertions (4-12)
⏰ 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: integration-tests (Node.js 22)
  • GitHub Check: integration-tests (Node.js 20)
🔇 Additional comments (6)
tests/tasks-and-batches.test.ts (3)

5-12: Consolidated helper imports keep these tests tidy

Pulling assert and objectEntries from the barrel keeps the helper surface compact.


35-101: Nice exhaustive coverage of the query variants

Enumerating every supported filter alongside the * fallbacks gives the parameterized runs great coverage.


194-215: Stricter result-shape validation is spot on

Validating with isTasksOrBatchesResults before drilling into items will surface regressions around total/from/next with minimal boilerplate.

tests/utils/object.ts (1)

1-8: Typed entry/key helpers make the parameterized tests clearer

These narrowed wrappers eliminate downstream casts when feeding describe.for, keeping the suites expressive.

tests/utils/assert.ts (1)

6-18: I like the single custom assert surface

Merging vitest’s assert with the domain-specific suites keeps call sites focused while preserving the base assertions.

tests/utils/assertions/promise.ts (1)

6-43: Promise helpers cover the usual edge cases

Capturing the thrown error and supporting optional message matchers will save a lot of repetitive test boilerplate.

Comment on lines +55 to +58
assert.lengthOf(Object.keys(batch), 8);

const { uid, progress, details, stats, duration, startedAt, finishedAt } =
batch;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Fix batch key count expectation

Batch currently defines 7 required properties (uid, progress, details, stats, duration, startedAt, finishedAt) in src/types/task-and-batch.ts. Requiring Object.keys(batch) to return 8 entries makes this helper explode for every valid payload that doesn’t include an extra field (e.g. network), so all tests using it will fail. Please relax the count and explicitly validate the optional network shape instead.

-    assert.lengthOf(Object.keys(batch), 8);
-
-    const { uid, progress, details, stats, duration, startedAt, finishedAt } =
-      batch;
+    const batchKeys = Object.keys(batch);
+    assert(
+      batchKeys.length === 7 || batchKeys.length === 8,
+      `expected batch to have 7 or 8 keys, got ${batchKeys.length}`,
+    );
+
+    const { uid, progress, details, stats, duration, startedAt, finishedAt } =
+      batch;
+    const network = (batch as { network?: unknown }).network;
+    assert(
+      network === undefined || (network !== null && typeof network === "object"),
+      "expected network to be undefined or an object",
+    );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
assert.lengthOf(Object.keys(batch), 8);
const { uid, progress, details, stats, duration, startedAt, finishedAt } =
batch;
// relaxed key count (7 required props, +1 optional network)
const batchKeys = Object.keys(batch);
assert(
batchKeys.length === 7 || batchKeys.length === 8,
`expected batch to have 7 or 8 keys, got ${batchKeys.length}`,
);
const { uid, progress, details, stats, duration, startedAt, finishedAt } =
batch;
// optional `network` must be undefined or an object
const network = (batch as { network?: unknown }).network;
assert(
network === undefined || (network !== null && typeof network === "object"),
"expected network to be undefined or an object",
);
🤖 Prompt for AI Agents
In tests/utils/assertions/tasks-and-batches.ts around lines 55 to 58, the
assertion expects 8 keys on batch but the Batch type defines 7 required
properties; change the length assertion to expect 7 instead of 8, and add an
explicit conditional check for the optional network property (if batch.network
exists, assert its shape separately) rather than counting it as required in
Object.keys(batch). Ensure the existing destructuring of uid, progress, details,
stats, duration, startedAt, finishedAt remains and add a dedicated assertion
block for batch.network when present.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[v1.19.0] Add sharding support

1 participant