Support providing the client id to the viewer for storage
This allows viewers to not have any logic regarding how to generate IDs.
Tracked at Google under b/30089828
TL;DR (by lannka@ 8/11/2016)
The final protocol we agreed on between Runtime and Viewer:
- Runtime sends message 'cid' with/without payload to Viewer to set/get the CID data.
- Viewer returns CID data or
null(not found) when receiving 'cid' without a payload. If there is a payload, the payload is persisted in viewer's storage as the CID data and then returned to Runtime.
CID data is a stringified JSON object:
{
time: number, // timestamp
cid: string, // cid string
}
The data flows like this:
- Runtime tries to retrieve CID from Viewer
- If Viewer returns
null, Runtime will generate a new CID data and then set it to Viewer. - If Viewer returns a CID,
- but the CID is expired (
timestampis more than 1-year old). Runtime will generate a new CID data and then set it to Viewer. - if CID is not expired, Runtime will update the
timestampof the CID data and set it to Viewer. To reduce unnecessary updates, Runtime only update a CID that is more than 1-day old.
- but the CID is expired (
- If Viewer returns
That's to say, the Viewer is simply a dumb storage. All the logic is consolidated at Runtime side.
The use case is as follow:
- The runtime sends a cid message to get the base cid from the viewer
- In case the viewer's storage has the cid it returns it --- That's exactly how it works today. However,
- Otherwise (no cid in storage), the viewer returns an empty cid 3.1) When the runtime gets an empty cid, it knows that it has to generate it itself 3.2) The runtime has to send a new message (STORE_CID maybe?) to the viewer to store the new generated cid.
Instead of sending the new Base CID in a second message, we can also send it as the payload of the first message. This way:
- saves one round trip of window.sendMessage in case viewer doesn't have base CID yet
- as an exchange, adds the cost of generating random base64 to every getBaseCid() call, even when viewer has base CID.
- simplifies code (no nested promises)
@peleyal how does this sound?
SGTM. I like that it saves a round-trip of window.sendMessage. I don't like that we will generate it anyway... how expensive is it?
How many times we expect the runtime to ask for a clientid? If I understand correctly it will happen only once, which is why sending and generating it anyway is a good idea.
Let me know.
Good question. My originally thought was that we cache base CID at our side once retrieved from viewer.
However, after taking a close look, I found something confusing. (code).
It might not be directly related to the issue we're solving here. But it's good to clarify before we touch this piece of code.
Assume a user visited several amp pages served from cache, the code implies the following behavior.
1st visit:
User visited an AMP page via a viewer. AMP runtime asked viewer for base CID. Viewer generated base CID of 12345 and persisted at viewer side.
2nd visit:
User visited another AMP page via a viewer. AMP runtime asked viewer for base CID. Viewer returned the persisted base CID of 12345.
3rd visit:
User visited another AMP page directly (served from cache), since there's no viewer, runtime created a base CID and persisted in local storage 54321.
4th visit:
User visited another AMP page via a viewer, the base CID in local storage is used at this time: 54321.
As you can see, the 3nd visit is the pivot point. All visits after that will have base CID of 54321.
@dvoytenko am I missing anything? Is the behavior intended?
Talked to @dvoytenko. It's working as intended.
- In frame embed mode (in a viewer), AMP runtime have limited local storage access (iframe limitation), so it has to let viewer to do it.
- In non-embed mode, AMP runtime will create a different ID. This ID will be used for all later visits, even in a viewer, because it is considered more universal (available in different viewers).
@dvoytenko correct me if I have any misunderstanding.
@lannka Yes. Correct.
RE:reducing number of post messages
My initial sense is that generating base CID for each impression would be more expensive than a post-message roundtrip. Also, we need to look at how likely the second roundtrip would actually be needed. It sounds like it's only needed very rarely.
To answer @peleyal's question:
- unfortunately in viewer mode, it will ask for base CID for every page view.
- Speed wise, I don't have the number yet. Basically it runs through 2 functions,
crypto.getRandomValues()andwindow.btoa(). They're both browser native function, so I assume it's pretty fast. Anyone has experience on it?
The 2 round-trip solution has some other things we need to consider:
- Right now if viewer fails to generate or retrieve a base CID,
viewer.getBaseCid()returnsnull, and then runtime will throw. But now we want to attach new meaning tonull, so once anullis returned, how do we know if it's actually a failure in viewer, or it is right time to callviewer.storeBaseCid()? - Once viewer expose such an interface as
storeBaseCid(), does it need to read before write? Or it should just blindly override?
Given those complications, I'm slightly leaning towards to the single round-trip solution. What do you think?
unfortunately in viewer mode, it will ask for base CID for every page view.
That's ok. But there's something we can do about it. Since we now always generate CID, we can always try to store it. It won't always work - but when it does - we win on a roundtrip to viewer.
Basically it runs through 2 functions, crypto.getRandomValues() and window.btoa()
At least getRandomValues works on a separate thread, so we are doing context switching anyway.
how do we know if it's actually a failure in viewer, or it is right time to call viewer.storeBaseCid()
I think our behavior should be the same. If for any reason we couldn't get Base CID from viewer, we need to generate our own and ask the viewer to store it.
Once viewer expose such an interface as storeBaseCid(), does it need to read before write? Or it should just blindly override?
Blind override.
Given those complications, I'm slightly leaning towards to the single round-trip solution. What do you think?
Let's try to estimate the cost of getRandomValues + atob and go from there. I'm still leaning toward two messages. Mostly because the probability of needing to execute the first message is about 100%, while the probability of needed the store message is much much lower. The only argument I see going for one message is simpler protocol.
I've created a snippet for getRandomValues + btoa, run it here.
On my desktop, it's 15ms for 1000 sequential runs. avg = 0.015ms.
On my nexus 6, it's 72ms for 1000 sequential runs. avg = 0.072ms.
I think it should not be a concern.
BTW, I don't think getRandomValues is on separate thread. It's a sync call.
And how fast would a second #postMessage be if it were needed? I think this is going to be faster than generating a throw-away cid for the normal case.
BTW, I don't think getRandomValues is on separate thread. It's a sync call.
Definitely on the same thread.
Right now if viewer fails to generate or retrieve a base CID, viewer.getBaseCid() returns null, ... But now we want to attach new meaning to null...?
We could just have the viewer send a message back and have it wait for the response before sending back the original?
We could just have the viewer send a message back and have it wait for the response before sending back the original?
Didn't quite understand this part. Could you expand?
The point I wanted to make is: having 2 round-trips complicates the APIs and logic at both sides (viewer and runtime). And I think < 0.1ms is a neglect-able cost to pay for it.
The getBaseCid waits for a response from the viewer. If the viewer doesn't want to generate the cid, it can send generateBaseCid to AMP. AMP will then respond with generatedBaseCid back to the viewer. Viewer then uses the response from generateBaseCid to respond to getBaseCid. (Naming all up for debate here)
The point I wanted to make is: having 2 round-trips complicates the APIs and logic at both sides
Why ask for a cid if AMP will just generate it in the request? It just seems wrong.
The getBaseCid waits for a response from the viewer. If the viewer doesn't want to generate the cid, it can send generateBaseCid to AMP. AMP will then respond with generatedBaseCid back to the viewer. Viewer then uses the response from generateBaseCid to respond to getBaseCid. (Naming all up for debate here)
That is exactly what I called "complicated protocol and logic".
Why ask for a cid if AMP will just generate it in the request? It just seems wrong.
I don't see anything wrong here. It's a very common protocol: getOrCreate()
If you have doubt, we used in everywhere in AMP, the getService(serviceId, factory|object). Though you can argue in most cases we passed a factory which is lazy called.
Also, don't we sha384 the cid, not btoa? https://jsfiddle.net/b649kaf7/5/
@jridgewell Good point. It's indeed sha384.
Didn't notice that. But why do we take a random number and then hash it? According to the documentation, getRandomValues() is a good enough source for randomness.
The RandomSource.getRandomValues() method lets you get cryptographically random values. The array given as the parameter is filled with random numbers (random in its cryptographic meaning).
To guarantee enough performance, implementations are not using a truly random number generator, but they are using a pseudo-random number generator seeded with a value with enough entropy. The PRNG used differs from one implementation to the other but is suitable for cryptographic usages. Implementations are also required to use a seed with enough entropy, like a system-level entropy source.
The thread is quite long now, let me try to summarize.
In the case viewer doesn't have a CID yet, we are choosing among the following protocols:
- runtime sends
get-cidto viewer. viewer returnsnull. runtime sendstore-cidwith a newly generated cid. viewer returns the stored cid - runtime sends
get-cidto viewer. viewer sendsgenerate-cidto runtime. runtime generates CID and returns to viewer. viewer store the cid and returns back to runtime. - runtime sends
get-cidto viewer together with a new cid. viewer stores the new cid and returns it back to runtime.
Both 1) and 2) need 2 round trips of postMessage.
-
has some implications that we need to deal with, as discussed in one of my previous post.
-
needs a 2-way communication between viewer and runtime. if we already have such a sophisticated mechanism, 2) is preferable to 1).
-
needs 1 round trip, with the cost of generating a cid for every pageview even when it's not used. However, according to our experiment, the average time of generating such an ID is less than 0.1ms (with btoa, with sha384).
I prefer 3), because
- 0.1ms is a neglectable cost to pay for a simpler protocol between 2 projects (under different code repositories).
- There will be many viewers, including 3P viewers. Simpler protocol means easier integration and future maintenance.
- We actually gain speed on the cases when we do need a new CID to to persisted. we saved the time for a postMessage round trip, and also saved the tiny latency caused by more complicated code.
We have 2-way communication sendMessage() can return a Promise which will contain the response from the viewer.
From the Viewer side, either a 1 step or 2 step protocol is fine. The handlers will be simple in either case. The one step approach just means there's one less message to document.
lannka, do you mean the runtime sends a post message to the viewer with 'cid' as the message name? I'm not if you are suggesting that 'get-cid' should be sent. From the perspective of an AMP Lite viewer I believe it would make sense to keep the strings as short and concise as possible to reduce bytes.
With regards to the protocols, from an AMP Lite perspective I would prefer option 3) because it requires the viewer code to have less strings in the code that parses the received messages and less back and forth, which could mean less bytes for the viewer and a faster experience for users with low bandwidth.