Skip to content

Scraper

Scraper.make declares a Definition, Scraper.layer implements it, and Scraper.run executes it with input and output checked.

The Scraper object is the centre of the domain SDK. It has four functions.

FunctionJob
Scraper.make(id, options)Declare a Definition.
Scraper.layer(definition, handler)Implement a Definition.
Scraper.run(definition, input)Run a Scraper in process, with input and output checked.
Scraper.rpc(definition)Read a Definition's ID and schemas.

Scraper.make ​

ts
Scraper.make(id, { input, output, error })
OptionMeaning
idThe Scraper's ID. It names the Release on an instance, the route /scrapers/<id>/run, the stored result and the scraper.id span attribute.
inputA schema for the Run's input.
outputA schema for one item.
errorA schema for every failure the Scraper can end with, usually a Schema.Union of error classes.

Example (A Definition)

ts
import {
  Blocked,
  QuotaExhausted,
  RateLimited,
  SchemaDrift,
  Scraper,
  UpstreamDown,
} from "@scwrap/domain";
import { Schema } from "effect";

export const Earthquakes = Scraper.make("earthquakes", {
  error: Schema.Union([
    Blocked,
    QuotaExhausted,
    RateLimited,
    SchemaDrift,
    UpstreamDown,
  ]),
  input: EarthquakeQuery,
  output: Earthquake,
});

A Definition is an effect/rpc RpcGroup with one streaming Rpc named by the ID. Scwrap adds no wrapper type, so everything effect/rpc offers works on it.

Everything else is derived ​

Never write a second description of a Scraper. These all come from the Definition:

DerivedBy
The input and output checks of a RunScraper.run
The typed run and items of the client@scwrap/client
The JSON Schemas in the instance catalog and the MCP tools The installed Release's Definition, read by the instance

Design the input ​

Make invalid input impossible to express. The Earthquakes input accepts only the feeds that exist:

ts
export const EarthquakeQuery = Schema.Struct({
  minMagnitude: Schema.Literals(["significant", "4.5", "2.5"]),
  period: Schema.Literals(["hour", "day", "week"]),
});

A caller cannot ask for a magnitude the source does not publish, so the Implementation never has to handle one.

Export the Definition alone ​

A Scraper package exports its Definition at a ./schema entry point, next to its full entry point.

ts
import { Earthquakes } from "@scwrap/earthquakes/schema";

Clients import ./schema. They get the contract and its types without the Implementation and its dependencies.

Scraper.layer ​

ts
Scraper.layer(definition, handler)

Scraper.layer turns one handler into an Implementation. The handler receives the decoded input and returns the items in one of two forms.

The handler returnsUse it when
A Stream of itemsItems arrive over time: page by page, round by round.
An Effect of all items, as an array or another iterableThe Scraper reads everything first and emits at the end.

Example (An Effect handler that needs an HttpClient)

ts
export const UsgsFeedLive = Scraper.layer(Earthquakes, readUsgsFeed);

Example (A Stream handler)

ts
export const QuotesApiLive = Scraper.layer(Quotes, ({ maxPages }) =>
  Stream.paginate(1, (page) =>
    readPage(page).pipe(
      Effect.map(({ has_next: hasNext, quotes }) => [
        quotes.map(({ author, tags, text }) => ({
          author: author.name,
          tags,
          text,
        })),
        hasNext && page < maxPages ? Option.some(page + 1) : Option.none(),
      ])
    )
  )
);

Three rules follow from the types.

The Layer's requirements are the Capabilities. Scraper.layer carries every requirement of the handler into the Layer. readUsgsFeed needs an HttpClient, so the type of UsgsFeedLive is Layer.Layer<Rpc.Handler<"earthquakes">, never, HttpClient.HttpClient>. Nothing else declares what the Scraper needs, and the handler does not capture its Capabilities first.

Undeclared errors do not compile. The handler may fail only with errors in the Definition's error schema. Map every other failure to a declared one, or add it to the Definition.

One Definition, several Implementations. An API reader and a browser reader can fulfil the same Definition. A Release uses exactly one. There is no fallback between them: a consumer that wants a second source when the first fails composes two Scrapers itself.

A Definition is an RpcGroup, so Definition.toLayer({ [id]: handler }) builds the same Layer from a Stream handler keyed by the Scraper's ID.

Keep expensive resources lazy ​

Open browsers and proxy routes inside the handler, not while the Layer is built. Then nothing starts before a Run asks for items.

An Effect handler runs in the Scope of its Run, which closes when the Run ends, fails or is interrupted. A Stream handler opens its resources with Stream.unwrap or Stream.scoped, which use the Stream's scope.

Scraper.run ​

ts
Scraper.run(definition, input)

Scraper.run is how a Scraper is executed in process. An instance and every test run through it; tests usually call it through ScraperTest.run. It returns a Stream of encoded items and needs the Implementation Layer.

Example (Running a Scraper)

ts
import { Scraper } from "@scwrap/domain";
import { Earthquakes, UsgsFeedLive } from "@scwrap/earthquakes";
import { Effect, Layer, Stream } from "effect";
import { FetchHttpClient } from "effect/http";

const items = await Effect.runPromise(
  Stream.runCollect(
    Scraper.run(Earthquakes, { minMagnitude: "significant", period: "week" })
  ).pipe(
    Effect.provide(UsgsFeedLive.pipe(Layer.provide(FetchHttpClient.layer)))
  )
);

It does five things, in order:

  1. Opens a Scraper.run span with the scraper.id attribute.
  2. Decodes the JSON input against the input schema and rejects unknown fields. A mismatch fails with InvalidInput, and the handler is never called.
  3. Calls the handler through effect/rpc's in-process client.
  4. Encodes every item through the output schema. An item that does not encode fails the Run with SchemaDrift, carrying a 500-character sample.
  5. Passes the handler's declared errors through unchanged.

Why it encodes every item ​

effect/rpc checks items only when they cross a serialized transport. Scraper.run calls the handler directly, so it checks the output itself. Whatever runs a Scraper, every item a caller sees has passed the Definition.

Outcomes ​

SituationThe Stream
Input fails the DefinitionFails with InvalidInput. Nothing ran.
The handler completes, even with zero itemsCompletes. An empty result is a success.
The handler fails with a declared errorFails with that error, after the items emitted before it.
The handler emits an item that breaks the output schemaFails with SchemaDrift, after the items emitted before it.

There is no deduplication. Items are emitted as the handler produces them, and whoever consumes them decides what a duplicate is.

A Run that fails after emitting items is a Partial Run. Its items stay delivered. On an instance they stay stored, and the result record says the Run failed.

Scraper.rpc ​

Scraper.rpc(definition) returns the Definition's single Rpc as an Effect. Use it when code needs the ID or the schemas of a Definition it was handed.

ts
const rpc = yield* Scraper.rpc(definition);

rpc._tag;
rpc.payloadSchema;
rpc.successSchema.success;
rpc.successSchema.error;

The client uses it to encode inputs and decode items. You rarely need it in a Scraper.

Types ​

TypeMeaning
ScraperDefinition<Tag, Input, Output, Error>A Definition with its four type parameters.
ScraperHandler<Definition>The service an Implementation Layer provides.
ScraperRpc<Tag, Input, Output, Error>The Rpc inside a Definition.

Source ​