Sharding.pollStorage: a bounded, awaitable form for runners hosted in a time-limited invocation

Abierto
#10,965 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
45/100
Tipo de issue
Nueva funcionalidad
Claridad
Bastante claro
Estado de actividad
Activo
Stack tecnológico
typescript

Línea de trabajo

Start by tracing Sharding.pollStorage and the storage read loop in the cluster implementation; the issue does not name specific files or tests. Check how the existing read limit, lock, and full-batch result are handled, then determine how an awaitable bounded call could report delivered messages and whether more are due. Done means the API shape is settled, the bounded read is covered by tests, and the existing pollStorage behavior remains available.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Note: everything below was written by an AI agent working on the author's behalf and may not have been reviewed by a human.

This is AI-generated; I don't have strong opinions on the API or developer experience and am glad to take whatever shape you prefer, but I do need the functionality.

Problem

I run SingleRunner inside one bounded invocation at a time: a Durable Object whose alarm wakes the runner, which then calls Sharding.pollStorage to deliver what is due and re-arms the alarm. The same shape fits any serverless host whose handler has a CPU or wall-clock limit. Each wake needs to do a bounded amount of work, return, and re-arm if more is due.

Sharding.pollStorage cannot be bounded or awaited:

  • It only opens the storage read latch (pollStorage: storageReadLatch.open) and returns at once, before anything is read.
  • The read loop then reads unprocessedMessageBatchSize rows (default 1,024) and, after a full batch that delivered something, reads again at once, until a batch comes back short. So one call delivers everything that is due, however much that is.
  • The caller learns neither how much was delivered nor whether more is due.

Measured

On main (db1629c626, Node 24.22.3), with the script below: N persisted messages to an entity, all due at one instant, entityMessagePollInterval set to an hour so that only pollStorage reads storage, then one pollStorage call:

Messages due pollStorage returned after Handled when it returned Handled after one call
100 0 ms 0 100 (within 250 ms)
1,000 0 ms 0 1,000 (within 250 ms)
3,000 0 ms 0 3,000 (2,088 at 250 ms, all by 500 ms)

Without the call, none of the 3,000 is delivered in 10 s, so the one call is what delivers all of them.

In a Durable Object (local workerd, Effect 4.1.4, SingleRunner + ClusterWorkflowEngine + @effect/sql-sqlite-do): N workflow executions all sleep to the same instant, and one alarm calls pollStorage and waits until nothing due is left:

Due at once Last wake late CPU for the drain Alarm
100 0.96 s 0.6 s 1, 424 ms wall
1,000 9.3 s 4.4 s 1, 3.56 s wall
3,000 28.5 s 11.6 s 1, 7.7 s wall, and the drain went on after the handler returned

At about 4 ms of CPU a wake, a backlog of about 7,500 due at once exceeds Cloudflare's default 30 s CPU limit in one invocation. The host's only bound today is to wrap MessageStorage.unprocessedMessages and hand out no rows once its budget is spent, which means reading the storage's row shapes.

Proposal

A bounded, awaitable form of pollStorage, for example:

// Runs one storage read of at most `limit` messages, delivers them, and returns.
readonly pollStorageBounded: (options: {
  readonly limit: number
}) => Effect.Effect<{ readonly delivered: number; readonly more: boolean }>
  • The read loop already reads with a limit (readAndProcess({ limit })), so this is mostly a way to run one read under the same lock and report its result, instead of opening the latch.
  • more would be true when the read was a full batch, as the loop already computes (fullBatch), so the host re-arms at once instead of waiting for its next poll.
  • pollStorage stays as it is.

@effect/platform-cloudflare's cluster does not implement pollStorage (each entity is its own Durable Object), so this is for Sharding / SingleRunner hosts.

Would you take this, and in which shape: a new member, an option on pollStorage, or something on SingleRunner? I'm glad to open the PR.

Reproduction

effect and @effect/sql-sqlite-node at main (or 4.1.6), run with node poll.ts 3000:

import { SqliteClient } from "@effect/sql-sqlite-node"
import { DateTime, Duration, Effect, Layer, PrimaryKey, Schema } from "effect"
import { ClusterSchema, DeliverAt, Entity, Sharding, SingleRunner } from "effect/cluster"
import * as Digest from "effect/crypto/Digest"
import { Rpc } from "effect/rpc"

const count = Number(process.argv[2] ?? 3000)
let handled = 0

class Job extends Schema.Class<Job>("Job")({ id: Schema.Number, at: Schema.DateTimeUtc }) {
  [PrimaryKey.symbol]() {
    return String(this.id)
  }
  [DeliverAt.symbol]() {
    return this.at
  }
}
const Worker = Entity.make("Worker", [Rpc.make("run", { payload: Job }).annotate(ClusterSchema.Persisted, true)])
const WorkerLayer = Worker.toLayer({ run: () => Effect.sync(() => void handled++) })

const program = Effect.gen(function*() {
  const sharding = yield* Sharding.Sharding
  const client = yield* Worker.client
  const at = DateTime.addDuration(yield* DateTime.now, Duration.seconds(2))
  for (let i = 0; i < count; i++) yield* client(`w${i}`).run(new Job({ id: i, at }), { discard: true })
  yield* Effect.sleep(Duration.seconds(2.5))
  yield* sharding.pollStorage // returns at once
  console.log("handled when pollStorage returned:", handled) // 0
  yield* Effect.sleep(Duration.seconds(1))
  console.log("handled after one call:", handled) // all of them
}).pipe(
  Effect.provide(WorkerLayer.pipe(Layer.provideMerge(SingleRunner.layer({
    runnerStorage: "memory",
    shardingConfig: { entityMessagePollInterval: Duration.hours(1) } // only pollStorage reads storage
  })))),
  Effect.provide(SqliteClient.layer({ filename: ":memory:" })),
  Effect.provide(Digest.layerWebCrypto),
  Effect.scoped
)

await Effect.runPromise(program)
Lenguaje dominante
TypeScript
Estrellas
16.7k
Forks
808
Merge medio
21 h 22 min
PR fusionados (30 d)
486

Preparar el entorno

Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de Effect-TS/effect

Todos los issues de Effect-TS/effect

Issues similares

Más issues de TypeScript

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.