-
Notifications
You must be signed in to change notification settings - Fork 3.9k
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
✨Analytics: CookieWriter #18406
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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); | ||
} | ||
|
||
/** | ||
* @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? | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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)) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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]; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. let's call them |
||
if (typeof cookieStr === 'string') { | ||
this.promises_.push(this.expandAndWrite_(cookieId, cookieStr)); | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. print user error otherwise |
||
} | ||
|
||
Promise.all(this.promises_).then(() => { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: |
||
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); | ||
}); | ||
} | ||
} | ||
|
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; | ||
}); | ||
}); | ||
}); | ||
}); |
There was a problem hiding this comment.
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 renamewhenReady
towrite
orrun
There was a problem hiding this comment.
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 thewrite()
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_))