Skip to main content

effect_core 0.0.3 copy "effect_core: ^0.0.3" to clipboard
effect_core: ^0.0.3 copied to clipboard

Lazy typed Dart effects with structured concurrency, scoped resources and dependency provision.

effect_core #

Lazy, typed asynchronous effects for Dart and Flutter. Describe a computation, compose it with other effects, and run it with explicit ownership of its resources.

Core release: 0.0.3.

The October 21 release includes effect_cache 0.0.1, effect_postgres 0.0.3, and effect_sql, effect_mysql, effect_http and effect_openai at 0.0.2. All adapters require effect_core ^0.0.3; database drivers also require effect_sql ^0.0.2. Pending-work limits can now reject overload; applications should handle the documented overload errors and set budgets for their workload.

Use the hosted dependencies below, or the local overrides for source development.

Features #

  • Lazy, reusable effects with typed expected failures.
  • Fibers, bounded concurrency, cancellation and awaited cleanup.
  • Scoped resources, dependency contexts and service layers.
  • Retry schedules, clocks, logging and same-isolate state primitives.
  • Pull-based streams and sinks with early exit and bounded buffering.
  • No runtime dependencies; core works on the Dart VM and web.

Installation #

Requires Dart 3.13 or later. Run:

dart pub add effect_core
# In a Flutter project:
flutter pub add effect_core

Or add these dependencies to pubspec.yaml:

dependencies:
  effect_core: ^0.0.3

Then run dart pub get or flutter pub get. Your Flutter installation must include a compatible Dart SDK.

Quick start #

Save as bin/main.dart and run dart run bin/main.dart:

import 'package:effect_core/effect_core.dart';

Future<void> main() async {
  final runtime = Runtime(Unit.value);
  final program = Effect.sync<int, String, Unit>(() => 21)
      .flatMap((value) => Effect.succeed(value * 2));

  try {
    print(await runtime.runFuture(program)); // 42
  } finally {
    await runtime.shutdown();
  }
}

Constructing program does not execute it. Each run evaluates it again. Effect<A, E, R> describes the returned value A, expected error E, and required environment R. Unit represents an empty environment.

Handle expected failures #

Use runExit when your API or UI needs to handle the result explicitly:

import 'package:effect_core/effect_core.dart';

Future<void> main() async {
  final runtime = Runtime(Unit.value);
  final request = Effect.fail<int, String, Unit>('Record not found');

  try {
    final result = await runtime.runExit(request);
    switch (result) {
      case Success(:final value):
        print(value);
      case Failure(:final cause):
        if (cause case Expected<String>(:final error)) {
          print(error); // Record not found
        } else {
          print('Request ended with ${cause.runtimeType}');
        }
    }
  } finally {
    await runtime.shutdown();
  }
}

Expected failures, programmer defects and interruption remain distinct. catchAll and retry recover only a standalone expected failure; they do not silently recover defects, interruption or composite cleanup failures.

Own a resource with a layer #

import 'package:effect_core/effect_core.dart';

Future<void> main() async {
  final service = ServiceKey<String>('greeting');
  final layer = Layer.resource<String, String>(
    service,
    Effect.sync<String, String, Context>(() => 'Hello from Effect'),
    (_) => Effect.sync<Unit, String, Context>(() {
      print('Resource released');
      return Unit.value;
    }),
  );
  final runtime = Runtime(Context());

  try {
    print(await runtime.runFuture(layer.use(service.effect<String>())));
  } finally {
    await runtime.shutdown();
  }
}

Layer.use owns the constructed service scope. The runtime waits for owned child fibers and finalizers before returning. For an application-wide service, keep the scope alive for the application's lifetime rather than rebuilding it per query.

Transform a stream #

import 'package:effect_core/effect_core.dart';

Future<void> main() async {
  final runtime = Runtime(Unit.value);
  final stream = EffectStream.fromIterable<int, String, Unit>([1, 2, 3, 4])
      .map((value) => value * 2)
      .filter((value) => value > 4)
      .buffer(2);

  try {
    print(await runtime.runFuture(stream.runCollect())); // [6, 8]
  } finally {
    await runtime.shutdown();
  }
}

runCollect retains every output value. Use a streaming sink or early-exit sink when collecting an entire stream would use too much memory.

Use with Flutter or an API server #

Core has no Flutter dependency. A widget/controller or server service can create its own Runtime, run effects from asynchronous handlers, and await shutdown when that owner closes. Flutter's synchronous dispose cannot itself await; provide an asynchronous close lifecycle in the runtime's owner.

For database and AI services, add only the integration you need:

Package Purpose Platform
effect_sql Shared SQL driver/transaction contracts VM and web with a compatible driver
effect_postgres PostgreSQL/PG through postgres Native VM; intended for server-side use
effect_mysql MySQL through mysql_client_plus Native VM; intended for server-side use
effect_openai Typed SDK HTTP requests and streams VM and web; keep API secrets server-side

Lifecycle and type boundaries #

Cancellation is cooperative. Without a cancellation hook, an underlying Future can continue after the fiber stops waiting. Timeout and shutdown await protected cleanup, so cleanup can extend the elapsed time. Fibers share an isolate and do not provide CPU parallelism.

Dart generic covariance means R documents requirements but is not a complete static proof of service provision. Context key presence is checked at runtime. Use explicit common error families and aggregate environments when composing services. Only map/flatMap/defer instruction chains have the advertised stack safety proof; arbitrary deeply nested region wrappers do not.

Roadmap and progress #

Roadmap updated: 21 October 2026. Seven packages are published: effect_core and effect_postgres at 0.0.3; effect_cache at 0.0.1; effect_sql, effect_mysql, effect_openai and effect_http at 0.0.2.

10 delivered milestones · 3 in progress · 5 planned · 1 awaiting input · 1 future proposals.

Draft PR #13 historical toolkit validation: 19 analyzers, 283 VM/Flutter tests and 226 Chrome tests. That draft contained thirteen new development packages; cache has since been released separately. The other twelve remain unpublished. Historical release validation includes 230 VM and 184 browser tests, real PostgreSQL/MySQL acceptance, and separately dated two native live Responses smoke checks. Broader live AI, production database and native Flutter acceptance remain open.

Priority Milestone Status
Delivered within scope Project website and documentation Delivered
Delivered within scope Reusable Effect runtime Delivered
Delivered within scope PostgreSQL and MySQL integrations Delivered
Delivered within scope OpenAI SDK integration Delivered
Delivered within scope Live OpenAI Responses smoke acceptance Delivered
Delivered within scope First pub.dev release Delivered
Delivered within scope OpenAI performance and bounded retention evidence Delivered
Delivered within scope Core and SQL performance and bounded retention Delivered
Next priorities Production database acceptance In progress
Next priorities Broader OpenAI live acceptance Awaiting input
Next priorities Runnable API and Flutter integration guides Planned
Next priorities Typed configuration, schemas and cache foundations In progress
Next priorities Advanced runtime, streams and schedule contracts Planned
Next priorities Complete tracing and exporter integrations Planned
Next priorities Native Flutter and broader platform acceptance Planned
Delivered within scope Reliability policies and HTTP/SSE integration Delivered
Next priorities Thirteen application toolkit package foundations In progress
Next priorities Toolkit API breadth and release preparation Planned
Future proposals RPC, workflows, clustering, CLI and GraphQL Proposed
Delivered within scope Cache lifecycle completion and dedicated acceptance Delivered

Next priorities are ordered above; production SQL acceptance is in progress. Trusted CA-chain and hostname checks passed for both drivers; recovery, network faults and soak remain open. Broader OpenAI acceptance needs an API-enabled test account. Future proposals need API design and scope agreement before implementation; they have no promised release version or date.

Follow the detailed roadmap for prerequisites and completion criteria, verified progress for evidence, and the feature matrix for operation-level support. Delivered means the documented scope is implemented and verified, not full Effect-TS parity or universal production acceptance.

Local development #

With access to the repository, clone it and add a pubspec_overrides.yaml beside your application's pubspec. Replace /path/to/effect_dart with your checkout:

dependency_overrides:
  effect_core:
    path: /path/to/effect_dart

Keep the version dependencies above in pubspec.yaml, then run dart pub get. The repository already contains overrides for its own examples. The source repository is currently private; repository access is required.

Examples and testing #

In a repository checkout, run:

dart analyze
dart test
dart test -p chrome
dart run example/retry.dart
dart run example/resources.dart
dart run example/bounded.dart
dart run example/services.dart
dart run example/stream.dart
dart run example/web.dart

The release validation recorded 107 VM and 107 Chrome tests for core. Type accept/reject fixtures are checked with dart run tool/check_fixtures.dart from the repository root. Native database and AI checks are separate from core tests.

Documentation and license #

MIT; see LICENSE. Independent and Effect-inspired; not affiliated with Effect-TS. The advertised scope is documented here, not full upstream parity.

Performance evidence #

Core and SQL benchmarks cover current JIT/AOT runtime workloads, direct Dart driver comparisons, post-GC retention and bounded database load. OpenAI measurements include SDK comparisons and native Flutter profile runs. These dated results expose measurable lifecycle overhead and remaining acceptance limits.

Reliability APIs in core 0.0.2 #

Core 0.0.2 adds retained timeout cleanup diagnostics, typed retries, capped backoff and Retry-After policies, independent jitter, elapsed retry budgets, lifecycle tracing/metrics, circuit breakers and rate limiting. An optional effect_http package provides HTTP/SSE support. See the contracts and verification boundaries and example/reliability.dart. The optional HTTP/SSE adapter is released as effect_http 0.0.1.

Cache development package #

The independently mergeable cache patch adds packages/effect_cache, optional monotonic clocks, Cause inspection and scoped acquisition. See cache contracts. The cache and core prerequisites remain unpublished. Other toolkit packages, ManagedRuntime, broader composition, streams and HTTP builders remain in draft PR #13 and are not part of this checkout.

memory and admission improvements #

The development branch includes the package memory fixes. These changes are not in the hosted versions above. Duration policies use the injected elapsed clock, error-cause conversion is stack safe, cache owners and service queues have finite admission budgets, and HTTP responses use packed bytes. Use one application-owned runtime and await its shutdown. Budget payload sizes and root/task creation at your API boundary as well as inside services.

For large streams, prefer a fold or runForEach; collecting remains explicit:

final bounded = stream.runCollect(
  maxItems: 1000,
  onLimit: () => AppFailure('Too many items'),
);

AppFailure must belong to the stream's declared error family. Pending queue saturation returns QueueFull; semaphore operations accept onFull for a typed application error. Event-queue fairness and protected finalization remain in place.

0
likes
150
points
99
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Lazy typed Dart effects with structured concurrency, scoped resources and dependency provision.

Homepage
Repository (GitHub)
View/report issues

License

MIT (license)

More

Packages that depend on effect_core