Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(web,server,worker): resolve threads bug in copier #1367

Merged
merged 4 commits into from
Jan 21, 2025

Conversation

nourbalaha
Copy link
Contributor

@nourbalaha nourbalaha commented Jan 21, 2025

Overview

This PR resolves threads bug when copying items with copier

Summary by CodeRabbit

Release Notes

  • New Features

    • None
  • Bug Fixes

    • Improved handling of thread references in various components
    • Enhanced nullable support for thread-related fields in GraphQL schema
  • Refactor

    • Updated dependency management
    • Modified item and thread-related data handling across multiple services
  • Documentation

    • None
  • Style

    • Converted ULID strings to lowercase in worker infrastructure

Copy link
Contributor

coderabbitai bot commented Jan 21, 2025

Walkthrough

This pull request introduces a series of changes across multiple files to modify how thread-related fields are handled, primarily making them nullable. The modifications span the GraphQL schema, resolver functions, data models, and various infrastructure components. The changes aim to provide more flexibility in handling thread associations, allowing for optional thread references in items and adjusting the corresponding data processing logic accordingly.

Changes

File Change Summary
server/go.mod Added github.com/labstack/gommon v0.4.2 as a direct dependency
server/schemas/item.graphql Changed threadId and thread fields from non-nullable to nullable types
server/internal/adapter/gql/... Updated GraphQL resolvers and generated code to handle nullable thread fields
server/internal/infrastructure/mongo/... Modified item document creation to conditionally handle thread references
web/src/components/... Added optional chaining for thread comments access

Sequence Diagram

sequenceDiagram
    participant Client
    participant GraphQL
    participant Resolver
    participant DataLoader
    participant Database

    Client->>GraphQL: Query Item
    GraphQL->>Resolver: Resolve Item
    Resolver->>DataLoader: Load Thread (if ThreadID exists)
    alt ThreadID is not null
        DataLoader->>Database: Fetch Thread
        Database-->>DataLoader: Return Thread
        DataLoader-->>Resolver: Return Thread
    else ThreadID is null
        Resolver-->>GraphQL: Return null
    end
    GraphQL-->>Client: Return Item with optional Thread
Loading

Possibly related PRs

Suggested Reviewers

  • rot1024
  • yk-eukarya

Poem

🐰 A Rabbit's Tale of Nullable Threads

Threads that dance, now free to be nil,
GraphQL schema with a softer will,
Resolvers adapt with graceful might,
Optional links, no longer tight!

Hop, hop, hooray for flexible code! 🌈

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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.
    • Generate unit testing code for this file.
    • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai 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

Documentation and Community

  • 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.

Copy link

netlify bot commented Jan 21, 2025

Deploy Preview for reearth-cms canceled.

Name Link
🔨 Latest commit dfdf4bf
🔍 Latest deploy log https://app.netlify.com/sites/reearth-cms/deploys/678fa1c1dcdf780008a4a5c7

@nourbalaha nourbalaha marked this pull request as ready for review January 21, 2025 14:28
@nourbalaha nourbalaha requested a review from rot1024 as a code owner January 21, 2025 14:28
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: 2

🧹 Nitpick comments (4)
server/internal/adapter/gql/generated.go (1)

5796-5798: LGTM! Making threadId nullable improves data model flexibility.

The change to make threadId nullable is a good architectural decision as it allows items to exist without requiring a thread association.

server/internal/infrastructure/mongo/mongodoc/item.go (2)

92-94: Consider consolidating thread validation logic.

The thread validation is now split between document creation and model conversion. Consider extracting this logic into a shared helper function to ensure consistent validation.


157-163: Improve error handling for thread ID conversion.

The error from ThreadIDFrom should include context about which field failed conversion. Consider wrapping the error with additional context.

 if d.Thread != "" {
   tid, err := id.ThreadIDFrom(d.Thread)
   if err != nil {
-    return nil, err
+    return nil, fmt.Errorf("invalid thread ID %q: %w", d.Thread, err)
   }
   ib.Thread(tid)
 }
