Repository navigation
chore: enrich event with bot details - #5836
Conversation
|
@coderabbitai full review |
WalkthroughThis 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
Tip ⚡️ Faster reviews with caching
Enjoy the performance boost—your workflow just got faster. ✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
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
Enrichmethod.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
⛔ Files ignored due to path filters (2)
go.modis excluded by!**/*.modgo.sumis 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
Enrichmethod signature has been updated to include a third parametereventParams *types.EventParams, which will pass bot-related fields likeIsBot,BotName,BotURL, andBotIsInvalidBrowserto 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
Enrichmethod have been updated to passnilas 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.Enrichnow correctly passes the&eventParamspointer 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 changesThe
Enrichmethod has been updated to include a new*types.EventParamsparameter, which is currently unused (marked with underscore). This change aligns with the updatedPipelineEnricherinterface that now requires this parameter to support bot enrichment functionality.processor/types/types.go (1)
246-249: New bot metadata fields added to EventParamsThese fields extend the event parameters to support bot detection and enrichment capabilities. The
omitemptyJSON 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 structThese 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 propertiesThe 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 enricherThis comprehensive test suite thoroughly validates the behavior of the
botEnrichercomponent 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
BotDetailsstruct is well-designed with appropriate JSON tags and theomitemptydirective 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.
| 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 { |
There was a problem hiding this comment.
@ktgowtham If the bot is not detected, we are not adding any fields, are we good with this?
Codecov ReportAttention: Patch coverage is
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. 🚀 New features to boost your workflow:
|
| } | ||
|
|
||
| if conf.GetBool("BotEnrichment.enabled", true) { | ||
| log.Infof("Setting up the bot pipeline enricher") |
There was a problem hiding this comment.
Non-Sugared logger please. Always. Even if you don't pass fields.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Updated other places also
fracasula
left a comment
There was a problem hiding this comment.
LGTM. It would be nice to have the whole setup.go use the non-sugared logger though.
fracasula
left a comment
There was a problem hiding this comment.
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)) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
This is also preventing us to use t.Parallel().
There was a problem hiding this comment.
…nd isInvalidBrowser are present
…into chore.enrich-event-with-bot-details
| } | ||
|
|
||
| func (s *botScenario) runRudderServer(ctx context.Context, port int, postgresContainer *postgres.Resource, cbURL, transformerURL, tmpDir string) (err error) { | ||
| config.Set("enableStats", false) |
There was a problem hiding this comment.
🤖 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).
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