It’s just data

Service Workers - First Impressions

Created by potrace 1.13, written by Peter Selinger 2001-2015

Successes, progress, and stumbling blocks encountered while exploring Service Workers.

Preface

The Apache Whimsy Board Agenda tool is designed to make ASF Board meetings run more smoothly. It does this by downloading all of the provided reports and collating them with comments, prior comments, action items, minutes, links to prior reports, links to committee information, and the like. It provides a UI to allow Directors and guests to enter comments. It provides a UI to allow the Secretary to take minutes.

The tool itself is built using React.JS. It starts by downloading all of the reports. Navigation between reports can be done via mouse clicks or cursor keys and doesn't involve any server interaction. As new data is received, the window is updated.

Finally, I'm new to Service Workers so I may be doing things in a profoundly dumb way. Any pointers would be appreciated. I am capable of RTFM and following examples.

First step - caching JSON

Some of the data (e.g., the list of ASF JIRA projects) is fetched on demand. Generally the page is first rendered using an empty list, and then updated once the actual list is received.

This process could be improved by caching the results received and using that data until fresh data arrives. As the Cache API is built on promises, and therefore asynchronous, this generally means rendering three times: once with a empty list, then with the cache, and finally with live data.

// retrieve an cached object.  Note: block may be dispatched twice,
// once with slightly stale data and once with current data
//
// Note: caches only work currently on Firefox and Chrome.  All
// other browsers fall back to XMLHttpRequest (AJAX).
JSONStorage.fetch = function(name, block) {
  if (typeof fetch !== 'undefined' && typeof caches !== 'undefined' && 
     (location.protocol == "https:" || location.hostname == "localhost")) {

    caches.open("board/agenda").then(function(cache) {
      var fetched = null;
      clock_counter++;

      // construct arguments to fetch
      var args = {
        method: "get",
        credentials: "include",
        headers: {Accept: "application/json"}
      };

      // dispatch request
      fetch("../json/" + name, args).then(function(response) {
        cache.put(name, response.clone());

        response.json().then(function(json) {
          if (!fetched || JSON.stringify(fetched) != JSON.stringify(json)) {
            if (!fetched) clock_counter--;
            fetched = json;
            if (json) block(json);
            Main.refresh()
          }
        })
      });

      // check cache
      cache.match(name).then(function(response) {
        if (response && !fetched) {
          response.json().then(function(json) {
            clock_counter--;
            fetched = json;
            if (json) block(json);
            Main.refresh()
          })
        }
      })
    })
  } else if (typeof XMLHttpRequest !== 'undefined') {
    // retrieve from the network only
    retrieve(name, "json", function(item) {return item.block})
  }
}

All in all remarkably painless and completely transparent to the calling application. Doesn't involve the activation of Service Workers, but it doesn't have to.

Second step - caching HTML

What's true for JSON should also be true for HTML. Prior to the caching logic introduced above, and continuing to be true for browsers that don't support the service workers caching interface, data that should appear on the page would be missing briefly and show up a second or two later. In the case of HTML, that data would be the entire page. This would typically be seen both on the initial page load as well as any time a link is opened in a new tab.

The HTML case is both simpler and more difficult. Fetching the HTML from cache and then replacing it wholesale from the network, while possible, would be jarring. Fortunately, there already is logic in place to update the content of the pages based on updates received by XHR. So initially displaying where the user last left off, as well as updating the cache, is sufficient.

Unfortunately, it isn't quite so simple. I've included the current code below complete with log statements and dead ends.

// simple hashcode to prevent authorization from leaking
var hashcode = function(s) {
  return s && s.split("").reduce(
    function(a, b) {
      return ((a << 5) - a) + b.charCodeAt(0)
    },

    0
  )
};

var status = {auth: null};

this.addEventListener("fetch", function(event) {
  var scope = this.registration.scope;
  var url = event.request.url;
  var path = url.slice(scope.length);
  var auth = hashcode(event.request.headers.get("Authorization"));

  if (/^\d\d\d\d-\d\d-\d\d//.test(path) && event.request.method == "GET") {
    console.log("Handling fetch event for", event.request.url);

    event.respondWith(caches.open("board/agenda").then(function(cache) {
      return cache.match(path).then(function(cached) {
        if (cached) console.log("matched");
        console.log("auth", auth, status.auth);

        if (!auth || auth != status.auth) {
          // the following doesn't work
          cached = new Response("Unauthorized", {
            status: 401,
            statusText: "Unauthorized",
            headers: {"WWW-Authenticate": "Basic realm="ASF Members and Officers""}
          });

          // fallback: ignore cache unless authorized
          cached = null
        };

        if (cached) console.log("serving from cache");

        var network = fetch(event.request).then(function(response) {
          if (!cached) console.log("fetching from network");
          if (cached) console.log("updating cache");
          console.log(response);
          if (response.ok) cache.put(path, response.clone());
          status.auth = auth;
          return response
        });

        return cached || network
      })
    }))
  } else if (auth) {
    // capture authorization from other pages, if provided
    status.auth = auth
  }
})

