Skip to content

[gateway] draft SSE implementation #243

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

Draft
wants to merge 9 commits into
base: master
Choose a base branch
from
Draft

Conversation

capcom6
Copy link
Owner

@capcom6 capcom6 commented Jul 22, 2025

Summary by CodeRabbit

  • New Features
    • Introduced a foreground service to maintain a persistent connection with server-sent events (SSE), ensuring real-time updates.
    • Added an SSE manager to handle SSE connections, event callbacks, and reconnection logic.
    • Added event routing to centralize handling of external events and trigger appropriate internal actions.
    • Added new event types and corresponding workers for message enqueueing, webhook updates, settings updates, and message export requests.
    • Introduced a receiver service to process message export requests asynchronously.
  • Enhancements
    • Updated app configuration to include OkHttp SSE dependencies.
    • Integrated SSE service lifecycle management with existing gateway operations.
    • Simplified push message handling by delegating event processing to the centralized event router.
    • Added persistent notification and resource string for SSE foreground service status.
    • Improved logging and error handling for event processing.
    • Updated notification service with new icon for real-time events.
    • Added management of FCM token within gateway settings for improved device registration handling.

Copy link

coderabbitai bot commented Jul 22, 2025

Walkthrough

The changes introduce Server-Sent Events (SSE) support to the Android app. This includes adding OkHttp SSE dependencies, a new SSEManager helper class for managing SSE connections, a new SSEForegroundService Android service for persistent SSE listening, and updates to the manifest and gateway service to integrate and manage this new foreground service. Additionally, event routing and handling were refactored and extended with new event classes, updated event receivers, and integration of a centralized EventsRouter. Some deprecated event classes and payloads were removed, and the PushService was refactored to delegate event handling to the new router.

Changes

Cohort / File(s) Change Summary
Build Configuration
app/build.gradle
Added OkHttp and OkHttp SSE dependencies with a version variable.
Android Manifest
app/src/main/AndroidManifest.xml
Added SSEForegroundService declaration; reordered some service attributes.
SSE Management Helper
app/src/main/java/me/capcom/smsgateway/helpers/SSEManager.kt
New class managing SSE connections using OkHttp with reconnection logic and event callbacks.
Foreground Service Implementation
app/src/main/java/me/capcom/smsgateway/modules/gateway/services/SSEForegroundService.kt
New Android foreground service maintaining persistent SSE connection with wake and Wi-Fi locks.
Gateway Service Integration
app/src/main/java/me/capcom/smsgateway/modules/gateway/GatewayService.kt
Modified to start and stop SSEForegroundService in its lifecycle methods; updated push token handling.
Event Classes Added
app/src/main/java/me/capcom/smsgateway/modules/gateway/events/MessageEnqueuedEvent.kt, .../SettingsUpdatedEvent.kt, .../WebhooksUpdatedEvent.kt, app/src/main/java/me/capcom/smsgateway/modules/receiver/events/MessagesExportRequestedEvent.kt
Added new event classes extending AppEvent for gateway and receiver modules with event name constants and payload handling.
Event Classes Removed
app/src/main/java/me/capcom/smsgateway/modules/push/events/PushMessageEnqueuedEvent.kt, app/src/main/java/me/capcom/smsgateway/modules/push/payloads/MessagesExportRequestedPayload.kt
Removed deprecated event and payload classes related to push events.
Event Routing and Handling
app/src/main/java/me/capcom/smsgateway/modules/orchestrator/EventsRouter.kt, .../Module.kt, .../OrchestratorService.kt
Added EventsRouter for mapping external events to internal events; updated orchestrator module and service to include receiver service and router.
Event Receivers and Services
app/src/main/java/me/capcom/smsgateway/modules/receiver/EventsReceiver.kt, .../ReceiverService.kt
Added new receiver class and service methods to start/stop event collection and processing.
Gateway Workers
app/src/main/java/me/capcom/smsgateway/modules/gateway/workers/WebhooksUpdateWorker.kt
Renamed worker constant from "CloudUpdateWorker" to "WebhooksUpdateWorker" for consistency.
EventsReceiver Update
app/src/main/java/me/capcom/smsgateway/modules/gateway/EventsReceiver.kt
Replaced PushMessageEnqueuedEvent with MessageEnqueuedEvent; added collectors for WebhooksUpdatedEvent, SettingsUpdatedEvent, and DeviceRegisteredEvent triggering corresponding workers and services.
PushService Refactor
app/src/main/java/me/capcom/smsgateway/services/PushService.kt
Refactored to remove coroutine event handling and direct worker calls; delegates event processing to EventsRouter. Removed related imports and coroutine scope.
Notifications Update
app/src/main/java/me/capcom/smsgateway/modules/notifications/NotificationsService.kt
Added new notification ID and icon mapping for real-time events notification.
Resource Strings
app/src/main/res/values/strings.xml
Added string resource for "Listening to the server events..." notification text.
Settings and Gateway Settings Update
app/src/main/java/me/capcom/smsgateway/helpers/SettingsHelper.kt, app/src/main/java/me/capcom/smsgateway/modules/gateway/GatewaySettings.kt
Removed fcmToken property from SettingsHelper; added fcmToken property to GatewaySettings with storage backing.

