• Stars
    star
    5,660
  • Rank 6,829 (Top 0.2 %)
  • Language
    C++
  • License
    Apache License 2.0
  • Created over 1 year ago
  • Updated 5 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

The JavaScript / Wasm runtime that powers Cloudflare Workers

๐Ÿ‘ท workerd, Cloudflare's JavaScript/Wasm Runtime

Banner

workerd (pronounced: "worker-dee") is a JavaScript / Wasm server runtime based on the same code that powers Cloudflare Workers.

You might use it:

  • As an application server, to self-host applications designed for Cloudflare Workers.
  • As a development tool, to develop and test such code locally.
  • As a programmable HTTP proxy (forward or reverse), to efficiently intercept, modify, and route network requests.

Introduction

Design Principles

  • Server-first: Designed for servers, not CLIs nor GUIs.

  • Standard-based: Built-in APIs are based on web platform standards, such as fetch().

  • Nanoservices: Split your application into components that are decoupled and independently-deployable like microservices, but with performance of a local function call. When one nanoservice calls another, the callee runs in the same thread and process.

  • Homogeneous deployment: Instead of deploying different microservices to different machines in your cluster, deploy all your nanoservices to every machine in the cluster, making load balancing much easier.

  • Capability bindings: workerd configuration uses capabilities instead of global namespaces to connect nanoservices to each other and external resources. The result is code that is more composable -- and immune to SSRF attacks.

  • Always backwards compatible: Updating workerd to a newer version will never break your JavaScript code. workerd's version number is simply a date, corresponding to the maximum "compatibility date" supported by that version. You can always configure your worker to a past date, and workerd will emulate the API as it existed on that date.

Read the blog post to learn more about these principles..

WARNING: This is a beta. Work in progress.

Although most of workerd's code has been used in Cloudflare Workers for years, the workerd configuration format and top-level server code is brand new. We don't yet have much experience running this in production. As such, there will be rough edges, maybe even a few ridiculous bugs. Deploy to production at your own risk (but please tell us what goes wrong!).

The config format may change in backwards-incompatible ways before workerd leaves beta, but should remain stable after that.

A few caveats:

  • General error logging is awkward. Traditionally we have separated error logs into "application errors" (e.g. a Worker threw an exception from JavaScript) and "internal errors" (bugs in the implementation which the Workers team should address). We then sent these errors to completely different places. In the workerd world, the server admin wants to see both of these, so logging has become entirely different and, at the moment, is a bit ugly. For now, it may help to run workerd with the --verbose flag, which causes application errors to be written to standard error in the same way that internal errors are (but may also produce more noise). We'll be working on making this better out-of-the-box.
  • Binary packages are only available via npm, not as distro packages. This works well for testing with Miniflare, but is awkward for a production server that doesn't actually use Node at all.
  • Multi-threading is not implemented. workerd runs in a single-threaded event loop. For now, to utilize multiple cores, we suggest running multiple instances of workerd and balancing load across them. We will likely add some built-in functionality for this in the near future.
  • Performance tuning has not been done yet, and there is low-hanging fruit here. workerd performs decently as-is, but not spectacularly. Experiments suggest we can roughly double performance on a "hello world" load test with some tuning of compiler optimization flags and memory allocators.
  • Durable Objects currently always run on the same machine that requested them, using local disk storage. This is sufficient for testing and small services that fit on a single machine. In scalable production, though, you would presumably want Durable Objects to be distributed across many machines, always choosing the same machine for the same object.
  • Parameterized workers are not implemented yet. This is a new feature specified in the config schema, which doesn't have any precedent on Cloudflare.
  • Tests for most APIs are conspicuously missing. This is because the testing harness we have used for the past five years is deeply tied to the internal version of the codebase. Ideally, we need to translate those tests into the new workerd test format and move them to this repo; this is an ongoing effort. For the time being, we will be counting on the internal tests to catch bugs. We understand this is not ideal for external contributors trying to test their changes.
  • Documentation is growing quickly but is definitely still a work in progress.

WARNING: workerd is not a hardened sandbox

workerd tries to isolate each Worker so that it can only access the resources it is configured to access. However, workerd on its own does not contain suitable defense-in-depth against the possibility of implementation bugs. When using workerd to run possibly-malicious code, you must run it inside an appropriate secure sandbox, such as a virtual machine. The Cloudflare Workers hosting service in particular uses many additional layers of defense-in-depth.

With that said, if you discover a bug that allows malicious code to break out of workerd, please submit it to Cloudflare's bug bounty program for a reward.

Getting Started

Supported Platforms

In theory, workerd should work on any POSIX system that is supported by V8 and Windows.

In practice, workerd is tested on:

  • Linux and macOS (x86-64 and arm64 architectures)
  • Windows (x86-64 architecture)

On other platforms, you may have to do tinkering to make things work.

Building workerd

To build workerd, you need:

  • Bazel
    • If you use Bazelisk (recommended), it will automatically download and use the right version of Bazel for building workerd.
  • On Linux:
    • Clang 11+ (e.g. package clang on Debian Bullseye)
    • libc++ 11+ (e.g. packages libc++-dev and libc++abi-dev on Debian Bullseye)
    • LLD 11+ (e.g. package lld on Debian Bullseye)
    • python3 and python3-distutils
  • On macOS:
    • Xcode 13+ installation
    • macOS 11 or higher
  • On Windows:
    • Install App Installer from the Microsoft Store for the winget package manager and then run install-deps.bat from an administrator prompt to install bazel, LLVM, and other dependencies required to build workerd on Windows.
    • Add startup --output_user_root=C:/tmp to the .bazelrc file in your user directory.
    • When developing at the command-line, run bazel-env.bat in your shell first to select tools and Windows SDK versions before running bazel.

You may then build workerd at the command-line with:

bazel build //src/workerd/server:workerd

You can also build from within Visual Studio Code using the instructions in docs/vscode.md.

The compiled binary will be located at bazel-bin/src/workerd/server/workerd.

If you run a Bazel build before you've installed some dependencies (like clang or libc++), and then you install the dependencies, you must resync locally cached toolchains, or clean Bazel's cache, otherwise you might get strange errors:

bazel sync --configure

If that fails, you can try:

bazel clean --expunge

The cache will now be cleaned and you can try building again.

If you have a fairly recent clang packages installed you can build a more performant release version of workerd:

bazel build --config=thin-lto //src/workerd/server:workerd

Configuring workerd

workerd is configured using a config file written in Cap'n Proto text format.

A simple "Hello World!" config file might look like:

using Workerd = import "/workerd/workerd.capnp";

const config :Workerd.Config = (
  services = [
    (name = "main", worker = .mainWorker),
  ],

  sockets = [
    # Serve HTTP on port 8080.
    ( name = "http",
      address = "*:8080",
      http = (),
      service = "main"
    ),
  ]
);

const mainWorker :Workerd.Worker = (
  serviceWorkerScript = embed "hello.js",
  compatibilityDate = "2023-02-28",
  # Learn more about compatibility dates at:
  # https://developers.cloudflare.com/workers/platform/compatibility-dates/
);

Where hello.js contains:

addEventListener("fetch", event => {
  event.respondWith(new Response("Hello World"));
});

Complete reference documentation is provided by the comments in workerd.capnp.

There is also a library of sample config files.

(TODO: Provide a more extended tutorial.)

Running workerd

To serve your config, do:

workerd serve my-config.capnp

For more details about command-line usage, use workerd --help.

Prebuilt binaries are distributed via npm. Run npx workerd ... to use these. If you're running a prebuilt binary, you'll need to make sure your system has the right dependencies installed:

  • On Linux:
    • glibc 2.31 or higher (already included on e.g. Ubuntu 20.04, Debian Bullseye)
  • On macOS:
    • macOS 11 or higher
    • The Xcode command line tools, which can be installed with xcode-select --install

Local Worker development with wrangler

You can use Wrangler (v3.0 or greater) to develop Cloudflare Workers locally, using workerd. Run:

wrangler dev

Serving in production

workerd is designed to be unopinionated about how it runs.

One good way to manage workerd in production is using systemd. Particularly useful is systemd's ability to open privileged sockets on workerd's behalf while running the service itself under an unprivileged user account. To help with this, workerd supports inheriting sockets from the parent process using the --socket-fd flag.

Here's an example system service file, assuming your config defines two sockets named http and https:

# /etc/systemd/system/workerd.service
[Unit]
Description=workerd runtime
After=local-fs.target remote-fs.target network-online.target
Requires=local-fs.target remote-fs.target workerd.socket
Wants=network-online.target

[Service]
Type=exec
ExecStart=/usr/bin/workerd serve /etc/workerd/config.capnp --socket-fd http=3 --socket-fd https=4
Sockets=workerd.socket

# If workerd crashes, restart it.
Restart=always

# Run under an unprivileged user account.
User=nobody
Group=nogroup

# Hardening measure: Do not allow workerd to run suid-root programs.
NoNewPrivileges=true

[Install]
WantedBy=multi-user.target

And corresponding sockets file:

# /etc/systemd/system/workerd.socket
[Unit]
Description=sockets for workerd
PartOf=workerd.service

[Socket]
ListenStream=0.0.0.0:80
ListenStream=0.0.0.0:443

[Install]
WantedBy=sockets.target

(TODO: Fully explain how to get systemd to recognize these files and start the service.)

More Repositories

1

quiche

๐Ÿฅง Savoury implementation of the QUIC transport protocol and HTTP/3
Rust
8,654
star
2

cfssl

CFSSL: Cloudflare's PKI and TLS toolkit
Go
8,049
star
3

cloudflared

Cloudflare Tunnel client (formerly Argo Tunnel)
Go
5,870
star
4

boringtun

Userspace WireGuardยฎ Implementation in Rust
Rust
5,768
star
5

flan

A pretty sweet vulnerability scanner
Python
3,910
star
6

miniflare

๐Ÿ”ฅ Fully-local simulator for Cloudflare Workers. For the latest version, see https://github.com/cloudflare/workers-sdk/tree/main/packages/miniflare.
TypeScript
3,656
star
7

wrangler-legacy

๐Ÿค  Home to Wrangler v1 (deprecated)
Rust
3,233
star
8

tableflip

Graceful process restarts in Go
Go
2,549
star
9

cloudflare-docs

Cloudflareโ€™s documentation
CSS
2,519
star
10

workers-rs

Write Cloudflare Workers in 100% Rust via WebAssembly
Rust
2,182
star
11

workers-sdk

โ›…๏ธ Home to Wrangler, the CLI for Cloudflare Workersยฎ
TypeScript
2,047
star
12

wildebeest

Wildebeest is an ActivityPub and Mastodon-compatible server
TypeScript
2,026
star
13

gokey

A simple vaultless password manager in Go
Go
1,836
star
14

ebpf_exporter

Prometheus exporter for custom eBPF metrics
C
1,639
star
15

lol-html

Low output latency streaming HTML parser/rewriter with CSS selector-based API
Rust
1,388
star
16

redoctober

Go server for two-man rule style file encryption and decryption.
Go
1,373
star
17

cf-ui

๐Ÿ’Ž Cloudflare UI Framework
JavaScript
1,297
star
18

sslconfig

Cloudflare's Internet facing SSL configuration
1,287
star
19

cloudflare-go

Go library for the Cloudflare v4 API
Go
1,246
star
20

hellogopher

Hellogopher: "just clone and make" your conventional Go project
Makefile
1,153
star
21

