Everyone can now run JavaScript on Cloudflare with Workers

综合技术 2018-03-13

Exactly one year ago today, Cloudflare gave me a mission: Make it so people can run code on Cloudflare's edge. At the time, we didn't yet know what that would mean. Would it be container-based? A new Turing-incomplete domain-specific language? Lua? "Functions"? There were lots of ideas.

Eventually, we settled on what now seems the obvious choice: JavaScript, using the standard Service Workers API, running in a new environment built on V8. Five months ago, we gave you a preview of what we were building, and started the beta.

Today, with thousands of scripts deployed and many billions of requests served, Cloudflare Workers is now ready for everyone.

"Moving away from VCL and adopting Cloudflare Workers will allow us to do some creative routing that will let us deliver JavaScript to npm's millions of users even faster than we do now. We will be building our next generation of services on Cloudflare's platform and we get to do it in JavaScript!"

— CJ Silverio, CTO, npm, Inc.

What is the Cloud, really?

Historically, web application code has been split between servers and browsers. Between them lies a vast but fundamentally dumb
network which merely ferries data from point to point.

We don't believe this lives up to the promise of "The Cloud."

We believe the true dream of cloud computing is that your code lives in the network itself. Your code doesn't run in "us-west-4" or "South Central Asia (Mumbai)", it runs everywhere
.

More concretely, it should run where it is most needed. When responding to a user in New Zealand, your code should run in New Zealand. When crunching data in your database, your code should run on the machines that store the data. When interacting with a third-party API, your code should run wherever that API is hosted. When human explorers reach Mars, they aren't going to be happy waiting a half an hour for your app to respond -- your code needs to be running on Mars.

Cloudflare Workers are our first step towards this vision. When you deploy a Worker, it is deployed to Cloudflare's entire edge network of over a hundred locations worldwide in under 30 seconds. Each request for your domain will be handled by your Worker at a Cloudflare location close to the end user, with no need for you to think about individual locations. The more locations we bring online, the more your code just "runs everywhere."

Well, OK… it won't run on Mars. Yet. You out there, Elon?

What's a Worker?

Cloudflare Workers derive their name from Web Workers, and more specifically Service Workers, the W3C standard API for scripts that run in the background in a web browser and intercept HTTP requests. Cloudflare Workers are written against the same standard API, but run on Cloudflare's servers, not in a browser.

Here are the tools you get to work with:

  • Execute any JavaScript code, using the latest standard language features.
  • Intercept and modify HTTP request and response URLs, status, headers, and body content.
  • Respond to requests directly from your Worker, or forward them elsewhere.
  • Send HTTP requests to third-party servers.
  • Send multiple requests, in serial or parallel, and use the responses to compose a final response to the original request.
  • Send asynchronous requests after the response has already been returned to the client (for example, for logging or analytics).
  • Control other Cloudflare features, such as caching behavior.

The possible uses for Workers are infinite, and we're excited to see what our customers come up with. Here are some ideas we've seen in the beta:

  • Route different types of requests to different origin servers.
  • Expand HTML templates on the edge, to reduce bandwidth costs at your origin.
  • Apply access control to cached content.
  • Redirect a fraction of users to a staging server.
  • Perform A/B testing between two entirely different back-ends.
  • Build "serverless" applications that rely entirely on web APIs.
  • Create custom security filters to block unwanted traffic unique to your app.
  • Rewrite requests to improve cache hit rate.
  • Implement custom load balancing and failover logic.
  • Apply quick fixes to your application without having to update your production servers.
  • Collect analytics without running code in the user's browser.
  • Much more.

Here's an example.

// A Worker which:
// 1. Redirects visitors to the home page ("/") to a
//    country-specific page (e.g. "/US/").
// 2. Blocks hotlinks.
// 3. Serves images directly from Google Cloud Storage.
addEventListener('fetch', event => {
  event.respondWith(handle(event.request))
})

async function handle(request) {
  let url = new URL(request.url)
  if (url.pathname == "/") {
    // This is a request for the home page ("/").
    // Redirect to country-specific path.
    // E.g. users in the US will be sent to "/US/".
    let country = request.headers.get("CF-IpCountry")
    url.pathname = "/" + country + "/"
    return Response.redirect(url, 302)

  } else if (url.pathname.startsWith("/images/")) {
    // This is a request for an image (under "/images").
    // First, block third-party referrers to discourage
    // hotlinking.
    let referer = request.headers.get("Referer")
    if (referer &&
        new URL(referer).hostname != url.hostname) {
      return new Response(
          "Hotlinking not allowed.",
          { status: 403 })
    }

    // Hotlink check passed. Serve the image directly
    // from Google Cloud Storage, to save serving
    // costs. The image will be cached at Cloudflare's
    // edge according to its Cache-Control header.
    url.hostname = "example-bucket.storage.googleapis.com"
    return fetch(url, request)
  } else {
    // Regular request. Forward to origin server.
    return fetch(request)
  }
}

It's Really Fast

Sometimes people ask us if JavaScript is "slow". Nothing could be further from the truth.

Workers uses the V8 JavaScript engine built by Google for Chrome. V8 is not only one of the fastest implementations of JavaScript, but one of the fastest implementations of any dynamically-typed language, period. Due to the immense amount of work that has gone into optimizing V8, it outperforms just about any popular server programming language with the possible exceptions of C/C++, Rust, and Go. (Incidentally, we will support those soon, via WebAssembly.)

The bottom line: A typical Worker script executes in less than one millisecond.
Most users are unable to measure any latency difference when they enable Workers -- except, of course, when their worker actually improves
latency by responding directly from the edge.

On another speed-related note, Workers deploy fast, too. Workers deploy globally in under 30 seconds
from the time you save and enable the script.

Pricing

Workers are a paid add-on to Cloudflare. We wanted to keep the pricing as simple as possible, so here's the deal:

Get Started

  • Log into your Cloudflare account and visit the "Workers" section to configure Workers.
  • Experiment with Workers in the Playground, no account required.
  • Read the documentation to learn how Workers are written.
  • Check out the original announcement blog post for more technical details.
  • Discuss Workers in the Cloudflare Community.

"Cloudflare Workers saves us a great deal of time. Managing bot traffic without Workers would consume valuable development and server resources that are better spent elsewhere."

— John Thompson, Senior System Administrator, MaxMind

您可能感兴趣的

The javascript function retrieves the [... I have several input fields of type number, which users have to fill in. I need a script that will display a new page only once users have at least on...
DOMException: The play() request was interrupted Did you just stumble upon this unexpected media error in the Chrome DevTools JavaScript Console? Uncaught (in promise) DOMException: The play() r...
javascript中!=、!==、==、===操作符总结 JavaScript 有两种比较方式:严格比较运算符和转换类型比较运算符。 在相等运算符中对应 === 、 !== 和 == 、 != 。 先举个栗子 var str = '1' var num0 = 0 var num1 = 1 var blT = true var blF ...
基础知识总结-前端面试(一) 打算写一个前端面试系列的知识,博客很久没有进行更新,更新的都是一些的基础知识。 最近在投简历进行面试,说是面试,其实就是一个自己的使用自己大白话的知识概括吧。欢迎感兴趣的小伙伴进行学习或者提出建议和改正! 大概计划章节如下 1-1 关于面试题 2-1 变量类型和计算-变量类型 2...
Memories of writing a parser for man pages in Java... Memories of writing a parser for man pages March 24th, 2018 xnix javascript I generally enjoy being bored, but sometimes enough is enough...