server/schemas/item.graphql (1)

4-4: LGTM! Consider updating documentation

The schema changes correctly make thread-related fields nullable. This is a breaking change that should be documented for API consumers.

Consider:

  1. Adding a comment in the schema explaining why these fields are nullable
  2. Updating API documentation to reflect this change
  3. Adding a migration guide for existing consumers

Also applies to: 19-19

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4946996 and dfdf4bf.

📒 Files selected for processing (13)
  • server/go.mod (1 hunks)
  • server/internal/adapter/gql/generated.go (5 hunks)
  • server/internal/adapter/gql/gqlmodel/convert_item.go (2 hunks)
  • server/internal/adapter/gql/gqlmodel/convert_item_test.go (1 hunks)
  • server/internal/adapter/gql/gqlmodel/models_gen.go (2 hunks)
  • server/internal/adapter/gql/resolver_item.go (1 hunks)
  • server/internal/infrastructure/mongo/mongodoc/item.go (3 hunks)
  • server/internal/usecase/interactor/model.go (1 hunks)
  • server/pkg/item/builder.go (1 hunks)
  • server/pkg/item/builder_test.go (1 hunks)
  • server/schemas/item.graphql (2 hunks)
  • web/src/components/organisms/Project/Content/ContentList/hooks.ts (1 hunks)
  • worker/internal/infrastructure/mongo/copier.go (2 hunks)
✅ Files skipped from review due to trivial changes (2)
  • web/src/components/organisms/Project/Content/ContentList/hooks.ts
  • server/internal/usecase/interactor/model.go
🔇 Additional comments (11)
server/internal/adapter/gql/generated.go (4)

5811-5814: LGTM! Thread field nullability matches threadId.

The change maintains consistency between thread and threadId fields, ensuring proper type safety in the GraphQL schema.


15855-15855: LGTM! Marshaling function correctly handles nullable thread.

The change to use marshalOThread properly implements the nullable thread field from the schema.


43614-43622: LGTM! Robust error handling in thread resolver.

The implementation includes proper panic recovery and error handling, following GraphQL resolver best practices.


15151-15153: Verify error handling for null threadId values.

The changes to handle nullable threadId look good, but let's verify the error handling in the resolver chain.

✅ Verification successful

Error handling for null threadId values is properly implemented

The resolver chain includes appropriate null checks and error handling at both the field context and resolver levels.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for error handling patterns in resolver chain
rg -A 5 "func.*_Item_threadId" server/

Length of output: 1070

worker/internal/infrastructure/mongo/copier.go (1)

101-101: Ensure case-insensitive ULID handling across the system.

Converting ULIDs to lowercase is good for consistency, but verify:

  1. Existing ULID comparisons are case-insensitive
  2. No parts of the system expect uppercase ULIDs
✅ Verification successful

ULID case handling is consistent across the system

The codebase already follows a consistent approach for ULID case handling:

  • Frontend generates lowercase ULIDs
  • Backend converts ULIDs to lowercase when needed
  • No case-sensitive comparisons found
  • Tests enforce lowercase format
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for case-sensitive ULID comparisons
rg -A 2 'ulid.*==|==.*ulid'

# Look for potential ULID string manipulations
ast-grep --pattern 'ulid.$$$String()'

Length of output: 69


Script:

#!/bin/bash
# Find ULID-related code with broader patterns
rg -i "ulid" -A 3

# Find string comparisons that might involve IDs
rg -A 2 'strings\.Equal|strings\.Compare|strings\.EqualFold'

# Look for ULID type declarations and implementations
ast-grep --pattern 'type $_ struct {
  $$$
  ULID $$$
  $$$
}'

Length of output: 3967

server/pkg/item/builder_test.go (1)

170-182: Verify the impact of removing thread validation

The removal of this test case aligns with making thread fields optional. However, we should ensure that:

  1. This change doesn't affect existing items with threads
  2. The system handles the transition between required and optional threads correctly
✅ Verification successful

Thread validation remains robust despite test case removal

