Skip to main content

angel3_production 10.2.0 copy "angel3_production: ^10.2.0" to clipboard
angel3_production: ^10.2.0 copied to clipboard

Helpers for concurrency, message-passing, rotating loggers, and other production functionality in Angel3.

Angel3 Production Runner #

Pub Version (including pre-releases) Null Safety Discord License

Helpers for concurrency, message-passing, rotating loggers, and other production functionality in Angel3 framework.

Screenshot

This will become the de-facto way to run Angel3 applications in deployed environments, as it takes care of inter-isolate communication, respawning dead processes, and other housekeeping for you automatically. Most users will want to use the Runner class.

Installation #

In your pubspec.yaml:

dependencies:
  angel3_production: ^10.2.0

Usage #

Runner #

Runner is a utility, powered by package:args, that is intended to be the entry point of your application.

Instantiate it as follows, and your file will become a command-line executable that spawns multiple instances of your application:

import 'dart:async';
import 'dart:isolate';
import 'package:angel3_framework/angel3_framework.dart';
import 'package:angel3_production/angel3_production.dart';

void main(List<String> args) => Runner('example', configureServer).run(args);

Future configureServer(Angel app) async {
  app.get('/', (req, res) => 'Hello, production world!');

  app.get('/crash', (req, res) {
    // We'll crash this instance deliberately, but the Runner will auto-respawn for us.
    Timer(const Duration(seconds: 3), Isolate.current.kill);
    return 'Crashing in 3s...';
  });
}

Runner will automatically re-spawn crashed instances, unless --no-respawn is passed. This can prevent your server from entirely going down at the first error, and adds a layer of fault tolerance to your infrastructure. An instance that keeps crashing is respawned after a delay that doubles from 1 s to 30 s, and is reset once it has run for a minute.

An instance that fails to start the first time (a port in use, a bad certificate, an error in configureServer) is not respawned: run ends with exit code 70, after closing the other instances, so that a supervisor such as systemd or Docker sees the failure. Once it has started, a failure to start again (say, a database that is briefly down) is respawned like a crash.

SIGINT (Ctrl+C) and SIGTERM (docker stop, systemctl stop; not on Windows) close every instance gracefully: it stops accepting requests, lets those in progress finish (for up to half of shutdownTimeout), and runs its shutdown hooks, all within shutdownTimeout (default 10 s), after which it is killed. A second signal exits at once. Runner.stop() does the same from code.

When combined with systemd, deploying Angel3 applications on Linux can be very simple.

The instances run in production mode, which caches the routes each request resolves to, unless ANGEL_ENV is set otherwise: run with ANGEL_ENV=development to debug the app in development mode, which resolves the routes of each request again and logs the time of each. In production mode the routes are read once, when an instance starts, so add them all in configureServer. See Production mode of the framework.

Message Passing #

The Runner class uses belatuk_pub_sub to coordinate message passing between isolates. When one isolate sends a message, all other isolates will receive the same message, except for the isolate that sent it. It is injected into your application's Container as pub_sub.Client, so you can use it as follows:

// Use the injected `pub_sub.Client` to send messages.
var client = app.container.make<Client>();

// We can listen for an event to perform some behavior.
//
// Here, we use message passing to synchronize some common state.
var onGreetingChanged = await client.subscribe('user_upgraded');
onGreetingChanged
    .cast<User>()
    .listen((user) {
      // Do something...
    });

Customising Response Header #

Additional parameters can be passed to the Runner class to:

  1. Remove headers from HTTP response.
  2. Add headers to HTTP response.

For example, the following code snippet removes X-FRAME-OPTIONS and adds X-XSRF-TOKEN to the response header.


void main(List<String> args) {
  // Remove 'X-FRAME-OPTIONS'
  var removeHeader = {'X-FRAME-OPTIONS': 'SAMEORIGIN'};

  // Add 'X-XSRF-TOKEN'
  var customHeader = {
    'X-XSRF-TOKEN':
        'a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e'
  };

  Runner('example', configureServer,
          removeResponseHeaders: removeHeader, responseHeaders: customHeader)
      .run(args);
}

The added headers are defaults: a header that a handler sets replaces one of the same name. removeResponseHeaders removes the given values from those defaults (including the ones dart:io adds, such as X-FRAME-OPTIONS: SAMEORIGIN), not a header a handler sets. Both apply the same way with --http2. A list value is sent as one header of its values, except Set-Cookie, which is sent once per value. A list in removeResponseHeaders removes each of its values, a value matches exactly, or ignoring case if nothing matches exactly, such as sameorigin for the SAMEORIGIN of dart:io, and a null value removes a header whatever its values, e.g. {'X-XSS-PROTECTION': null}.

Run-time Metadata #

At run-time, you may want to know information about the currently-running instance, for example, which number instance. For this, the InstanceInfo class is injected into each instance:

var instanceInfo = app.container.make<InstanceInfo>();
print('This is instance #${instanceInfo.id}');

Metrics #

Each instance is an isolate with metrics of its own, and the instances share the app's port, so a scrape of that port by Prometheus reaches one instance at random. Serve the metrics of each instance on a port of its own instead, from its InstanceInfo, and add them up in Prometheus. angel3_prometheus times the requests and serves the metrics:

