Skip to main content

dioman 0.8.4 copy "dioman: ^0.8.4" to clipboard
dioman: ^0.8.4 copied to clipboard

A Dio-powered request wrapper with an onion pipeline, normalized results, and composable request policies for Dart and Flutter.

0.8.4 #

  • Docs: pubspec homepage and repository now point to the package directory on the main branch.

0.8.3 #

  • Docs only: rewrote README wording in plain language; the package archive drops internal reports, archives and scripts (12 MB to under 1 MB).

Changelog #

0.8.2 #

  • Fix: automatic cache/share keys no longer throw ArgumentError for a plain List<int> body holding negative or >255 values; only Uint8List is treated as raw bytes (hash plus full base64, up to 64 KiB), every other List is encoded as a JSON array. A plain List<int> and a Uint8List with the same content now produce different keys.
  • Docs: README states the Dio ^5.4.0 floor and the Uint8List key rule; example/real_run.dart covers decode, raw and deadline.

0.8.1 #

  • Fix: 0.8.0 was published from a working tree with unresolved merge conflict markers in lib/ and does not compile; use 0.8.1. No API changes versus the intended 0.8.0.
  • Examples now await api.dispose() and demonstrate decode and a default deadline.

0.8.0 #

  • Dependency: minimum dio raised from 5.0.0 to 5.4.0 (earlier versions lack BaseOptions.preserveHeaderCase, so lower-bound analysis failed).

  • 新增客户端与请求级 deadline: Duration?:以 DiomanClock 计时,覆盖逻辑请求的排队、重试、共享等待与完整传输;到期为 timeout/deadline,独立于 Dio 阶段超时。share 保持调用方自身预算归属,落定清理计时器;testkit 执行器声明 timeout-total 并映射原生预算。

  • R5: get/post/put/patch/delete/head/request/send accept an optional decode callback after successful settlement. Expected failures skip decoding; decoder exceptions bypass plugins and preserve their original stack. Share callers decode independently.

  • Breaking (R5): plugin instance dispose returns FutureOr

  • R5: eject keeps its bool return value while client disposal also waits for ejected async instances and reports cleanup errors; ejection after disposal starts is rejected.

  • R5: debug validates retry.jitter and cache.clone field types before use. Both README exhaustive failure switches retain the null branch.

  • Breaking (R3/C30): all results default to null raw/error. Use DiomanCall(raw: true) to attach the caller's native transport data, including headers on success. Cache hits and share followers never borrow native objects. ctx.native is readonly; its shared slot is cleared and sealed at settlement. Top-level errorStack is removed; internal error/errorStack move into failureOf and retain original-stack rethrows.

  • C31: Retry-After is extracted at the transport boundary and read through a private result field, including by share followers.

  • C32: memory cache stores snapshots and rebuilds hits through the same factory with the current caller's request. Persistent format and share request semantics are unchanged.

  • C24: Use a conditional IO network classifier, preserving unknown SocketException/HttpException/TlsException precision on VM and web/Wasm compatibility.

  • Breaking — C25: Automatic deep/fast keys include responseType; Map keys have type tags. Explicit keys/builders stay unchanged; B8 byte keys retain hash plus full base64. Existing automatic cache keys are invalidated.

  • C26: Internal and cancel results never enter memory or persistent cache, even when shouldStore returns true.

  • C27: expectJson respects explicit plain/bytes/stream response types. next() short-circuits cancellation; cancelAll(reason) and caller CancelToken preserve the first reason as a string, or null when omitted.

  • C28: Debug warns once per client/option key when a plugin is absent. Dioman

  • Breaking — C29: Retry defaults to max: 2, exponential waits from 300ms, delayMax: 10s. The idempotent method allowlist and Retry-After precedence, 60s limit, and exemption from jitter/delayMax remain unchanged.

  • Breaking — C22: Replace top-level kind/reason and DiomanKind with readonly failureOf and DiomanFailureKind. Kernel markers survive create and derivation; marked results always have ok=false. Remove httpStatus; status is HTTP only. Add statusOf, cancellation predicates and parse/DiomanParsed; remove Envelope, envelope/isEnvelope/logicalStatus and call.envelope. Missing business code is 0.

  • Breaking — C23: Retry/auth/breaker use effective status; mock uses HTTP status; notify formats failure markers with HTTP status and suppresses internal/cancel. Business style requires explicit client statusOf.

  • Cache persistence keeps the data/expiresAt/result layout. New result metadata stores ok and an optional failure kind/reason, with HTTP status only. Reads remain compatible with 0.7 two-field entries and B4 kind/status/httpStatus metadata.

  • C19: Share auth refresh and expiration state by TokenManager with explicit owner counts. Release the association on the last disposal; late refresh failures then neither clear credentials nor notify. Remaining owners handle a shared failure once.

  • C20: Notify missing credentials once per session, reset when a login token is observed. Share loading by callback equality across clients, track each client's occupancy, and transfer pending hide windows to new owners. Disposing a window owner completes its final false.

  • C21: Add extend(dio: engine) to retain a supplied engine's interceptors, adapter and transformer. Default extend still clones BaseOptions into a fresh Dio and omits those extensions. Passing the parent's engine shares mutable options; overrides affect both clients.

  • Fixed: Treat ordinary integer lists as JSON when building automatic cache/share keys; only Uint8List uses byte hashing, so out-of-range integers no longer throw and JSON lists have distinct keys from raw bytes.

  • Fixed: Preserve internal errors and their original stacks when cache/mock observes cancellation after the inner pipeline returns.

  • Behavior change (B8): Auth adds plugin/call refreshTimeout (30s, DiomanClock); timeout follows refresh failure and session notification deduplication. Failed refresh after a new login continues with the new token. Refresh requests through the same client must set DiomanAuth.option: false for that call.

  • Behavior change (B8): retryAfterMax defaults to 60s; larger server waits return the current result without retry. Use an explicitly very large Duration to honor practically unlimited Retry-After. No jitter or delayMax is applied to server waits.

  • Behavior change (B8): Unsafe automatic body keys now bypass cache/share. R2b supersedes Map/String key compatibility; JSON arrays use content, byte bodies up to 64 KiB use a content hash, and larger bytes/FormData/streams/opaque objects/encoding failures return null.

  • Behavior change (B8): Default notify suppresses internal results; Dio decoding FormatException is parse with the available HTTP status. HTML text remains accepted by default; expectJson rejects nonempty 2xx text regardless of MIME type; C27 adds explicit response type exceptions.

  • Fix share end/race participant withdrawal, cancellation before cache hits, and replay of one-shot bodies in retry/auth/mock/share retry; plugins return the current result when the body cannot be replayed.

Changes since 0.7.2. See the migration guide for plugin-by-plugin examples and the complete API replacement table.

  • Breaking: Replace Dioman.install and interceptor handles with a Dioman client so every logical request uses the same pipeline. Construct the client with dio and plugins, and call api.get/api.send; use use, eject and inspect for changes.

Before:

final handle = Dioman.install(dio, plugins: plugins);
final response = await dio.get('/users');

After:

import 'package:dio/dio.dart';
import 'package:dioman/dioman.dart';

Future<void> main() async {
  final api = Dioman(dio: Dio(BaseOptions(baseUrl: 'https://api.example.com')),
      plugins: [const DiomanRepath(), const DiomanFilter(), const DiomanCache()]);
  try {
    final data = await api.get<Map<String, dynamic>>('/users/{id}',
        query: {'id': 42},
        call: DiomanCall(options: {DiomanCache.option: const Duration(minutes: 1)}));
    print(data);
    final result = await api.send<dynamic>('GET', '/health');
    print('${failureOf(result)?.kind.name}: ${result.status}, code ${result.code}');
  } on DiomanResponse catch (failure) {
    print('${failureOf(failure)?.kind.name}: ${failure.message}');
  } finally {
    api.dispose();
    api.dio.close(force: true);
  }
}
  • Breaking: Return data from verb methods and a normalized DiomanResponse from send, so callers and plugins share one result model. Replace response.data after dio.get with the value from api.get; use send for metadata.

Before:

final response = await dio.get('/items', queryParameters: {'page': 1},
    options: Options(extra: {'dioman:retry': 2}));
print(response.data);

After:

import 'package:dio/dio.dart';
import 'package:dioman/dioman.dart';

Future<void> main() async {
  final api = Dioman(dio: Dio());
  try {
    final data = await api.get<List<dynamic>>('/items', query: {'page': 1},
        call: DiomanCall(options: {DiomanRetry.option: 2}));
    print(data);
    final result = await api.send<dynamic>('GET', '/items');
    print(result.status);
  } finally {
    api.dispose();
    api.dio.close(force: true);
  }
}
  • Breaking: Replace the exception family with failureOf(result)?.kind and failureOf(result)?.reason to represent expected failures consistently. Catch DiomanResponse around verb methods, or inspect the result of send; programming errors still throw with their original stack.

Before:

try { await dio.get('/items'); }
on DioException catch (error) {
  if (error.error is DiomanException) print(error.error);
}

After:

import 'package:dio/dio.dart';
import 'package:dioman/dioman.dart';

Future<void> main() async {
  final api = Dioman(dio: Dio());
  try {
    try {
      await api.get<dynamic>('/items');
    } on DiomanResponse catch (failure) {
      print('${failureOf(failure)?.kind}: ${failureOf(failure)?.reason}');
    }
    final result = await api.send<dynamic>('GET', '/items');
    if (!result.ok) print(result.message);
  } finally {
    api.dispose();
    api.dio.close(force: true);
  }
}
  • Breaking: Move request policy options out of string-keyed Options.extra into DiomanCall and plugin option keys to separate configuration from internal state. Use query instead of queryParameters; pass false to disable a policy.

Before:

final response = await dio.get('/items', queryParameters: {'page': 1},
    options: Options(extra: {'dioman:retry': 2}));
print(response.data);

After:

import 'package:dio/dio.dart';
import 'package:dioman/dioman.dart';

Future<void> main() async {
  final api = Dioman(dio: Dio());
  try {
    await api.send<dynamic>('GET', '/items', call: DiomanCall(
      key: false, silent: true,
      options: {DiomanRetry.option: 2},
    ));
  } finally {
    api.dispose();
    api.dio.close(force: true);
  }
}
  • Breaking: Route auth failures by the effective status configured with client statusOf, including business 401 inside HTTP 200. Change onFailure(store, response) to onFailure(result, store) and read HTTP result.status or business result.code; the callback may now be asynchronous. Return a RequestPatch from ready instead of mutating Dio options.

Before:

DiomanAuth(tokenManager: tokens, onRefresh: refresh, onAccessExpired: expired,
  onFailure: (store, response) => response.statusCode == 401
      ? DiomanAuthFailureAction.refresh : DiomanAuthFailureAction.others);

After:

import 'package:dio/dio.dart';
import 'package:dioman/dioman.dart';

class Tokens implements DiomanTokenManager {
  @override
  String? accessToken = 'demo';
  @override
  String? refreshToken;
  @override
  void setTokens({required String accessToken, String? refreshToken}) {
    this.accessToken = accessToken;
    this.refreshToken = refreshToken;
  }
  @override
  void clear() { accessToken = null; refreshToken = null; }
}

Future<void> main() async {
  final tokens = Tokens();
  final api = Dioman(dio: Dio(BaseOptions(baseUrl: 'https://api.example.com')),
      plugins: [DiomanAuth(tokenManager: tokens, onRefresh: (store, result) async { store.setTokens(accessToken: 'renewed'); }, onAccessExpired: (store, result) { store.clear(); },
        onFailure: (result, store) async => result.status == 401
            ? DiomanAuthFailureAction.refresh : DiomanAuthFailureAction.others)]);
  try {
    final result = await api.send<dynamic>('GET', '/items',
        call: DiomanCall(options: {DiomanAuth.option: false}));
    print(failureOf(result)?.kind);
  } finally {
    api.dispose();
    api.dio.close(force: true);
  }
}
  • Breaking: Run mock as the outermost source plugin so an inline match can return without cache, share or offline processing. Replace interceptor handlers with routes accepting DiomanRequest and returning data or a Dio Response; real fallback re-enters the inner sources, by default only after HTTP 404 or network failure.

Before:

Dioman.install(dio, mock: DiomanMock(enabled: true, routes: {
  'GET:/items': (options) async => ResponseBody.fromString(
    '{"code":0,"data":[]}', 200,
    headers: {Headers.contentTypeHeader: ['application/json']}),
}));

After:

import 'package:dio/dio.dart';
import 'package:dioman/dioman.dart';

Future<void> main() async {
  final api = Dioman(dio: Dio(BaseOptions(baseUrl: 'https://api.example.com')),
      plugins: [DiomanMock(routes: {'GET:/items': (request) => {'code': 0, 'data': <String>[]}})]);
  try {
    final result = await api.send<dynamic>('GET', '/items',
        call: DiomanCall(options: {DiomanMock.option: true}));
    print(failureOf(result)?.kind);
  } finally {
    api.dispose();
    api.dio.close(force: true);
  }
}
  • Breaking: Observe the final logical call in loading and notify callbacks so retries and refreshes do not create extra UI cycles. Keep loading onChanged(bool); change notify to (message, result) and stringify to (result, ctx). Read the normalized result instead of re-parsing the envelope.

Before:

Dioman.install(dio, loading: DiomanLoading(onChanged: (busy) => print(busy)));
await dio.get('/items');
Dioman.install(dio, plugins: [DiomanNotify(
  notify: (message) => print(message),
  stringify: (data, message, status, options) => message,
)]);

After:

import 'package:dio/dio.dart';
import 'package:dioman/dioman.dart';

Future<void> main() async {
  final api = Dioman(dio: Dio(BaseOptions(baseUrl: 'https://api.example.com')),
      plugins: [DiomanNotify(
        notify: (message, result) => print(message),
        stringify: (result, ctx) => result.ok ? '' : result.message,
      ), DiomanLoading(onChanged: (visible) => print(visible))]);
  try {
    final result = await api.send<dynamic>('GET', '/items',
        call: DiomanCall(options: {DiomanNotify.option: false}));
    print(failureOf(result)?.kind);
  } finally {
    api.dispose();
    api.dio.close(force: true);
  }
}
  • Breaking: Replace before/after/requires ordering, sort, validate and anchor insertion with fixed stages and enforce: pre/post. This makes replay follow the same inner pipeline; move custom extensions to setup/handle and inspect the resulting order.
  • Breaking: Move key generation, cancellation, normalization and debug logging into the kernel so they cover every logical call. Remove the corresponding plugins; use DiomanKeyOptions, cancelAll/pending, DiomanResponseFactory and debug or Dio LogInterceptor.
  • Breaking: Make retry, breaker and auth consume ctx.statusOf(result); cache consumes ok. Update predicates to distinguish HTTP status, business code and ok; breaker now counts each retry attempt and an open breaker stops retries.
  • Breaking: Filter top-level NaN as well as null and blank strings to avoid sending invalid numeric values. Supply a predicate or disable filter for requests that need to retain them; zero and false remain intact.
  • Breaking: Remove DiomanTokenManager.canRefresh because auth owns refresh validity. Keep token access, token updates and clear in the store; let the auth instance decide whether another refresh is allowed.
  • Breaking: Propagate decision-callback errors as programming errors while isolating notification errors, so invalid policy code cannot silently change a request. Fix throwing predicates at their source; treat onRefresh exceptions as refresh failure.
  • Breaking: Remove per-request clocks, unused per-request cache capacity and cache/share none policies. Use the client clock, plugin capacity and request-level false; cache now defaults to memo once enabled, so persistence is only required for persistent policies.
  • Breaking: Share one read-only result per attempt and cancel its transport only after the last subscriber leaves. Enable share per call, choose start/end/race/retry explicitly, and budget for a whole-call subscriber timeout; each logical caller retains its own retry budget.
  • Breaking: Cache normalized successful GET/HEAD results with separate read/write snapshots. Enable cache per call with a Duration TTL, preserve the new result metadata in persistent entries, and obtain clear/remove through api.plugin<DiomanCacheApi>(); remove invalidates only its key.
  • Breaking: Remove host setters, manual settlement, extra registries and plugin-owned management state because setup instances own client state. Use StateKey, next(patch) and api.plugin<...>(); handle offline FIFO exits through kind=offline and reason=queueFull/timeout/disposed. Auth now runs before cached results can be returned.
  • Feature: compose 12 request plugins in fixed onion stages, with setup-only environment configuration and independent state for each client.
  • Feature: derive inner requests with next(patch), declare replay support on demand, and customize envelopes through the response factory.
  • Fix shared failure, cancellation and replay settlement to release subscriptions and timers when the logical call ends.
  • Fix cache hits being unwrapped again and stale in-flight writes surviving invalidation.
  • Fix refresh, retry, offline waits and loading/notify lifecycles to compose through one logical request.

0.7.2 #

  • Feature: add optional DiomanKey(namespace: () => currentAccountId) to isolate cache and in-flight share keys by account, including explicit/custom keys. Non-empty namespaces are encoded as separate fields; unset/null/empty namespaces preserve existing keys. Callback failures reject with DioException.
  • Fix request keys to include origin and merged URL queries, with separate query/body encoding.
  • Fix cache/mock exception exits, await and serialize cache persistence, invalidate stale reads/responses, enforce capacity on hydration, and isolate inserted data with the clone policy.
  • Remove canceled offline entries and release canceled breaker probes using recovery-window credentials.
  • Fix repeated/encoded path substitutions and immutable Map bodies; pair loading callbacks per display cycle.
  • Deprecate unused per-request cache capacity and empty notify options; refresh key/cache/leaf-plugin documentation.
  • Fix share/auth/retry settlement: responsibility is now registered per request (auth/retry claim the request in onRequest and hand off the true final outcome), so public requests, mock short-circuits and auth's early hand-off can no longer hang or mis-settle DiomanShare waiters, and removing/rebinding auth/retry leaves no stale registration. DiomanShare.registerDownstreamSettler, hasMultipleDownstreamSettlers and the share/cancel setters on DiomanAuth/DiomanRetry are deprecated no-ops.
  • Fix share forwarding: typed response/error forwarders (no dynamic handler.reject(e, true) on an ErrorInterceptorHandler, which throws on dio 5.9); every follower/loser gets its own Response bound to its own RequestOptions; followers never re-run retry/auth recovery.
  • Fix recovered results skipping later processing: an auth refresh replay, retry success and share policy: retry success now flow through the interceptors installed after them (normalize, breaker, log), matching a first-time success. Add dio setter on DiomanShare/DiomanAuth/DiomanRetry (bound by Dioman.install/DiomanHandle); replays reuse the host's httpClientAdapter/transformer, clone FormData, and never auto-replay a Stream body.
  • Fix cancelAll() gaps: a request stays tracked through retry back-off and auth refresh waits; share's internal retry and retry back-off are cancellable (cancel-aware Timer), and a cancel is never retried.
  • Fix auth session handling: a transient replay failure (500, network) after a successful refresh no longer clears the fresh token and surfaces the replay's error instead of the stale 401; only a 401 expires the session, guarded by a token-generation check.
  • Fix retry callback failures: exceptions from shouldRetry/delay/onRetry become a DioException and the handler completes exactly once. DiomanTimeout resolves the tier with a two-level lookup instead of building a merged map per request.
  • Fix recovery follow-ups: a downstream interceptor's handler.reject(e) after a recovered result now terminates the chain while reject(e, true) still passes the error to the remaining error interceptors (both release the request's claim); a recovered result is settled to share as the snapshot taken before later interceptors (normalize) run, so followers process it once instead of re-unwrapping an already-normalized envelope.
  • Fix DiomanShare end/race arbitration: a loser that fails in share's error stage now finishes through the same path as a first success (downstream onResponse cleanup, so loading counts return to zero, cancel tokens unregister, auth/retry claims release); a request whose final outcome loses (race: other attempts still in flight or already won; end: superseded during recovery) waits for and returns the winning result instead of its own failure/stale recovery.
  • Fix DiomanAuth: exceptions thrown by isProtected/expiresAt/now/buildHeader in the request stage become a DioException (handler completes exactly once, claim released) instead of hanging on dio versions that do not observe async interceptor futures; waiting on a refresh (request entry or 401 replay) races the request's CancelToken, so a cancelled request completes and releases its claim without waiting for the shared refresh, which keeps running.
  • Fix DiomanCache: clearing an expired entry after a slow persistent read is now compare-and-delete (matching the entry's expiresAt), so it can no longer delete a fresher entry written for the same key in the meantime.
  • Fix share end/race corner cases: DiomanRetry no longer recovers a result in a share-registered request it never claimed (e.g. a mock short-circuit failure), so leader and followers stay consistent; exceptions from shouldRetry/delay/onRetry/auth callbacks now exit through the same arbitrated hand-off as a normal failure (a race loser waits for the winner instead of surfacing the callback error, with no unhandled async error); and a caller waiting for the winner's result stays tracked by cancelAll() and is cancelled promptly.
  • Known limitations: a recovered result handed to a downstream QueuedInterceptor calls its onResponse directly and so bypasses that interceptor's own serialization queue; reusing one CancelToken across many requests accumulates a cancel listener per back-off/refresh wait (released when the token is garbage collected or cancelled).
  • Feature: DiomanBreaker now reclaims idle buckets lazily (on new-bucket creation, no timer). New optional idleTtl (default 1 hour) and maxBuckets (soft cap, default 1000) apply only to closed buckets with zero failure count and no in-flight request; open/halfOpen/in-flight/failing buckets are never reclaimed, so recovery-window credentials are unaffected. Also adds bucketCount and an injectable clock for tests.
  • Feature: declarative plugin ordering. DiomanPlugin.ordering (DiomanPluginOrder(before, after, requires), default none) lets plugins state ordering constraints; new Dioman.sort (stable topological sort), Dioman.validate, Dioman.installPlugins and an optional plugins: argument on Dioman.install for custom plugins. Duplicate names, cycles, missing required plugins and violated constraints throw DiomanPluginOrderException naming the plugins involved (before dio is touched); DiomanHandle.insertBefore/insertAfter/prepend/append validate before mutating and remove refuses to drop a plugin another one requires. Built-ins declare only the README's hard constraints, so Dioman.install's order is unchanged.
  • Feature: DiomanExtraKeys registry of every extra key (public config / cross-plugin protocol / internal state) with owner plugin and value type, findSharedState / DiomanHandle.diagnoseSharedStateKeys / assertNoSharedState to diagnose duplicate plugin instances sharing state keys, and register for custom plugins. No existing key name or runtime behavior changes.

0.7.1 #

  • Style: wrap single-statement ifs in braces to clear analyzer lints; no behavior change.
  • Test: extend the powerset baseline sweep to all 16 plugins.

0.7.0 #

Three new plugins, all additive (no breaking changes) — each self-contained, each with a static const pluginName, a nullable-field DiomanXxxOptions per-request override, and a constructor-level enabled flag, following the existing plugin conventions.

  • Feature: DiomanTimeout (timeout_plugin.dart, dioman:timeout) — dynamic per-request connect/receive/send timeouts by network tier. A host-supplied probe: () => NetworkQuality (excellent/good/poor/none) selects a DiomanTimeouts(connect?, receive?, send?) from a tier map; only non-null fields are written, so a partially-configured tier leaves the other timeouts as BaseOptions set them, and a tier absent from the map is a no-op. Pure config, no request/response coupling — install right after DiomanEnvs. Per-request timeouts merge by tier.
  • Feature: DiomanOffline (offline_plugin.dart, dioman:offline) — offline queue-and-replay. Parks a request (captures its handler, does NOT call next) while a host-supplied isOnline: () => bool reports offline; a true event on the injected onConnectivityChanged: Stream<bool> (or a manual flush()) resumes each parked request down the rest of the chain. shouldQueue gates what's parked (reads normally pass through to cache), maxQueueSize (default 50, oldest evicted with a queueFull rejection) and maxWait (default unbounded, timeout rejection) bound the queue, and dispose() rejects everything pending. Rejections wrap DiomanOfflineException in a response-less DioException so DiomanRetry won't retry them. Install after DiomanCache, before DiomanShare.
  • Feature: DiomanBreaker (breaker_plugin.dart, dioman:breaker) — circuit breaker, one bucket per METHOD:path (override via keyBuilder). closed → open → halfOpen: failureThreshold (default 10) consecutive failures trip open, resetDuration (default 30s) cooldown then halfOpenMaxCalls (default 3) probes decide recovery. Open buckets fail fast in onRequest with a response-less DiomanBreakerOpenException (not retried by DiomanRetry's default). Install AFTER DiomanRetry so it counts only each top-level request's final outcome. DiomanRetry.breaker setter (auto-wired by Dioman.install) lets an in-progress retry loop stop the instant the breaker trips. shouldTrip/onStateChange hooks; a user cancel is recorded as neither success nor failure so it can't reset the consecutive-failure count.
  • Dioman.install gains timeout:/offline:/breaker: parameters, slotted into the canonical order envs → timeout → repath → filter → key → cache → offline → share → mock → cancel → loading → auth → retry → breaker → log → normalize, and auto-wires retry.breaker = breaker.

0.6.0 #

  • Breaking: ApiException renamed to DiomanException (normalize_plugin.dart) — update any catch/is/as sites and the error: object DiomanNormalize rejects with.
  • Breaking: DiomanCache gains a durable persistence layer. persist: DiomanCachePersist is a new required constructor parameter — there is no built-in no-op implementation, so every existing DiomanCache(...) call site needs one (implement read/write/remove/erase yourself; the shape mirrors the get_storage package's container API — read may be sync or async (FutureOr), write/remove/erase always async). A new cachePolicy: DiomanCachePolicy (none default / memo / persist / both, also overridable per request via DiomanCacheOptions.cachePolicy) picks where a cached entry lives: none never caches, memo is the old in-memory-only behavior, persist uses only the durable layer, both keeps memory and persist in sync (a memory miss falls back to persist.read and backfills memory). Note the default changed from an implicit always-on memory cache to DiomanCachePolicy.none — pass cachePolicy: memo explicitly to keep the old behavior.
  • Breaking: DiomanCache.removeWhere()/.size removed — DiomanCachePersist has no key-enumeration capability, so these could never be correct once a persist/both policy is in play (silently a no-op / always 0). remove(key) and clear() stay — both already touch persist unconditionally and work correctly under every policy.

0.5.1 #

  • Feature: each plugin's fixed name/extra key is now also exposed as a public static const pluginName on the class (e.g. DiomanCache.pluginName), so callers can reference a plugin's key without constructing an instance. The instance String get name getter is unchanged and still delegates to it.

0.5.0 #

DiomanRetry overhaul, ported from the same rewrite in this monorepo's @codejoo/axp (its TypeScript/axios counterpart) — new capabilities and a few breaking signature changes:

  • Breaking: shouldRetry's return type is now bool? (was bool) — an exact true/false still wins outright, but null (including when shouldRetry isn't set at all) now falls through to the new statusCodes table instead of a hardcoded "≥500 or a timeout/connection error" default. statusCodes defaults to [408,429,500,502,503,504]; the timeout/connection-error fallback still applies, but only when there's no HTTP status at all (a pure network failure).
  • Breaking: delay's function signature is now Duration Function(int current, int max, Response<dynamic>? response, DioException? err) (was Duration Function(int attempt)), and its default changed from exponential back-off (1s/2s/4s) to a flat 3000ms — matching axp's IRetryOptions.delay. Existing delay: (_) => ... callbacks need an extra three params.
  • Feature: methods — a List<String> whitelist of HTTP methods eligible for retry (case insensitive), checked BEFORE shouldRetry and unconditional — even an explicit shouldRetry true can't retry a method outside it. Defaults to idempotent verbs, excluding post/patch: [GET,PUT,HEAD,DELETE,OPTIONS,TRACE].
  • Feature: jitter (true for uniform-random in [Duration.zero, delay), or a DiomanJitter function) and delayMax (a cap applied after jitter) — both apply only to this plugin's own computed delay, never to a Retry-After-derived wait.
  • Feature: Retry-After response-header support — respectRetryAfter (default true), afterStatusCodes (default [413,429,503], restricting which statuses trust the header even though they're otherwise retry-eligible), and retryAfterMax (an uncapped-by-default cap on the header-derived wait). Parses both a numeric-seconds value and an RFC 1123 HTTP-date.
  • Feature: the wait before a retry now races RequestOptions.cancelToken's whenCancel — cancelling mid-wait stops it immediately instead of idling until the timer fires only to find the request was already cancelled.
  • DiomanRetryOptions (the per-request extra['dioman:retry'] override) gained matching methods/statusCodes/jitter/delayMax/respectRetryAfter/afterStatusCodes/ retryAfterMax fields; extra['dioman:retry'] also now accepts a plain int (overrides max only) or false (disables retry for this request, highest-priority veto), not just a DiomanRetryOptions object.
  • Docs: README (EN/ZH) now link the live interactive demo.

0.4.1 #

Fixed: a DiomanCache hit and a DiomanShare follower's resolve() now both pass callFollowingResponseInterceptor: true, matching DiomanMock's existing behavior. Previously a cache hit or a share follower skipped onResponse of everything installed after it — most notably, DiomanNormalize never unwrapped a cached or follower response even though a live network response was unwrapped correctly. Both now flow through the rest of the chain exactly like a real response.

Significantly expanded automated test coverage (line coverage ~84% → ~99%), including full exercise of DiomanEnvs rule matching, DiomanRepath substitution, DiomanMock's mockUrl-redirect path, and DiomanShare's end/race policies, none of which had dedicated tests before.

0.4.0 #

Breaking: every plugin class renamed XxxPlugin → DiomanXxx (DioPlugin base → DiomanPlugin), and the 0.3.0 configProperty mechanism is gone — replaced by a fixed, non-reconfigurable name (which is the plugin's extra key) plus a typed DiomanXxxOptions class for every per-request override (no more dynamic bool/Map read with is/== checks inside a plugin):

  • AuthPlugin → DiomanAuth, CachePlugin → DiomanCache, CancelPlugin → DiomanCancel, EnvsPlugin → DiomanEnvs, FilterPlugin → DiomanFilter (already renamed from ReqcleanPlugin in 0.3.0), KeyPlugin → DiomanKey (already renamed from ReqkeyPlugin in 0.3.0), LoadingPlugin → DiomanLoading, LogPlugin → DiomanLog, MockPlugin → DiomanMock, NormalizePlugin → DiomanNormalize, RepathPlugin → DiomanRepath, RetryPlugin → DiomanRetry, SharePlugin → DiomanShare. Dioman.install's named parameters are unaffected (key:, filter:, etc.).
  • XxxPlugin.configProperty removed. name is now the fixed extra key (unchanged values: dioman:auth, dioman:qid, dioman:cache, dioman:share, dioman:mock, dioman:loading, dioman:log, dioman:retry, dioman:filter, dioman:repath, dioman:normalize) — it can no longer be remapped.
  • Every per-request extra value is now a DiomanXxxOptions instance instead of a raw bool/Map/enum — e.g. extra['dioman:cache'] = const DiomanCacheOptions(enabled: false) instead of extra['dioman:cache'] = false. DiomanAuthOptions drops the old function-typed per-call override (redundant with the constructor's isProtected callback); every other plugin's previous dynamic shapes map 1:1 onto named fields.
  • Every plugin constructor gained a matching enabled flag (default true) that disables the plugin entirely — on top of the per-request enabled in its DiomanXxxOptions. DiomanAuth's existing enable param was renamed enabled for consistency.
  • Every DiomanXxxOptions field now mirrors a constructor parameter 1:1 (excluding constructor-only dependencies like tokenManager/onRefresh/dio/onChanged that can't sensibly vary per call): DiomanCacheOptions.maxEntries, DiomanKeyOptions.fastMode/ ignoreParams/ignoreDataKeys, DiomanLogOptions.logRequest/logResponse/logError/ logHeaders/logBody/maxBodyLength, DiomanNormalizeOptions.dataKey/codeKey/ messageKey, DiomanRepathOptions.removeKey/pattern, DiomanShareOptions.retries/ interval, DiomanMockOptions.routes, and DiomanLoadingOptions.onChanged (documented as never consulted per-request — see below) are new.
  • Full constructor↔DiomanXxxOptions parity, and every new field is actually wired (read at request/response/error time), not just structurally mirrored: DiomanCacheOptions.shouldCache/ now, DiomanFilterOptions.predicate, DiomanKeyOptions.builder, DiomanMockOptions.fallbackWhen, DiomanNormalizeOptions.isSuccess/shouldNormalize, DiomanRetryOptions.delay/retryIf, DiomanLogOptions.writer, and on DiomanAuthOptions: onAccessDenied, onAccessExpired, onFailure, ready, isProtected, expiresAt, refreshLeeway, now, headerKey, buildHeader (still excluded: tokenManager, onRefresh — tied to the single shared refresh window, can't vary per call without breaking it for every concurrent caller).
  • DiomanAuth's internal token-manager parameter/field is now named tokenManager throughout (was tm in callback signatures and the private _tm field) for consistency with the constructor's own tokenManager parameter.
  • Every field and constructor parameter across all 13 plugins now has a bilingual (English + Chinese) doc comment.
  • Fix: every enabled (and other) field on DiomanXxxOptions is now nullable and defaults to null, not a hardcoded default like true/const []. null means "inherit whatever the constructor set" — a per-request override that only sets one field (e.g. expires) no longer silently resets enabled back to true on a plugin constructed with enabled: false.
  • Fix: List/Map-typed per-request overrides now merge (union) with the plugin's own defaults instead of replacing them outright — DiomanFilterOptions.ignoreKeys/ignoreValues, DiomanKeyOptions.ignoreParams/ignoreDataKeys, and DiomanMockOptions.routes all keep the plugin's defaults and the per-request additions.
  • Every onRequest/onResponse/onError now reads extra[name] and type-checks it into a local variable exactly once, then reuses that variable for every field — no more repeated override is DiomanXxxOptions checks scattered through a method.
  • Internal cross-plugin/bookkeeping extra keys are now built as '$name:detail' off each plugin's own fixed name (e.g. DiomanCache's dioman:cache:key/ttl/clone, DiomanAuth's dioman:auth:decision/protected/refreshed/denied/tokenUsed) instead of separately-typed-out literals — same values as 0.3.0, just derived rather than duplicated.

See the Quick start for full per-plugin usage.

0.3.0 #

  • Feature: DiomanHandle.remove<T>() ejects a single installed plugin from dio.interceptors and calls its own dispose(), leaving the rest of the chain untouched — the single-plugin counterpart to dispose()'s teardown-everything. Returns the removed plugin, or null (a no-op) if that type was never installed.

Breaking changes to every plugin's extra key:

  • Every plugin with a per-request extra option now exposes it as a mutable static String configProperty (e.g. DiomanLoading.configProperty) instead of a hardcoded string literal — read/write options.extra[XxxPlugin.configProperty], and reassign the static field to remap the key if it collides with another package's extra usage. Defaults: DiomanAuth → dioman:auth, DiomanKey → dioman:qid, DiomanCache → dioman:cache, DiomanShare → dioman:share, DiomanMock → dioman:mock, DiomanLoading → dioman:loading, DiomanLog → dioman:log, DiomanRetry → dioman:retry, DiomanFilter → dioman:filter, DiomanRepath → dioman:repath, DiomanNormalize → dioman:normalize.
  • All internal (plugin-private / cross-plugin coordination) extra keys dropped their underscore-prefixed form (_key, _cache_ttl, __auth_decision, ...) in favor of a namespaced dioman:<plugin>:<detail> form (dioman:cache:ttl, dioman:auth:decision, ...); the cross-plugin request key (kRequestKey) is now 'dioman:key'.
  • ReqkeyPlugin renamed to DiomanKey (reqkey_plugin.dart → key_plugin.dart, name: 'reqkey' → 'key', Dioman.install(reqkey: ...) → Dioman.install(key: ...)).
  • ReqcleanPlugin renamed to DiomanFilter (reqclean_plugin.dart → filter_plugin.dart, name: 'reqclean' → 'filter', Dioman.install(reqclean: ...) → Dioman.install(filter: ...)).

See the Quick start for full per-plugin usage.

0.2.0 #

First release of dioman — a set of composable, self-contained [Dio] interceptor plugins, all extending a common DiomanPlugin base (a named Interceptor with dispose), plus the documented correct install order (Dio runs onRequest/onResponse/onError in forward add-order for all phases). Plugins: DiomanEnvs, DiomanRepath, DiomanFilter, DiomanKey, DiomanNormalize, DiomanCache, DiomanShare, DiomanMock, DiomanCancel, DiomanLoading, DiomanAuth, DiomanRetry, DiomanLog. Wire them with Dioman.install or by hand.

Notable capabilities and behaviors:

  • Feature: DiomanAuth proactive refresh (opt-in) — pass expiresAt (+ optional refreshLeeway) to refresh an already-expired token before sending, so requests avoid a doomed 401 round-trip. Concurrent expiring requests collapse onto the existing single shared refresh window; the plugin stays an ordinary parallel Interceptor (no QueuedInterceptor). Off by default → purely reactive.
  • Feature: Dioman.install(dio, {...}) wires the given plugins in the canonical order and returns a DiomanHandle for lookup (plugin<T>()) and coordinated teardown (dispose() ejects every plugin and calls each one's dispose()).
  • DiomanCache: a cache hit now promotes the entry to most-recently-used (true LRU eviction, not merely oldest-write); the default clone is now CacheClone.shallow and is type-preserving (a Map<String, dynamic> stays one, so typed get<...>() doesn't break); added an injectable now clock for deterministic TTL tests.
  • DiomanNormalize: default envelope detection now requires codeKey and (dataKey or messageKey), so a plain payload that merely carries a code field isn't mistaken for an envelope.
  • DiomanKey: a non-serialisable body (FormData/bytes/stream) now folds in object identity, so two distinct bodies never key identically (no false dedup/cache).
  • DiomanAuth/DiomanShare/DiomanMock now reuse a single bare Dio for replays/retries/redirects (instead of allocating one per call) and close it on dispose.
  • Fix: DiomanShare.dispose now completes pending shared completers with an error before clearing _active (was leaving them dangling); DiomanMock gained a dispose that closes its redirect Dio.
  • Fix: DiomanAuth compared the formatted Authorization header against the raw store token, so the default Bearer builder made the refresh action unreachable (always fell through to replay/expire); token refresh is now correctly triggered, and a post-refresh replay carries the freshly refreshed token instead of the stale one.
  • Fix: DiomanAuth's onRequest rejects now propagate to earlier brackets (callFollowingErrorInterceptor: true), so DiomanCancel/DiomanLoading/DiomanShare release their state on a denied request instead of leaking a token / stuck spinner / dead completer.
  • Fix: DiomanShare.retry now actually retries up to retries times (previously gave up after one internal attempt) and properly settles the shared completer and removes the entry from _active on both success and exhaustion — previously a successful internal retry left every waiter (and every future request with the same key) permanently hung.
  • Fix: DiomanShare.end/race now deliver the correct cross-caller result (the last request for end, the winning sibling's result for race) to every caller, including superseded/losing ones — previously each caller only ever saw its own response.
  • Fix: DiomanMock inline handlers now decode the ResponseBody before resolving (previously .data held the raw undecoded stream wrapper); mock hits now propagate through normalize/cache/share (callFollowingResponseInterceptor: true) so envelopes are unwrapped and shared-request followers don't hang; the mock-server redirect no longer duplicates query parameters; the route key now matches DiomanKey's resolved-path scheme.
  • Fix: DiomanRetry now honors extra['retry'] == false on the business-retry (onResponse) path too, and gives up immediately after the back-off delay if the request was cancelled.
  • Fix: DiomanCancel re-registers a token it previously injected when DiomanRetry re-dispatches the same RequestOptions — previously cancelAll() silently stopped covering a request once it entered its first retry.
  • Fix: DiomanEnvs no longer resets a user-configured responseType back to the json default when an applied rule didn't explicitly set one.
  • DiomanCache gained maxEntries (default 500) to LRU-bound the store, which previously grew without limit under deep DiomanKey keys.
  • Added test/dioman_test.dart, a fake-adapter regression suite covering all of the above.
1
likes
160
points
684
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

A Dio-powered request wrapper with an onion pipeline, normalized results, and composable request policies for Dart and Flutter.

Repository (GitHub)
View/report issues

License

MIT (license)

Dependencies

dio

More

Packages that depend on dioman