The primary problem is that the board agenda tool requires authentication to use as the data presented may contain Apache Software Foundation confidential information.

Without accounting for this, what often would be placed into the cache would be the HTTP 401 challenge response. That's not desirable.

Attempting to force the return of a challenge when an Authorization header is not present results in the display of the challenge response. Again, not what we want.

Falling back to only providing the cached data when the Authorization header is present (and matches the one used for the cache) results in the cache being used sometimes with Firefox. And, unfortunately, never with Chrome.

A secondary problem, of lesser importance, is that the cache never gets updated if the service worker responds with a cache copy. Of if it does, the console.log messages aren't getting executed or aren't producing output.

Third step - monitoring

To help with debugging, it occurred to me that it would make sense to produce a page that shows Service Worker and Cache status.

Plans

One thing I haven't explored yet is replacing the fetch call with one with different values for the request mode and credentials mode. I figured I would ask for guidance before proceeding down that path.

Once caching HTML is mastered, caching related artifacts like stylesheets and javascripts would be in order. An online fallfack approach would likely be the best match.

After that, the next order of business would be queuing of updates while offline. While in general, that would be a hard problem, in this case as user operations are limited by role and generaally to editing their own changes, it should be manageable.


The Student Room has the best writer for you in Australia to provide assignment help.Contact us today for instant writing services & get delivery before the submission date.

Posted by Myassignmenthelp at

Thanks For Sharing your information.

Posted by High Profile Escorts In Bangalore at

This is great information for students. This article is very helpful i really like this blog thanks. I also have some information relevant for online dissertation help.

Posted by Help With Programming Homework at

Well thanks for posting such an outstanding idea. I like this blog & I like the topic and thinking of making it right.

Posted by Electronics Engineering Homework Help at

I’ve been searching about this tools, gladly now I can make something out of it. Thanks for the share.

Posted by Mobile application Development Company at

The Student Room has the best author for you in Australia to give task help.Contact us today to moment composing administrations and get conveyance before the accommodation date.

Posted by Homework Writing Service at

service worker provide the service of the customer if your service is not good and your customer do not satisfied from your service so your customer will not again take the  service so your service is the first impression for your service in front of the customer.

Posted by service registration corrupt at

Great work

Posted by gapps download at

Ruchita Sinha provides top quality and best escorts in Pune. Pune Escorts services like independent escorts, high profile escorts, vip escorts in Pune, models and housewife. These hot and provocative escorts are available 24/7.

Posted by Ruchita Sinha at

Things Are Very Open And Intensely Clear Explanation Of Issues. Was Truly Information. Your Website Is Very Beneficial. MBA Assignment Help

Posted by MBA Assignment Help at

I’m Really Impressed With Your Article, Such Great & Usefull Knowledge You Mentioned Here Case Studies Analysis

Posted by Case Studies Analysis at

Calendar 2018 march for students

Posted by vav viv at

Cash Advance terms are generally straightforward.Cash Advance ChicagoAuto Title Loans ChicagoPayday Loans Chula-vistaCash Advance Corona

Posted by cash advance corona at

Check your cell phone and browse your email account. You will unquestionably observe the distinction. Tarjetas De Cumpleaños Feliz

Posted by aftab ali at

Check your cell phone and browse your email account. You will unquestionably observe the distinction. Tarjetas De Cumpleaños Feliz

Posted by aftab ali at

Be wary of people that solely translate a manuscript.

Posted by shoes in stock at

Take a look here for all the latest technological news from all over the globe

Posted by tekinancereporter at

hey guys if you are a roblox player then must try my link to get lots of robux for free

Posted by get free robux at

All the details are in this post is awesome

Posted by leona at

Facetime is the best video calling application for smartphones. In Facetime Apk, you can make both video and audio calls via Wifi or mobile network. Facetime Apk has its best alternative free video calls and chat app which allows you to do free video chat.

Posted by facetime app download at

Interesting topic shown here, i am now working on it regularly here and would say keep the future posts like this continuously.

Posted by 200-310 practice tests at

Great article

Posted by blanche at

A debt of gratitude is in order for sharing such a decent article and for educational things. Your articles are extremely stunning and I got a considerable measure of data and direction understanding them. It helped me a considerable measure and I will without a doubt take after your article strategies. Sitting tight for more valuable updates and new things

