handleRawRequest method

Future handleRawRequest(
  1. Request request,
  2. Response response
)

Handles a single request.

Implementation

Future handleRawRequest(Request request, Response response) {
  // Future.sync turns a synchronous throw into a failed Future, so callers'
  // error handlers see it.
  return Future.sync(() => createRequestContext(request, response)).then((
    req,
  ) {
    return createResponseContext(request, response, req).then((res) {
      Future handle() {
        var path = req.path;
        if (path == '/') path = '';

        Tuple4<
          List,
          Map<String, dynamic>,
          ParseResult<RouteResult>,
          MiddlewarePipeline
        >
        resolveTuple() {
          var r = app.optimizedRouter;
          // Not through the router's own cache: in production this one is
          // in front of it, with the same keys, so it would only miss.
          var resolved = resolveRequest(
            r,
            path,
            req.method,
            strip: false,
            cached: false,
          );
          if (resolved.isEmpty) {
            throw AngelHttpException.notFound();
          }
          var pipeline = MiddlewarePipeline<RequestHandler>(resolved);
          return Tuple4(
            pipeline.handlers,
            resolved.fold<Map<String, dynamic>>(
              <String, dynamic>{},
              (out, r) => out..addAll(r.allParams),
            ),
            resolved.first.parseResult,
            pipeline,
          );
        }

        var cacheKey = req.method + path;
        var tuple = app.environment.isProduction
            ? _cachedResolve(cacheKey, resolveTuple)
            : resolveTuple();
        var line = tuple.item4 as MiddlewarePipeline<RequestHandler>;
        var it = MiddlewarePipelineIterator<RequestHandler>(line);

        req.params.addAll(tuple.item2);

        req.container
          ?..registerSingleton<RequestContext>(req)
          ..registerSingleton<ResponseContext>(res)
          ..registerSingleton<MiddlewarePipeline>(tuple.item4)
          ..registerSingleton<MiddlewarePipeline<RequestHandler>>(line)
          ..registerSingleton<MiddlewarePipelineIterator>(it)
          ..registerSingleton<MiddlewarePipelineIterator<RequestHandler>>(it)
          ..registerSingleton<ParseResult<RouteResult>?>(tuple.item3)
          ..registerSingleton<ParseResult?>(tuple.item3);

        if (!app.environment.isProduction) {
          req.container?.registerSingleton<Stopwatch>(Stopwatch()..start());
        }

        return runPipeline(it, req, res, app).then((continued) {
          // Every handler continued, as a fallback that returns `true`
          // (or calls `next`) does, and none answered: there is no route
          // for the request, as when none matched.
          if (continued && notFoundIfUnanswered && _unanswered(res)) {
            throw AngelHttpException.notFound();
          }
          return sendResponse(request, response, req, res);
        });
      }

      if (useZone == false) {
        Future f;

        try {
          f = handle();
        } catch (e, st) {
          f = Future.error(e, st);
        }

        return f
            .catchError((e, StackTrace st) {
              if (e is FormatException) {
                throw AngelHttpException.badRequest(message: e.message)
                  ..stackTrace = st;
              }
              throw AngelHttpException(
                stackTrace: st,
                statusCode: (e is AngelHttpException) ? e.statusCode : 500,
                message: e?.toString() ?? '500 Internal Server Error',
              );
            }, test: (e) => e is! AngelHttpException)
            .catchError((ee, StackTrace st) {
              //print(">>>> Framework error: $ee");
              //var t = (st).runtimeType;
              //print(">>>> StackTrace: $t");
              AngelHttpException e;
              if (ee is AngelHttpException) {
                e = ee;
              } else {
                e = AngelHttpException(
                  stackTrace: st,
                  statusCode: 500,
                  message: ee?.toString() ?? '500 Internal Server Error',
                );
              }

              var error = e.error ?? e;
              var trace = Trace.from(StackTrace.current).terse;
              app.logger.severe(e.message, error, trace);

              return handleAngelHttpException(
                e,
                st,
                req,
                res,
                request,
                response,
              );
            });
      } else {
        // Completed explicitly once the request is done: an error inside
        // the request's error zone never reaches listeners outside it, so
        // a future returned from the zone would never complete whenever a
        // handler throws.
        var done = Completer<void>();
        void finish() {
          if (!done.isCompleted) done.complete();
        }

        var zoneSpec = ZoneSpecification(
          print: (self, parent, zone, line) {
            app.logger.info(line);
          },
          handleUncaughtError: (self, parent, zone, error, stackTrace) {
            var trace = Trace.from(stackTrace).terse;

            // TODO: To be revisited
            Future(() {
                  AngelHttpException e;

                  if (error is FormatException) {
                    e = AngelHttpException.badRequest(message: error.message);
                  } else if (error is AngelHttpException) {
                    e = error;
                  } else {
                    e = AngelHttpException(
                      stackTrace: stackTrace,
                      message: error.toString(),
                    );
                  }

                  app.logger.severe(e.message, error, trace);

                  return handleAngelHttpException(
                    e,
                    trace,
                    req,
                    res,
                    request,
                    response,
                  );
                })
                .catchError((e, StackTrace st) {
                  var trace = Trace.from(st).terse;
                  closeResponse(response);
                  // Ideally, we won't be in a position where an absolutely fatal error occurs,
                  // but if so, we'll need to log it.
                  app.logger.severe(
                    'Fatal error occurred when processing $uri.',
                    e,
                    trace,
                  );
                })
                .whenComplete(finish);
          },
        );

        var zone = Zone.current.fork(specification: zoneSpec);
        req.container?.registerSingleton<Zone>(zone);
        req.container?.registerSingleton<ZoneSpecification>(zoneSpec);

        // If a synchronous error is thrown, it's not caught by `zone.run`,
        // so use a try/catch, and recover when need be.

        try {
          // On failure the error goes to handleUncaughtError, which
          // finishes once the error response has been sent.
          zone.run(() => handle().then((_) => finish()));
        } catch (e, st) {
          zone.handleUncaughtError(e, st);
        }
        return done.future;
      }
    });
  });
}