Skip to content
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

✨Analytics: CookieWriter #18406

Merged
merged 5 commits into from
Sep 28, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions build-system/conformance-config.textproto
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,7 @@ requirement: {
whitelist: 'src/experiments.js'
whitelist: 'src/service/cid-api.js'
whitelist: 'src/service/cid-impl.js'
whitelist: 'extensions/amp-analytics/0.1/cookie-writer.js'
}

# Function
Expand Down
1 change: 1 addition & 0 deletions build-system/tasks/presubmit-checks.js
Original file line number Diff line number Diff line change
Expand Up @@ -818,6 +818,7 @@ const forbiddenTermsSrcInclusive = {
whitelist: [
'extensions/amp-form/0.1/amp-form.js',
'src/service/url-replacements-impl.js',
'extensions/amp-analytics/0.1/cookie-writer.js',
],
},
'\\.expandInputValueSync\\(': {
Expand Down
5 changes: 5 additions & 0 deletions extensions/amp-analytics/0.1/amp-analytics.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import {Activity} from './activity-impl';
import {AnalyticsConfig, mergeObjects} from './config';
import {AnalyticsEventType} from './events';
import {CookieWriter} from './cookie-writer';
import {
ExpansionOptions,
installVariableService,
Expand Down Expand Up @@ -211,6 +212,10 @@ export class AmpAnalytics extends AMP.BaseElement {
})
.then(config => {
this.config_ = config;
return new CookieWriter(this.win,
this.element, this.config_).whenReady();
})
.then(() => {
this.transport_ =
new Transport(this.win, this.config_['transport'] || {});
})
Expand Down
136 changes: 136 additions & 0 deletions extensions/amp-analytics/0.1/cookie-writer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
/**
* Copyright 2018 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import {isObject, toWin} from '../../../src/types';
import {hasOwn, map} from '../../../src/utils/object';
import {user} from '../../../src/log';
import {Services} from '../../../src/services';
import {setCookie} from '../../../src/cookies';
import {BASE_CID_MAX_AGE_MILLIS} from '../../../src/service/cid-impl';
import {isInFie} from '../../../src/friendly-iframe-embed';
import {Deferred} from '../../../src/utils/promise';
import {isProxyOrigin} from '../../../src/url';


const TAG = 'amp-analytics/cookie-writer';

const EXPAND_WHITELIST = {
'QUERY_PARAM': true,
// TODO: Add linker_param
}

export class CookieWriter {

/**
* @param {!Window} win
* @param {!Element} element
* @param {!JsonObject} config
*/
constructor (win, element, config) {
/** @private {!Window} */
this.win_ = win;

/** @private {!Element} */
this.element_ = element;

/** @private {!../../../src/service/url-replacements-impl.UrlReplacements} */
this.urlReplacementService_ = Services.urlReplacementsForDoc(element);

/** @private {!Array<!Promise>} */
this.promises_ = [];

/** @private {!../../../src/utils/promise.Deferred} */
this.readyPromise_ = new Deferred();

this.init_(config);
Copy link
Contributor

Choose a reason for hiding this comment

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

instead of doing all the work in constructor, we can move it to whenReady. Actually, we'd rename whenReady to write or run

run() {
  ...
  return readyPromise;
}

Copy link
Contributor Author

@zhouyx zhouyx Sep 27, 2018

Choose a reason for hiding this comment

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

Good idea. I'll switch to write, but one thing I want to make sure is that we only write cookies once no matter how many times the write() has been invoked. To achieve that I'll need to make some extra change.
For example can longer switch to this.readyPromise_.resolve(Promise.all(this.promises_))

}

/**
* @return {!Promise}
*/
whenReady() {
return this.readyPromise_.promise;
}

/**
* @param {!JsonObject} config
*/
init_(config) {
if (!hasOwn(config, 'writeCookies')) {
this.readyPromise_.resolve();
return;
}

if (!isObject(config['writeCookies'])) {
user().error(TAG, 'writeCookies config must be an object');
this.readyPromise_.resolve();
return;
}

if (isInFie(this.element_)) {
// TODO: Need the consider the case for shadow doc.
// QQ: Is this even an error since vendor defines it?
Copy link
Contributor

Choose a reason for hiding this comment

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

right, let's not print an error

user().error(TAG, 'writeCookies is disabled in friendly iframe');
this.readyPromise_.resolve();
return;
}
if (isProxyOrigin(this.win_.location)) {
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: let's move cases that we ignore to the beginning (together with FIE).

// Disable cookie writter for proxy origin
// It's important to check here so that setCookie doesn't throw error on
// "should not attempt ot set cookie on proxy origin"
this.readyPromise_.resolve();
return;
}

const inputConfig = config['writeCookies'];
const ids = Object.keys(inputConfig);
for (let i = 0; i < ids.length; i++) {
const cookieId = ids[i];
const cookieStr = inputConfig[cookieId];
Copy link
Contributor

Choose a reason for hiding this comment

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

let's call them cookieName & cookieValue

if (typeof cookieStr === 'string') {
this.promises_.push(this.expandAndWrite_(cookieId, cookieStr));
}
Copy link
Contributor

Choose a reason for hiding this comment

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

print user error otherwise

}

Promise.all(this.promises_).then(() => {
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: this.readyPromise_.resolve(Promise.all(this.promises_))

this.readyPromise_.resolve();
});
}

/**
* Expand the value and write to cookie if necessary
* @param {string} cookieId
* @param {string} cookieStr
* @return {!Promise}
*/
expandAndWrite_(cookieId, cookieStr) {
// Note: Have to use `expandStringAsync` because QUERY_PARAM can wait for
// trackImpressionPromise and resolve async
return this.urlReplacementService_.expandStringAsync(cookieStr,
/* TODO: Add opt_binding */ undefined, EXPAND_WHITELIST).then(
cookieValue => {
// Note: We ignore empty cookieValue, that means currently we don't
// provide a way to overwrite or erase existing cookie
if (cookieValue) {
const expireDate = Date.now() + BASE_CID_MAX_AGE_MILLIS;
setCookie(this.win_, cookieId, cookieValue, expireDate);
}
}).catch(e => {
user().error(TAG, 'Error expanding cookie string', e);
});
}
}

