Skip to content

ダイクストラ法を用いた経路検索PoC#1193

Merged
TinyKitten merged 3 commits into
devfrom
feature/route-search-by-dijkstra
Mar 2, 2025
Merged

ダイクストラ法を用いた経路検索PoC#1193
TinyKitten merged 3 commits into
devfrom
feature/route-search-by-dijkstra

Conversation

@TinyKitten

@TinyKitten TinyKitten commented Mar 2, 2025

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • 新機能
    • データベースのダンプ形式をMariaDBに移行し、ホスト名や文字セット、数値型などのフィールド仕様を更新。さらに、接続情報を管理する新規テーブルを導入。
    • 非同期処理に対応した接続リポジトリを実装し、接続駅情報取得APIおよび最短経路計算(Dijkstraアルゴリズムを利用)の機能を追加。
    • グラフ計算ライブラリの依存関係を導入し、経路再構築機能も強化。
    • サブプロジェクトのバージョン更新を実施。

@TinyKitten TinyKitten self-assigned this Mar 2, 2025
@coderabbitai

coderabbitai Bot commented Mar 2, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

このプルリクエストでは、データベースのダンプ形式変更(MySQL → MariaDB)や文字セット・型定義の見直し、新規テーブルの追加が行われています。さらに、Rustプロジェクト内で新たな依存ライブラリ(petgraph)の導入、接続機能用のモジュール、構造体、非同期リポジトリ、そしてDijkstraアルゴリズムを利用した最短経路計算機能が追加されています。

Changes

