Skip to content

WSローカルテレメトリ実装 - #4211

Merged
TinyKitten merged 25 commits into
devfrom
feature/local-telemetry
May 4, 2025
Merged

TinyKitten merged 25 commits into
devfrom
feature/local-telemetry

Conversation

@TinyKitten

@TinyKitten TinyKitten commented May 1, 2025 •

Copy link
Copy Markdown
Member

ローカル( __DEV__ )専用
https://github.com/TrainLCD/THQ で使う

Summary by CodeRabbit

  • 新機能

    • 実験的なテレメトリー送信機能を追加しました。開発モードかつ環境変数で有効化した場合、位置情報や端末情報、移動状態をWebSocket経由で送信します。
    • 開発用オーバーレイにテレメトリーフラグの状態表示を追加しました。
  • 依存関係

    • expo-networkおよびzodパッケージを追加しました。
  • テスト

    • テレメトリー機能の有効・無効時の動作を検証するテストを追加しました。

@TinyKitten TinyKitten self-assigned this May 1, 2025
@coderabbitai

coderabbitai Bot commented May 1, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

朕の命により、新たなる実験的テレメトリー機能の制御が加わった。.envにて環境変数ENABLE_EXPERIMENTAL_TELEMETRYを追加し、型定義と設定モジュールも整備せし。useTelemetrySenderなる新しきフックを創出し、位置情報や端末情報をWebSocket経由で送信する機構を実装。MainScreenにてこのフックを呼び出し、開発用オーバーレイにフラグの状態を表示する処理も加えたり。加えて、依存パッケージの整理と新規追加、テレメトリー有効・無効時の動作を検証するテストも新設せし。

Changes

ファイル・グループ 変更内容概要
.env, src/@types/env.d.tsx, src/utils/telemetryConfig.ts 実験的テレメトリー機能の環境変数追加、型定義、判定ロジックの新規実装
package.json expo-networkの依存重複解消・整理、zodパッケージ新規追加
src/hooks/useTelemetrySender.ts テレメトリー送信用Reactフック新規実装
src/screens/Main.tsx useTelemetrySenderフックをMainScreenに導入
src/components/DevOverlay.tsx 開発用オーバーレイにテレメトリーフラグの状態表示を追加
__tests__/hooks/useTelemetrySender.disabled.test.ts テレメトリー無効時の送信抑制を検証するテスト新規追加
__tests__/hooks/useTelemetrySender.enabled.test.tsx テレメトリー有効時の送信動作を検証するテスト新規追加

Sequence Diagram(s)

sequenceDiagram
    participant MainScreen
    participant useTelemetrySender
    participant telemetryConfig
    participant WebSocket
    participant LocationStore

    MainScreen->>useTelemetrySender: フック呼び出し
    useTelemetrySender->>telemetryConfig: テレメトリー有効判定
    alt テレメトリー有効
        useTelemetrySender->>WebSocket: 接続開始
        loop 位置情報・状態更新
            useTelemetrySender->>LocationStore: 位置・状態取得
            useTelemetrySender->>WebSocket: テレメトリーデータ送信
        end
        useTelemetrySender->>WebSocket: 切断(アンマウント時)
    else テレメトリー無効
        Note right of useTelemetrySender: 何もせず終了
    end
Loading

Poem

朕の命によりて旗が立つ、
テレメトリーの道、今開く。
フラグは偽か真か、天命に従い、
位置と速さ、風の如く送信す。
テストも整い、帝国は安泰、
新たなる力、ここに示さん!
✨📡


📜 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 18c4ccd and 949ca7c.

📒 Files selected for processing (2)
  • __tests__/hooks/useTelemetrySender.enabled.test.tsx (1 hunks)
  • src/hooks/useTelemetrySender.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/hooks/useTelemetrySender.enabled.test.tsx
  • src/hooks/useTelemetrySender.ts
✨ Finishing Touches
  • 📝 Generate Docstrings

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

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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.