Posted by essay writing services UK at

Really great

Posted by london at

I think it is very interesting

Posted by monica at

Indeed, the squandering of time and showing untruthfulness in the arrangements can really hurt the esteem. olymptrade

Posted by aftab ali at

we have the best betting platform for you. Just come to our website, signup and get your bonus amount
online casino Singapore
Singapore online casino
mobile casino singapore
singapore 4D results
Yuriantibet
Singapore 4d results
4D results
Malaysia 4D results
Singapore betting tips
online Sportsbook Singapore
online Singapore online casino 2018
Singapore Casino
Singapore Casino Guide
yuriantibet betting agent
casino guide
yuriantibet betting agent
Singapore Casino

Posted by mian rohail at

google

Posted by Google at

Really i appreciate the effort you made to share the knowledge. This is really a great stuff for sharing. Keep it up . Thanks for sharing.

Posted by J2me Programming Assignment Help at

Some people do work for the Apache Software Foundation but the mostly people are volunteers like myself. A lot of the software is written by those that do not “work for” the foundation. Generally, if you commit time to a project typically knows you by awarding you committer status. Our native writers are fortified to turn your strategy write my essay please into an outstanding piece of work that will deliver an impression on its reader.

Posted by write my essay please at

Welcome to the All assignment help Reviews, Here you can get the best assignment help review sites. We strongly urge you to check our entire website once and we will assure you will find this review website very useful. Our hard work will be rewarded if students like you will appreciate our effort and spread the message about this site with your class-fellows and friends

Posted by All assignment help Reviews at

Very nice post. Interesting news.

Posted by Arkady2 at

Thanks you for sharing

Posted by website designing company in India at

norton online chat
norton symantec endpoint protection
norton 360 will not uninstall
removal norton tool
norton internet security reinstall
norton 360 install
symantec phone support
redownload norton 360
norton toolbar
norton 360 removal tool

Posted by Norton Support at

How do you spend Christmas?

Posted by Derek4 at

The Singapore 4D Result can help you to get to the perfect betting destination. The latest results can help you learn whether you’ve come to be any richer. Therefore, if you’re looking for The 4D Result like The <a href=" [link]-singapore">Singapore toto Result</a>, The Singapore 4D Result or The Magnum 4D Result
. If you’re looking for The Magnum 4D Result , magnum website is where to find the results. All you have to do is to learn to minimize your possible loss instead of going crazy by pursuing the different strategies on how best to maximize your own profits by the money that you’ve been in a position to spend on the The sports live betting. Then you watch for the outcomes of them to decide if you’ve won or not. Therefore, if you’re looking for  Magnum 4D past result or The <a href=" [link]-singapore">toto 4D Results</a> history to understand which numbers were won lottery in past and the number of times then you need to have a look at a website that’s active and have fresh database of The 4D Past Result and the update their site continuously.
In any sort of gambling, the longer you remain in the game the greater your odds of losing. It’s possible to elect for The toto 4D  small in addition to big game. Now the Toto 4D lottery game is extremely common in nearly all sections of the country. Exploring the The <a href=" [link]-singapore"> 4D live Results Singapore pools</a> information is able to help you identify what you’ve won and what you might have lost. It’s quite tough to find reliable info about the biggest prize that’s been handed out in the history of The <a href=" [link]-singapore">Singapore Pools 4D Result</a>

Posted by yuriantibet at

Thank you for the amazing post, I will be awaiting for your next post.

Posted by product key at

The Singapore 4D Result can help you to get to the perfect betting destination. The latest results can help you learn whether you’ve come to be any richer. Therefore, if you’re looking for The 4D Result like The Singapore toto Result, The Singapore 4D Result or The Magnum 4D Result
. If you’re looking for The Magnum 4D Result , magnum website is where to find the results. All you have to do is to learn to minimize your possible loss instead of going crazy by pursuing the different strategies on how best to maximize your own profits by the money that you’ve been in a position to spend on the The sports live betting. Then you watch for the outcomes of them to decide if you’ve won or not. Therefore, if you’re looking for  Magnum 4D past result or The toto 4D Results history to understand which numbers were won lottery in past and the number of times then you need to have a look at a website that’s active and have fresh database of The 4D Past Result and the update their site continuously.
In any sort of gambling, the longer you remain in the game the greater your odds of losing. It’s possible to elect for The toto 4D  small in addition to big game. Now the Toto 4D lottery game is extremely common in nearly all sections of the country. Exploring the The 4D live Results Singapore pools information is able to help you identify what you’ve won and what you might have lost. It’s quite tough to find reliable info about the biggest prize that’s been handed out in the history of The Singapore Pools 4D Result

