/
index.html
508 lines (354 loc) · 21.4 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
<!DOCTYPE html>
<!--[if IEMobile 7 ]><html class="no-js iem7"><![endif]-->
<!--[if lt IE 9]><html class="no-js lte-ie8"><![endif]-->
<!--[if (gt IE 8)|(gt IEMobile 7)|!(IEMobile)|!(IE)]><!--><html class="no-js" lang="en"><!--<![endif]-->
<head>
<meta charset="utf-8">
<title>Cross-domain AJAX Served From CDN</title>
<meta name="author" content="Alexander Todorov">
<meta name="description" content="This week Amazon announced
support for dynamic content in their CDN solution Amazon CloudFront.
The announce coincided with my efforts to migrate …">
<!-- http://t.co/dKP3o1e -->
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="canonical" href="http://atodorov.org/blog/2012/05/19/cross-domain-ajax-served-from-cdn/">
<link href="/favicon.png" rel="icon">
<link href="/stylesheets/screen.css" media="screen, projection" rel="stylesheet" type="text/css">
<script src="/javascripts/modernizr-2.0.js"></script>
<script src="/javascripts/ender.js"></script>
<script src="/javascripts/octopress.js" type="text/javascript"></script>
<link href="http://feeds.feedburner.com/atodorov" rel="alternate" title="atodorov.org - you can logoff, but you can never leave" type="application/atom+xml">
<!--Fonts from Google"s Web font directory at http://google.com/webfonts -->
<link href="http://fonts.googleapis.com/css?family=PT+Serif:regular,italic,bold,bolditalic" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=PT+Sans:regular,italic,bold,bolditalic" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Russo+One" rel="stylesheet" type="text/css" />
<meta name="google-site-verification" content="XynqZtldWNBbmsynVQZremIxaaO8Wgs6AGR8UZ7KIkM" />
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-37979549-1', 'atodorov.org');
ga('send', 'pageview');
</script>
</head>
<body >
<header role="banner"><hgroup>
<div id="logo-container">
<div id="logo">atodorov.org</div>
<div id="logo-sub"><em>
you can logoff, but you can never leave
</em></div>
</div>
</hgroup>
</header>
<nav role="navigation"><ul class="subscription" data-subscription="rss">
<li><a href="http://feeds.feedburner.com/atodorov" rel="subscribe-rss" title="subscribe via RSS">RSS</a></li>
</ul>
<ul class="main-navigation">
<li><a href="/">Home</a></li>
<li><a href="/give-away/">Give Away List</a></li>
<li><a href="/projects/">Projects</a></li>
<li><a href="/domains/">Domains</a></li>
<li><a href="http://amzn.to/1wTPaLe">Previous: Traction</a></li>
<li><a href="http://amzn.to/1lLi5NU">Previous: How to Win Friends</a></li>
</ul>
</nav>
<div id="main">
<div id="content">
<div>
<article class="hentry" role="article">
<header>
<h1 class="entry-title">Cross-domain AJAX Served From CDN</h1>
<p class="meta">
<time datetime="2012-05-19T16:58:00+03:00" pubdate data-updated="true">May 19<span>th</span>, 2012</time>
| <a href="#disqus_thread">Comments</a>
</p>
</header>
<div class="entry-content"><p>This week Amazon <a href="http://aws.typepad.com/aws/2012/05/amazon-cloudfront-support-for-dynamic-content.html">announced</a>
support for dynamic content in their CDN solution <a href="http://aws.amazon.com/cloudfront/"><em>Amazon CloudFront</em></a>.
The announce coincided with my efforts to migrate more pieces of <em>Difio</em>’s <a href="http://www.dif.io">website</a> to <em>CloudFront</em>.</p>
<p>In this article I will not talk about hosting static files on CDN. This is easy and I’ve already written
about it <a href="/blog/2012/04/17/using-openshift-as-amazon-cloudfront-origin-server/">here</a>. I will show how to
cache AJAX(JSONP actually) responses and serve them directly from <em>Amazon CloudFront</em>.</p>
<h2>Background</h2>
<p>For those of you who may not be familiar (are there any) CDN stands for
<a href="https://en.wikipedia.org/wiki/Content_delivery_network">Content Delivery Network</a>. In short
this employs numerous servers with identical content. The requests from the browser are served
from the location which gives best performance for the user. This is used by all major websites
to speed-up static content like images, video, CSS and JavaScript files.</p>
<p>AJAX means <a href="https://en.wikipedia.org/wiki/Ajax_%28programming%29">Asynchronous JavaScript and XML</a>.
This is what Google uses to create dynamic user interface which doesn’t require to reload the page.</p>
<h2>Architecture</h2>
<p><em>Difio</em> has two web interfaces. The primary one is a static HTML website
which employs JavaScript for the dynamic areas. It is hosted on the dif.io domain.
The other one is powered by Django and provides the same interface plus the
<a href="https://difio-otb.rhcloud.com/dashboard/">applications dashboard</a> and several API functions
which don’t have a visible user interface. This is under the *.rhcloud.com domain b/c it is hosted on
<a href="http://openshift.redhat.com"><em>OpenShift</em></a>.</p>
<p>The present state of the website is the result of rapid development using conventional methods -
HTML templates and server-side processing. This is migrating to modern web technology like static HTML
and JavaScript while the server side will remain pure API service.</p>
<p>For this migration to happen I need the HTML pages at dif.io to execute JavaScript and load information
which comes from the rhcloud.com domain. Unfortunately this is not easily doable with AJAX because
of the <a href="https://en.wikipedia.org/wiki/Same_origin_policy">Same origin policy</a> in browsers.</p>
<p>I’m using the <a href="http://dojotoolkit.org/"><em>Dojo Toolkit</em></a> JavaScript framework which has a solution.
It’s called <a href="https://en.wikipedia.org/wiki/JSONP">JSONP</a>. Here’s how it works:</p>
<pre><code> dif.io ------ JSONP request --> abc.rhcloud.com --v
^ |
| |
JavaScript processing |
| |
+------------------ JSONP response ------------+
</code></pre>
<p>This is pretty standard configuration for a web service.</p>
<h2>Going to the clouds</h2>
<p>The way <em>Dojo</em> implements JSONP is through the
<a href="http://dojotoolkit.org/reference-guide/1.7/dojo/io/script.html">dojo.io.script</a> module.
It works by appending a query string parameter of the form <em>?callback=funcName</em> which the server uses
to generate the JSONP response. This callback name is dynamically generated by <em>Dojo</em> based on the order
in which your call to <em>dojo.io.script</em> is executed.</p>
<p>Until recently <em>Amazon CloudFront</em> ignored all query string parameters when requesting the content from
the origin server. Without the query string it was not possible to generate the JSONP response.
Luckily Amazon resolved the issue only one day after I asked about it on their forums.</p>
<p>Now <em>Amazon CloudFront</em> will use the URL path and the query string parameters to identify the objects in cache.
To enable this edit the CloudFront distribution <em>behavior(s)</em> and set <em>Forward Query Strings</em> to Yes.</p>
<p>When a visitor of the website requests the data <em>Amazon CloudFront</em> will use exactly the same url path and query strings
to fetch the content from the origin server. All that I had to do is switch the domain of the JSONP service
to point to the cloudfront.net domain. It became like this:</p>
<pre><code> | Everything on this side is handled by Amazon.
| No code required!
|
dif.io ------ JSONP request --> xyz.cloudfront.net -- JSONP request if cache miss --> abc.rhcloud.com --v
^ | ^ |
| | | |
JavaScript processing | +---------- JSONP response --------------------------+
| |
+---- cached JSONP response ---+
</code></pre>
<p>As you can see the website structure and code didn’t change at all. All that changed was a single domain name.</p>
<h2>Controlling the cache</h2>
<p><em>Amazon CloudFront</em> will keep the contents in cache based on the origin headers if present or the manual configuration
from the AWS Console. To work around frequent requests to the origin server it is considered best practice to set the
Expires header to a value far in the future, like 1 year.
However if the content changes you need some way to tell <em>CloudFront</em> about it. The most commonly used method is through
using different URLs to access the same content. This will cause <em>CloudFront</em> to cache the content under the new location
while keeping the old content until it expires.</p>
<p><em>Dojo</em> makes this very easy:</p>
<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nx">require</span><span class="p">([</span><span class="s2">"dojo/io/script"</span><span class="p">],</span>
</span><span class='line'> <span class="kd">function</span><span class="p">(</span><span class="nx">script</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'> <span class="nx">script</span><span class="p">.</span><span class="nx">get</span><span class="p">({</span>
</span><span class='line'> <span class="nx">url</span><span class="o">:</span> <span class="s2">"https://xyz.cloudfront.net/api/json/updates/1234"</span><span class="p">,</span>
</span><span class='line'> <span class="nx">callbackParamName</span><span class="o">:</span> <span class="s2">"callback"</span><span class="p">,</span>
</span><span class='line'> <span class="nx">content</span><span class="o">:</span> <span class="p">{</span><span class="nx">t</span><span class="o">:</span> <span class="nx">timeStamp</span><span class="p">},</span>
</span><span class='line'> <span class="nx">load</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">jsonData</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'> <span class="p">....</span>
</span><span class='line'> <span class="p">},</span>
</span><span class='line'><span class="p">....</span>
</span></code></pre></td></tr></table></div></figure>
<p>The <em>content</em> property allows additional key/value pairs to be sent in the query string. The
<em>timeStamp</em> parameter serves only to control <em>Amazon CloudFront</em> cache. It’s not processed server side.</p>
<p>On the server-side we have:</p>
<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='python'><span class='line'><span class="n">response</span><span class="p">[</span><span class="s">'Cache-Control'</span><span class="p">]</span> <span class="o">=</span> <span class="s">'max-age=31536000'</span>
</span><span class='line'><span class="n">response</span><span class="p">[</span><span class="s">'Expires'</span><span class="p">]</span> <span class="o">=</span> <span class="p">(</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">()</span><span class="o">+</span><span class="n">timedelta</span><span class="p">(</span><span class="n">seconds</span><span class="o">=</span><span class="mi">31536000</span><span class="p">))</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s">'%a, </span><span class="si">%d</span><span class="s"> %b %Y %H:%M:%S GMT'</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>
<h2>Benefits</h2>
<p>There were two immediate benefits:</p>
<ul>
<li>Reduced page load time. Combined with serving static files from CDN this greatly improves the user experience;</li>
<li>Reduced server load. Content is requested only once if it is missing from the cache and then served from CloudFront.
The server isn’t so busy serving content so it can be used to do more computations or simply reduce the bill.</li>
</ul>
<p>The presented method works well for <em>Difio</em> because of two things:</p>
<ul>
<li>The content which <em>Difio</em> serves usually doesn’t change at all once made public. In rare occasions, for example an error
has been published, we have to regenerate new content and publish it under the same URL.</li>
<li>Before content is made public it is inspected for errors and this also preseeds the cache.</li>
</ul>
</div>
<footer>
<p class="meta">
<span class="byline author vcard">Posted by <span class="fn">Alexander Todorov</span></span>
<time datetime="2012-05-19T16:58:00+03:00" pubdate data-updated="true">May 19<span>th</span>, 2012</time>
<span class="categories">
<a class='category' href='/blog/categories/amazon/'>Amazon</a>, <a class='category' href='/blog/categories/cloudfront/'>CloudFront</a>, <a class='category' href='/blog/categories/cloud/'>cloud</a>
</span>
</p>
<div class="sharing">
<!-- AddThis Button BEGIN -->
<div class="addthis_toolbox addthis_default_style addthis_32x32_style">
<a class="addthis_button_preferred_1"></a>
<a class="addthis_button_preferred_2"></a>
<a class="addthis_button_preferred_3"></a>
<a class="addthis_button_preferred_4"></a>
<a class="addthis_button_preferred_5"></a>
<a class="addthis_button_preferred_6"></a>
<a class="addthis_button_preferred_7"></a>
<a class="addthis_button_preferred_8"></a>
<a class="addthis_button_preferred_9"></a>
<a class="addthis_button_compact"></a>
<a class="addthis_counter addthis_bubble_style"></a>
</div>
<script type="text/javascript" src="http://s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5103cc5a2bc6ba17"></script>
<!-- AddThis Button END -->
</div>
<p class="meta">
<a class="basic-alignment left" href="/blog/2012/04/17/using-openshift-as-amazon-cloudfront-origin-server/" title="Previous Post: Using OpenShift as Amazon CloudFront Origin Server">« Using OpenShift as Amazon CloudFront Origin Server</a>
<a class="basic-alignment right" href="/blog/2012/07/12/combining-pdf-files-on-the-command-line/" title="Next Post: Combining PDF Files On The Command Line">Combining PDF Files On The Command Line »</a>
</p>
</footer>
</article>
<section>
<h1>Comments</h1>
<div id="disqus_thread" aria-live="polite"><noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>
</section>
</div>
<aside class="sidebar">
<section>
<p>
I am a QA contractor at Red Hat responsible for over
<a href="/blog/2014/02/19/7-years-1400-bugs-red-hat-qa/">1500 bugs</a>,
a general purpose open source developer, Red Hat Certified professional,
cloud hacker and an <a href="/projects/">entrepreneur</a>.
</p>
<p>
I'm living in the <a href="http://planet.sofiavalley.com">Sofia Valley</a>
which is emerging as a busy place for start-up founders and tech enthusiasts
in Eastern Europe! You can find more about me <a href="/about/">here</a>.
</p>
</section>
<section>
<a href="http://twitter.com/atodorov_" class="twitter-follow-button" data-show-count="true">Follow @atodorov_</a>
</section>
<form action="http://google.com/search" method="get">
<fieldset role="search">
<input type="hidden" name="sitesearch" value="atodorov.org" />
<input class="search" type="text" name="q" results="0" placeholder="Search"/>
</fieldset>
</form>
<section>
<h1>
<a href="/blog/categories/books/">Book Reviews</a>
</h1>
</section>
<section>
<h1>Recent Posts</h1>
<ul id="recent_posts">
<li class="post">
<a href="/blog/2015/07/27/call-for-ideas-graphical-test-coverage-reports/">Call for Ideas: Graphical Test Coverage Reports</a>
</li>
<li class="post">
<a href="/blog/2015/07/01/open-data-event-coming-to-sofia/">Open Data Event Coming to Sofia</a>
</li>
<li class="post">
<a href="/blog/2015/05/22/devit-conf-2015-impressions/">DEVit Conf 2015 Impressions</a>
</li>
<li class="post">
<a href="/blog/2015/05/20/free-software-testing-books/">Free Software Testing Books</a>
</li>
<li class="post">
<a href="/blog/2015/05/13/why-does-sysctl-not-write-under-slash-sys/">Why does sysctl not write under /sys</a>
</li>
<li class="post">
<a href="/blog/2015/05/05/using-usb-to-vga-adapter-on-macbook-air-with-linux/">Using USB to VGA Adapter on MacBook Air with Linux</a>
</li>
<li class="post">
<a href="/blog/2015/05/04/thunderbolt-to-ethernet-adapter-on-linux/">Thunderbolt to Ethernet Adapter on Linux</a>
</li>
<li class="post">
<a href="/blog/2015/05/01/compiling-twinkle-sip-phone-on-rhel-7/">Compiling Twinkle SIP Phone on RHEL 7</a>
</li>
<li class="post">
<a href="/blog/2015/04/30/fixing-tilde-and-function-keys-mapping-for-macbook-air-on-linux/">Fixing Tilde and Function Keys Mapping for MacBook Air on Linux</a>
</li>
<li class="post">
<a href="/blog/2015/04/29/rhel-7-repository-for-macbook-air/">RHEL 7 Repository for MacBook Air</a>
</li>
</ul>
</section>
<section>
<h1>Disclaimer</h1>
<p>
Some of the links contained within this site have my referral id (e.g., Amazon), which provides me with a small commission for each sale. Thank you for your support.
</p>
</section>
</aside>
</div>
</div>
<footer role="contentinfo"><p>
<a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/deed.en_US">CC-BY-SA</a>
&
<a rel="license" href="http://opensource.org/licenses/MIT">MIT</a>
2011-2015 ♦ Alexander Todorov
♦
<a href="/about/">About Me</a>
♦
Popular categories:
<a href="/blog/categories/rhel/">Red Hat</a>,
<a href="/blog/categories/cloud/">Cloud</a>,
<a href="/blog/categories/fedora/">Fedora</a>,
<a href="/blog/categories/qa/">QA</a>,
<a href="/blog/categories/start-up/">Start-up</a>
<a href="http://planet.sofiavalley.com" style="float:right">SofiaValley Blog</a>
</p>
<script type="text/javascript">
var uri = window.location.toString();
if (uri.indexOf("?") > 0) {
var clean_uri = uri.substring(0, uri.indexOf("?"));
window.history.replaceState({}, document.title, clean_uri);
}
</script>
</footer>
<script type="text/javascript">
var disqus_shortname = 'atodorov';
// var disqus_developer = 1;
var disqus_identifier = 'http://atodorov.org/blog/2012/05/19/cross-domain-ajax-served-from-cdn/';
var disqus_url = 'http://atodorov.org/blog/2012/05/19/cross-domain-ajax-served-from-cdn/';
var disqus_script = 'embed.js';
(function () {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/' + disqus_script;
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
}());
</script>
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#appId=212934732101925&xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<script type="text/javascript">
(function() {
var script = document.createElement('script'); script.type = 'text/javascript'; script.async = true;
script.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(script, s);
})();
</script>
<script type="text/javascript">
(function(){
var twitterWidgets = document.createElement('script');
twitterWidgets.type = 'text/javascript';
twitterWidgets.async = true;
twitterWidgets.src = 'http://platform.twitter.com/widgets.js';
document.getElementsByTagName('head')[0].appendChild(twitterWidgets);
})();
</script>
</body>
</html>