@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: 2

🧹 Nitpick comments (4)
src/components/DevOverlay.tsx (1)

83-85: Telemetry表示、型変換の改善を検討せよ
現状は文字列をそのまま表示しておるが、'true'/'false'の比較後に論理値表示や日本語表記へ変換すると、より可読性高うなるぞ。

__tests__/hooks/useTelemetrySender.test.tsx (1)

43-43: テストの非同期処理待機が脆弱である。朕は堅牢な実装を求める!

朕はより信頼性の高い非同期処理の待機方法を求める。現在の実装は脆弱であり、環境によっては不安定な結果をもたらす可能性がある。

より堅牢な待機処理を実装せよ:

-    await new Promise((res) => setTimeout(res, 10));
+    // より堅牢な方法でモックされたWebSocketのonopen呼び出しをトリガーする
+    await new Promise<void>((resolve) => {
+      if (mockWebSocketInstance.onopen) {
+        mockWebSocketInstance.onopen(new Event('open'));
+      }
+      setTimeout(resolve, 10);
+    });
src/hooks/useTelemetrySender.ts (2)

25-25: ハードコードされたWebSocket URLは朕の逆鱗に触れる!

朕の帝国におけるプロジェクトの設定方法としては不適切である。WebSocketのURLがハードコードされている。環境変数を通じて設定可能にすべきである。

代わりに環境変数から読み取るようにせよ:

