startServer method

Future<void> startServer({
  1. ServerAdapter? server,
})

Start the server, in every isolate.

server is the HTTP server. Default: the native server (dox_http_native, BuiltInServer.nativeHttpServer). BuiltInServer.ioHttpServer is the dart:io server of the Dart SDK, with no package to add (no HTTP/2). A server package gives its own ServerAdapter, eg. DoxHttpServer.binder of dox_http_server (add the package to the app first). Dox opens each port with it and the settings of AppConfig: body limits, timeouts, maxConnections, compress, http2, tls, and the http2 and tls of each port of AppConfig.ports.

Dox opens the server in every server isolate, and for every port (the main port, AppConfig.additionalPorts and AppConfig.ports). With CoreFlags.isolateGroups, each isolate runs main() again, so it calls startServer(server:) with its own server. Without it, server is sent to the other isolates: it must hold only values that can be sent between isolates (no open socket, no database connection). Else the start fails with an ArgumentError.

A CustomServer runs any function that gives a dart:io HttpServer: dart:io itself, or another package. Then:

  • the server does the TLS and HTTP/2: AppConfig.tls, http2 and the tls and http2 of AppConfig.ports stop the start with an ArgumentError. Dox treats the server as plain HTTP.
  • the other settings of AppConfig for the server do nothing: maxConnections, idleTimeout, bodyTimeout, minBodyRate, minBodyRateGrace, compress, maxConcurrentStreams, tlsHandshakesPerTick, fileThreads. Dox still checks maxBodySize and maxMultipartSize when it reads a body.
  • Windows runs all the isolates, also when the native server would run one.
await Dox().startServer();
await Dox().startServer(server: BuiltInServer.ioHttpServer);
await Dox().startServer(server: DoxHttpServer.binder);
await Dox().startServer(
  server: CustomServer(
    (int port, Object? address) => HttpServer.bind(
      address ?? InternetAddress.anyIPv4,
      port,
      shared: true,
    ),
  ),
);

Implementation

Future<void> startServer({ServerAdapter? server}) async {
  checkAppKey();
  addProviders(config.providers);
  GroupIdentity? group = _group;
  if (group != null) {
    // an isolate of its own group: the primary started it, so it only
    // serves. It does not start isolates, watch signals or exit.
    isWebServer = true;
    await GroupWorker.run(group, server);
    return;
  }
  _totalIsolate ??= Dox().config.totalIsolate;
  int isolatesToSpawn = _totalIsolate!;

  /// tls or http2 with a CustomServer stops the start here
  DoxServer.checkBinder(server, config);

  /// stop here, before any isolate starts, when the server can not run.
  /// The error says why and how to fix it.
  ServerAdapter? builtIn = ServerAdapters.builtIn(server);
  builtIn?.ensureAvailable();

  /// a bad certificate file stops the start here, once. Else every
  /// isolate fails on it and is started again, in a loop.
  await DoxServer().checkCertificate(server: server);

  /// the same for a port that `AppConfig.ports` lists two times
  DoxServer.checkPorts(
    DoxServer.portFor(config.serverPort),
    config.additionalPorts,
    config.ports,
  );

  /// a bad gzip level stops the start here, before a port is open
  RangeError.checkValueInInterval(
    config.compressLevel,
    1,
    12,
    'compressLevel',
  );

  /// the same for the threads of the file pool
  RangeError.checkValueInInterval(config.fileThreads, 1, 64, 'fileThreads');

  /// the same for the handshakes per tick of the Dart server
  if (config.tlsHandshakesPerTick < 1) {
    throw ArgumentError.value(
      config.tlsHandshakesPerTick,
      'tlsHandshakesPerTick',
      'must be 1 or more',
    );
  }

  /// Windows has no SO_REUSEPORT: with the native server one isolate
  /// owns the listener. The Dart server shares one listener between the
  /// isolates of the process.
  if (Platform.isWindows &&
      isolatesToSpawn > 1 &&
      (builtIn?.needsReusePort ?? false)) {
    Logger.info('Windows: the server runs on one isolate', null, 'server');
    isolatesToSpawn = 1;
  }

  isolateCount = isolatesToSpawn;
  isWebServer = true;
  // each isolate group has its own slots, so there the warning is only
  // for the fallback
  bool tryGroups = config.flags.isolateGroups && isolatesToSpawn > 1;
  if (!tryGroups) warnIsolateSlots(isolatesToSpawn, IsolateSlots.available);
  if (isolatesToSpawn > 1) {
    bool groups = await _spawnIsolates(isolatesToSpawn, server);
    if (tryGroups && !groups) {
      warnIsolateSlots(isolatesToSpawn, IsolateSlots.available);
    }
  }

  await startProviders();
  warnWebSocketOrigin();
  warnCorsCredentials();
  DoxServer().setResponseHandler(config.responseHandler);
  HttpServer httpServer = await DoxServer().listen(
    DoxServer.portFor(config.serverPort),
    address: DoxServer.hostFor(config.host),
    additionalPorts: config.additionalPorts,
    ports: config.ports,
    server: server,
  );
  List<int> others = <int>[
    ...config.additionalPorts,
    for (PortConfig p in config.ports) p.port,
  ];
  String more = others.isEmpty ? '' : ' (and port ${others.join(', ')})';

  Logger.info(
    'Server started at ${serverUrl(httpServer)}$more with $isolatesToSpawn '
        'isolate (${httpServer.runtimeType})',
    null,
    'server',
  );
  _watchSignals();
}