reloadCertificate method

Future<void> reloadCertificate()

Reads the certificate and key files of AppConfig.tls, and of each port of AppConfig.ports with tls, again, for example after certbot renewed them. New connections get the new certificate. Open connections keep the old one until they close. One call is enough: every isolate of the process gets it. When a file is bad, it throws a TlsException and the server keeps the old certificate. With more than one certificate, it checks all the files first, so a bad file changes no port. A file that changes between the check and the reload can still stop it half way: then call it again. It throws a StateError when no port has tls, before the server starts and after it is closed. Dox does not watch the files: the app decides when to call it (eg. on SIGHUP).

await Dox().server.reloadCertificate();

Implementation

Future<void> reloadCertificate() async {
  HttpServer? main = _main;
  if (main == null) {
    throw StateError('reloadCertificate: the server does not run');
  }

  /// one server for each pair of files: the ports (and isolates) with
  /// the same files share the certificate
  Map<String, HttpServer> secure = <String, HttpServer>{};
  for (HttpServer s in _open) {
    ServerTls? files = adapter.tlsFiles(s);
    if (files == null) continue;
    secure.putIfAbsent('${files.certificatePath}\n${files.keyPath}', () => s);
  }
  if (secure.isEmpty) {
    throw StateError('reloadCertificate: the server has no tls');
  }

  /// all the files first: a bad file must not leave one port with the
  /// new certificate and one with the old
  if (secure.length > 1) {
    for (HttpServer s in secure.values) {
      adapter.checkTls(adapter.tlsFiles(s)!);
    }
  }
  for (HttpServer s in secure.values) {
    await adapter.reloadCertificate(s);
  }
}