Skip to content

Add device-level association and validation for webhooks in SMS gateway #140

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

Merged
merged 1 commit into from
May 17, 2025

Conversation

capcom6
Copy link
Member

@capcom6 capcom6 commented May 16, 2025

Summary by CodeRabbit

  • New Features

    • Webhooks can now be associated with specific devices, enabling device-level filtering and management.
    • Device ownership is validated when assigning a webhook to a device.
    • Added the ability to check if a device exists for a user.
    • Webhook registration API now supports specifying a device ID.
  • Improvements

    • Notifications for webhook changes can be targeted to specific devices.
    • Enhanced logging provides detailed context, including device information, during device notifications.
  • Database Changes

    • The webhooks table now includes a device association with indexing and cascade delete support for improved performance and data integrity.

@coderabbitai coderabbitai bot changed the title @coderabbitai Add device-level association and validation for webhooks in SMS gateway May 16, 2025
Copy link

coderabbitai bot commented May 16, 2025

Walkthrough

This change introduces device-level association for webhooks in the SMS gateway system. It updates the database schema, models, and repository filters to support an optional device_id on webhooks, adds device existence checks, enhances service logic for device validation, and updates notification logic to target specific devices. Logging and dependency versions are also updated.

Changes

File(s) Change Summary
go.mod Updated github.com/android-sms-gateway/client-go dependency from v1.5.7 to v1.5.8.
internal/sms-gateway/handlers/webhooks/mobile.go Modified MobileController.get to filter webhooks by both user ID and device ID using webhooks.WithDeviceID(device.ID, false).
internal/sms-gateway/models/migrations/mysql/20250516022136_webhooks_by_device.sql Added a device_id column to the webhooks table, set up a foreign key constraint to devices(id) with cascade delete, and created an index for device_id. Down migration reverses these changes.
internal/sms-gateway/modules/devices/repository.go Added Exists method to the device repository for checking the existence of devices matching given filters.
internal/sms-gateway/modules/devices/service.go Added Exists method to the device service to check for device existence for a user with filters, calling the repository's Exists.
internal/sms-gateway/modules/webhooks/converters.go Updated webhookToDTO to include DeviceID in the returned DTO struct.
internal/sms-gateway/modules/webhooks/models.go Added DeviceID *string and Device *models.Device fields to the Webhook struct, establishing optional device association and foreign key relationship.
internal/sms-gateway/modules/webhooks/repository_filter.go Extended selectFilter with deviceID and deviceIDExact, added WithDeviceID filter constructor, and updated apply to support device-specific filtering (exact or non-exact).
internal/sms-gateway/modules/webhooks/service.go Updated Replace to validate device ownership and include DeviceID, modified notifyDevices to accept and process optional device ID, updated logging, and changed notification logic to target specific devices if applicable. Also updated Delete to pass nil for device ID.
pkg/swagger/docs/requests.http Added deviceId field to the JSON body of the POST request for webhook registration to associate the webhook with a specific device ID.
pkg/swagger/docs/swagger.json Added deviceId property to the smsgateway.Webhook definition, specifying it as a string with max length 21 and providing an example value.
pkg/swagger/docs/swagger.yaml Added deviceId property to the smsgateway.Webhook definition with description, max length, and example value.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant MobileController
    participant WebhooksService
    participant DevicesService
    participant WebhooksRepo
    participant DevicesRepo
    participant DB

    Client->>MobileController: GET /webhooks (device context)
    MobileController->>WebhooksService: Select(userID, WithDeviceID(deviceID, false))
    WebhooksService->>WebhooksRepo: Select(userID, WithDeviceID(deviceID, false))
    WebhooksRepo->>DB: Query webhooks WHERE user_id AND (device_id=deviceID OR device_id IS NULL)
    DB-->>WebhooksRepo: Webhook records
    WebhooksRepo-->>WebhooksService: Webhook records
    WebhooksService-->>MobileController: Webhook DTOs
    MobileController-->>Client: Webhook DTOs