The removal of this test case is safe because:

  • ThreadID validation is enforced at the type system level through idx.ID[Thread]
  • Other test cases in the file continue to verify thread-related functionality
  • The base validation is handled by the underlying idx package
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for existing items that might be affected by the thread field change
ast-grep --pattern 'func $name($params) {
  $$$
  thread: $thread
  $$$
}'

Length of output: 76


Script:

#!/bin/bash
# Search for thread-related code and validation
echo "=== Thread field declarations ==="
rg "thread\s+[*]?(?:string|Thread)" -t go

echo -e "\n=== Thread validation logic ==="
rg "validate.*[Tt]hread|[Tt]hread.*validate" -t go

echo -e "\n=== Thread usage in tests ==="
rg "thread:" server/pkg/item/

Length of output: 847


Script:

#!/bin/bash
# Check ThreadID type and schema definitions
echo "=== ThreadID type definition ==="
rg "type ThreadID" -A 5 -t go

echo -e "\n=== Thread-related schema changes ==="
rg "thread.*\b(optional|nullable)" -t go

echo -e "\n=== ThreadID validation or conversion ==="
ast-grep --pattern 'func $name($_) ThreadID {
  $$$
}'

Length of output: 1720

server/internal/adapter/gql/resolver_item.go (1)

51-54: LGTM! Proper null handling implemented

The resolver now correctly handles the case where ThreadID is nil, returning null without attempting to load the thread. This is a clean implementation that aligns with GraphQL best practices.

server/internal/adapter/gql/gqlmodel/models_gen.go (1)

527-527: LGTM! Proper nullable field implementation

The changes correctly implement nullable fields in the Go struct:

  • ThreadID is now a pointer type (*ID) to support null values
  • The omitempty tag ensures proper JSON serialization

Also applies to: 542-542

server/internal/adapter/gql/gqlmodel/convert_item.go (2)

44-44: LGTM! Clean and maintainable code.

Returning the address of a local variable is cleaner than returning an inline struct pointer.


Line range hint 23-43: LGTM! The thread handling is now more robust.

The conditional assignment of ThreadID prevents potential nil pointer dereferences and aligns with making thread fields nullable.

Let's verify that this change doesn't break existing thread references:

✅ Verification successful

ThreadID handling is consistent across the codebase

The null-safe ThreadID assignment pattern is correctly implemented and aligns with:

  • Nullable ThreadID fields in the GraphQL schema
  • Null-safe resolver implementations
  • Consistent use of IDFromRef for nullable references
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for direct thread ID assignments that might need similar null checks
rg -l "ThreadID\s*=\s*(?!IDFromRef)" --type go

Length of output: 295


Script:

#!/bin/bash
# Find ThreadID assignments using ast-grep
ast-grep --pattern 'ThreadID = $_'

# Backup search using ripgrep for ThreadID occurrences with context
rg "ThreadID.*=" -A 2 -B 2 --type go

Length of output: 6326

server/go.mod (1)

26-26: Verify direct usage of the gommon package.

The dependency has been promoted from indirect to direct. Let's ensure it's being used directly in the codebase.

✅ Verification successful

Direct usage of gommon package confirmed

The package is properly imported and used for error logging in server/internal/usecase/interactor/item_export.go. The promotion to a direct dependency is correct.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for direct imports of gommon package
rg -l "github.com/labstack/gommon" --type go

Length of output: 94


Script:

#!/bin/bash
# Check the specific import and usage context
rg "github.com/labstack/gommon" server/internal/usecase/interactor/item_export.go -B 2 -A 5

Length of output: 368


Script:

#!/bin/bash
# Check for actual usage of the log package
rg "log\." server/internal/usecase/interactor/item_export.go -B 2 -A 5

Length of output: 228

server/pkg/item/builder.go Show resolved Hide resolved
@nourbalaha nourbalaha merged commit ed5b3f1 into main Jan 21, 2025
28 checks passed
@nourbalaha nourbalaha deleted the fix-copier-item-thread branch January 21, 2025 14:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants