Skip to content

Effect essentials

The few Effect ideas these docs rely on - typed effects, streams, schemas, services and Layers.

Scwrap is built on Effect, a TypeScript library for programs whose results, failures and requirements are visible in their types. You do not need to know all of Effect to write a Scraper. This page covers the parts the guides use.

TIP

Scwrap uses Effect 4, which differs from Effect 3. Read the installed node_modules/effect/AGENTS.md, and the pinned sources that pnpm vendor:agent-sources fetches in the Scwrap repository, before copying examples from elsewhere.

The Effect type ​

An Effect describes work. It does nothing until something runs it.

ts
Effect.Effect<Success, Error, Requirements>
ParameterMeaning
SuccessWhat the work produces.
ErrorThe failures you expect, as types.
RequirementsThe services the work needs before it can run.

never in the last two positions means "cannot fail" and "needs nothing".

Familiar ideaIn Effect
async / awaitEffect.gen / yield*
A thrown error you expectA tagged error in the Error type
try / catch by kindEffect.catchTag
Retry with backoffEffect.retry with a Schedule
finallyA Scope with finalizers

Example (Sequencing work with a generator)

ts
const readPage = Effect.fn("Quotes.readPage")(function* readPage(
  page: number
) {
  const { quotes } = yield* Download.json(
    `${quotesOrigin}/api/quotes?page=${page}`,
    Page
  );

  yield* Effect.annotateCurrentSpan("rows", quotes.length);

  return quotes;
});

yield* waits for an Effect and gives you its result. If the Effect fails, the function stops there and fails the same way. Effect.fn("name") also names the function as a span in a trace.

You build the program first and run it once, at the edge: Effect.runPromise in a script, it.effect in a test, the instance's request handler in production.

Streams ​

A Stream is an Effect that produces many values over time.

ts
Stream.Stream<Item, Error, Requirements>

A Scraper's handler returns a Stream of items, or an Effect of all of them. A Stream can emit some items and then fail. The items already emitted stay emitted, which is why a failed Run can still have items.

FunctionUse
Stream.fromIterableEffectEmit every element of an array an Effect produces.
Stream.paginateEmit page after page until there is no next page.
Stream.unwrapRun an Effect first, then emit the Stream it returns.
Stream.runCollectRun a Stream and collect its items.
Stream.runForEachRun a Stream and handle each item as it arrives.

Schemas ​

A Schema describes a shape and checks values against it.

ts
export const Quote = Schema.Struct({
  author: Schema.NonEmptyString,
  tags: Schema.Array(Schema.NonEmptyString),
  text: Schema.NonEmptyString,
});

A schema has two sides. Encoded is the value as it travels, such as JSON. Type is the value your code works with. A Scraper's handler receives its input as Type, and Scraper.run emits items as Encoded.

Schemas also define errors. Because an error is a schema, it keeps its type across the network.

ts
export class RateLimited extends Schema.TaggedError<RateLimited>()(
  "RateLimited",
  {
    reason: Schema.String,
  }
) {}

Services and Layers ​

A service is an interface with a key. Code asks for a service by its key and does not care who implements it.

ts
const http = yield* HttpClient.HttpClient;

Asking for a service adds it to the Requirements of the surrounding Effect. The program cannot run until something provides it. Requirements travel outward: Download.json asks for the HttpClient, so every Effect and Stream built on it needs one too, up to the Implementation's Layer. A handler does not ask for the client itself.

A Layer is a recipe that builds services, and may need other services to do so.

ts
Layer.Layer<Provides, Error, Requires>
FunctionUse
Layer.succeed(Service, value)A Layer from a ready value. Tests use it for fakes.
Layer.effect(Service, effect)A Layer built by an Effect.
Layer.provide(dependency)Satisfy a Layer's requirements with another Layer.
Layer.mergeAll(a, b)Combine Layers side by side.
Effect.provide(layer)Give a program the services a Layer builds.

This is the whole idea behind Capabilities. An Implementation is a Layer. Its Requires are its Capabilities. A test, a script and a Release each call Layer.provide with a different provider, and the Implementation never changes.

ts
QuotesApiLive.pipe(Layer.provide(FetchHttpClient.layer));

QuotesApiLive.pipe(Layer.provide(Layer.succeed(HttpClient.HttpClient, fake)));

pipe applies functions left to right. a.pipe(f, g) is g(f(a)).

Scopes ​

A Scope is a lifetime. A resource opened in a scope is closed when the scope ends, whether the work succeeded, failed or was interrupted.

Browser.open and ProxiedHttpClient.route both need a Scope. When you call them inside a Stream, the Stream's own scope is used: the browser closes when the Stream ends. That is why the guides open expensive resources inside the handler's Stream and never when the Layer is built.

Native Effect first ​

Scwrap uses Effect's own modules before writing anything of its own:

NeedEffect module
A Scraper's contracteffect/rpc
HTTPeffect/http
AI modelseffect/ai
The scwrap CLIeffect/cli
Retries and schedulesEffect.retry, Schedule
Tests@effect/vitest

Scwrap adds code only where Effect has a gap: the proxy and captcha ports, the Browser port and the instance runtime.

Learn more ​