Loading
sequenceDiagram
    participant Client
    participant WebhooksService
    participant DevicesService
    participant DevicesRepo
    participant WebhooksRepo
    participant DB

    Client->>WebhooksService: Replace(userID, webhook{DeviceID})
    alt webhook.DeviceID provided
        WebhooksService->>DevicesService: Exists(userID, WithID(DeviceID))
        DevicesService->>DevicesRepo: Exists(userID, WithID(DeviceID))
        DevicesRepo->>DB: Query device WHERE user_id AND id=DeviceID
        DB-->>DevicesRepo: Device exists?
        DevicesRepo-->>DevicesService: true/false
        DevicesService-->>WebhooksService: true/false
        alt not exists
            WebhooksService-->>Client: Error (device not found)
        end
    end
    WebhooksService->>WebhooksRepo: Replace webhook (with DeviceID)
    WebhooksRepo->>DB: Upsert webhook row
    WebhooksService->>WebhooksService: notifyDevices(userID, DeviceID)
    WebhooksService->>DevicesService: Select(userID, WithID(DeviceID))
    DevicesService->>DevicesRepo: Select(userID, WithID(DeviceID))
    DevicesRepo->>DB: Query device(s)
    DB-->>DevicesRepo: Device(s)
    DevicesRepo-->>DevicesService: Device(s)
    DevicesService-->>WebhooksService: Device(s)
    WebhooksService->>Devices: Send push notification (if push token)
    WebhooksService-->>Client: Success
Loading

Possibly related PRs