ファイル 変更内容
data/create_table.sql MariaDBダンプへ移行、文字セット設定の変更、整数型の修正、不要な文字セット指定の削除、および新規テーブル(connectionstypes)の追加
stationapi/Cargo.toml petgraph = "0.7.1" の依存関係追加
stationapi/proto サブプロジェクトのコミットID更新(3a623d0735...f91762a625...
stationapi/src/domain/entity.rs
stationapi/src/domain/entity/connection.rs
新モジュール connection の追加、Connection構造体の定義、コンストラクタとテストの追加
stationapi/src/domain/repository.rs
stationapi/src/domain/repository/connection_repository.rs
新モジュール connection_repository の追加、ConnectionRepository トレイトの定義
stationapi/src/infrastructure.rs
stationapi/src/infrastructure/connection_repository.rs
インフラ層に接続リポジトリ追加、SQLx利用の実装とDB行からエンティティへの変換処理実装
stationapi/src/infrastructure/station_repository.rs 新メソッド get_route_stops の追加、および get_by_id_vec のSQLクエリに DISTINCT を導入
stationapi/src/main.rs run 関数で MyConnectionRepository を生成し、query_use_case に接続リポジトリを追加
stationapi/src/presentation/controller/grpc.rs gRPC APIに新メソッド get_connected_stations を追加、及び接続リポジトリ依存関係の更新
stationapi/src/use_case/interactor/query.rs
stationapi/src/use_case/traits/query.rs
QueryInteractor/QueryUseCase に接続リポジトリ用フィールドと
新メソッド(dijkstra_with_pathreconstruct_pathget_connected_stations)を追加
.sqlx/query-*.json connections テーブルからデータ取得するためのSQLクエリ定義

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant gRPC
  participant QueryUseCase
  participant ConnectionRepo
  participant Database

  Client->>gRPC: get_connected_stationsリクエスト送信
  gRPC->>QueryUseCase: get_connected_stations呼び出し
  QueryUseCase->>ConnectionRepo: 全接続データ取得リクエスト
  ConnectionRepo->>Database: SQLクエリ実行
  Database-->>ConnectionRepo: 接続データ返送
  ConnectionRepo-->>QueryUseCase: 接続データ返送
  QueryUseCase->>QueryUseCase: Dijkstraアルゴリズムで最短経路計算
  QueryUseCase-->>gRPC: 計算結果返送
  gRPC-->>Client: MultipleStationResponse返送
Loading

Possibly related PRs

Poem

ふわふわうさぎ、コードの森を駆け抜け
変更の風に耳をすませて
データとRustが奏でるメロディ
新たな繋がりが道を開く
うさぎの心、跳ねる喜び🐇✨
コードの春を祝福する、ぽかぽか陽気に!


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

@TinyKitten TinyKitten added the enhancement New feature or request label Mar 2, 2025
@TinyKitten TinyKitten marked this pull request as ready for review March 2, 2025 12:40
@TinyKitten TinyKitten requested a review from 10mocy as a code owner March 2, 2025 12:40

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (15)
stationapi/src/domain/entity/connection.rs (1)

1-9: 適切なエンティティ構造

Connection構造体は駅間の接続を表現するのに適した設計になっています。CloneDebugSerializeDeserializePartialEqの派生トレイトの選択も適切です。

distanceフィールドについて、単位(メートル、キロメートルなど)をコメントで明記することを検討しましょう。

 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
 pub struct Connection {
     pub id: u32,
     pub station_cd1: u32,
     pub station_cd2: u32,
+    // メートル単位の距離
     pub distance: f64,
 }
stationapi/src/presentation/controller/grpc.rs (1)

305-324: 新しいgRPCエンドポイントの実装が適切です

get_connected_stationsメソッドはリクエストパラメータを適切に抽出し、query_use_caseを呼び出してエラーハンドリングを行っています。既存の他のエンドポイントと一貫したスタイルで実装されています。

ただし、エラーメッセージがユーザーに表示されるものであれば、より具体的なエラーメッセージにすることを検討してください。例えば、「経路が見つかりませんでした」など、問題の性質を明確にするようなメッセージです。

             Err(err) => {
-                return Err(PresentationalError::OtherError(anyhow::anyhow!(err).into()).into())
+                return Err(PresentationalError::OtherError(anyhow::anyhow!(format!("経路検索に失敗しました: {}", err)).into()).into())
             }
stationapi/src/use_case/traits/query.rs (4)

1-2: HashMap導入の意図を簡潔にコメントすると分かりやすいです。
Dijkstra実装を想定した型の追加であることが推測できますが、利用用途が明確だと保守が容易になります。


98-105: dijkstra_with_pathメソッドの返り値設計
経路コストのマップ(HashMap<NodeIndex, f64>)と親ノードのマップ(HashMap<NodeIndex, Option>)を返却されていますが、Dijkstra実行中のエラー可能性などを考えると、Result型などのエラーハンドリング活用も検討できます。


106-111: reconstruct_pathメソッドにおけるエラー分岐
prev_map からパスを再構成できないケースがあるため、None の返却理由が分かりやすいようにコメントを添えるなどの工夫があると保守性が上がります。


112-116: get_connected_stationsメソッドの非同期処理設計
最短経路の検索も想定すると、大量のデータ取得・計算が発生しうる可能性があります。十分なタイムアウトやキャンセル制御が行われるかご留意ください。

stationapi/src/infrastructure/station_repository.rs (1)

286-295: get_route_stopsメソッドのテスト検討
途中駅の取得ロジックが複雑なので、ユニットテストや結合テストで想定通りの駅が返るか検証することをおすすめします。

stationapi/src/infrastructure/connection_repository.rs (5)

1-4: 必要な import のみを利用
将来的に拡張性を考慮している場合は問題ありませんが、使われていないモジュールがあれば削減してください。


10-16: ConnectionRow構造体のフィールド名
station_cd1, station_cd2 は可読性を高めるためにもう少し説明的な名前 (station_cd_start / station_cd_end など) へ変更を検討しても良いでしょう。


33-37: new関数のインターフェース
Arc<Pool> を直接受け取っている点は妥当です。意図しないクローンを防ぐためにも、ドキュメントコメントを追加すると親切です。


39-45: get_allメソッドのIO負荷に注意
全件取得ではレコード数が増えるとパフォーマンスに影響が出る可能性があります。必要に応じて LIMIT やページネーションを検討しても良いでしょう。


47-47: 内部実装の構造体
InternalConnectionRepository という命名は分かりやすいですが、将来的に用途が増えるのであれば名前のみでなくサブモジュール化も検討可能です。

data/create_table.sql (3)

162-190: stationsテーブルの定義変更
各種VARCHAR(255)へ変更されたことで文字数制限が緩和されています。検索パフォーマンスに影響しないか留意ください。


192-215: typesテーブルの再作成
追加されたカラムやデフォルト値の設定に問題はなさそうです。ユニークキー type_cd の運用を考慮し、重複エラー時のハンドリングを設計してください。


226-227: ダンプ終了時刻の更新
バックアップ実行環境が変わった際は、リストア可能性を定期的にテストすることを推奨します。

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b0951b9 and 0aefbf0.

⛔ Files ignored due to path filters (2)
  • Cargo.lock is excluded by !**/*.lock
  • data/8!connections.csv is excluded by !**/*.csv
📒 Files selected for processing (15)
  • .sqlx/query-4bd021d7621ae8024aa730ae36eca717445802294780b27fb1e5c3ec89430b1a.json (1 hunks)
  • data/create_table.sql (5 hunks)
  • stationapi/Cargo.toml (1 hunks)
  • stationapi/proto (1 hunks)
  • stationapi/src/domain/entity.rs (1 hunks)
  • stationapi/src/domain/entity/connection.rs (1 hunks)
  • stationapi/src/domain/repository.rs (1 hunks)
  • stationapi/src/domain/repository/connection_repository.rs (1 hunks)
  • stationapi/src/infrastructure.rs (1 hunks)
  • stationapi/src/infrastructure/connection_repository.rs (1 hunks)
  • stationapi/src/infrastructure/station_repository.rs (2 hunks)
  • stationapi/src/main.rs (2 hunks)
  • stationapi/src/presentation/controller/grpc.rs (3 hunks)
  • stationapi/src/use_case/interactor/query.rs (2 hunks)
  • stationapi/src/use_case/traits/query.rs (2 hunks)
✅ Files skipped from review due to trivial changes (2)
  • .sqlx/query-4bd021d7621ae8024aa730ae36eca717445802294780b27fb1e5c3ec89430b1a.json
  • stationapi/proto
🔇 Additional comments (34)
stationapi/src/infrastructure.rs (1)

2-2: モジュール追加による拡張が適切に行われています。

新しい connection_repository モジュールの追加は、接続データを管理するための良い拡張です。既存の構造に沿って適切に宣言されています。

stationapi/Cargo.toml (1)

26-26: petgraphの依存関係追加は適切です。

ダイクストラ法による経路検索を実装するために petgraph クレートを追加したのは適切な選択です。バージョン 0.7.1 は安定したリリースであり、グラフ操作と最短経路アルゴリズムをサポートしています。

stationapi/src/domain/repository.rs (1)

2-2: ドメイン層のリポジトリ構造に適切な拡張が行われています。

connection_repository モジュールの追加は、接続に関連する操作を処理するためのリポジトリパターンに従っており、プロジェクトのアーキテクチャと一貫しています。

stationapi/src/domain/entity.rs (1)

2-2: 新しいエンティティモジュールの追加は適切です。

connection モジュールの追加により、駅間の接続を表現するためのエンティティが適切に定義されています。これはダイクストラ法による経路検索に必要なデータ構造をサポートするための良い基盤となります。

stationapi/src/domain/repository/connection_repository.rs (1)

1-8: 適切なトレイト定義です!

ConnectionRepositoryトレイトはリポジトリパターンを適切に実装しており、非同期操作用のasync_traitマクロを正しく使用しています。SendSyncの境界は並行処理環境での使用に必要なものです。

get_allメソッドのシグネチャは明確でエラーハンドリングも適切です。

stationapi/src/main.rs (3)

4-5: インポートの追加が適切です

新しいMyConnectionRepositoryのインポートがこれまでのリポジトリのインポートパターンに従って適切に追加されています。


67-67: ConnectionRepositoryの初期化が適切です

他のリポジトリと同様のパターンで接続プールを利用してMyConnectionRepositoryを初期化しています。


74-74: QueryInteractorへの追加が適切です

新しいconnection_repositoryフィールドがQueryInteractor構造体に適切に追加されています。これにより、クエリインタラクターが接続データにアクセスできるようになります。

stationapi/src/domain/entity/connection.rs (2)

11-20: コンストラクタの実装が適切です

Connection構造体のコンストラクタが簡潔に実装されています。


22-39: 適切なテスト実装

コンストラクタの機能をテストしており、適切なアサーションが含まれています。テストデータとして実際のような値を使用していて良いです。

stationapi/src/presentation/controller/grpc.rs (3)

3-5: 適切なインポートの追加

MyConnectionRepositoryのインポートが他のリポジトリと一貫したパターンで追加されています。


10-11: 必要なリクエスト型のインポートを追加

GetConnectedStationsRequestが適切にインポートされています。


27-27: QueryInteractorの型パラメータ更新が適切です

MyConnectionRepositoryQueryInteractorの型パラメータとして追加されています。

stationapi/src/use_case/traits/query.rs (1)

4-4: petgraphインポートの確認
パスが正しく設定されているか、Cargo.toml の依存関係に petgraph が追記されているかを再度ご確認ください。

stationapi/src/infrastructure/station_repository.rs (1)

395-395: SELECT DISTINCT の利用
重複を除外する目的だと思われますが、複数テーブルをJOINしている箇所では意図せずレコードが欠落する可能性もあります。要件的に問題ないかご確認ください。

stationapi/src/infrastructure/connection_repository.rs (3)

5-8: domain::entity などの読み込み確認
Connectionエンティティ定義に変更があった場合、同期が必要です。Cargo.tomlでのモジュール設定もお忘れなく。


18-27: From の変換処理
変換ロジックに問題はなさそうです。テーブル構造とフィールド定義の整合性を随時ご確認ください。


29-31: MyConnectionRepository構造体の可視性
他のモジュールからの利用範囲に応じて pub struct で問題ないか、適切なスコープ確認をお願いします。

stationapi/src/use_case/interactor/query.rs (9)

2-2: コレクションの導入を確認
Dijkstraなどのアルゴリズムで必要なデータ構造を活用しており問題ありません。


13-15: 新しいリポジトリ依存注入
connection_repository が追加され、データ取得に対応しやすくなっています。


21-26: petgraphの活用
グラフ操作に必要なクレートの導入が確認でき、有用な選択と考えます。


29-35: QueryInteractorへの新規ジェネリクス追加
CNR が追加され、接続情報を管理する仕組みが拡張されています。


37-45: DijkstraStateの順序付け
Ord 実装でコストを比較し、優先度付きキューに適しています。浮動小数点による比較不具合が起きないよう注意が必要です。


61-61: QueryUseCaseへの対応
新たなリポジトリ型が追加され、既存インターフェイスへ自然に組み込まれています。

Also applies to: 67-67


859-903: Dijkstraアルゴリズムの実装
基本的なロジックは正しく構成されており、ヒープを用いた処理手順も妥当です。浮動小数点の誤差を想定したテスト検証をお勧めします。


905-924: 経路復元ロジック
start に到達するまで辿り、最後に反転して返すシンプルで明快な実装です。


926-955: 駅接続経路探索の追加
Undirected グラフを使用して Dijkstra を適用していますが、双方向扱いで問題ないか再確認をお勧めします。また、無効な distance や存在しない駅IDの接続に対するエラー制御が必要になる可能性があります。

data/create_table.sql (7)

1-1: MariaDBダンプ情報の更新
コメントや文字コード設定がMariaDB向けに変更されました。意図と環境を再度確認してください。

Also applies to: 3-3, 5-5, 10-10


24-35: aliasesテーブルの定義変更
列の型や AUTO_INCREMENT の指定が明確になっています。既存データ移行時に不整合が発生しないよう注意しましょう。


44-57: companiesテーブルの構造修正
int(10) unsigned の導入は問題ありませんが、既存利用箇所で互換性をチェックしてください。


62-63: connectionsテーブルの新規追加
駅IDペアと距離情報を格納するテーブルが追加されました。Dijkstra連携に必須な情報として妥当です。

Also applies to: 64-66, 67-68, 69-75


84-95: line_aliasesテーブルのクライアント文字セット変更
テーブル仕様に大きな差異はありませんが、文字セットやCollationの変更で文字のソート順に影響が出ないか注意してください。


100-131: linesテーブルの定義変更
会社コードとのFK制約を維持しつつ、新しいカラム仕様が導入されています。average_distance 等の型が正しく設定されているか要確認。


138-153: station_station_typesの定義見直し
複数カラムに int(10) unsigned が設定されています。StationやTypeとの整合性をデータ投入時に確認してください。

Comment thread stationapi/src/infrastructure/connection_repository.rs

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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)
.sqlx/query-68f68188c05f61bee98158103be8bde861c09ad7e1b2c678aa93a0407df9a6c8.json (1)