Posted by mianrohail at

Excellent feats of strength, incomparable specimens of the human physique, and powerful poses are just a few aspects of the spectacle that is bodybuilding. The greatest body builders in history have possessed all of these traits and more. Bodybuilding is known as a progressive resistance exercise that is designed to control and develop a person’s musculature. Those who practice this are known as body builders. Though the greatest body builders have come from different places around the world; five of the most prominent body builders in history hail from Britain.
https://buycrazybulksteroids.com/

Posted by steroids uk at

Great Information sharing .. I am very happy to read this article .. thanks for giving us go through info.Fantastic nice. I appreciate this post.

Posted by college essay at

Thanks for sharing this quality information with us. I really enjoyed reading. Will surely going to share this URL with my friends.

Posted by KFZ at

Thank you for posting such a great article! I found your website perfect for my needs. It contains wonderful and helpful posts. Keep up the good work!. Thank you for this wonderful Article! five nights at freddy’s

Posted by kakbrus at

Thanks for your post. I’ve been thinking about writing a very comparable post over the last couple of weeks, I’ll probably keep it short and sweet and link  to this instead if thats cool. Thanks.

Posted by click here now at

It is imperative that we read blog post very carefully. I am already done it and find that this post is really amazing.

Posted by West Coast 420 Express at

A showstopping pork dish that’s a great Sunday lunch for a crowd, the trim from the rack makes a flavourful stuffing, infused with wild garlic or use a combination of spinach and garlic.

Posted by fnaf 3 at

Lifestyle Magazine India; Lifestyle is a elite magazine circulated to the elite at page3 parties. Lifestyle Magazine also circulated to the elite at clubs, lounge bars etc.

Posted by Lifestyle Magazine india at

I like its sharing. Thanks you. My spingurus is the best audio engineering course provide.

Posted by Sound Design Courses In Delhi at

Much obliged to you for posting such an incredible article! I discovered your site ideal for my necessities. It contains superb and supportive posts. Everything thought of you as, need to go up against your family and friends; and if you fail or get low scores, by then you will feel mortified. Along these lines, don’t waste your chance in hypothesis too much.

Posted by Pay for Essay Cheap at

I have read your blog it is very helpful for me. I want to say thanks to you. I have bookmark your site for future updates.

Posted by rental mobil jogja at

I don’t have a blog, but I just want to say that that’s really nice of you to do that. you know use up some of your points to help out other.

Posted by Baywatch Red Jacket at

I read your blog frequently and I just thought I’d say keep up the amazing work!

Posted by a course in miracles at

Hi there! Nice stuff, do keep me posted when you post again something like this!

Posted by a course in miracles at

Keep up the good  work , I read few posts  on this  web site  and I  conceive that your blog  is very  interesting and has  sets  of  fantastic  information.

Posted by acim at

The fastest way to increase customer loyalty is by improving the quality of customer service you deliver. In fact, I dislike thinking of it as “customer service”. I prefer calling it “Remarkable Service”. When you take care of your customers so well they tell others, then you’ve delivered remarkable service.

Posted by kroger feedback at

I like this post,And I guess that they having fun to read this post,they shall take a good site to make a information,thanks for sharing it to me.

Posted by small business administration at

I think a blog is an amazing way to explain our thoughts to others and also everybody can discuss his issue any place like a blog. Well I appreciated to this post.

Posted by QuickBooks Pro 2016 Upgrade at

This is a fantastic list of ideas!

Posted by hole io at

I believe you have remarked some very interesting points , thanks for the post.
\\

Posted by retha JOBS at

I am constantly surprised by the amount of information accessible on this subject.  What you presented was well researched and well written to get your stand on this over to all your readers. Thanks a lot my dear. numero voyance gratuite

Posted by sohail khatri at

This generally means rendering three times: once with a empty list, then with the cache, and finally with live data.

Posted by geometry dash at

This is my first time i visit here and I found so many interesting stuff in your blog especially it’s discussion, thank you.

Posted by search engine marketing at

Great article. It helped me a lot. Thank you. Hope you have a more positive post.

Posted by Duck life at

I am glad to found this website and reading this brilliant post, this is very $1 web Hosting useful information you share, thanks and keep it up!

Posted by Webhostingonedollar at

Very good and interesting, I appreciate your work.Tutuapp APK

Posted by Tutuapp APK at

This is really a nice and informative, containing all information and also has a great impact on the new technology. Thanks for sharing it,

Posted by Healing Empire at

Add your comment