Angel3 Hot Reloader

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

Screenshot of terminal

Supports hot reloading of Angel3 servers on file changes. This is faster and more reliable than merely reactively restarting a Process. This package only works with the Angel3 framework.

Not recommended to use in production, unless you are specifically intending for a "hot code push" in production.

Installation

In your pubspec.yaml:

dependencies:
  angel3_framework: ^10.0.0
  angel3_hot: ^10.0.0

Usage

This package is dependent on the Dart VM service, so you must run Dart with the --observe (or --enable-vm-service) argument. Usage is fairly simple. Pass a function that creates an Angel server, along with a collection of paths to watch, to the HotReloader constructor. The recommended pattern is to only use hot-reloading in your application entry point. Create your Angel instance within a separate function, conventionally named createServer.

You can watch:

  • Files
  • Directories
  • Globs
  • URI's
  • package: URI's
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:angel3_framework/angel3_framework.dart';
import 'package:angel3_hot/angel3_hot.dart';
import 'package:logging/logging.dart';
import 'src/foo.dart';

main() async {
  var hot = HotReloader(createServer, [
    Directory('src'),
    'main.dart',
    Uri.parse('package:angel3_hot/angel3_hot.dart')
  ]);
  await hot.startServer('127.0.0.1', 3000);
}

Future<Angel> createServer() async {
  var app = Angel()..serializer = json.encode;

  // Edit this line, and then refresh the page in your browser!
  app.get('/', (req, res) => {'hello': 'hot world!'});
  app.get('/foo', (req, res) => Foo(bar: 'baz'));

  app.fallback((req, res) => throw AngelHttpException.notFound());

  app.encoders.addAll({
    'gzip': gzip.encoder,
    'deflate': zlib.encoder,
  });

  app.logger = Logger('angel')
    ..onRecord.listen((rec) {
      print(rec);
      if (rec.error != null) {
        print(rec.error);
        print(rec.stackTrace);
      }
    });

  return app;
}

HTTPS

Pass a SecurityContext to serve over HTTPS (HTTP/1.1); the app made by createServer is unchanged:

var hot = HotReloader(
  createServer,
  [Directory('lib')],
  securityContext: SecurityContext()
    ..useCertificateChain('dev.pem')
    ..usePrivateKey('dev.key', password: 'dartdart'),
);
await hot.startServer('127.0.0.1', 8443);

For a certificate your browser trusts, use e.g. mkcert localhost 127.0.0.1. With requestClientCertificate: true, clients are asked for a certificate, which handlers read from HttpRequest.certificate. Plain HTTP is then not served on that port, and HTTP/2 is not supported.

How a reload works

  • Changes are gathered for debounce (default 200 ms), and trigger one reload; reloads run one at a time, and changes during one trigger one more after it.
  • The VM's sources are reloaded (with the VM service, and hotReload: true), then createServer makes a new server. Requests that come meanwhile wait for it, for at most timeout. Once it serves, the old one is closed: its WebSockets, then, once the requests it is answering are done (or after shutdownGracePeriod, default 10 s), its shutdown hooks and its app.
  • If createServer throws, or the reload fails, the error is logged, and the last good server goes on serving; the next change tries again.
  • Without the VM service, a change makes the server again, of the code already loaded, as for files it reads (templates, configuration).
  • Paths that are relative, and Globs, are of the current working directory. A Glob also matches files created after the start.
  • reload() reloads on demand; one called during a reload returns once the reload after it has run. close() answers the requests waiting for a reload with 503, stops watching, closes the server and the app, and gives the terminal back.
  • A Glob watches only the directory of its leading segments without wildcards (lib of lib/**.dart).

Customising Response Header

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

import 'dart:io';
import 'package:angel3_hot/angel3_hot.dart';
import 'server.dart';

void main() async {
  var hot = HotReloader(createServer, [
    Directory('src'),
    'server.dart',
    // Also allowed: Platform.script,
    Uri.parse('package:angel3_hot/angel3_hot.dart')
  ]);
  var http = await hot.startServer('127.0.0.1', 3000);

  // Remove 'X-FRAME-OPTIONS'
  http.defaultResponseHeaders.remove('X-FRAME-OPTIONS', 'SAMEORIGIN');

  // Add 'X-XSRF-TOKEN'
  http.defaultResponseHeaders.add('X-XSRF-TOKEN',
      'a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e');
}

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:

  • startServer throws a StateError if called again on the same HotReloader. Call reload() to reload on demand.

Libraries

angel3_hot