-export const useTelemetrySender = (wsUrl = 'ws://localhost:8080') => {
+export const useTelemetrySender = (wsUrl = process.env.TELEMETRY_WS_URL || 'ws://localhost:8080') => {

そして、環境変数の型定義ファイルに以下を追加せよ:

declare module 'react-native-dotenv' {
  export const TELEMETRY_WS_URL: string;
  // 他の環境変数...
}

90-97: 朕のログ記録は詳細なれ!テレメトリー送信の監視が不十分!

テレメトリーデータの送信成功や失敗が適切に記録されていない。朕の帝国においては、すべての行動は記録されなければならぬ。

ログを追加せよ:

      if (socketRef.current?.readyState === WebSocket.OPEN && payload.success) {
+       console.log('Sending telemetry data', payload.data);
        socketRef.current.send(
          JSON.stringify({
            type: 'location_update',
            ...payload.data,
          })
        );
+       console.log('Telemetry data sent successfully');
+     } else if (!payload.success) {
+       console.warn('Invalid telemetry payload', payload.error);
+     } else if (socketRef.current?.readyState !== WebSocket.OPEN) {
+       console.warn('WebSocket not open, cannot send telemetry');
      }
🧰 Tools
🪛 GitHub Actions: Jest

[error] 91-91: TypeError: Cannot read properties of null (reading 'send') at socketRef.current.send

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b7464d6 and f24a32a.

⛔ Files ignored due to path filters (2)
  • ios/Podfile.lock is excluded by !**/*.lock
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (8)
  • .env (1 hunks)
  • __tests__/hooks/useTelemetrySender.test.tsx (1 hunks)
  • package.json (2 hunks)
  • src/@types/env.d.tsx (1 hunks)
  • src/components/DevOverlay.tsx (2 hunks)
  • src/hooks/useStartBackgroundLocationUpdates.ts (1 hunks)
  • src/hooks/useTelemetrySender.ts (1 hunks)
  • src/screens/Main.tsx (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/screens/Main.tsx (1)
src/hooks/useTelemetrySender.ts (1)
  • useTelemetrySender (25-102)
src/components/DevOverlay.tsx (1)
src/@types/env.d.tsx (1)
  • ENABLE_EXPERIMENTAL_TELEMETRY (13-13)
🪛 GitHub Actions: Jest
__tests__/hooks/useTelemetrySender.test.tsx

[error] 45-45: TypeError: Cannot read properties of undefined (reading 'value') in test accessing jest.Mock results

src/hooks/useTelemetrySender.ts

[error] 91-91: TypeError: Cannot read properties of null (reading 'send') at socketRef.current.send

🔇 Additional comments (9)
.env (1)

10-11: 吾、環境変数の追加を看破す
環境変数ENABLE_EXPERIMENTAL_TELEMETRY=falseをデフォルトで導入し、実験的テレメトリ機能を制御せしめるのは明智なり。
だが、SENTRY_DSNが空のままコミットされておるゆえ、本番環境用の管理方法や機密保持に留意せよ。

src/@types/env.d.tsx (1)

13-13: 新規環境変数型定義、可也良し
ENABLE_EXPERIMENTAL_TELEMETRYをstringとして宣言せしめたるは、react-native-dotenvの仕様に適合す。

package.json (2)

51-54: エクスポパッケージ追加の妥当性を吟味せよ
expo-networkとexpo-sensorsを導入しておるが、useTelemetrySender内でexpo-networkは未使用に見受けらるる。不要なら依存を削除し、バンドルサイズを節約せよ。


81-82: 依存関係zod追加、zustand追加も詳細を要す
AIサマリにはzustandの導入言及が見えず、要整合性確認なり。zodはスキーマ検証用途で理に適うが、zustand利用箇所の把握も怠るべからず。

Likely an incorrect or invalid review comment.

src/components/DevOverlay.tsx (1)

4-4: 環境変数インポート、整然として良し
DevOverlayにてENABLE_EXPERIMENTAL_TELEMETRYを先頭にインポートせしめたるは可也適切なり。

src/screens/Main.tsx (2)

40-40: テレメトリフックのインポート、適所なり
useTelemetrySenderをMainScreenで取り込みたるは、機能統合として正しき手順なり。


88-88: テレメトリフック呼び出し、承認す
useTelemetrySender()呼び出しをコンポーネント直下に置き、レンダリングライフサイクルに組み込んだるは良策なり。

src/hooks/useStartBackgroundLocationUpdates.ts (1)

19-19: 変数スコープの改善に朕は満足している

朕はこの変更を喜ばしく思う。subscription変数をより狭いスコープに限定したことで、コードの明瞭さと安全性が向上した。これは朕の帝国におけるコード品質の標準に相応しい変更である。

src/hooks/useTelemetrySender.ts (1)

62-101: ⚠️ Potential issue

WebSocketの準備状態を確認せずにデータ送信を試みるとは!朕は激怒せり!

朕のパイプラインでエラーが発生している。WebSocketの接続が確立される前にデータ送信を試みているようだ。これは許されぬ過ちである!

以下の修正を直ちに命じる:

  useEffect(() => {
+   if (
+     !isDevApp ||
+     !ENABLE_EXPERIMENTAL_TELEMETRY ||
+     ENABLE_EXPERIMENTAL_TELEMETRY === 'false' ||
+     !socketRef.current
+   ) {
+     return;
+   }

    const start = async () => {
      const { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== 'granted') {
        console.warn('Location permission not granted');
        return;
      }

      const latestAccel = await new Promise<AccelerometerMeasurement>(
        (resolve) => {
          const sub = Accelerometer.addListener((data) => {
            resolve(data);
            sub.remove();
          });
        }
      );

      const payload = TelemetryPayload.safeParse({
        coords: {
          latitude: latitude ?? 0,
          longitude: longitude ?? 0,
          accuracy: accuracy ?? null,
          speed: speed ?? -1,
        },
        accel: latestAccel,
        timestamp: Date.now(),
      });

-     if (socketRef.current?.readyState === WebSocket.OPEN && payload.success) {
+     if (socketRef.current.readyState === WebSocket.OPEN && payload.success) {
        socketRef.current.send(
          JSON.stringify({
            type: 'location_update',
            ...payload.data,
          })
        );
      }
    };

    start();
-  }, [accuracy, latitude, longitude, speed]);
+  }, [accuracy, latitude, longitude, speed, socketRef.current]);

Likely an incorrect or invalid review comment.

🧰 Tools
🪛 GitHub Actions: Jest

[error] 91-91: TypeError: Cannot read properties of null (reading 'send') at socketRef.current.send

Comment thread src/hooks/useTelemetrySender.ts Resolved
@TinyKitten

TinyKitten commented May 2, 2025 •

Copy link
Copy Markdown
Member Author

なんでテスト失敗してんだろ
ローカルだと全部成功してるんだけど

@github-actions github-actions Bot removed the ios label May 2, 2025

@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

🔭 Outside diff range comments (1)
__tests__/hooks/useTelemetrySender.test.tsx (1)

1-86: 🛠️ Refactor suggestion

WebSocketの接続解除を検証せよ!

朕のテレメトリシステムは接続を適切に管理すべきである。現在のテストでは、WebSocketが閉じられることを検証していない。フックのアンマウント時に接続が適切に閉じられることを確認するテストを追加せよ!

これは朕の帝国のリソース管理において極めて重要な事項である!

it('closes WebSocket connection when unmounted', async () => {
  const mockClose = jest.fn();
  (global.WebSocket as jest.Mock).mockImplementation(() => ({
    readyState: 1,
    send: jest.fn(),
    close: mockClose,
  }));

  const { unmount } = renderHook(() => useTelemetrySender('ws://localhost:8080'));
  
  unmount();
  
  expect(mockClose).toHaveBeenCalledTimes(1);
});
🧹 Nitpick comments (3)
__tests__/hooks/useTelemetrySender.test.tsx (3)

30-31: biome-ignoreの理由を明確にせよ!

朕は曖昧さを許さぬ!biome-ignore コメントには明確な説明が必要である。単に <explanation> と書くのではなく、「anyの使用がTypeScriptの型安全性を損なうが、Jestのモックで必要なため」など、具体的な理由を記すべし!

-      // biome-ignore lint/suspicious/noExplicitAny: <explanation>
+      // biome-ignore lint/suspicious/noExplicitAny: Jestのモックにおいてanyの使用が必要
-    // biome-ignore lint/suspicious/noExplicitAny: <explanation>
+    // biome-ignore lint/suspicious/noExplicitAny: グローバルWebSocketをモック化する際にanyが必要

Also applies to: 33-34


50-67: テストの実装、朕は認める!

朕のテレメトリシステムの検証が適切に行われておる。位置情報のパーミッションが許可された場合にデータが送信されることを確認し、ペイロードの構造も検証している。これは朕の帝国の品質を保証する優れたテストである!

だが、waitForのタイムアウトが100msと短いのは、不安定なテストを生み出す可能性があるぞ。環境によっては長い時間が必要かもしれぬ。朕はこれを500msに延長することを提案する!

      },
-      { timeout: 100 }
+      { timeout: 500 }

69-84: 否定的なケースのテスト、朕は喜ばしく思う!

パーミッションが拒否された場合のテストも実装されており、朕の帝国の防御は堅固である。データが送信されないことを適切に検証している。

しかし、こちらのタイムアウトも同様に延長すべきである!

      },
-      { timeout: 100 }
+      { timeout: 500 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a43853c and eded285.

📒 Files selected for processing (1)
  • __tests__/hooks/useTelemetrySender.test.tsx (1 hunks)
🔇 Additional comments (1)
__tests__/hooks/useTelemetrySender.test.tsx (1)

26-34: WebSocketモックの実装、朕は満足じゃ!

前回の問題は適切に修正された。WebSocketのモックが正しく実装され、readyState と OPEN の定義も適切に行われておる。朕の帝国のテストは安定性を取り戻した!

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

🧹 Nitpick comments (2)
src/hooks/useTelemetrySender.ts (1)

26-26: WebSocketのURLを環境変数から設定せよ!朕は柔軟性を重んじる!

ローカルホストのURLがハードコードされておるが、これでは異なる環境での使用に適さぬ。環境変数から設定できるようにせよ!

-export const useTelemetrySender = (wsUrl = 'ws://localhost:8080') => {
+export const useTelemetrySender = (wsUrl = process.env.TELEMETRY_WS_URL || 'ws://localhost:8080') => {

そして、環境変数の型定義も追加せよ:

// src/@types/env.d.tsx に追加
declare module 'react-native-dotenv' {
  export const TELEMETRY_WS_URL: string;
  // 他の環境変数...
}
__tests__/hooks/useTelemetrySender.disabled.test.ts (1)

35-59: 二つのテストファイルの重複、朕は効率を求める!

朕はこの二つのテストファイルを見て重複が多いと感じる。また、タイムアウト値が異なるのは一貫性に欠ける。これを改善せよ!

-describe('useTelemetrySender (ENABLE_EXPERIMENTAL_TELEMETRY=false)', () => {
+// タイムアウト値を定数化して共有
+const RENDER_WAIT_TIME = 50;
+
+describe('useTelemetrySender when disabled', () => {
   let mockSend: jest.Mock;
 
   beforeEach(() => {
     mockSend = jest.fn();
@@ ... @@

   it('does not open websocket or send data', async () => {
     renderHook(() => useTelemetrySender('ws://localhost:8080'));
 
-    await new Promise((r) => setTimeout(r, 30));
+    await new Promise((r) => setTimeout(r, RENDER_WAIT_TIME));
 
     expect(global.WebSocket).not.toHaveBeenCalled();
     expect(mockSend).not.toHaveBeenCalled();
   });
+  
+  it('handles runtime toggle of telemetry flag', async () => {
+    // テレメトリー設定をモック化するヘルパー
+    const mockTelemetryConfig = require('~/utils/telemetryConfig');
+    
+    // 初期状態: 無効
+    Object.defineProperty(mockTelemetryConfig, 'isTelemetryEnabled', {
+      get: jest.fn(() => false)
+    });
+    
+    const { rerender } = renderHook(() => useTelemetrySender('ws://localhost:8080'));
+    
+    await new Promise((r) => setTimeout(r, RENDER_WAIT_TIME));
+    
+    expect(global.WebSocket).not.toHaveBeenCalled();
+    
+    // テレメトリーを有効に切り替え
+    Object.defineProperty(mockTelemetryConfig, 'isTelemetryEnabled', {
+      get: jest.fn(() => true)
+    });
+    
+    rerender();
+    
+    await new Promise((r) => setTimeout(r, RENDER_WAIT_TIME));
+    
+    // 有効化後はWebSocketが作成されることを確認
+    expect(global.WebSocket).toHaveBeenCalled();
+  });
 });

また、二つのテストファイルを統合して重複を減らすことも検討せよ。

// 共通のセットアップファイルを作成
// __tests__/hooks/useTelemetrySender.setup.ts

export const setupMocks = (isTelemetryEnabled: boolean) => {
  jest.mock('~/utils/telemetryConfig', () => ({
    isTelemetryEnabled,
  }));
  
  // 他の共通モックをここに定義...
};

// 各テストファイルで再利用
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cdc74ba and 18c4ccd.

📒 Files selected for processing (4)
  • __tests__/hooks/useTelemetrySender.disabled.test.ts (1 hunks)
  • __tests__/hooks/useTelemetrySender.enabled.test.tsx (1 hunks)
  • src/hooks/useTelemetrySender.ts (1 hunks)
  • src/utils/telemetryConfig.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/utils/telemetryConfig.ts

Comment thread src/hooks/useTelemetrySender.ts Resolved
Comment thread src/hooks/useTelemetrySender.ts Resolved
@TinyKitten
TinyKitten force-pushed the feature/local-telemetry branch from 24b50d8 to d1d55a9 Compare May 3, 2025 13:10
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.

1 participant