187 changes: 187 additions & 0 deletions extensions/amp-analytics/0.1/test/test-cookie-writer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
/**
* Copyright 2018 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import {CookieWriter} from '../cookie-writer';
import * as cookie from '../../../../src/cookies';
import {dict} from '../../../../src/utils/object';

const TAG = '[amp-analytics/cookie-writer]'

describes.realWin('amp-analytics.cookie-writer', {
amp: true,
runtimeOn: true,
}, env => {

let sandbox;
let win;
let doc;
let setCookieSpy;
let element;
let ampdoc;

beforeEach(() => {
sandbox = env.sandbox;
setCookieSpy = sandbox.spy();
win = env.win;
ampdoc = env.ampdoc;
doc = win.document;
sandbox.stub(cookie, 'setCookie').callsFake(
(win, name, value, expirationTime) => {
setCookieSpy(name, value);
});
element = doc.createElement('div');
doc.body.appendChild(element);
});

describe('whenReady', () => {
it('Resolve when no config', () => {
const config = dict({});
const cookieWriter = new CookieWriter(win, element, config);
expect(setCookieSpy).to.not.be.called;
return cookieWriter.whenReady();
});

it('Resovle when config is invalid', () => {
const config = dict({
'writeCookies': 'invalid',
});
expectAsyncConsoleError(TAG + ' writeCookies config must be an object');
const cookieWriter = new CookieWriter(win, element, config);
expect(setCookieSpy).to.not.be.called;
return cookieWriter.whenReady();
});

it('Resolve when element is in FIE', () => {
const config = dict({
'writeCookies': {
'testId': 'testValue',
},
});
const parent = doc.createElement('div');
parent.classList.add('i-amphtml-fie');
doc.body.appendChild(parent);
parent.appendChild(element);
expectAsyncConsoleError(TAG +
' writeCookies is disabled in friendly iframe');
const cookieWriter = new CookieWriter(win, element, config);
expect(setCookieSpy).to.not.be.called;
return cookieWriter.whenReady();
});

it('Resolve when in viewer', () => {
const config = dict({
'writeCookies': {
'testId': 'testValue',
},
});
const mockWin = {
location: 'https://www-example-com.cdn.ampproject.org',
}
const cookieWriter = new CookieWriter(mockWin, element, config);
expect(setCookieSpy).to.not.be.called;
return cookieWriter.whenReady();
});

it('Resolve with nothing to write', () => {
const config = dict({
'writeCookies': {},
});
const cookieWriter = new CookieWriter(win, element, config);
expect(setCookieSpy).to.not.be.called;
return cookieWriter.whenReady();
});
});

describe('Cookie value', () => {
it('Write cookie', () => {
const config = dict({
'writeCookies': {
'testId': 'testValue'
},
});
const cookieWriter = new CookieWriter(win, element, config);
return cookieWriter.whenReady().then(() => {
expect(setCookieSpy).to.be.calledOnce;
expect(setCookieSpy).to.be.calledWith('testId', 'testValue');
});
});

it('Write multiple cookie', () => {
const config = dict({
'writeCookies': {
'testId': 'testValue',
'testId2': 'testValue2',
},
});
const cookieWriter = new CookieWriter(win, element, config);
return cookieWriter.whenReady().then(() => {
expect(setCookieSpy).to.be.calledTwice;
expect(setCookieSpy).to.be.calledWith('testId', 'testValue');
expect(setCookieSpy).to.be.calledWith('testId2', 'testValue2');
});
});

it('Expand whitelist macro', () => {
const config = dict({
'writeCookies': {
'testId': 'pre-QUERY_PARAM(noexist)',
'testId2': 'pre-RANDOM',
},
});
const cookieWriter = new CookieWriter(win, element, config);
return cookieWriter.whenReady().then(() => {
expect(setCookieSpy).to.be.calledTwice;;
// QUERY_PARAM resolve to empty string
expect(setCookieSpy).to.be.calledWith('testId', 'pre-');
// Never try to resolve RANDOM
expect(setCookieSpy).to.be.calledWith('testId2', 'pre-RANDOM');
});
});

it('Do not write when string is empty', () => {
const config = dict({
'writeCookies': {
'testId': 'QUERY_PARAM(noexist)',
'testId2': '',
},
});
const cookieWriter = new CookieWriter(win, element, config);
return cookieWriter.whenReady().then(() => {
// Both cookie value resolve to empty string
expect(setCookieSpy).to.not.be.called;
});
});

it('Handle expandString error', () => {
const config = dict({
'writeCookies': {
'testId': 'QUERY_PARAM',
'testId2': 'testValue',
},
});
const cookieWriter = new CookieWriter(win, element, config);
expectAsyncConsoleError(TAG + ' Error expanding cookie string ' +
'Error: The first argument to QUERY_PARAM, ' +
'the query string param is required​​​');
expectAsyncConsoleError('The first argument to QUERY_PARAM, ' +
'the query string param is required')
return cookieWriter.whenReady().then(() => {
// Both cookie value resolve to empty string
expect(setCookieSpy).to.be.calledOnce;
});
});
});
});
2 changes: 1 addition & 1 deletion src/service/cid-impl.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ const ONE_DAY_MILLIS = 24 * 3600 * 1000;
/**
* We ignore base cids that are older than (roughly) one year.
*/
const BASE_CID_MAX_AGE_MILLIS = 365 * ONE_DAY_MILLIS;
export const BASE_CID_MAX_AGE_MILLIS = 365 * ONE_DAY_MILLIS;

const SCOPE_NAME_VALIDATOR = /^[a-zA-Z0-9-_.]+$/;

Expand Down
7 changes: 5 additions & 2 deletions src/service/url-replacements-impl.js
Original file line number Diff line number Diff line change
Expand Up @@ -804,10 +804,13 @@ export class UrlReplacements {
* or override existing ones.
* @param {string} source
* @param {!Object<string, *>=} opt_bindings
* @param {!Object<string, boolean>=} opt_whiteList
* @return {!Promise<string>}
*/
expandStringAsync(source, opt_bindings) {
return /** @type {!Promise<string>} */ (this.expand_(source, opt_bindings));
expandStringAsync(source, opt_bindings, opt_whiteList) {
return /** @type {!Promise<string>} */ (this.expand_(source, opt_bindings,
/* opt_collectVars */ undefined,
/* opt_sync */ undefined, opt_whiteList));
}

/**
Expand Down
Loading