47-49: パラメータ定義の見直し
parameters オブジェクトで "Right": 0 が指定されています。

  • このキー名が意図通りの意味を持つのか(予約語との競合や命名の一貫性など)確認してください。
  • 将来的に他のパラメータが増える可能性がある場合、命名規則の統一も検討すると良いでしょう。
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0aefbf0 and 45f5aac.

📒 Files selected for processing (2)
  • .sqlx/query-68f68188c05f61bee98158103be8bde861c09ad7e1b2c678aa93a0407df9a6c8.json (1 hunks)
  • stationapi/src/infrastructure/connection_repository.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • stationapi/src/infrastructure/connection_repository.rs
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Test Suite
🔇 Additional comments (7)
.sqlx/query-68f68188c05f61bee98158103be8bde861c09ad7e1b2c678aa93a0407df9a6c8.json (7)

1-3: DB名とクエリ文字列の確認
行 1-3 では、db_name"MySQL" と明示され、クエリ文字列も MySQL/MariaDB 互換の構文(バックティックで囲んだテーブル名など)になっています。
もしデータベースのダンプ形式変更や MariaDB への移行が目的であれば、ここも併せて確認する必要があります。


4-15: idカラムの定義の確認
id カラムは、Long 型と属性 "NOT_NULL | PRIMARY_KEY | UNSIGNED | AUTO_INCREMENT" で定義されており、テーブル設計の意図に合致しています。


16-25: station_cd1カラムの定義の確認
station_cd1 カラムは、Long 型かつ "NOT_NULL | UNSIGNED | NO_DEFAULT_VALUE" の属性で定義されており、問題ありません。


26-35: station_cd2カラムの定義の確認
station_cd2 カラムも station_cd1 と同様の形式で正しく定義されています。


36-45: distanceカラムの定義に関する確認
distance カラムは Double 型かつ "NOT_NULL | UNSIGNED | NO_DEFAULT_VALUE" として定義されています。MariaDB における DOUBLE UNSIGNED のサポート状況や、アプリケーション上のデータ要件に沿っているか再確認すると良いです。


50-55: nullable配列の確認
nullable 配列では、4つのカラムすべてが false に設定され、各カラムが必須(NOT NULL)であることが正しく反映されています。


57-57: ハッシュ値の確認
ファイル整合性検証のための hash フィールドが設定されています。生成されたハッシュが期待通りであることを確認してください。

@TinyKitten TinyKitten merged commit 20e122c into dev Mar 2, 2025
@TinyKitten TinyKitten deleted the feature/route-search-by-dijkstra branch March 2, 2025 12:51
@coderabbitai coderabbitai Bot mentioned this pull request Aug 6, 2025
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.

1 participant