Skip to content

chore: enrich event with bot details - #5836

Merged
itsmihir merged 12 commits into
masterfrom
chore.enrich-event-with-bot-details
May 12, 2025
Merged

itsmihir merged 12 commits into
masterfrom
chore.enrich-event-with-bot-details

Conversation

@itsmihir

@itsmihir itsmihir commented May 9, 2025

Copy link
Copy Markdown
Contributor

Description

Add bot encicher, which will add bot details present in event parameters to event context.

Linear Ticket

[Resolves PIPE-2028] (https://linear.app/rudderstack/issue/PIPE-2028/implement-event-flagging)

Depedency

rudderlabs/rudder-schemas#66

Security

  • The code changed/added as part of this pull request won't create any security issues with how the software is being used.

@itsmihir

itsmihir commented May 9, 2025

Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented May 9, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

This update introduces bot enrichment functionality to the event processing pipeline. It adds a new bot enricher component that annotates events identified as bots with detailed bot metadata. The enrichment process is conditionally enabled via configuration. Supporting changes extend event parameter structures and update method signatures to propagate bot-related data throughout the pipeline, with comprehensive unit tests added for the new enricher.

Changes

Files/Group Change Summary
internal/enricher/bot.go, internal/enricher/bot_test.go Added a new bot enricher implementing the PipelineEnricher interface, enriching events with bot metadata; introduced comprehensive unit tests for various enrichment scenarios and error cases.
internal/enricher/enricher.go, internal/enricher/geolocation.go Updated the PipelineEnricher interface and its implementations to accept an additional *types.EventParams argument in the Enrich method; geolocation enricher updated accordingly.
internal/enricher/geolocation_test.go Updated all calls to the geolocation enricher's Enrich method to include the new third argument (nil) for compatibility with the revised interface.
processor/types/types.go Extended the EventParams struct with fields for bot detection: IsBot, BotName, BotURL, and BotIsInvalidBrowser.
gateway/handle.go Modified job parameter extraction to include and marshal new bot-related fields from incoming message properties into job parameters.
processor/processor.go Updated calls to the Enrich method within the preprocessing stage to pass the new eventParams argument.
app/apphandlers/setup.go Added logic to conditionally initialize and append the bot enricher to the pipeline based on configuration.

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

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:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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 or @coderabbitai title 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: 0

🧹 Nitpick comments (4)
internal/enricher/bot.go (4)

16-20: Consider adding constructor options for future extensibility.

While the current implementation is clean and stateless, consider using a functional options pattern for the constructor to make it easier to add configuration parameters in the future without breaking changes.

-type botEnricher struct{}
+type botEnricher struct{
+    // Fields for future configuration options
+}

-func NewBotEnricher() (PipelineEnricher, error) {
-    return &botEnricher{}, nil
+// Option defines a functional option for configuring botEnricher
+type Option func(*botEnricher)
+
+func NewBotEnricher(opts ...Option) (PipelineEnricher, error) {
+    e := &botEnricher{}
+    for _, opt := range opts {
+        opt(e)
+    }
+    return e, nil
}

22-52: The enrichment logic is correct, but could benefit from additional documentation.

The implementation handles the various cases well - checking if events are bots, ensuring context exists, validating context type, and enriching with bot information. However, consider adding godoc-style comments to explain the purpose and behavior of the Enrich method.

Also, the error collection strategy assumes that we want to process all events even if some fail. This is generally a good approach for batch processing, but make sure it aligns with the error handling strategy throughout the codebase.

+// Enrich adds bot information to the context of events that are identified as bots.
+// It skips non-bot events, ensures each bot event has a context section,
+// and adds bot metadata to the context. If any errors are encountered during
+// enrichment, they are collected and returned combined.
 func (e *botEnricher) Enrich(_ *backendconfig.SourceT, request *types.GatewayBatchRequest, eventParams *types.EventParams) error {

37-41: Consider caching the type assertion result.

Since you're using the type asserted context in the next few lines, consider optimizing by caching the result after checking.

-		// if the context is other than map[string]interface{}, add error and continue
-		context, ok := event["context"].(map[string]interface{})
-		if !ok {
-			enrichErrs = append(enrichErrs, errors.New("event doesn't have a valid context section"))
-			continue
-		}
+		// if the context is other than map[string]interface{}, add error and continue
+		contextValue := event["context"]
+		context, ok := contextValue.(map[string]interface{})
+		if !ok {
+			enrichErrs = append(enrichErrs, errors.New("event doesn't have a valid context section"))
+			continue
+		}

51-52: Consider including more context in error messages.

When joining errors, it might be helpful to include more context about which events failed enrichment, especially for debugging purposes.

-	return errors.Join(enrichErrs...)
+	if len(enrichErrs) == 0 {
+		return nil
+	}
+	return errors.Join(append([]error{errors.New("bot enrichment errors")}, enrichErrs...)...)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9165e8c and 9be8b28.

⛔ Files ignored due to path filters (2)
  • go.mod is excluded by !**/*.mod
  • go.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (9)
  • app/apphandlers/setup.go (1 hunks)
  • gateway/handle.go (2 hunks)
  • internal/enricher/bot.go (1 hunks)
  • internal/enricher/bot_test.go (1 hunks)
  • internal/enricher/enricher.go (1 hunks)
  • internal/enricher/geolocation.go (1 hunks)
  • internal/enricher/geolocation_test.go (7 hunks)
  • processor/processor.go (1 hunks)
  • processor/types/types.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (4)
app/apphandlers/setup.go (1)
internal/enricher/bot.go (1)
  • NewBotEnricher (18-20)
internal/enricher/enricher.go (3)
backend-config/types.go (1)
  • SourceT (62-77)
processor/types/types.go (2)
  • GatewayBatchRequest (37-41)
  • EventParams (240-250)
processor/eventfilter/eventfilter.go (1)
  • EventParams (92-94)
internal/enricher/geolocation.go (2)
backend-config/types.go (1)
  • SourceT (62-77)
processor/types/types.go (2)
  • GatewayBatchRequest (37-41)
  • EventParams (240-250)
internal/enricher/bot_test.go (2)
processor/types/types.go (3)
  • GatewayBatchRequest (37-41)
  • EventParams (240-250)
  • SingularEventT (20-20)
internal/enricher/bot.go (2)
  • BotDetails (10-14)
  • NewBotEnricher (18-20)
🔇 Additional comments (12)
app/apphandlers/setup.go (1)

153-161: Well-structured addition of bot enricher to the pipeline.

The implementation follows the same pattern as the existing geolocation enricher, conditionally initializing the bot enricher based on configuration. Note that the bot enricher is enabled by default (unlike the geolocation enricher which is disabled by default).

internal/enricher/enricher.go (1)

11-11: Interface change to support bot information in event enrichment.

The Enrich method signature has been updated to include a third parameter eventParams *types.EventParams, which will pass bot-related fields like IsBot, BotName, BotURL, and BotIsInvalidBrowser to enrichers. This change supports the new bot enrichment feature.

internal/enricher/geolocation_test.go (1)

85-85: Updated test calls to match the new Enrich method signature.

All calls to the Enrich method have been updated to pass nil as the third parameter to match the updated interface. The geolocation enricher doesn't use this parameter, but the interface change requires it to be passed.

Also applies to: 106-106, 132-132, 177-177, 211-211, 263-263, 324-324

processor/processor.go (1)

1805-1805: Updated enricher call site to pass event parameters.

The call to e.Enrich now correctly passes the &eventParams pointer as required by the updated interface. This allows the bot enricher to access the bot-related information in the event parameters.

internal/enricher/geolocation.go (1)

66-66: Updated method signature to align with interface changes

The Enrich method has been updated to include a new *types.EventParams parameter, which is currently unused (marked with underscore). This change aligns with the updated PipelineEnricher interface that now requires this parameter to support bot enrichment functionality.

processor/types/types.go (1)

246-249: New bot metadata fields added to EventParams

These fields extend the event parameters to support bot detection and enrichment capabilities. The omitempty JSON tag ensures these fields don't appear in serialized output when empty. This aligns well with the new bot enricher functionality.

gateway/handle.go (2)

756-759: Added bot-related fields to internal params struct

These new fields in the params struct support capturing bot metadata for job processing. This aligns with the EventParams struct changes seen in processor/types/types.go.


941-944: Populating bot metadata from message properties

The implementation correctly propagates bot metadata from message properties to job parameters, ensuring that bot information flows through to the enrichment pipeline.

internal/enricher/bot_test.go (1)

11-203: Well-structured test suite for the new bot enricher

This comprehensive test suite thoroughly validates the behavior of the botEnricher component under various scenarios:

  • Non-bot events (no enrichment)
  • Bot events needing new context
  • Bot events with invalid browsers
  • Bot events with existing context (merged)
  • Bot events with outdated bot info (overwritten)
  • Error cases with invalid context types

The tests are well-organized with clear expectations and appropriate assertions. The table-driven approach makes it easy to understand each test case and its purpose.

internal/enricher/bot.go (3)

10-14: Good structured definition for bot metadata.

The BotDetails struct is well-designed with appropriate JSON tags and the omitempty directive to ensure clean output. This will help maintain a consistent interface for bot information throughout the application.


43-49: LGTM! The bot enrichment implementation looks solid.

The enrichment implementation is straightforward and adds the necessary bot information to the event context. The structure follows the expected format with a boolean flag and detailed metadata.


54-56: The Close method is appropriately implemented for a stateless enricher.

Since the enricher doesn't maintain any state or resources that need cleanup, the no-op implementation of Close is correct.

Comment thread internal/enricher/bot.go
var enrichErrs []error
for _, event := range request.Batch {
// if the event is not a bot, we don't need to enrich it
if !eventParams.IsBot {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ktgowtham If the bot is not detected, we are not adding any fields, are we good with this?

@codecov

codecov Bot commented May 9, 2025 •

Copy link
Copy Markdown

Codecov Report

Attention: Patch coverage is 91.93548% with 5 lines in your changes missing coverage. Please review.

Project coverage is 77.00%. Comparing base (c068920) to head (3af1a2c).
Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
app/apphandlers/setup.go 66.66% 3 Missing and 1 partial ⚠️
processor/processor.go 0.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #5836      +/-   ##
==========================================
+ Coverage   76.95%   77.00%   +0.04%     
==========================================
  Files         493      494       +1     
  Lines       67733    67773      +40     
==========================================
+ Hits        52127    52189      +62     
+ Misses      12779    12757      -22     
  Partials     2827     2827              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Comment thread app/apphandlers/setup.go Outdated
}

if conf.GetBool("BotEnrichment.enabled", true) {
log.Infof("Setting up the bot pipeline enricher")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-Sugared logger please. Always. Even if you don't pass fields.

@fracasula fracasula May 12, 2025 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, since the culprit might be copy-and-paste without reviewing your own code, perhaps you can change the other ones in this file as well?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are more up above, Info instead of Infon. It'd be nice to have the whole as per standards given how small the file is.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated other places also

Comment thread internal/enricher/bot.go Resolved
Comment thread internal/enricher/bot_test.go Resolved
@itsmihir
itsmihir requested a review from fracasula May 12, 2025 09:33

@fracasula fracasula left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. It would be nice to have the whole setup.go use the non-sugared logger though.

@ktgowtham
ktgowtham requested a review from fracasula May 12, 2025 11:13

@fracasula fracasula left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM but please fix the new test with Eventually.

func (s *botScenario) requireJobsCount(t *testing.T, db *sql.DB, queue, state string, expectedCount int) {
require.Eventually(t, func() bool {
var jobsCount int
require.NoError(t, db.QueryRow(fmt.Sprintf("SELECT count(*) FROM unionjobsdbmetadata('%s',10) WHERE job_state = '%s'", queue, state)).Scan(&jobsCount))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

require makes the test fail right away. Both require and assert must be avoided inside Eventually. The function invoked by Eventually is not meant to do any kind of assertion, it is meant to return just true or false. If it keeps returning false for the specified timeout (in this case 20s) then Eventually itself will make the test fail. The way you wrote it might make the test fail at the first attempt without the retries every each second.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suggest you just do return err != nil && jobsCount == expectedCount.

}

func (s *botScenario) runRudderServer(ctx context.Context, port int, postgresContainer *postgres.Resource, cbURL, transformerURL, tmpDir string) (err error) {
config.Set("enableStats", false)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a shame that we are still using global variables in our test. I understand that refactoring the runner to make it use a *config.Config instance is beyond the scope of this PR, just making a note of this.

You can leave it as is or use t.Setenv. Sooner or later we should remove this as it could lead to undesired behaviour cc @ktgowtham

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is also preventing us to use t.Parallel().

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.

Comment thread internal/enricher/bot_test.go Resolved
}

func (s *botScenario) runRudderServer(ctx context.Context, port int, postgresContainer *postgres.Resource, cbURL, transformerURL, tmpDir string) (err error) {
config.Set("enableStats", false)

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.

@itsmihir
itsmihir merged commit 6035658 into master May 12, 2025
@itsmihir
itsmihir deleted the chore.enrich-event-with-bot-details branch May 12, 2025 18:55
satishrudderstack pushed a commit that referenced this pull request May 13, 2025
🤖 I have created a release *beep* *boop*
---


##
[1.49.0](v1.48.0...v1.49.0)
(2025-05-13)


### Features

* add dynamic config existence flag for destinations
([#5821](#5821))
([1b4ea06](1b4ea06))
* add support for processing of upload_v2 job type by slave
([#5796](#5796))
([67988d1](67988d1))
* batch staging files for creating upload_v2 notifier jobs
([#5765](#5765))
([7dc3a45](7dc3a45))
* enable worker-based kafka client batching
([#5788](#5788))
([66dc19f](66dc19f))
* support claim renewal in notifier jobs
([#5818](#5818))
([a499d9c](a499d9c))
* support new consent resolution strategy values
([#5798](#5798))
([181b95b](181b95b))
* update config to add account details with destination in
workspaceConfig
([#5753](#5753))
([dbd46bf](dbd46bf))
* update contract for account and accountDefinition
([#5830](#5830))
([c704b07](c704b07))
* use account to decide oauth type of a destination
([#5810](#5810))
([9165e8c](9165e8c))


### Bug Fixes

* add check for nil secret on oauthv2
([#5807](#5807))
([fbc4abe](fbc4abe))
* convert bad request errors to 500 errors in oauth interceptor to
prevent panics
([#5813](#5813))
([3a08ec4](3a08ec4))
* embedded transformations upload
([#5848](#5848))
([0b19968](0b19968))
* **jobsdb:** completed datasets don't get deleted without a pair
([#5793](#5793))
([54aee71](54aee71))
* reporting common client path with query
([#5842](#5842))
([c068920](c068920))
* transformer client recycle ttl bound to connection idle timeout
([#5800](#5800))
([b13f92c](b13f92c))
* update account type to remove id which we are getting as map key
([#5835](#5835))
([bc52242](bc52242))
* ut mirroring race condition
([#5824](#5824))
([a4d579f](a4d579f))
* warehouse cached schema mismatch
([#5805](#5805))
([4656247](4656247))
* warehouse transformations mismatches
([#5779](#5779))
([01a7b83](01a7b83))


### Miscellaneous

* **deps:** bump github.com/snowflakedb/gosnowflake from 1.13.2 to
1.13.3 in the go_modules group
([#5787](#5787))
([41db33e](41db33e))
* **deps:** bump golangci/golangci-lint-action from 7 to 8
([#5815](#5815))
([bf3e808](bf3e808))
* enrich event with bot details
([#5836](#5836))
([6035658](6035658))
* **jobsdb:** cache distinct parameters query result for all datasets
except last
([#5752](#5752))
([e85811e](e85811e))
* migrate from denisenkom/go-mssqldb to microsoft/go-mssqldb
([#5776](#5776))
([dbd46bf](dbd46bf))
* revert synapse staging table with max varchar length
([#5817](#5817))
([2418329](2418329))
* **router:** support destination-specific configuration overrides for
all options
([#5841](#5841))
([695cf53](695cf53))
* synapse staging table with max varchar length
([#5775](#5775))
([2fc5384](2fc5384))
* update accountDefination type with authenticationType
([#5791](#5791))
([2a24e59](2a24e59))
* update rudder-go-kit to 0.49.2
([#5832](#5832))
([01a7b83](01a7b83))
* upload embedded dt response difference samples to s3
([#5792](#5792))
([c81001f](c81001f))
* warehouse transformer migration to embedded destination transformer
package
([#5827](#5827))
([e124bb0](e124bb0))
* warehouse transformer sample diff
([#5837](#5837))
([8af55de](8af55de))
* warehouse transformer uploader
([#5828](#5828))
([fc640bf](fc640bf))
* webhook integration test module upgrade
([#5665](#5665))
([f4130d1](f4130d1))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
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.

3 participants