Sequence Diagram(s)

sequenceDiagram
    participant App
    participant GatewayService
    participant SSEForegroundService
    participant SSEManager
    participant Server

    App->>GatewayService: start(context)
    GatewayService->>SSEForegroundService: start(context)
    SSEForegroundService->>SSEManager: connect()
    SSEManager->>Server: Establish SSE connection
    Server-->>SSEManager: Send event(s)
    SSEManager-->>SSEForegroundService: onEvent callback
    SSEForegroundService-->>GatewayService: (optional event handling)
    App->>GatewayService: stop(context)
    GatewayService->>SSEForegroundService: stop(context)
    SSEForegroundService->>SSEManager: disconnect()
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~40 minutes


📜 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 fc273b6 and 8c56016.

📒 Files selected for processing (5)
  • app/src/main/java/me/capcom/smsgateway/helpers/SettingsHelper.kt (0 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/EventsReceiver.kt (3 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/GatewayService.kt (5 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/GatewaySettings.kt (2 hunks)
  • app/src/main/java/me/capcom/smsgateway/services/PushService.kt (3 hunks)
💤 Files with no reviewable changes (1)
  • app/src/main/java/me/capcom/smsgateway/helpers/SettingsHelper.kt
✅ Files skipped from review due to trivial changes (1)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/GatewaySettings.kt
🚧 Files skipped from review as they are similar to previous changes (3)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/EventsReceiver.kt
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/GatewayService.kt
  • app/src/main/java/me/capcom/smsgateway/services/PushService.kt
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/sse-events

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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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 generate unit tests to generate unit tests 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.

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

🧹 Nitpick comments (1)
app/src/main/java/me/capcom/smsgateway/helpers/SSEManager.kt (1)

20-23: Consider making timeout configurable and improve scope management.

The hardcoded 30-second timeout might need to be configurable for different use cases. Also, consider using SupervisorJob() for better error isolation.

-    private val client = OkHttpClient.Builder()
-        .readTimeout(30, TimeUnit.SECONDS)
-        .build()
-    private val scope = CoroutineScope(Dispatchers.IO + Job())
+    private val client = OkHttpClient.Builder()
+        .readTimeout(30, TimeUnit.SECONDS)
+        .build()
+    private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 404dd29 and 430f8f9.

📒 Files selected for processing (5)
  • app/build.gradle (2 hunks)
  • app/src/main/AndroidManifest.xml (2 hunks)
  • app/src/main/java/me/capcom/smsgateway/helpers/SSEManager.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/GatewayService.kt (2 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/services/SSEForegroundService.kt (1 hunks)
🔇 Additional comments (8)
app/build.gradle (2)

60-60: LGTM! Version variable properly defined.

The OkHttp version variable is well-structured and follows the existing pattern.


84-85: OkHttp 4.10.0 & SSE added – no known CVEs found
Verified via OSS Index for pkg:maven/com.squareup.okhttp3/okhttp@4.10.0: no reported vulnerabilities. Please confirm this version is compatible with your project’s Android API levels (minSdk/targetSdk).

• app/build.gradle (lines 84-85):

implementation("com.squareup.okhttp3:okhttp:$okhttp_version")
implementation("com.squareup.okhttp3:okhttp-sse:$okhttp_version")
app/src/main/java/me/capcom/smsgateway/modules/gateway/GatewayService.kt (3)

12-12: LGTM! Import properly added.

The SSEForegroundService import follows the existing import pattern.


49-49: Good placement of SSE service startup.

The SSE service is properly started after other workers, which ensures dependencies are initialized first.


57-57: Excellent service shutdown ordering.

The SSE service is stopped before other workers, which is the correct order to prevent connection issues during shutdown.

app/src/main/java/me/capcom/smsgateway/modules/gateway/services/SSEForegroundService.kt (1)

79-93: Excellent service lifecycle management.

The companion object methods properly handle Android API differences for starting foreground services and provide clean start/stop functionality.

app/src/main/java/me/capcom/smsgateway/helpers/SSEManager.kt (2)

34-82: Excellent SSE connection implementation.

The connection logic properly handles authentication, event callbacks, and error scenarios. The event listener implementation covers all necessary cases.


92-105: Well-implemented reconnection strategy.

The exponential backoff pattern with reasonable delay intervals provides good resilience against connection failures.

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

🧹 Nitpick comments (3)
app/src/main/java/me/capcom/smsgateway/modules/receiver/ReceiverService.kt (1)

24-30: Consider adding error handling and state management.

The lifecycle methods lack error handling and protection against multiple start/stop calls.

Consider adding basic state management and error handling:

+private var isStarted = false
+
 fun start(context: Context) {
+    if (isStarted) return
+    try {
         eventsReceiver.start()
+        isStarted = true
+    } catch (e: Exception) {
+        Log.e("ReceiverService", "Failed to start events receiver", e)
+        throw e
+    }
 }

 fun stop(context: Context) {
+    if (!isStarted) return
+    try {
         eventsReceiver.stop()
+        isStarted = false
+    } catch (e: Exception) {
+        Log.e("ReceiverService", "Failed to stop events receiver", e)
+    }
 }
app/src/main/java/me/capcom/smsgateway/modules/receiver/events/MessagesExportRequestedEvent.kt (1)

7-17: Consider using java.time API instead of Date

The Date class is legacy and has various issues. Consider using java.time.Instant or java.time.LocalDateTime for better date/time handling.

-import java.util.Date
+import java.time.Instant

 class MessagesExportRequestedEvent(
-    val since: Date,
-    val until: Date,
+    val since: Instant,
+    val until: Instant,
 ) : AppEvent(NAME) {
     data class Payload(
         @SerializedName("since")
-        val since: Date,
+        val since: Instant,
         @SerializedName("until")
-        val until: Date,
+        val until: Instant,
     )
app/src/main/java/me/capcom/smsgateway/services/PushService.kt (1)

31-44: Consider adding debug logging for received events

For better observability, consider logging the routed events.

 override fun onMessageReceived(message: RemoteMessage) {
     try {
         Log.d(this.javaClass.name, message.data.toString())

         val event = message.data["event"]?.let { ExternalEventType.valueOf(it) }
             ?: ExternalEventType.MessageEnqueued
         val data = message.data["data"]
+        
+        Log.d(this.javaClass.name, "Routing event: $event with data: $data")

         eventsRouter.route(
             ExternalEvent(
                 type = event,
                 data = data,
             )
         )
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6e34d8c and b58170d.

📒 Files selected for processing (18)
  • app/src/main/java/me/capcom/smsgateway/helpers/SSEManager.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/events/ExternalEvent.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/events/ExternalEventType.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/EventsReceiver.kt (3 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/events/MessageEnqueuedEvent.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/events/SettingsUpdatedEvent.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/events/WebhooksUpdatedEvent.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/services/SSEForegroundService.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/workers/WebhooksUpdateWorker.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/orchestrator/EventsRouter.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/orchestrator/Module.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/orchestrator/OrchestratorService.kt (3 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/push/events/PushMessageEnqueuedEvent.kt (0 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/push/payloads/MessagesExportRequestedPayload.kt (0 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/receiver/EventsReceiver.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/receiver/ReceiverService.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/receiver/events/MessagesExportRequestedEvent.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/services/PushService.kt (2 hunks)
💤 Files with no reviewable changes (2)
  • app/src/main/java/me/capcom/smsgateway/modules/push/payloads/MessagesExportRequestedPayload.kt
  • app/src/main/java/me/capcom/smsgateway/modules/push/events/PushMessageEnqueuedEvent.kt
✅ Files skipped from review due to trivial changes (6)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/workers/WebhooksUpdateWorker.kt
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/events/WebhooksUpdatedEvent.kt
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/events/SettingsUpdatedEvent.kt
  • app/src/main/java/me/capcom/smsgateway/modules/events/ExternalEvent.kt
  • app/src/main/java/me/capcom/smsgateway/modules/events/ExternalEventType.kt
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/events/MessageEnqueuedEvent.kt
🚧 Files skipped from review as they are similar to previous changes (2)
  • app/src/main/java/me/capcom/smsgateway/helpers/SSEManager.kt
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/services/SSEForegroundService.kt
🔇 Additional comments (9)
app/src/main/java/me/capcom/smsgateway/modules/orchestrator/Module.kt (1)

8-8: LGTM!

The addition of EventsRouter as a singleton follows the correct Koin DI pattern and aligns with the new event routing architecture.

app/src/main/java/me/capcom/smsgateway/modules/orchestrator/OrchestratorService.kt (2)

21-21: LGTM!

The addition of ReceiverService as a dependency follows the correct constructor injection pattern.


58-58: LGTM!

The service stop order follows the reverse startup sequence, which is the correct lifecycle management pattern.

app/src/main/java/me/capcom/smsgateway/modules/gateway/EventsReceiver.kt (4)

9-11: LGTM!

The import updates correctly reflect the new event classes that replace the old push event architecture.


14-15: LGTM!

The worker imports are correctly updated to match the new worker classes.


27-28: LGTM!

The transition from PushMessageEnqueuedEvent to MessageEnqueuedEvent is correctly implemented while maintaining the same functional behavior.


61-81: LGTM!

The new event collectors for WebhooksUpdatedEvent and SettingsUpdatedEvent follow the established patterns:

  • Consistent logging and event handling structure
  • Proper settings validation before processing
  • Correct worker invocation with dependency injection
app/src/main/java/me/capcom/smsgateway/modules/receiver/ReceiverService.kt (1)

22-22: LGTM!

Lazy initialization of eventsReceiver is appropriate for performance optimization.

app/src/main/java/me/capcom/smsgateway/modules/receiver/EventsReceiver.kt (1)

1-30: LGTM!

The EventsReceiver implementation follows established patterns correctly:

  • Proper async event handling with coroutineScope and launch
  • Consistent logging structure matching other EventsReceiver classes
  • Correct dependency injection using Koin
  • Clean event delegation to the service layer

The inline use of get() for context dependency is consistent with patterns used elsewhere in the codebase.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant