Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,51 @@
## 1.35.0

API/server layer clean-up (behavior-preserving):

- `APIServerWorker`: both branches of `_processAPIResponse` end in one
`_finishResponse`; helpers renamed to what they do (`_buildShelfResponse`,
`_disposeAndCompressResponse`, `_startServersAndInitializeAPIRoot`,
`_errorResponse`). The `CORS` headers are set once (they were set again
when building the headers).
- Request payload: one `_readPayloadBytes` for text and binary payloads, one
`maxPayloadLength` check (no copy of a single `Uint8List` block).
- `APIServer.toAPIRequest`: headers and query parameters flattened by one
helper. New constants: `APIServer.sessionIDCookieName` (`SESSIONID`),
`headerServerTiming`, `headerKeepAlive`, `headerContentLength`,
`headerXAPIServerWorker`; `APIRoot.apiInfoRoute` (`API-INFO`) and
`APIRoot.defaultAuthenticationRoute` (`authenticate`).
- `APIServerConfig.normalizeHeaderValue`: the `k3` path key is used (it was
ignored).
- `APISecurity`: one `resolveMapped` chain resolving a token's credential;
the `disposeAuthentication*` methods share one helper.
- `APIRoot`: the default-module fallback shared by `acceptsRequest` and the
call.
- `APIServerResponseCache`: an evicted entry is removed once (not per
alternative); one `GET` check in `cacheResponse`.
- `APICronScheduler._execute` split (`_runCalls`, `_storeRunResult`).
- `FieldsFromMap`: one lookup helper for the lower-case and simple keys.
- Private cache fields named `*Cache`, documented, declared before their
users.

Fixes:

- `APIServerResponseCache`: the eviction (`maxMemorySize` reached) sorted
the cached values, which hold a `List` for an entry with compressed
alternatives: a `TypeError`. The entries are now sorted with all their
alternatives (by total usage and memory size).
- `APIServerResponseCache`: an expired entry (file modified) was removed
without subtracting its memory size from `totalMemorySize`.
- `APIServerConfig`: the user directory (Let's Encrypt paths) fell back to
`Directory('~/')`, a literal `~` directory, not the home: it's resolved
from `HOME`/`USERPROFILE` only (`resolveUserDirectory`).
- `APIServer`: the JSON-decode error log printed the stack trace in place
of the invalid payload (a shadowed `catch` variable).
- `IdenticalSet`: grouped elements by `hashCode`, missing an element whose
`hashCode` changed: now by `identityHashCode`.
- `FieldsFromMap.getFieldsKeysInMap`: the given `fieldLC`/`fieldSimple`
(of one field) were used for every field: now computed per field (the
parameters are ignored and `@Deprecated`).

## 1.34.0

`null` and `[]` mean the same in a condition: an empty set for `=~`/`!~`, a
Expand Down
89 changes: 57 additions & 32 deletions lib/src/bones_api_base.dart
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ typedef APILogger = void Function(
/// Bones API Library class.
class BonesAPI {
// ignore: constant_identifier_names
static const String VERSION = '1.34.0';
static const String VERSION = '1.35.0';

static bool _boot = false;

Expand Down Expand Up @@ -1033,7 +1033,7 @@ abstract class APIRoot with Initializable, Closable {
// first part.
var pathPartRoot = apiRequest.pathPartFirst;

if (pathPartRoot == 'API-INFO') {
if (pathPartRoot == apiInfoRoute) {
var info = apiInfo(apiRequest);
return APIResponse.ok(info as T, mimeType: _mimeTypeJson);
}
Expand Down Expand Up @@ -1068,13 +1068,7 @@ abstract class APIRoot with Initializable, Closable {

/// Returns `true` if [apiRequest] is an accepted route/call.
bool acceptsRequest(APIRequest apiRequest) {
var module = getModuleByRequest(apiRequest);
if (module == null) {
var def = defaultModuleName;
if (def != null) {
module = _modules![def];
}
}
var module = _resolveModuleOrDefault(getModuleByRequest(apiRequest));

if (module == null) {
if (apiRequest.pathPartAt(0) == authenticationRoute ||
Expand All @@ -1096,12 +1090,7 @@ abstract class APIRoot with Initializable, Closable {
APIModule? module,
APIRequest request,
) {
if (module == null) {
var def = defaultModuleName;
if (def != null) {
module = _modules![def];
}
}
module = _resolveModuleOrDefault(module);

if (module == null) {
return onNoRouteForPath<T>(request);
Expand All @@ -1110,6 +1099,19 @@ abstract class APIRoot with Initializable, Closable {
return module.call(request);
}

/// Returns [module] (the module matched by the request path), or the
/// [defaultModuleName] module when no module matched.
/// Shared by [acceptsRequest] and [_callModule], so both resolve a request
/// to the same module. It takes the already matched module (not the
/// request) because `_callImpl` checks the authentication route between
/// matching and this fallback.
APIModule? _resolveModuleOrDefault(APIModule? module) {
if (module != null) return module;

var def = defaultModuleName;
return def != null ? _modules![def] : null;
}

FutureOr<APIResponse<T>> onNoRouteForPath<T>(APIRequest request) {
var posResponse = callHandlers<T>(
posApiRequestHandlers,
Expand All @@ -1126,22 +1128,31 @@ abstract class APIRoot with Initializable, Closable {
return _responseNotFoundNoRouteForPath<T>(request);
}

String get authenticationRoute => 'authenticate';
/// The route that returns the [APIRootInfo]/[APIModuleInfo] of an API.
static const String apiInfoRoute = 'API-INFO';

/// The default [authenticationRoute] (of [APIRoot] and [APIModule]).
static const String defaultAuthenticationRoute = 'authenticate';

String get authenticationRoute => defaultAuthenticationRoute;

String? get securityModuleName => null;

APIModule? get securityModule => _securityModuleImpl();

APIModule? _securityModule;
/// Cache of the module named [securityModuleName], resolved by
/// [_securityModuleImpl] (a lookup in the modules map), so that each
/// [securityModule] read doesn't repeat the lookup.
APIModule? _securityModuleCache;

APIModule? _securityModuleImpl() {
if (_securityModule != null) return _securityModule;
if (_securityModuleCache != null) return _securityModuleCache;

var securityModuleName = this.securityModuleName;
if (securityModuleName != null) {
var module = getModule(securityModuleName);
if (module != null) {
return _securityModule = module;
return _securityModuleCache = module;
} else {
throw StateError(
"Can't find security module with name: $securityModuleName",
Expand All @@ -1154,15 +1165,20 @@ abstract class APIRoot with Initializable, Closable {

APISecurity? get security => _securityImpl();

APISecurity? _security;
bool _securityResolved = false;
/// Cache of the [APISecurity] of the [securityModule] (possibly `null`),
/// filled by [_securityImpl]: [security] is read on every call.
APISecurity? _securityCache;

/// Whether [_securityCache] was resolved: needed because `null` is a valid
/// (cached) [security].
bool _securityCacheResolved = false;

APISecurity? _securityImpl() {
if (_securityResolved) return _security;
_securityResolved = true;
if (_securityCacheResolved) return _securityCache;
_securityCacheResolved = true;

var securityModule = this.securityModule;
return _security = securityModule?.security;
return _securityCache = securityModule?.security;
}

@override
Expand Down Expand Up @@ -2501,9 +2517,11 @@ class APIRequest extends APIMetricSet with APIPayload {
}
}

String? _hostname;
/// Cache of [hostname], parsed from the `Host` header by [_hostnameImpl]
/// on first read (the headers don't change during the request).
String? _hostnameCache;

String get hostname => _hostname ??= _hostnameImpl();
String get hostname => _hostnameCache ??= _hostnameImpl();

String _hostnameImpl() {
var host = getHeader('host');
Expand All @@ -2525,9 +2543,11 @@ class APIRequest extends APIMetricSet with APIPayload {
return host;
}

int? _port;
/// Cache of [port], parsed from the `Port`/`Host` headers by [_portImpl]
/// on first read.
int? _portCache;

int get port => _port ??= _portImpl();
int get port => _portCache ??= _portImpl();

int _portImpl() {
var port = getHeader('port');
Expand All @@ -2553,10 +2573,13 @@ class APIRequest extends APIMetricSet with APIPayload {

String get hostnameAndPort => '$hostname:$port';

String? _requesterAddressResolved;
/// Cache of [requesterAddress], resolved by [_requesterAddressImpl]
/// (the given address, or the `X-Forwarded-For`/`Remote-Address`
/// headers). A `null` result isn't cached (it's re-resolved on each read).
String? _requesterAddressCache;

String? get requesterAddress =>
_requesterAddressResolved ??= _requesterAddressImpl();
_requesterAddressCache ??= _requesterAddressImpl();

String? _requesterAddressImpl() {
if (_requesterAddress != null) return _requesterAddress;
Expand All @@ -2579,9 +2602,11 @@ class APIRequest extends APIMetricSet with APIPayload {
return null;
}

String? _origin;
/// Cache of [origin], resolved by [_originImpl] (the `Origin` header, or
/// built from [scheme] and [hostnameAndPort]) on first read.
String? _originCache;

String get origin => _origin ??= _originImpl();
String get origin => _originCache ??= _originImpl();

String _originImpl() {
var origin = getHeader('origin');
Expand Down
Loading
Loading