production-saas

(WIP) Example SaaS application built in public on the Cloudflare stack!
TypeScript
1,099
star
22

bpftools

BPF Tools - packet analyst toolkit
Python
1,087
star
23

cloudflare-blog

Cloudflare Blog code samples
C
1,065
star
24

foundations

Cloudflare's Rust service foundations library.
Rust
1,005
star
25

wrangler-action

๐Ÿง™โ€โ™€๏ธ easily deploy cloudflare workers applications using wrangler and github actions
TypeScript
993
star
26

templates

A collection of starter templates and examples for Cloudflare Workers and Pages
JavaScript
979
star
27

circl

CIRCL: Cloudflare Interoperable Reusable Cryptographic Library
Go
970
star
28

wirefilter

An execution engine for Wireshark-like filters
Rust
913
star
29

pingora

A library for building fast, reliable and evolvable network services.
Rust
896
star
30

next-on-pages

CLI to build and develop Next.js apps for Cloudflare Pages
TypeScript
845
star
31

utahfs

UtahFS is an encrypted storage system that provides a user-friendly FUSE drive backed by cloud storage.
Go
805
star
32

cf-terraforming

A command line utility to facilitate terraforming your existing Cloudflare resources.
Go
793
star
33

workers-chat-demo

JavaScript
779
star
34

pint

Prometheus rule linter/validator
Go
772
star
35

Stout

A reliable static website deploy tool
Go
749
star
36

goflow

The high-scalability sFlow/NetFlow/IPFIX collector used internally at Cloudflare.
Go
729
star
37

unsee

Alert dashboard for Prometheus Alertmanager
Go
710
star
38

mitmengine

A MITM (monster-in-the-middle) detection tool. Used to build MALCOLM:
Go
690
star
39

terraform-provider-cloudflare

Cloudflare Terraform Provider
Go
662
star
40

workers-graphql-server

๐Ÿ”ฅLightning-fast, globally distributed Apollo GraphQL server, deployed at the edge using Cloudflare Workers
JavaScript
635
star
41

react-gateway

Render React DOM into a new context (aka "Portal")
JavaScript
569
star
42

xdpcap

tcpdump like XDP packet capture
Go
567
star
43

cloudflare-php

PHP library for the Cloudflare v4 API
PHP
566
star
44

ahocorasick

A Golang implementation of the Aho-Corasick string matching algorithm
Go
541
star
45

lua-resty-logger-socket

Raw-socket-based Logger Library for Nginx (based on ngx_lua)
Perl
477
star
46

nginx-google-oauth

Lua module to add Google OAuth to nginx
Lua
425
star
47

gokeyless

Go implementation of the keyless protocol
Go
420
star
48

worker-typescript-template

ส• โ€ขฬุˆโ€ขฬ€) TypeScript template for Cloudflare Workers
TypeScript
416
star
49

golibs

Various small golang libraries
Go
402
star
50

stpyv8

Python 3 and JavaScript interoperability. Successor To PyV8 (https://github.com/flier/pyv8)
C++
388
star
51

sandbox

Simple Linux seccomp rules without writing any code
C
385
star
52

speedtest

Component to perform network speed tests against Cloudflare's edge network
JavaScript
371
star
53

mmproxy

mmproxy, the magical PROXY protocol gateway
C
370
star
54

mmap-sync

Rust library for concurrent data access, using memory-mapped files, zero-copy deserialization, and wait-free synchronization.
Rust
356
star
55

pages-action

JavaScript
355
star
56

rustwasm-worker-template

A template for kick starting a Cloudflare Worker project using workers-rs. Write your Cloudflare Worker entirely in Rust!
Rust
350
star
57

workers-types

TypeScript type definitions for authoring Cloudflare Workers.
TypeScript
350
star
58

cobweb

COBOL to WebAssembly compiler
COBOL
345
star
59

cloudflare-ingress-controller

A Kubernetes ingress controller for Cloudflare's Argo Tunnels
Go
344
star
60

lua-resty-cookie

Lua library for HTTP cookie manipulations for OpenResty/ngx_lua
Perl
340
star
61

svg-hush

Make it safe to serve untrusted SVG files
Rust
333
star
62

boring

BoringSSL bindings for the Rust programming language.
Rust
330
star
63

node-cloudflare

Node.js API for Client API
JavaScript
319
star
64

cfweb3

JavaScript
309
star
65

workerskv.gui

(WIP) A cross-platform Desktop application for exploring Workers KV Namespace data
Svelte
307
star
66

JSON.is

Open-source documentation for common JSON formats.
JavaScript
302
star
67

sqlalchemy-clickhouse

Python
299
star
68

cloudflare.github.io

Cloudflare โค๏ธ Open Source
CSS
298
star
69

json-schema-tools

Packages for working with JSON Schema and JSON Hyper-Schema
JavaScript
296
star
70

chatgpt-plugin

Build ChatGPT plugins with Cloudflare's Developer Platform ๐Ÿค–
JavaScript
290
star
71

tls-tris

crypto/tls, now with 100% more 1.3. THE API IS NOT STABLE AND DOCUMENTATION IS NOT GUARANTEED.
Go
283
star
72

gortr

The RPKI-to-Router server used at Cloudflare
Go
283
star
73

react-modal2

๐Ÿ’ญ Simple modal component for React.
JavaScript
279
star
74

doom-wasm

Chocolate Doom WebAssembly port with WebSockets support
C
273
star
75

keyless

Cloudflare's Keyless SSL Server Reference Implementation
C
272
star
76

isbgpsafeyet.com

Is BGP safe yet?
HTML
262
star
77

go

Go with Cloudflare experimental patches
Go
260
star
78

dog

Durable Object Groups
TypeScript
255
star
79

kv-asset-handler

Routes requests to KV assets
TypeScript
244
star
80

mod_cloudflare

C
243
star
81

tubular

BSD socket API on steroids
C
242
star
82

semver_bash

Semantic Versioning in Bash
Shell
238
star
83

cloudflare-rs

Rust library for the Cloudflare v4 API
Rust
236
star
84

cfssl_trust

CFSSL's CA trust store repository
Go
226
star
85

doca

A CLI tool that scaffolds API documentation based on JSON HyperSchemas.
JavaScript
224
star
86

pmtud

Path MTU daemon - broadcast lost ICMP packets on ECMP networks
C
218
star
87

alertmanager2es

Receives HTTP webhook notifications from AlertManager and inserts them into an Elasticsearch index for searching and analysis
Go
218
star
88

itty-router-openapi

OpenAPI 3 and 3.1 schema generator and validator for Cloudflare Workers
TypeScript
218
star
89

origin-ca-issuer

Go
216
star
90

worker-template-router

JavaScript
216
star
91

cloudflare-docs-engine

A documentation engine built on Gatsby, powering Cloudflareโ€™s docs https://github.com/cloudflare/cloudflare-docs
JavaScript
215
star
92

python-worker-hello-world

Python hello world for Cloudflare Workers
JavaScript
209
star
93

saffron

The cron parser powering Cron Triggers on Cloudflare Workers
Rust
207
star
94

Cloudflare-WordPress

A Cloudflare plugin for WordPress
PHP
204
star
95

certmgr

Automated certificate management using a CFSSL CA.
Go
202
star
96

collapsify

Collapsify inlines all the resources of a page into a single document
JavaScript
200
star
97

worker-speedtest-template

JavaScript
195
star
98

har-sanitizer

TypeScript
192
star
99

zkp-ecdsa

Proves knowledge of an ECDSA-P256 signature under one of many public keys that are stored in a list.
TypeScript
187
star
100

shellflip

Graceful process restarts in Rust
Rust
183
star