📜 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 86247ac and a57c523.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (12)
  • go.mod (1 hunks)
  • internal/sms-gateway/handlers/webhooks/mobile.go (1 hunks)
  • internal/sms-gateway/models/migrations/mysql/20250516022136_webhooks_by_device.sql (1 hunks)
  • internal/sms-gateway/modules/devices/repository.go (1 hunks)
  • internal/sms-gateway/modules/devices/service.go (1 hunks)
  • internal/sms-gateway/modules/webhooks/converters.go (1 hunks)
  • internal/sms-gateway/modules/webhooks/models.go (1 hunks)
  • internal/sms-gateway/modules/webhooks/repository_filter.go (2 hunks)
  • internal/sms-gateway/modules/webhooks/service.go (2 hunks)
  • pkg/swagger/docs/requests.http (1 hunks)
  • pkg/swagger/docs/swagger.json (1 hunks)
  • pkg/swagger/docs/swagger.yaml (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (11)
  • go.mod
  • pkg/swagger/docs/requests.http
  • internal/sms-gateway/modules/webhooks/models.go
  • internal/sms-gateway/modules/webhooks/converters.go
  • pkg/swagger/docs/swagger.json
  • internal/sms-gateway/models/migrations/mysql/20250516022136_webhooks_by_device.sql
  • pkg/swagger/docs/swagger.yaml
  • internal/sms-gateway/modules/devices/repository.go
  • internal/sms-gateway/modules/devices/service.go
  • internal/sms-gateway/handlers/webhooks/mobile.go
  • internal/sms-gateway/modules/webhooks/repository_filter.go
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build / Docker image (linux/arm64)
🔇 Additional comments (5)
internal/sms-gateway/modules/webhooks/service.go (5)

78-87: Good implementation of device ownership validation.

The addition of device ownership validation is well-implemented. You're correctly checking if the device exists and belongs to the user before allowing the webhook to be associated with it. The error handling is appropriate, and you're using the structured validation error as recommended in the previous review.


89-95: Webhook model correctly updated to include DeviceID.

The Webhook struct now includes the DeviceID field, properly aligning with the schema changes mentioned in the PR summary.


101-101: Good notification handling for the specific device.

You're correctly notifying the specific device when a webhook is updated, which aligns with the PR objective of enhancing notification logic to target specific devices.


114-114: Appropriate notification handling for webhook deletion.

When deleting webhooks, you're correctly notifying all devices (by passing nil deviceID) since the deletion could affect any device.


120-158: Well-implemented device-specific notification logic with improved logging.

The updated notifyDevices function is well-implemented with several improvements:

  1. It now accepts a deviceID parameter to support targeted notifications
  2. Logging has been significantly enhanced with contextual information
  3. The function handles both specific device notifications and broadcasting to all devices
  4. Edge cases are properly handled (no devices found, devices without push tokens)

These changes align perfectly with the PR objective of enhancing notification logic to target specific devices.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Commit Unit Tests in branch webhooks/by-device-management
  • Post Copyable Unit Tests in Comment

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

🧹 Nitpick comments (4)
internal/sms-gateway/models/migrations/mysql/20250516022136_webhooks_by_device.sql (1)

1-20: Well-structured migration with appropriate constraints and index.

The migration correctly:

  • Adds a nullable device_id column with the appropriate data type
  • Creates a foreign key constraint with CASCADE delete behavior to maintain referential integrity
  • Adds an index on the device_id column to improve query performance
  • Provides a proper down migration that removes constraints before removing the column

Consider whether a composite index on (user_id, device_id) might be beneficial if queries frequently filter on both user and device, but only if the webhooks table already has a user_id column.

internal/sms-gateway/modules/webhooks/service.go (3)

101-102: Unmanaged goroutine may leak / hide errors

Spawning a goroutine without a context or error handling means:
• the process can’t be shut down gracefully (goroutine outlives request)
• any panic inside the goroutine will crash the program
• failures are only logged, never propagated to callers/tests

If the notification is not strictly fire-and-forget, pass a context.Context and let callers decide whether they care about completion. At minimum expose a channel/WaitGroup so the application can drain before exiting.


120-130: Shadowing the imported devices package hampers readability

The local variable devices later declared on line 135 shadows the imported devices package, which can confuse readers and static analysis tools.

-var devices, err := s.devicesSvc.Select(userID, filters...)
+devList, err := s.devicesSvc.Select(userID, filters...)

(You’ll need to update subsequent references.)


146-154: Ensure consistent structured logging across branches

Most log statements use the pre-built logFields, but the “no push token” / “Failed to send push” paths rebuild fields ad-hoc. This slightly diverges field ordering and risks missing context if new fields are added to logFields later.

-           s.logger.Info("Device has no push token", zap.String("user_id", userID), zap.String("device_id", device.ID))
+           s.logger.Info("Device has no push token",
+               append(logFields, zap.String("device_id", device.ID))...,
+           )

Apply the same pattern for the error log at line 153.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4e6b4e7 and 9d8c1ca.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (9)
  • go.mod (1 hunks)
  • internal/sms-gateway/handlers/webhooks/mobile.go (1 hunks)
  • internal/sms-gateway/models/migrations/mysql/20250516022136_webhooks_by_device.sql (1 hunks)
  • internal/sms-gateway/modules/devices/repository.go (1 hunks)
  • internal/sms-gateway/modules/devices/service.go (1 hunks)
  • internal/sms-gateway/modules/webhooks/converters.go (1 hunks)
  • internal/sms-gateway/modules/webhooks/models.go (1 hunks)
  • internal/sms-gateway/modules/webhooks/repository_filter.go (2 hunks)
  • internal/sms-gateway/modules/webhooks/service.go (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
internal/sms-gateway/handlers/webhooks/mobile.go (1)
internal/sms-gateway/modules/webhooks/repository_filter.go (1)
  • WithDeviceID (41-46)
internal/sms-gateway/modules/devices/repository.go (2)
internal/sms-gateway/modules/devices/repository_filter.go (1)
  • SelectFilter (5-5)
internal/sms-gateway/models/models.go (1)
  • Device (31-42)
internal/sms-gateway/modules/webhooks/models.go (1)
internal/sms-gateway/models/models.go (2)
  • User (23-29)
  • Device (31-42)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Build / Docker image (linux/amd64)
  • GitHub Check: Build / Docker image (linux/arm64)
  • GitHub Check: Analyze (go)
🔇 Additional comments (10)
internal/sms-gateway/modules/devices/repository.go (1)

33-47: Well-implemented repository method for device existence check.

This implementation follows good repository patterns by:

  • Using the established filter application mechanism
  • Efficiently checking existence without retrieving all device data
  • Properly distinguishing between "not found" (false, nil) and actual errors (false, err)
  • Including clear documentation that explains the return values
go.mod (1)

9-9:

✅ Verification successful

Verify that the specific client-go dependency commit exists and is stable.

The dependency has been updated to a pseudo-version (v1.5.8-0.20250516025314-5876d8deb355) which references a specific commit rather than a tagged release. Ensure this specific commit exists and contains the necessary features to support the device-specific webhook functionality being added.


🏁 Script executed:

#!/bin/bash
# Check if the module version exists and get its info
go list -m -versions github.com/android-sms-gateway/client-go
go mod why github.com/android-sms-gateway/client-go

Length of output: 8907


Pseudo-version dependency verified
The pseudo-version v1.5.8-0.20250516025314-5876d8deb355 was successfully downloaded by go mod—the referenced commit exists. No blocking issues remain.

• Optional: consider tagging an official v1.5.8 release to avoid relying on a commit-based pseudo-version.

internal/sms-gateway/modules/webhooks/converters.go (1)

8-13: Appropriate update to include DeviceID in the webhook DTO.

The addition of the DeviceID field to the webhook DTO is necessary to properly propagate the device association through to API responses. This change is aligned with the overall goal of adding device-level association for webhooks.

internal/sms-gateway/handlers/webhooks/mobile.go (1)

41-41: Great implementation of device-specific webhook filtering!

The change to include the device ID filter in webhooksSvc.Select() is well implemented. Using false for the exact match parameter correctly ensures that both device-specific webhooks and device-agnostic webhooks (with null device ID) are returned to the mobile client.

internal/sms-gateway/modules/webhooks/models.go (2)

14-14: Well-structured model field addition.

The DeviceID field is properly defined as an optional pointer to string, which aligns with the device ID type in the Device model. The GORM index tag will help with query performance, and the JSON tag includes omitempty which is appropriate for optional fields.


19-20: Properly configured foreign key relationships.

The foreign key relationships are correctly established with cascade delete behavior. This ensures that when devices are deleted, their associated webhooks are properly cleaned up.

internal/sms-gateway/modules/devices/service.go (1)

55-64: Well-documented and secure device existence check.

The Exists method is well documented with clear explanations of return values and error conditions. Appending the user ID filter ensures the device existence check is properly scoped to the specified user, which is a good security practice that prevents unauthorized access to device information.

internal/sms-gateway/modules/webhooks/repository_filter.go (3)

22-23: Good extension of the filter struct.

The additions to the selectFilter struct are appropriate for supporting device-based filtering.


38-46: Well-documented filter constructor.

The WithDeviceID filter constructor is clearly documented and follows the established pattern of other filter constructors in this file. The boolean exact parameter provides flexibility in how filtering is applied.


53-59: Properly implemented conditional query logic.

The conditional query logic correctly implements the documented behavior:

  • When deviceIDExact is true, only records with the exact device ID are matched
  • When deviceIDExact is false, records with either the specified device ID or with a null device ID are matched

This flexible approach allows both device-specific and device-agnostic webhooks to be retrieved when needed.

@capcom6 capcom6 force-pushed the webhooks/by-device-management branch from 4951241 to 86247ac Compare May 17, 2025 00:15
@capcom6 capcom6 force-pushed the webhooks/by-device-management branch from 86247ac to a57c523 Compare May 17, 2025 06:45
@capcom6 capcom6 merged commit 632ef46 into master May 17, 2025
10 checks passed
@capcom6 capcom6 deleted the webhooks/by-device-management branch May 17, 2025 08:22
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