Future<void> configureServer(Angel app) async {
  var metrics = PrometheusMetrics();
  // First, so that it measures every request.
  await app.configure(metrics.configureServer);

  app.get('/hello', (req, res) => 'Hello!');

  // Last: instance #0 serves its metrics on 9100, #1 on 9101, and so on.
  var instance = app.container.make<InstanceInfo>();
  await metrics.serve(app, InternetAddress.loopbackIPv4, 9100 + instance.id);
}

Prometheus then scrapes 127.0.0.1:9100 up to 9100 plus --concurrency minus one. The README of angel3_prometheus lists the metrics, and queries for Grafana.

Things to know, with or without that package:

  • Close the metrics server, and open it last. A server that an instance opens is closed when the instance closes only if a shutdown hook closes it, as serve does. Open it last in configureServer: an instance that fails to start exits its isolate without closing the app, and a port that the isolate has bound stays bound to the process, so an instance started again in its place could not bind it.
  • A middleware that measures requests with app.all('*', ...) or app.fallback(...), and returns true, makes a path that no other route matches an empty 200 instead of a 404. End the routes with app.fallback((req, res) => throw AngelHttpException.notFound()), or use angel3_prometheus, which keeps the 404.
  • Memory and CPU are those of the one process of all the instances. process_resident_memory_bytes is the same from each instance; for CPU, use the Prometheus node exporter, or cAdvisor for containers.

Command-line Options #

The Runner class supplies options like the following:

appuser$ dart example/main.dart --help
     _    _   _  ____ _____ _     _____ 
    / \  | \ | |/ ___| ____| |   |___ / 
   / _ \ |  \| | |  _|  _| | |     |_ \ 
  / ___ \| |\  | |_| | |___| |___ ___) |
 /_/   \_\_| \_|\____|_____|_____|____/                                                                                 

A batteries-included, full-featured, full-stack framework in Dart.

https://angel3-framework.web.app

Options:
-h, --help                          Print this help information.
    --[no-]respawn                  Automatically respawn crashed application instances.
                                    (defaults to on)
    --use-zone                      Create a new Zone for each request.
    --quiet                         Completely mute logging.
    --ssl                           Listen for HTTPS instead of HTTP.
    --http2                         Listen for HTTP/2 instead of HTTP/1.1.
-a, --address                       The address to listen on.
                                    (defaults to "127.0.0.1")
-j, --concurrency                   The number of isolates to spawn.
                                    (defaults to "4")
-p, --port                          The port to listen on.
                                    (defaults to "3000")
    --certificate-file              The PEM certificate file to read.
    --certificate-password          The PEM certificate file password; prefer ANGEL_CERTIFICATE_PASSWORD, as arguments are seen by other users.
    --key-file                      The PEM key file to read.
    --key-password                  The PEM key file password; prefer ANGEL_KEY_PASSWORD, as arguments are seen by other users.
    --client-ca-file                The PEM file of the CAs that may sign client certificates: asks each client for one (mutual TLS).
    --require-client-certificate    Refuse a client that presents no certificate; needs --client-ca-file.

Command-line arguments are visible to other users of the machine (ps), and end up in shell history, so give the passwords in the ANGEL_CERTIFICATE_PASSWORD and ANGEL_KEY_PASSWORD environment variables instead; an option given on the command line takes precedence.

Mutual TLS #

With --client-ca-file, the server asks each client for a certificate (mutual TLS), for --ssl and --http2 alike, and accepts those that the CAs of the file sign; a handler reads it as req.clientCertificate. A client may still connect without one, unless --require-client-certificate is given too:

dart example/main.dart --ssl \
  --certificate-file server.pem --key-file server.key \
  --client-ca-file client_ca.pem --require-client-certificate

A certificate that the CAs did not sign fails the TLS handshake. Leave out --require-client-certificate for a server that clients without a certificate use too, such as an OAuth 2.0 server that browsers reach.

Migrating from 9.x to 10.0.0 #

The breaking changes of each release are listed in the CHANGELOG. Those of 10.0.0 that may need changes in an app:

  • Failing to start: an instance that fails to start the first time ends run with exit code 70, instead of leaving the runner up with nothing serving, so a supervisor such as systemd or Docker sees the failure.
  • InstanceInfo.id is a non-nullable int.
  • Runner.isolateMain sends the runner's own messages on RunnerArgs.loggingSendPort, not LogRecords, and the instance it starts runs until the runner stops it. Start instances with run, or spawnIsolate, instead of spawning isolateMain with a port of your own.
1
likes
160
points
627
downloads

Documentation

API reference

Publisher

verified publisherdukefirehawk.com

Weekly Downloads

Helpers for concurrency, message-passing, rotating loggers, and other production functionality in Angel3.

Homepage
Repository (GitHub)
View/report issues
Contributing

License

BSD-3-Clause (license)

Dependencies

angel3_container, angel3_framework, args, belatuk_pub_sub, intl, io, logging

More

Packages that depend on angel3_production