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

chore(server): move export csv items and GeoJSON ability to Item Usecase Layer #1347

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

jasonkarel
Copy link
Contributor

@jasonkarel jasonkarel commented Jan 8, 2025

Overview

Moving ItemsAsCSV and ItemsAsGeoJSON data export ability to usecase layer

What I've done

What I haven't done

How I tested

local:
testing in local environment. ensuring csv is generated through /api/models/01jd19w4esd28p6m45sn35mycs/items.csv?page=1&perPage=50&ref=latest

cases:

  1. success case. generates the CSV/GeoJSON
  2. error case pointFieldIsNotSupportedError.
  3. pagination cases.
  4. ID not found cases

Screenshot

Which point I want you to review particularly

  1. Code best practice.
  2. Code functionality to the existing import csv feature.

Memo

Summary by CodeRabbit

Release Notes

  • New Features

    • Added export functionality for items in CSV and GeoJSON formats.
    • Implemented pagination support for item exports.
  • Improvements

    • Enhanced error handling for export operations, including more precise error categorization.
    • Simplified response construction for item exports.
  • Technical Updates

    • Refined item retrieval and conversion methods to improve clarity and efficiency.
    • Introduced new types and methods for handling export responses.

@jasonkarel jasonkarel requested a review from yk-eukarya as a code owner January 8, 2025 08:25
Copy link
Contributor

coderabbitai bot commented Jan 8, 2025

Walkthrough

The changes introduce new functionality for exporting items in CSV and GeoJSON formats across multiple components of the server. The implementation adds methods to retrieve and convert items with support for pagination and operator-based access control. New export methods are introduced in the item interactor, interfaces, and adapter layers, enabling flexible data export capabilities with robust error handling and format conversion.

Changes

File Change Summary
server/internal/adapter/integration/item.go - Renamed sp to schemaPackage
- Updated error response types from 400 to 404
- Modified item retrieval logic to use dedicated methods for GeoJSON and CSV
- Simplified response construction for exports
server/internal/usecase/interactor/item.go - Added ItemsAsCSV and ItemsAsGeoJSON methods
- Introduced fromPagination helper function for pagination
- Added constants for pagination limits
server/internal/usecase/interactor/item_export.go - Added functions for converting items to GeoJSON feature collections
- Implemented CSV generation with error handling
- Created goroutine-based CSV export mechanism
server/internal/usecase/interfaces/item.go - Added ExportItemsToCSVResponse type with PipeReader
- Added ExportItemsToGeoJSONResponse type with FeatureCollections
- Introduced new interface methods for item export
server/internal/usecase/interactor/item_export_test.go - Added TestCSVFromItems to validate csvFromItems functionality
server/internal/usecase/interactor/item_test.go - Added TestItem_ItemsAsCSV and TestItem_ItemsAsGeoJSON for testing export functionalities

Sequence Diagram

sequenceDiagram
    participant Client
    participant Adapter
    participant Interactor
    participant Repository

    Client->>Adapter: Request Items Export
    Adapter->>Interactor: Call ItemsAsGeoJSON/ItemsAsCSV
    Interactor->>Repository: Fetch Items with Pagination
    Repository-->>Interactor: Return Versioned Items
    Interactor->>Interactor: Convert Items to Format
    Interactor-->>Adapter: Return Exported Data
    Adapter-->>Client: Stream Exported Items
Loading

Poem

🐰 Hop, hop, data's on the move!
CSV and GeoJSON groove
Pagination dances with grace
Export magic leaves no trace
Rabbit's code leaps with delight! 🌈


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4c1a689 and 8a9b4cf.

📒 Files selected for processing (1)
  • server/internal/adapter/integration/item.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • server/internal/adapter/integration/item.go

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.

@github-actions github-actions bot added the server label Jan 8, 2025
Copy link

netlify bot commented Jan 8, 2025

Deploy Preview for reearth-cms canceled.

Name Link
🔨 Latest commit 8a9b4cf
🔍 Latest deploy log https://app.netlify.com/sites/reearth-cms/deploys/677e43e524e77a0008a9079a

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: 3

🧹 Nitpick comments (7)
server/internal/usecase/interactor/item_export.go (2)

33-41: Add error handling for pipe writer close operations.

The function ignores errors from pw.Close() and pw.CloseWithError(). While this might be acceptable in some cases, it's better to log these errors for debugging purposes.

Apply this diff to improve error handling:

 func handleCSVGeneration(pw *io.PipeWriter, l item.VersionedList, s *schema.Schema) {
 	err := generateCSV(pw, l, s)
 	if err != nil {
 		log.Errorf("failed to generate CSV: %v", err)
-		_ = pw.CloseWithError(err)
+		if closeErr := pw.CloseWithError(err); closeErr != nil {
+			log.Errorf("failed to close pipe writer with error: %v", closeErr)
+		}
 	} else {
-		_ = pw.Close()
+		if closeErr := pw.Close(); closeErr != nil {
+			log.Errorf("failed to close pipe writer: %v", closeErr)
+		}
 	}
 }

42-62: Add timeout mechanism to prevent potential memory leaks.

The CSV generation process could potentially run indefinitely without any timeout mechanism, which might lead to memory leaks if clients disconnect unexpectedly.

Consider implementing a timeout mechanism using context:

-func generateCSV(pw *io.PipeWriter, l item.VersionedList, s *schema.Schema) error {
+func generateCSV(ctx context.Context, pw *io.PipeWriter, l item.VersionedList, s *schema.Schema) error {
 	w := csv.NewWriter(pw)
 	defer w.Flush()
+
+	done := make(chan error, 1)
+	go func() {
 	headers := integrationapi.BuildCSVHeaders(s)
 	if err := w.Write(headers); err != nil {
-		return err
+		done <- err
+		return
 	}
 	nonGeoFields := lo.Filter(s.Fields(), func(f *schema.Field, _ int) bool {
 		return !f.IsGeometryField()
@@ -53,10 +56,19 @@
 		row, ok := integrationapi.RowFromItem(ver.Value(), nonGeoFields)
 		if ok {
 			if err := w.Write(row); err != nil {
-				return err
+				done <- err
+				return
 			}
 		}
 	}
+	done <- w.Error()
+	}()
 
-	return w.Error()
+	select {
+	case <-ctx.Done():
+		return ctx.Err()
+	case err := <-done:
+		return err
+	}
 }
server/internal/usecase/interactor/item.go (3)

29-30: Ensure type consistency for pagination constants

The pagination constants have inconsistent types: maxPerPage is untyped int while defaultPerPage is int64. This could lead to unnecessary type conversions.

-const maxPerPage = 100
-const defaultPerPage int64 = 50
+const maxPerPage int64 = 100
+const defaultPerPage int64 = 50

1214-1215: Enhance method documentation

The method documentation should include details about the response structure and any validation rules for the GeoJSON conversion.

-// ItemsAsGeoJSON converts items to Geo JSON type given the schema package
+// ItemsAsGeoJSON converts items to GeoJSON format based on the schema package.
+// It returns a FeatureCollection containing all valid geometry fields from the items.
+// Only items with valid geometry fields will be included in the response.
+// Returns an error if no geometry fields are found in the schema or if the operator is invalid.
func (i Item) ItemsAsGeoJSON(ctx context.Context, schemaPackage *schema.Package, page *int, perPage *int, operator *usecase.Operator) (interfaces.ExportItemsToGeoJSONResponse, error) {

1242-1263: Add documentation and input validation

The helper function lacks documentation and could benefit from additional input validation.

+// fromPagination creates a pagination object from page and perPage parameters.
+// If page is nil or <= 0, defaults to 1.
+// If perPage is nil, uses defaultPerPage.
+// If perPage > maxPerPage, uses maxPerPage.
+// Returns a configured pagination object with calculated offset and limit.
 func fromPagination(page, perPage *int) *usecasex.Pagination {
+    if page == nil && perPage == nil {
+        return usecasex.OffsetPagination{
+            Offset: 0,
+            Limit:  defaultPerPage,
+        }.Wrap()
+    }
+
     p := int64(1)
     if page != nil && *page > 0 {
         p = int64(*page)
     }
server/internal/usecase/interactor/item_test.go (2)

1089-1253: Improve test organization and assertions in TestItem_ItemsAsCSV

The test cases are comprehensive but could be improved:

  1. Consider using test helper functions to reduce duplication in test setup
  2. Add test cases for concurrent access to the pipe reader
  3. Add assertions for error cases in pipe reading

Example test helper:

func setupTestSchema(t *testing.T, fields schema.FieldList) (*schema.Schema, *model.Model) {
    t.Helper()
    prj := project.New().NewID().Workspace(accountdomain.NewWorkspaceID()).RequestRoles([]workspace.Role{workspace.RoleReader, workspace.RoleWriter}).MustBuild()
    s := schema.New().NewID().Workspace(prj.Workspace()).Project(prj.ID()).Fields(fields).MustBuild()
    m := model.New().NewID().Schema(s.ID()).Key(id.RandomKey()).Project(s.Project()).MustBuild()
    return s, m
}

1255-1422: Enhance test coverage in TestItem_ItemsAsGeoJSON

The test cases could be improved:

  1. Add test cases for invalid GeoJSON data
  2. Test pagination edge cases (empty pages, last page)
  3. Add test cases for concurrent access

Example test cases to add:

{
    name: "invalid_geojson",
    args: args{
        ctx:           context.Background(),
        schemaPackage: sp1,
        page:          &page1,
        perPage:       &perPage1,
        op:            op,
    },
    seedsItems: item.List{itemWithInvalidGeoJSON},
    want:       nil,
    wantError:  errInvalidGeoJSON,
},
{
    name: "empty_page",
    args: args{
        ctx:           context.Background(),
        schemaPackage: sp1,
        page:          lo.ToPtr(999),
        perPage:       &perPage1,
        op:            op,
    },
    seedsItems: item.List{i1},
    want:       emptyFeatureCollection,
    wantError:  nil,
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2943e6f and 4c1a689.

📒 Files selected for processing (6)
  • server/internal/adapter/integration/item.go (3 hunks)
  • server/internal/usecase/interactor/item.go (3 hunks)
  • server/internal/usecase/interactor/item_export.go (1 hunks)
  • server/internal/usecase/interactor/item_export_test.go (1 hunks)
  • server/internal/usecase/interactor/item_test.go (4 hunks)
  • server/internal/usecase/interfaces/item.go (3 hunks)
🧰 Additional context used
📓 Learnings (1)
server/internal/usecase/interactor/item_export_test.go (1)
Learnt from: jasonkarel
PR: reearth/reearth-cms#1329
File: server/internal/usecase/interactor/item_test.go:1147-1151
Timestamp: 2024-12-10T05:29:09.961Z
Learning: In the test `TestItem_ItemsAsCSV` in `server/internal/usecase/interactor/item_test.go`, negative test cases are intentionally fulfilled by not setting operator permissions, which is acceptable for testing purposes.
🔇 Additional comments (4)
server/internal/usecase/interactor/item_export.go (1)

20-23: LGTM!

The function provides a clean abstraction over the integrationapi package's functionality.

server/internal/usecase/interfaces/item.go (1)

85-92: LGTM!

The new types and interface methods are well-defined and properly documented. The design provides a clean separation of concerns for the export functionality.

Also applies to: 113-116

server/internal/usecase/interactor/item_export_test.go (1)

18-97: LGTM! Comprehensive test coverage.

The test cases thoroughly cover both success and error scenarios for CSV generation, including:

  • Successful export with geometry fields
  • Error handling for unsupported point fields
  • Various geometry field configurations
server/internal/usecase/interactor/item.go (1)

1202-1206: ⚠️ Potential issue

Fix potential resource leak in pipe handling

The pipe writer is not being closed after writing, which could lead to resource leaks. Additionally, error handling for csvFromItems could be improved.

 pr, pw := io.Pipe()
-err = csvFromItems(pw, items, schemaPackage.Schema())
-if err != nil {
-    return interfaces.ExportItemsToCSVResponse{}, err
-}
+go func() {
+    defer pw.Close()
+    if err := csvFromItems(pw, items, schemaPackage.Schema()); err != nil {
+        pw.CloseWithError(err)
+    }
+}()
⛔ Skipped due to learnings
Learnt from: jasonkarel
PR: reearth/reearth-cms#1329
File: server/internal/usecase/interactor/item.go:1235-1239
Timestamp: 2024-12-03T05:29:34.471Z
Learning: In the Go code file `server/internal/usecase/interactor/item.go`, the `csvFromItems` function already handles closing the pipe writer, so it's unnecessary to wrap it in a goroutine and close it again in the `ItemsAsCSV` function.

server/internal/usecase/interactor/item_export.go Outdated Show resolved Hide resolved
server/internal/adapter/integration/item.go Outdated Show resolved Hide resolved
server/internal/usecase/interactor/item.go Show resolved Hide resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants