dioman 0.8.4
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
homepageandrepositorynow point to the package directory on themainbranch.
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
ArgumentErrorfor a plainList<int>body holding negative or >255 values; onlyUint8Listis treated as raw bytes (hash plus full base64, up to 64 KiB), every otherListis encoded as a JSON array. A plainList<int>and aUint8Listwith the same content now produce different keys. - Docs: README states the Dio ^5.4.0 floor and the
Uint8Listkey rule;example/real_run.dartcoversdecode,rawanddeadline.
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 demonstratedecodeand a defaultdeadline.
0.8.0 #
-
Dependency: minimum
dioraised from 5.0.0 to 5.4.0 (earlier versions lackBaseOptions.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.nativeis 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 setDiomanAuth.option: falsefor that call. -
Behavior change (B8):
retryAfterMaxdefaults 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 ordelayMaxis 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.installand interceptor handles with aDiomanclient so every logical request uses the same pipeline. Construct the client withdioandplugins, and callapi.get/api.send; useuse,ejectandinspectfor 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
DiomanResponsefromsend, so callers and plugins share one result model. Replaceresponse.dataafterdio.getwith the value fromapi.get; usesendfor 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)?.kindandfailureOf(result)?.reasonto represent expected failures consistently. CatchDiomanResponsearound verb methods, or inspect the result ofsend; 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.extraintoDiomanCalland plugin option keys to separate configuration from internal state. Usequeryinstead ofqueryParameters; passfalseto 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. ChangeonFailure(store, response)toonFailure(result, store)and read HTTPresult.statusor businessresult.code; the callback may now be asynchronous. Return aRequestPatchfromreadyinstead 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
DiomanRequestand returning data or a DioResponse; 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,validateand anchor insertion with fixed stages andenforce: pre/post. This makes replay follow the same inner pipeline; move custom extensions tosetup/handleand 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,DiomanResponseFactoryanddebugor DioLogInterceptor. - Breaking: Make retry, breaker and auth consume
ctx.statusOf(result); cache consumesok. Update predicates to distinguish HTTPstatus, businesscodeandok; 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.canRefreshbecause 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
onRefreshexceptions as refresh failure. - Breaking: Remove per-request clocks, unused per-request cache capacity and cache/share
nonepolicies. Use the client clock, plugin capacity and request-levelfalse; 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)andapi.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 withDioException. - 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
onRequestand hand off the true final outcome), so public requests, mock short-circuits and auth's early hand-off can no longer hang or mis-settleDiomanSharewaiters, and removing/rebinding auth/retry leaves no stale registration.DiomanShare.registerDownstreamSettler,hasMultipleDownstreamSettlersand theshare/cancelsetters onDiomanAuth/DiomanRetryare deprecated no-ops. - Fix share forwarding: typed response/error forwarders (no dynamic
handler.reject(e, true)on anErrorInterceptorHandler, which throws on dio 5.9); every follower/loser gets its ownResponsebound to its ownRequestOptions; followers never re-run retry/auth recovery. - Fix recovered results skipping later processing: an auth refresh replay, retry success and share
policy: retrysuccess now flow through the interceptors installed after them (normalize, breaker, log), matching a first-time success. Adddiosetter onDiomanShare/DiomanAuth/DiomanRetry(bound byDioman.install/DiomanHandle); replays reuse the host'shttpClientAdapter/transformer, cloneFormData, and never auto-replay aStreambody. - 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-awareTimer), 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/onRetrybecome aDioExceptionand the handler completes exactly once.DiomanTimeoutresolves 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 whilereject(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
DiomanShareend/racearbitration: a loser that fails in share's error stage now finishes through the same path as a first success (downstreamonResponsecleanup, 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 byisProtected/expiresAt/now/buildHeaderin the request stage become aDioException(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'sCancelToken, 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'sexpiresAt), so it can no longer delete a fresher entry written for the same key in the meantime. - Fix
shareend/racecorner cases:DiomanRetryno 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 fromshouldRetry/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 bycancelAll()and is cancelled promptly. - Known limitations: a recovered result handed to a downstream
QueuedInterceptorcalls itsonResponsedirectly and so bypasses that interceptor's own serialization queue; reusing oneCancelTokenacross many requests accumulates a cancel listener per back-off/refresh wait (released when the token is garbage collected or cancelled). - Feature:
DiomanBreakernow reclaims idle buckets lazily (on new-bucket creation, no timer). New optionalidleTtl(default 1 hour) andmaxBuckets(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 addsbucketCountand an injectableclockfor tests. - Feature: declarative plugin ordering.
DiomanPlugin.ordering(DiomanPluginOrder(before, after, requires), default none) lets plugins state ordering constraints; newDioman.sort(stable topological sort),Dioman.validate,Dioman.installPluginsand an optionalplugins:argument onDioman.installfor custom plugins. Duplicate names, cycles, missing required plugins and violated constraints throwDiomanPluginOrderExceptionnaming the plugins involved (beforediois touched);DiomanHandle.insertBefore/insertAfter/prepend/appendvalidate before mutating andremoverefuses to drop a plugin another one requires. Built-ins declare only the README's hard constraints, soDioman.install's order is unchanged. - Feature:
DiomanExtraKeysregistry of everyextrakey (public config / cross-plugin protocol / internal state) with owner plugin and value type,findSharedState/DiomanHandle.diagnoseSharedStateKeys/assertNoSharedStateto diagnose duplicate plugin instances sharing state keys, andregisterfor 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-suppliedprobe: () => NetworkQuality(excellent/good/poor/none) selects aDiomanTimeouts(connect?, receive?, send?)from a tier map; only non-null fields are written, so a partially-configured tier leaves the other timeouts asBaseOptionsset them, and a tier absent from the map is a no-op. Pure config, no request/response coupling — install right afterDiomanEnvs. Per-requesttimeoutsmerge by tier. - Feature:
DiomanOffline(offline_plugin.dart,dioman:offline) — offline queue-and-replay. Parks a request (captures its handler, does NOT callnext) while a host-suppliedisOnline: () => boolreports offline; atrueevent on the injectedonConnectivityChanged: Stream<bool>(or a manualflush()) resumes each parked request down the rest of the chain.shouldQueuegates what's parked (reads normally pass through to cache),maxQueueSize(default 50, oldest evicted with aqueueFullrejection) andmaxWait(default unbounded,timeoutrejection) bound the queue, anddispose()rejects everything pending. Rejections wrapDiomanOfflineExceptionin a response-lessDioExceptionsoDiomanRetrywon't retry them. Install afterDiomanCache, beforeDiomanShare. - Feature:
DiomanBreaker(breaker_plugin.dart,dioman:breaker) — circuit breaker, one bucket perMETHOD:path(override viakeyBuilder).closed → open → halfOpen:failureThreshold(default 10) consecutive failures trip open,resetDuration(default 30s) cooldown thenhalfOpenMaxCalls(default 3) probes decide recovery. Open buckets fail fast inonRequestwith a response-lessDiomanBreakerOpenException(not retried byDiomanRetry's default). Install AFTERDiomanRetryso it counts only each top-level request's final outcome.DiomanRetry.breakersetter (auto-wired byDioman.install) lets an in-progress retry loop stop the instant the breaker trips.shouldTrip/onStateChangehooks; a usercancelis recorded as neither success nor failure so it can't reset the consecutive-failure count. Dioman.installgainstimeout:/offline:/breaker:parameters, slotted into the canonical orderenvs → timeout → repath → filter → key → cache → offline → share → mock → cancel → loading → auth → retry → breaker → log → normalize, and auto-wiresretry.breaker = breaker.
0.6.0 #
- Breaking:
ApiExceptionrenamed toDiomanException(normalize_plugin.dart) — update anycatch/is/assites and theerror:objectDiomanNormalizerejects with. - Breaking:
DiomanCachegains a durable persistence layer.persist: DiomanCachePersistis a new required constructor parameter — there is no built-in no-op implementation, so every existingDiomanCache(...)call site needs one (implementread/write/remove/eraseyourself; the shape mirrors theget_storagepackage's container API —readmay be sync or async (FutureOr),write/remove/erasealways async). A newcachePolicy: DiomanCachePolicy(nonedefault /memo/persist/both, also overridable per request viaDiomanCacheOptions.cachePolicy) picks where a cached entry lives:nonenever caches,memois the old in-memory-only behavior,persistuses only the durable layer,bothkeeps memory and persist in sync (a memory miss falls back topersist.readand backfills memory). Note the default changed from an implicit always-on memory cache toDiomanCachePolicy.none— passcachePolicy: memoexplicitly to keep the old behavior. - Breaking:
DiomanCache.removeWhere()/.sizeremoved —DiomanCachePersisthas no key-enumeration capability, so these could never be correct once apersist/bothpolicy is in play (silently a no-op / always0).remove(key)andclear()stay — both already touchpersistunconditionally and work correctly under every policy.
0.5.1 #
- Feature: each plugin's fixed name/
extrakey is now also exposed as a publicstatic const pluginNameon the class (e.g.DiomanCache.pluginName), so callers can reference a plugin's key without constructing an instance. The instanceString get namegetter 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 nowbool?(wasbool) — an exacttrue/falsestill wins outright, butnull(including whenshouldRetryisn't set at all) now falls through to the newstatusCodestable instead of a hardcoded "≥500 or a timeout/connection error" default.statusCodesdefaults 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 nowDuration Function(int current, int max, Response<dynamic>? response, DioException? err)(wasDuration Function(int attempt)), and its default changed from exponential back-off (1s/2s/4s) to a flat 3000ms — matching axp'sIRetryOptions.delay. Existingdelay: (_) => ...callbacks need an extra three params. - Feature:
methods— aList<String>whitelist of HTTP methods eligible for retry (case insensitive), checked BEFOREshouldRetryand unconditional — even an explicitshouldRetrytruecan't retry a method outside it. Defaults to idempotent verbs, excluding post/patch:[GET,PUT,HEAD,DELETE,OPTIONS,TRACE]. - Feature:
jitter(truefor uniform-random in[Duration.zero, delay), or aDiomanJitterfunction) anddelayMax(a cap applied after jitter) — both apply only to this plugin's own computeddelay, never to aRetry-After-derived wait. - Feature:
Retry-Afterresponse-header support —respectRetryAfter(defaulttrue),afterStatusCodes(default[413,429,503], restricting which statuses trust the header even though they're otherwise retry-eligible), andretryAfterMax(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'swhenCancel— cancelling mid-wait stops it immediately instead of idling until the timer fires only to find the request was already cancelled. DiomanRetryOptions(the per-requestextra['dioman:retry']override) gained matchingmethods/statusCodes/jitter/delayMax/respectRetryAfter/afterStatusCodes/retryAfterMaxfields;extra['dioman:retry']also now accepts a plainint(overridesmaxonly) orfalse(disables retry for this request, highest-priority veto), not just aDiomanRetryOptionsobject.- 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 fromReqcleanPluginin 0.3.0),KeyPlugin→DiomanKey(already renamed fromReqkeyPluginin 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.configPropertyremoved.nameis now the fixedextrakey (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
extravalue is now aDiomanXxxOptionsinstance instead of a rawbool/Map/enum — e.g.extra['dioman:cache'] = const DiomanCacheOptions(enabled: false)instead ofextra['dioman:cache'] = false.DiomanAuthOptionsdrops the old function-typed per-call override (redundant with the constructor'sisProtectedcallback); every other plugin's previous dynamic shapes map 1:1 onto named fields. - Every plugin constructor gained a matching
enabledflag (defaulttrue) that disables the plugin entirely — on top of the per-requestenabledin itsDiomanXxxOptions.DiomanAuth's existingenableparam was renamedenabledfor consistency. - Every
DiomanXxxOptionsfield now mirrors a constructor parameter 1:1 (excluding constructor-only dependencies liketokenManager/onRefresh/dio/onChangedthat 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, andDiomanLoadingOptions.onChanged(documented as never consulted per-request — see below) are new. - Full constructor↔
DiomanXxxOptionsparity, 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 onDiomanAuthOptions: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 namedtokenManagerthroughout (wastmin callback signatures and the private_tmfield) for consistency with the constructor's owntokenManagerparameter.- Every field and constructor parameter across all 13 plugins now has a bilingual (English + Chinese) doc comment.
- Fix: every
enabled(and other) field onDiomanXxxOptionsis now nullable and defaults tonull, not a hardcoded default liketrue/const [].nullmeans "inherit whatever the constructor set" — a per-request override that only sets one field (e.g.expires) no longer silently resetsenabledback totrueon a plugin constructed withenabled: 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, andDiomanMockOptions.routesall keep the plugin's defaults and the per-request additions. - Every
onRequest/onResponse/onErrornow readsextra[name]and type-checks it into a local variable exactly once, then reuses that variable for every field — no more repeatedoverride is DiomanXxxOptionschecks scattered through a method. - Internal cross-plugin/bookkeeping
extrakeys are now built as'$name:detail'off each plugin's own fixedname(e.g.DiomanCache'sdioman:cache:key/ttl/clone,DiomanAuth'sdioman: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 fromdio.interceptorsand calls its owndispose(), leaving the rest of the chain untouched — the single-plugin counterpart todispose()'s teardown-everything. Returns the removed plugin, ornull(a no-op) if that type was never installed.
Breaking changes to every plugin's extra key:
- Every plugin with a per-request
extraoption now exposes it as a mutablestatic String configProperty(e.g.DiomanLoading.configProperty) instead of a hardcoded string literal — read/writeoptions.extra[XxxPlugin.configProperty], and reassign the static field to remap the key if it collides with another package'sextrausage. 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)
extrakeys dropped their underscore-prefixed form (_key,_cache_ttl,__auth_decision, ...) in favor of a namespaceddioman:<plugin>:<detail>form (dioman:cache:ttl,dioman:auth:decision, ...); the cross-plugin request key (kRequestKey) is now'dioman:key'. ReqkeyPluginrenamed toDiomanKey(reqkey_plugin.dart→key_plugin.dart,name: 'reqkey'→'key',Dioman.install(reqkey: ...)→Dioman.install(key: ...)).ReqcleanPluginrenamed toDiomanFilter(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:
DiomanAuthproactive refresh (opt-in) — passexpiresAt(+ optionalrefreshLeeway) 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 parallelInterceptor(noQueuedInterceptor). Off by default → purely reactive. - Feature:
Dioman.install(dio, {...})wires the given plugins in the canonical order and returns aDiomanHandlefor lookup (plugin<T>()) and coordinated teardown (dispose()ejects every plugin and calls each one'sdispose()). DiomanCache: a cache hit now promotes the entry to most-recently-used (true LRU eviction, not merely oldest-write); the default clone is nowCacheClone.shallowand is type-preserving (aMap<String, dynamic>stays one, so typedget<...>()doesn't break); added an injectablenowclock for deterministic TTL tests.DiomanNormalize: default envelope detection now requirescodeKeyand (dataKeyormessageKey), so a plain payload that merely carries acodefield 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/DiomanMocknow reuse a single bareDiofor replays/retries/redirects (instead of allocating one per call) and close it ondispose.- Fix:
DiomanShare.disposenow completes pending shared completers with an error before clearing_active(was leaving them dangling);DiomanMockgained adisposethat closes its redirect Dio. - Fix:
DiomanAuthcompared the formattedAuthorizationheader 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'sonRequestrejects now propagate to earlier brackets (callFollowingErrorInterceptor: true), soDiomanCancel/DiomanLoading/DiomanSharerelease their state on a denied request instead of leaking a token / stuck spinner / dead completer. - Fix:
DiomanShare.retrynow actually retries up toretriestimes (previously gave up after one internal attempt) and properly settles the shared completer and removes the entry from_activeon 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/racenow deliver the correct cross-caller result (the last request forend, the winning sibling's result forrace) to every caller, including superseded/losing ones — previously each caller only ever saw its own response. - Fix:
DiomanMockinline handlers now decode theResponseBodybefore resolving (previously.dataheld 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 matchesDiomanKey's resolved-path scheme. - Fix:
DiomanRetrynow honorsextra['retry'] == falseon the business-retry (onResponse) path too, and gives up immediately after the back-off delay if the request was cancelled. - Fix:
DiomanCancelre-registers a token it previously injected whenDiomanRetryre-dispatches the sameRequestOptions— previouslycancelAll()silently stopped covering a request once it entered its first retry. - Fix:
DiomanEnvsno longer resets a user-configuredresponseTypeback to thejsondefault when an applied rule didn't explicitly set one. DiomanCachegainedmaxEntries(default 500) to LRU-bound the store, which previously grew without limit under deepDiomanKeykeys.- Added
test/dioman_test.dart, a fake-adapter regression suite covering all of the above.