Skip to content

feat(eventbuilder): Track attributes with valid attribute types #166

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 7 commits into from
Sep 21, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright 2016, Optimizely
* Copyright 2016, 2018, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -19,6 +19,9 @@ var conditionEvaluator = require('./');

var browserConditionSafari = {'name': 'browser_type', 'value': 'safari'};
var deviceConditionIphone = {'name': 'device_model', 'value': 'iphone6'};
var booleanCondition = {'name': 'is_firefox', 'value': true};
var integerCondition = {'name': 'num_users', 'value': 10};
var doubleCondition = {'name': 'pi_value', 'value': 3.14};

describe('lib/core/condition_evaluator', function() {
describe('APIs', function() {
Expand All @@ -39,6 +42,17 @@ describe('lib/core/condition_evaluator', function() {
assert.isFalse(conditionEvaluator.evaluate(['and', browserConditionSafari], userAttributes));
});

it('should evaluate different typed attributes', function() {
var userAttributes = {
browser_type: 'safari',
is_firefox: true,
num_users: 10,
pi_value: 3.14,
};

assert.isTrue(conditionEvaluator.evaluate(['and', browserConditionSafari, booleanCondition, integerCondition, doubleCondition], userAttributes));
});

describe('and evaluation', function() {
it('should return true when ALL conditions evaluate to true', function() {
var userAttributes = {
Expand Down
32 changes: 23 additions & 9 deletions packages/optimizely-sdk/lib/core/decision_service/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,15 +62,7 @@ function DecisionService(options) {
*/
DecisionService.prototype.getVariation = function(experimentKey, userId, attributes) {
// by default, the bucketing ID should be the user ID
var bucketingId = userId;

// If the bucketing ID key is defined in attributes, than use that in place of the userID for the murmur hash key
if (!fns.isEmpty(attributes)) {
if (attributes.hasOwnProperty(enums.CONTROL_ATTRIBUTES.BUCKETING_ID)) {
bucketingId = attributes[enums.CONTROL_ATTRIBUTES.BUCKETING_ID];
this.logger.log(LOG_LEVEL.DEBUG, sprintf('Setting the bucketing ID to %s.', bucketingId));
}
}
var bucketingId = this._getBucketingId(userId, attributes);

if (!this.__checkIfExperimentIsActive(experimentKey, userId)) {
return null;
Expand Down Expand Up @@ -432,6 +424,28 @@ DecisionService.prototype._getVariationForRollout = function(feature, userId, at
};
};

/**
* Get bucketing Id from user attributes.
* @param {String} userId
* @param {Object} attributes
* @returns {String} Bucketing Id if it is a string type in attributes, user Id otherwise.
*/
DecisionService.prototype._getBucketingId = function(userId, attributes) {
var bucketingId = userId;

// If the bucketing ID key is defined in attributes, than use that in place of the userID for the murmur hash key
if ((attributes != null && typeof attributes === 'object') && attributes.hasOwnProperty(enums.CONTROL_ATTRIBUTES.BUCKETING_ID)) {
if (typeof attributes[enums.CONTROL_ATTRIBUTES.BUCKETING_ID] === 'string') {
bucketingId = attributes[enums.CONTROL_ATTRIBUTES.BUCKETING_ID];
this.logger.log(LOG_LEVEL.DEBUG, sprintf(LOG_MESSAGES.VALID_BUCKETING_ID, MODULE_NAME, bucketingId));
} else {
this.logger.log(LOG_LEVEL.WARNING, sprintf(LOG_MESSAGES.BUCKETING_ID_NOT_STRING, MODULE_NAME));
}
}

return bucketingId;
};

module.exports = {
/**
* Creates an instance of the DecisionService.
Expand Down
47 changes: 46 additions & 1 deletion packages/optimizely-sdk/lib/core/decision_service/index.tests.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/****************************************************************************
* Copyright 2017, Optimizely, Inc. and contributors *
* Copyright 2017-2018, Optimizely, Inc. and contributors *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
Expand Down Expand Up @@ -461,6 +461,51 @@ describe('lib/core/decision_service', function() {
});
});

describe('_getBucketingId', function() {
var configObj;
var decisionService;
var mockLogger = logger.createLogger({logLevel: LOG_LEVEL.INFO});
var userId = 'testUser1';
var userAttributesWithBucketingId = {
'browser_type': 'firefox',
'$opt_bucketing_id': '123456789'
};
var userAttributesWithInvalidBucketingId = {
'browser_type': 'safari',
'$opt_bucketing_id': 50
};

beforeEach(function() {
sinon.stub(mockLogger, 'log');
configObj = projectConfig.createProjectConfig(testData);
decisionService = DecisionService.createDecisionService({
configObj: configObj,
logger: mockLogger,
});
});

afterEach(function() {
mockLogger.log.restore();
});

it('should return userId if bucketingId is not defined in user attributes', function() {
assert.strictEqual(userId, decisionService._getBucketingId(userId, null));
assert.strictEqual(userId, decisionService._getBucketingId(userId, {'browser_type': 'safari'}));
});

it('should log warning in case of invalid bucketingId', function() {
assert.strictEqual(userId, decisionService._getBucketingId(userId, userAttributesWithInvalidBucketingId));
assert.strictEqual(1, mockLogger.log.callCount);
assert.strictEqual(mockLogger.log.args[0][1], 'DECISION_SERVICE: BucketingID attribute is not a string. Defaulted to userId');
});

it('should return correct bucketingId when provided in attributes', function() {
assert.strictEqual('123456789', decisionService._getBucketingId(userId, userAttributesWithBucketingId));
assert.strictEqual(1, mockLogger.log.callCount);
assert.strictEqual(mockLogger.log.args[0][1], 'DECISION_SERVICE: BucketingId is valid: "123456789"');
});
});

describe('feature management', function() {
describe('#getVariationForFeature', function() {
var configObj;
Expand Down
22 changes: 13 additions & 9 deletions packages/optimizely-sdk/lib/core/event_builder/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ var enums = require('../../utils/enums');
var fns = require('../../utils/fns');
var eventTagUtils = require('../../utils/event_tag_utils');
var projectConfig = require('../project_config');
var attributeValidator = require('../../utils/attributes_validator');

var ACTIVATE_EVENT_KEY = 'campaign_activated';
var CUSTOM_ATTRIBUTE_FEATURE_TYPE = 'custom';
Expand Down Expand Up @@ -58,15 +59,18 @@ function getCommonEventParams(options) {
anonymize_ip: anonymize_ip,
};

fns.forOwn(attributes, function(attributeValue, attributeKey){
var attributeId = projectConfig.getAttributeId(options.configObj, attributeKey, options.logger);
if (attributeId) {
commonParams.visitors[0].attributes.push({
entity_id: attributeId,
key: attributeKey,
type: CUSTOM_ATTRIBUTE_FEATURE_TYPE,
value: attributes[attributeKey],
});
// Omit attribute values that are not supported by the log endpoint.
fns.forOwn(attributes, function(attributeValue, attributeKey) {
if (attributeValidator.isAttributeValid(attributeKey, attributeValue)) {
var attributeId = projectConfig.getAttributeId(options.configObj, attributeKey, options.logger);
if (attributeId) {
commonParams.visitors[0].attributes.push({
entity_id: attributeId,
key: attributeKey,
type: CUSTOM_ATTRIBUTE_FEATURE_TYPE,
value: attributes[attributeKey],
});
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Should we log a message if isAttributeValid returns false?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think not, because attributes are omitted for log tier, nothing to deal at user side. User will get all attributes. it will be confusing if logtier message is logged.

}
});

Expand Down
137 changes: 137 additions & 0 deletions packages/optimizely-sdk/lib/core/event_builder/index.tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,143 @@ describe('lib/core/event_builder', function() {

assert.deepEqual(actualParams, expectedParams);
});

it('should create proper params for getImpressionEvent with typed attributes', function() {
var expectedParams = {
url: 'https://logx.optimizely.com/v1/events',
httpVerb: 'POST',
params: {
'account_id': '12001',
'project_id': '111001',
'visitors': [{
'attributes': [{
'entity_id': '111094',
'key': 'browser_type',
'type': 'custom',
'value': 'Chrome'
}, {
'entity_id': '323434545',
'key': 'boolean_key',
'type': 'custom',
'value': true
}, {
'entity_id': '616727838',
'key': 'integer_key',
'type': 'custom',
'value': 10
}, {
'entity_id': '808797686',
'key': 'double_key',
'type': 'custom',
'value': 3.14
}],
'visitor_id': 'testUser',
'snapshots': [{
'decisions': [{
'variation_id': '111128',
'experiment_id': '111127',
'campaign_id': '4'
}],
'events': [{
'timestamp': Math.round(new Date().getTime()),
'entity_id': '4',
'uuid': 'a68cf1ad-0393-4e18-af87-efe8f01a7c9c',
'key': 'campaign_activated'
}]
}]
}],
'revision': '42',
'client_name': 'node-sdk',
'client_version': packageJSON.version,
'anonymize_ip': false,
}
};

var eventOptions = {
attributes: {
'browser_type': 'Chrome',
'boolean_key': true,
'integer_key': 10,
'double_key': 3.14,
},
clientEngine: 'node-sdk',
clientVersion: packageJSON.version,
configObj: configObj,
experimentId: '111127',
variationId: '111128',
userId: 'testUser',
};

var actualParams = eventBuilder.getImpressionEvent(eventOptions);

assert.deepEqual(actualParams, expectedParams);
});

it('should remove invalid params from impression event payload', function() {
var expectedParams = {
url: 'https://logx.optimizely.com/v1/events',
httpVerb: 'POST',
params: {
'account_id': '12001',
'project_id': '111001',
'visitors': [{
'attributes': [{
'entity_id': '111094',
'key': 'browser_type',
'type': 'custom',
'value': 'Chrome'
}, {
'entity_id': '616727838',
'key': 'integer_key',
'type': 'custom',
'value': 10
}, {
'entity_id': '323434545',
'key': 'boolean_key',
'type': 'custom',
'value': false
}],
'visitor_id': 'testUser',
'snapshots': [{
'decisions': [{
'variation_id': '111128',
'experiment_id': '111127',
'campaign_id': '4'
}],
'events': [{
'timestamp': Math.round(new Date().getTime()),
'entity_id': '4',
'uuid': 'a68cf1ad-0393-4e18-af87-efe8f01a7c9c',
'key': 'campaign_activated'
}]
}]
}],
'revision': '42',
'client_name': 'node-sdk',
'client_version': packageJSON.version,
'anonymize_ip': false,
}
};

var eventOptions = {
attributes: {
'browser_type': 'Chrome',
'integer_key': 10,
'boolean_key': false,
'double_key': [1, 2, 3],
},
clientEngine: 'node-sdk',
clientVersion: packageJSON.version,
configObj: configObj,
experimentId: '111127',
variationId: '111128',
userId: 'testUser',
};

var actualParams = eventBuilder.getImpressionEvent(eventOptions);

assert.deepEqual(actualParams, expectedParams);
});
});

describe('getConversionEvent', function() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright 2016-2017, Optimizely
* Copyright 2016-2018, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -70,6 +70,9 @@ describe('lib/core/project_config', function() {

var expectedAttributeKeyMap = {
browser_type: testData.attributes[0],
boolean_key: testData.attributes[1],
integer_key: testData.attributes[2],
double_key: testData.attributes[3],
};

assert.deepEqual(configObj.attributeKeyMap, expectedAttributeKeyMap);
Expand Down
Loading