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

Amp analytics 3p vendors, impl side #10185

Closed
wants to merge 4 commits into from
Closed
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
15 changes: 13 additions & 2 deletions 3p/iframe-messaging-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export class IframeMessagingClient {
this.win_ = win;
/** @private {?string} */
this.rtvVersion_ = getMode().rtvVersion || null;
/** @private {!Window} */
/** @private {!(Window|HTMLIFrameElement)} */
this.hostWindow_ = win.parent;
/** @private {?string} */
this.sentinel_ = null;
Expand Down Expand Up @@ -101,6 +101,15 @@ export class IframeMessagingClient {
*/
setupEventListener_() {
listen(this.win_, 'message', event => {
if (this.hostWindow_ instanceof HTMLIFrameElement) {
// this.hostWindow_ can now be set to an iframe, after it has been
// created but before it has finished loading. If we've gotten a
// message from that iframe, then it must exist, so its
// contentWindow is now non-null.
this.hostWindow_ =
/** @type {!Window} */ (this.hostWindow_.contentWindow);
}

// Does it look a message from AMP?
if (event.source != this.hostWindow_) {
return;
Expand All @@ -116,7 +125,9 @@ export class IframeMessagingClient {
}

/**
* @param {!Window} win
* @param {!(Window|HTMLIFrameElement)} win The window to communicate with.
* This may be set to a newly-created iframe instead, since its
* contentWindow will be null until it renders.
*/
setHostWindow(win) {
this.hostWindow_ = win;
Expand Down
4 changes: 4 additions & 0 deletions build-system/dep-check-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,10 @@ exports.rules = [
{
filesMatching: '{src,extensions}/**/*.js',
mustNotDependOn: '3p/**/*.js',
whitelist: [
'extensions/amp-analytics/0.1/transport.js->' +
'3p/iframe-messaging-client.js',
],
},

// Rules for extensions.
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 @@ -318,6 +318,7 @@ var forbiddenTerms = {
'3p/ampcontext.js',
'3p/ampcontext-integration.js',
'dist.3p/current/integration.js', // includes previous
'extensions/amp-analytics/0.1/transport.js',
],
},
'\\.sendMessageAwaitResponse\\(': {
Expand Down
26 changes: 26 additions & 0 deletions examples/analytics-3p.amp.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<!doctype html>
<html ⚡>
<head>
<meta charset="utf-8">
<title>3P AMP Analytics Example</title>
<link rel="canonical" href="amps.html" >
<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
<link href='https://fonts.googleapis.com/css?family=Georgia|Open+Sans|Roboto' rel='stylesheet' type='text/css'>
<script async custom-element="amp-analytics" src="https://cdn.ampproject.org/v0/amp-analytics-0.1.js"></script>
<script async custom-element="amp-ad" src="https://cdn.ampproject.org/v0/amp-ad-0.1.js"></script>
<style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
<script async src="https://cdn.ampproject.org/v0.js"></script>
</head>
<body>
Here is some text above the ad.<br/>
<amp-ad width="300" height="400"
type="fake"
src="fake_amp_ad_with_3p_analytics.json"
data-use-a4a="true" fakesig="true">
<div placeholder>Loading...</div>
<div fallback>Could not display the fake ad :(</div>
</amp-ad>
<br/>
Here is some text below the ad.<br/>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"creative": "<!doctype html><html amp4ads><head><meta charset=utf-8><script async src=https://cdn.ampproject.org/v0.js></script><script async custom-element=amp-analytics src=https://cdn.ampproject.org/v0/amp-analytics-0.1.js></script><style amp4ads-boilerplate>body{visibility:hidden}</style><meta name=viewport content=width=device-width,minimum-scale=1></head><body><a href=\"http://localhost/landing.html?testStatus=3PANALYTICS(test,status)&testOther=3PANALYTICS(test,somethingElse)&test2Status=3PANALYTICS(test2,status)&test2Other=3PANALYTICS(test2,somethingElse)\"><amp-img height=300 id=img src=https://upload.wikimedia.org/wikipedia/commons/6/6e/Golde33443.jpg width=256></amp-img> <p class=frob>By Golden Trvs Gol twister (Own work) [CC BY-SA 4.0 (http://creativecommons.org/licenses/by-sa/4.0)], via Wikimedia Commons</p></a><amp-analytics type=\"test\"><script type=application/json>{\"requests\":{\"pageview\":\"viewed=true&url=${canonicalUrl}&title=${title}&acct=${account}\",\"event\":\"eid=click&acct=${account}\"},\"vars\":{\"account\":\"ABC123\"},\"triggers\":{\"defaultPageview\":{\"on\":\"visible\",\"request\":\"pageview\"},\"anchorClicks\":{\"on\":\"click\",\"selector\":\"img\",\"request\":\"event\"}},\"transport\":{\"iframe\":\"http://localhost:8000/examples/analytics-3p-remote-frame.html\",\"extraData\":\"ThisIsExtraData\"}}</script></amp-analytics><script type=\"application/json\" amp-ad-metadata>{\"ampRuntimeUtf16CharOffsets\":[55,222],\"bodyAttributes\":\"\",\"bodyUtf16CharOffsets\":[356,2436],\"customElementExtensions\":[\"amp-analytics\"],\"jsonUtf16CharOffsets\":{\"amp-analytics\":[661,2410]}}</script></body></html>",
"signature": "ACWMjZE6z6W9JyytdwVJ6FpbUxDxRcyRbYVT9mv/eYZbaUHP4x9nVHPA9B298mIZeqr73aWipv4aldRrb6SWS7SBi9rgKRvB2F6ppS5mXsEQCkZaBxuBgPKrz4hl2F3mElpV60ScN7xX2kt5tGJp+E9sZCU6K9w9j7XKJRhQ6Hc5TZnPvrWeUiT0Pth0O/KREKIBbR3EocM/5TYEHlQ38e2dtEIiyY6B1BgPLBz80uKASIDNS/IgJoaFWqR7VkZkztq7sjrhgKEGPscJiqVSviN9r9beAJnsBzFio4Onu+FMwY0+kkdKvZ7fhiuMvuSmGqcyrwqwLlGSc0dqYiqx7EGhTDKM"
}

220 changes: 220 additions & 0 deletions extensions/amp-analytics/0.1/amp-analytics-3p-message-queue.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
/**
* Copyright 2017 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 {dev} from '../../../src/log';
import {AMP_ANALYTICS_3P_MESSAGE_TYPE} from '../../../src/3p-analytics-common';

/** @private @const {string} */
const TAG_ = 'amp-analytics.CrossDomainIframeMessageQueue';

/** @private @const {number} */
const MAX_QUEUE_SIZE_ = 100;

/**
* @visibleForTesting
* @abstract
*/
class AbstractAmpAnalytics3pMessageQueue {
Copy link
Contributor

Choose a reason for hiding this comment

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

We plan to handle the batching use case in a different level. @zhouyx has started looking into it.

Ideally, pub should be able to do

transport: {
  beacon: true,
  xhrpost: true,
  image: true,
  batchRequestsInMs: 100,
}

For example, we can enable it for the GoogleAnalytics post API, which does support batching.

So can you hold the message queue code for now, and assume throttling will happen in a later phase.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Interesting...are there docs for that which I could look at?

Copy link
Contributor

Choose a reason for hiding this comment

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

not yet. i was over simplifying the spec. there will be challenges of how pub can specify different endpoint for batch request.

nevertheless, we can further scope down this PR by moving batching out.

/**
* Constructor
* @param {!Window} win The window element
* @param {!../../../src/iframe-helper.SubscriptionApi}
* sender Facilitates cross-frame communication
* @param {!string} messageType The type that will be used to
* contain the queued data (see 3p-analytics-common)
*/
constructor(win, sender, messageType) {
/** @private {!Window} */
this.win_ = win;

/** @private {!../../../src/iframe-helper.SubscriptionApi} */
this.sender_ = sender;

/** @private {string} */
this.messageType_ = messageType;

/** @private {boolean} */
this.isReady_ = false;

/** @private {!Object<string,!string|!Array<string>>} */
this.creativeToPendingMessages_ = {};
}

/**
* Indicate that a cross-domain frame is ready to receive messages, and
* send all messages that were previously queued for it.
*/
setIsReady() {
this.isReady_ = true;
this.flushQueue_();
}

/**
* Send queued data (if there is any) to a cross-domain iframe
* @private
*/
flushQueue_() {
if (this.isReady_ && this.queueSize()) {
const jsonMsg = /** @type {JsonObject} */ (this.buildMessage());
this.sender_.send(this.messageType_, jsonMsg);
this.creativeToPendingMessages_ = {};
}
}

/**
* @return {../../../src/3p-analytics-common.AmpAnalytics3pNewCreative|
* ../../../src/3p-analytics-common.AmpAnalytics3pEvent}
* @abstract
* @VisibleForTesting
*/
buildMessage() {
}

/**
* Returns how many senderId -> message(s) mappings there are
* @return {number}
* @VisibleForTesting
*/
queueSize() {
return Object.keys(this.creativeToPendingMessages_).length;
}

/**
* Returns whether the queue has been marked as ready yet
* @return {boolean}
* @VisibleForTesting
*/
isReady() {
return this.isReady_;
}
}

export class AmpAnalytics3pNewCreativeMessageQueue extends
AbstractAmpAnalytics3pMessageQueue {

/**
* Constructor
* @param {!Window} win The window element
* @param {!../../../src/iframe-helper.SubscriptionApi}
* sender Facilitates cross-frame communication
*/
constructor(win, sender) {
super(win, sender, AMP_ANALYTICS_3P_MESSAGE_TYPE.CREATIVE);
}

/**
* Enqueues an AmpAnalytics3pNewCreative message to be sent to a cross-domain
* iframe.
* @param {!string} senderId Identifies which creative is sending the message
* @param {string=} opt_data The data to be enqueued and then sent to the
* iframe
*/
enqueue(senderId, opt_data) {
dev().assert(!this.messageFor(senderId),
'Replacing existing extra data for: ' + senderId);
this.creativeToPendingMessages_[senderId] = opt_data || '';
this.flushQueue_();
}

/**
* Builds a message object containing the queued data
* @return {../../../src/3p-analytics-common.AmpAnalytics3pNewCreative}
* @override
* @VisibleForTesting
*/
buildMessage() {
Copy link
Contributor

Choose a reason for hiding this comment

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

buildMessage and messageFor is duplicated across both classes. Any way to save that?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

For buildMessage()...they are building different types of messages: AmpAnalytics3pNewCreativeMessageQueue.buildMessage() builds a AmpAnalytics3pNewCreative message, whereas AmpAnalytics3pEventMessageQueue.buildMessage() builds a AmpAnalytics3pEvent.

Also note that AmpAnalytics3pNewCreativeMessageQueue has messageFor() whereas AmpAnalytics3pEventMessageQueue has messagesFor(), since a creative will only init once but can send any number of events.

I originally had just the superclass and was jumping through hoops to enforce these things, but pivoted and created the subclasses for these reasons.

const message =
/** @type {../../../src/3p-analytics-common.AmpAnalytics3pNewCreative} */
({
type: this.messageType_,
data: this.creativeToPendingMessages_,
});
return message;
}

/**
* Test method to see which message (if any) is associated with a given
* senderId
* @param {!string} senderId Identifies which creative is sending the message
* @return {string}
* @VisibleForTesting
*/
messageFor(senderId) {
return /** @type {string} */ (
Copy link
Contributor

Choose a reason for hiding this comment

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

I'm surprised you need to type this given creativeToPendingMessages_ is typed as having string based keys

Copy link
Contributor Author

@jonkeller jonkeller Jun 29, 2017

Choose a reason for hiding this comment

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

It's typed has having string-based keys, but we are returning the value, which is typed as string|Array<string>. (String for this subclass, Array for the other.) So without the cast:

extensions/amp-analytics/0.1/amp-analytics-3p-message-queue.js:167: ERROR - inconsistent return type
found   : (Array<string>|string)
required: string
    return this.creativeToPendingMessages_[senderId];

this.creativeToPendingMessages_[senderId]);
}
}

export class AmpAnalytics3pEventMessageQueue extends
AbstractAmpAnalytics3pMessageQueue {

/**
* Constructor
* @param {!Window} win The window element
* @param {!../../../src/iframe-helper.SubscriptionApi}
* sender Facilitates cross-frame communication
*/
constructor(win, sender) {
super(win, sender, AMP_ANALYTICS_3P_MESSAGE_TYPE.EVENT);
}

/**
* Enqueues an AmpAnalytics3pEvent message to be sent to a cross-domain
* iframe.
* @param {!string} senderId Identifies which creative is sending the message
* @param {!string} data The data to be enqueued and then sent to the iframe
*/
enqueue(senderId, data) {
this.creativeToPendingMessages_[senderId] =
this.creativeToPendingMessages_[senderId] || [];
if (this.queueSize() >= MAX_QUEUE_SIZE_) {
dev().warn(TAG_, 'Exceeded maximum size of queue for: ' + senderId);
this.creativeToPendingMessages_[senderId].shift();
}
this.creativeToPendingMessages_[senderId].push(data);

this.flushQueue_();
}

/**
* Builds a message object containing the queued data
* @return {../../../src/3p-analytics-common.AmpAnalytics3pEvent}
* @override
* @VisibleForTesting
*/
buildMessage() {
const message =
/** @type {../../../src/3p-analytics-common.AmpAnalytics3pEvent} */
({
type: this.messageType_,
data: this.creativeToPendingMessages_,
});
return message;
}

/**
* Test method to see which messages (if any) are associated with a given
* senderId
* @param {!string} senderId Identifies which creative is sending the message
* @return {Array<string>}
* @VisibleForTesting
*/
messagesFor(senderId) {
return /** @type {Array<string>} */ (
this.creativeToPendingMessages_[senderId]);
}
}

Loading