@gjermundgaraba/effect-actions-cloudflare 0.21.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/ActionDurableObject.d.mts +7 -1
  2. package/dist/ActionDurableObject.mjs +7 -7
  3. package/dist/alarm.d.mts +15 -6
  4. package/dist/alarm.mjs +42 -39
  5. package/dist/batches.mjs +0 -1
  6. package/dist/calls.mjs +0 -11
  7. package/dist/events.mjs +0 -15
  8. package/dist/frames.mjs +6 -9
  9. package/dist/idempotency.mjs +2 -8
  10. package/dist/placed.mjs +0 -4
  11. package/dist/sockets.d.mts +0 -4
  12. package/dist/sockets.mjs +7 -14
  13. package/dist/stub.d.mts +4 -4
  14. package/dist/stub.mjs +9 -8
  15. package/dist/subscriptions.mjs +10 -22
  16. package/dist/tasks.mjs +3 -8
  17. package/dist/webhooks.mjs +5 -21
  18. package/docs/ActionDurableObject-events.md +0 -20
  19. package/docs/ActionDurableObject-failures.md +1 -1
  20. package/docs/ActionDurableObject-placement.md +1 -4
  21. package/docs/ActionDurableObject-stub.md +3 -31
  22. package/docs/ActionDurableObject-testing.md +0 -5
  23. package/docs/ActionDurableObject.md +4 -50
  24. package/docs/README.md +1 -1
  25. package/examples/chat-rooms/README.md +2 -2
  26. package/examples/chat-rooms/src/Api.ts +0 -3
  27. package/examples/chat-rooms/src/Rpc.ts +0 -7
  28. package/examples/chat-rooms/src/browser.ts +2 -34
  29. package/examples/chat-rooms/src/chat/Chat.ts +3 -23
  30. package/examples/chat-rooms/src/chat/activity.ts +0 -5
  31. package/examples/chat-rooms/src/chat/authorize.ts +0 -3
  32. package/examples/chat-rooms/src/chat/events.ts +0 -12
  33. package/examples/chat-rooms/src/chat/handlers.ts +0 -6
  34. package/examples/chat-rooms/src/chat/room.ts +2 -7
  35. package/examples/chat-rooms/src/chat/store.ts +0 -6
  36. package/examples/chat-rooms/src/identity/Identity.ts +0 -6
  37. package/examples/chat-rooms/src/identity/members.ts +1 -3
  38. package/examples/chat-rooms/src/identity/verifier.ts +6 -9
  39. package/examples/chat-rooms/src/lobby/Calls.ts +0 -5
  40. package/examples/chat-rooms/src/lobby/Lobby.ts +2 -7
  41. package/examples/chat-rooms/src/lobby/events.ts +0 -5
  42. package/examples/chat-rooms/src/lobby/handlers.ts +0 -3
  43. package/examples/chat-rooms/src/lobby/host.ts +0 -1
  44. package/examples/chat-rooms/src/lobby/store.ts +2 -4
  45. package/examples/chat-rooms/src/platform/kv-previews.ts +6 -5
  46. package/examples/chat-rooms/src/platform/lobby-stubs.ts +0 -15
  47. package/examples/chat-rooms/src/platform/sql-store.ts +1 -13
  48. package/examples/chat-rooms/src/rooms-entrypoint.ts +2 -10
  49. package/examples/chat-rooms/src/routes.ts +0 -25
  50. package/examples/chat-rooms/src/worker.ts +3 -24
  51. package/examples/chat-rooms/test/platform/sql-store.test.ts +0 -5
  52. package/examples/chat-rooms/test/support/socket.ts +0 -9
  53. package/examples/chat-rooms/test/worker.test.ts +17 -24
  54. package/examples/chat-rooms/vite.config.ts +0 -5
  55. package/package.json +3 -3
  56. package/examples/chat-rooms/node_modules/.vite/vitest/CACHEDIR.TAG +0 -3
  57. package/examples/chat-rooms/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -5,7 +5,7 @@ import { RpcClient, RpcSerialization } from "effect/rpc";
5
5
  import { Socket } from "effect/socket";
6
6
 
7
7
  import { MessagePosted } from "./chat/Chat.js";
8
- import type { RoomName } from "./chat/Chat.js";
8
+ import type { DemoRoomName } from "./chat/Chat.js";
9
9
  import { PreviewsChanged } from "./lobby/Lobby.js";
10
10
  import {
11
11
  LobbyRpc,
@@ -14,17 +14,6 @@ import {
14
14
  unsupportedProtocol,
15
15
  } from "./Rpc.js";
16
16
 
17
- // Client module: what a web page imports. It holds the binding and nothing of the server.
18
-
19
- // Effect's own client protocol, one WebSocket to an object, speaking JSON: the socket's URL is
20
- // `wss://<host>/rooms/<room>/rpc` for a room and `wss://<host>/lobby/rpc` for the lobby, given the version of the rpcs the page was built
21
- // with. An object serving another closes the socket at once with `unsupportedProtocol`, which
22
- // fails every call and stream with a `SocketCloseError` of that code; `reconnectUntil` stops
23
- // the client there, which Effect's own policy would not, connecting again every five seconds,
24
- // each attempt waking the object: show "reload". The layer owns the socket, so provide it
25
- // once, around the page's whole program; a page provides `Socket.layerWebSocketConstructorGlobal`, the browser's own
26
- // WebSocket. The client pings every five seconds and the object's runtime answers, so a page
27
- // left open does not wake the object.
28
17
  export const connection = (url: string) =>
29
18
  RpcClient.layerProtocolSocket({
30
19
  retryPolicy: ActionRpc.reconnectUntil(unsupportedProtocol),
@@ -33,27 +22,18 @@ export const connection = (url: string) =>
33
22
  Layer.provide(RpcSerialization.layerJson)
34
23
  );
35
24
 
36
- // A room as a page uses it, over the socket to that room's object: each call names the room, as
37
- // every call of a room does, and the object refuses one naming another. A browser WebSocket sets
38
- // no header when it connects, so the token travels on each message; a client that can set headers
39
- // on the upgrade, such as a Worker or a native app, sends it once there, and the socket keeps it.
40
- export const openRoom = (room: RoomName, token: string) =>
25
+ export const openRoom = (room: DemoRoomName, token: string) =>
41
26
  Effect.gen(function* () {
42
27
  const client = yield* ActionRpc.client(RoomRpc);
43
28
  const headers = { authorization: `Bearer ${token}` };
44
29
  const signedIn = RpcClient.withHeaders(headers);
45
30
 
46
31
  return {
47
- // The room's messages after `after`, the id of the last one the page holds: 0 reads them
48
- // all.
49
32
  read: (after: number) =>
50
33
  client.readMessages({ room, after }).pipe(
51
34
  signedIn,
52
35
  Effect.map(({ messages }) => messages)
53
36
  ),
54
- // A post the socket lost, as the room's object restarted, fails with an `RpcClientError`,
55
- // whether or not it reached the room: sent again with its `request`, made once for the
56
- // message, it is posted once.
57
37
  post: (text: string) =>
58
38
  Effect.flatMap(
59
39
  Effect.sync(() => crypto.randomUUID()),
@@ -66,14 +46,6 @@ export const openRoom = (room: RoomName, token: string) =>
66
46
  })
67
47
  )
68
48
  ),
69
- // Each message posted to the room after `after`, the id of the last one the page holds: a
70
- // page opening the room reads it, then watches from the last id it read, so a post between
71
- // the two is not lost. The room's object keeps the watch while it hibernates, and resumes it
72
- // when it next wakes, authenticating its token again: a token that expired meanwhile ends
73
- // the watch with `Unauthenticated`, so watch again with a fresh one. `watch` connects again
74
- // after a drop and resumes from the last message it delivered; a `Gap` says some were
75
- // missed, which the page reads with `read`. The headers go with the stream, as `signedIn`
76
- // puts them on a call, and so with every request it sends again.
77
49
  messages: (after: number) =>
78
50
  client
79
51
  .watch(MessagePosted, { room }, { cursor: String(after) })
@@ -95,10 +67,6 @@ export const openRoom = (room: RoomName, token: string) =>
95
67
  };
96
68
  });
97
69
 
98
- // The lobby as a page follows it, signed in or not: every room's preview, first as it is, then
99
- // whole again at each change. A watch given no cursor starts with the previews, so the page reads
100
- // nothing first; after a drop it resumes from the last it received, and hears the previews again
101
- // only if they changed meanwhile. A `Gap` needs no read either: the next occurrence is whole.
102
70
  export const followLobby = Effect.map(ActionRpc.client(LobbyRpc), (client) =>
103
71
  client.watch(PreviewsChanged, {}).pipe(
104
72
  Stream.filter((received) => Predicate.isTagged(received, "Occurrence")),
@@ -4,15 +4,10 @@ import { Schema } from "effect";
4
4
 
5
5
  import { CurrentMember } from "../identity/Identity.js";
6
6
 
7
- // DEMO ONLY: the rooms, fixed. Each name is one Durable Object, which the Worker reaches only
8
- // for a name listed here, so no caller creates an object of its own. A real application keeps
9
- // its rooms in a store and checks a name there before it reaches `getByName`.
10
- export const RoomName = Schema.Literals(["general", "design"]);
7
+ export const DemoRoomName = Schema.Literals(["general", "design"]);
11
8
 
12
- export type RoomName = typeof RoomName.Type;
9
+ export type DemoRoomName = typeof DemoRoomName.Type;
13
10
 
14
- // A message's `id` counts up within its room, so a client asks for what came after the last
15
- // one it holds. `at` is when it was posted, in milliseconds: messages expire a day later.
16
11
  export const Message = Schema.Struct({
17
12
  id: Schema.Int,
18
13
  author: Schema.String,
@@ -22,8 +17,6 @@ export const Message = Schema.Struct({
22
17
 
23
18
  export type Message = typeof Message.Type;
24
19
 
25
- // A declared error is part of the contract: every client decodes it as this class. Its status is
26
- // for the JSON routes; an rpc carries none.
27
20
  export class MessageNotFound extends Schema.TaggedError<
28
21
  MessageNotFound,
29
22
  { readonly brand: unique symbol }
@@ -34,16 +27,10 @@ export class NotAuthor extends Schema.TaggedError<
34
27
  { readonly brand: unique symbol }
35
28
  >()("NotAuthor", { id: Schema.Int }, { httpApiStatus: 403 }) {}
36
29
 
37
- // Every call and watch of a room names it in its input: the Worker sends each on to the room's
38
- // object, and the object refuses an input naming another room, so a page's socket to one room
39
- // cannot reach another. Its schema is the room names, so an unknown room is `InvalidInput`
40
- // before any object is reached.
41
- const inRoom = { room: RoomName };
30
+ const inRoom = { room: DemoRoomName };
42
31
 
43
32
  const signedIn = { caller: CurrentMember } as const;
44
33
 
45
- // Reads once: a page opening a room reads what is there, then watches `MessagePosted` below from
46
- // the last id it read.
47
34
  export const ReadMessages = Action.make("readMessages", {
48
35
  ...signedIn,
49
36
  description: "Read the room's messages after the given id; 0 reads them all.",
@@ -52,9 +39,6 @@ export const ReadMessages = Action.make("readMessages", {
52
39
  readOnly: true,
53
40
  });
54
41
 
55
- // `request` is the post's idempotency key: a page makes one at random for each message and
56
- // sends it again when it retries the post, and the room answers the repeat as it answered the
57
- // first, posting once. A model reads its description beside the tool, so it does the same.
58
42
  export const PostMessage = Action.make("postMessage", {
59
43
  ...signedIn,
60
44
  description: "Post a message to the room. It expires a day later.",
@@ -83,10 +67,6 @@ export const DeleteMessage = Action.make("deleteMessage", {
83
67
 
84
68
  export const Messages = [ReadMessages, PostMessage, DeleteMessage] as const;
85
69
 
86
- // Each message posted to the room, as it is posted: a page watches it on the socket it keeps
87
- // open to the room's object. Signed-in, so each watch authenticates and runs `authorize` as it
88
- // starts, and again each time the object wakes after hibernating, refused for a member outside
89
- // the room, or one whose token has expired meanwhile.
90
70
  export const MessagePosted = Event.make("message.posted", {
91
71
  description: "A message posted to the room.",
92
72
  input: inRoom,
@@ -1,11 +1,6 @@
1
1
  import { Context } from "effect";
2
2
  import type { Effect } from "effect";
3
3
 
4
- /**
5
- * Where a room says its latest activity may have changed: the lobby's object, which worker.ts
6
- * chooses. `changing` runs a change, then tells, answering as the change did: a post stands
7
- * whether the lobby hears of it or not.
8
- */
9
4
  export class Activity extends Context.Service<
10
5
  Activity,
11
6
  {
@@ -4,9 +4,6 @@ import { Effect } from "effect";
4
4
  import { CurrentMember } from "../identity/Identity.js";
5
5
  import { Room } from "./room.js";
6
6
 
7
- // The one rule: a member reads and writes only the rooms they belong to. It is built as
8
- // handlers are: this Effect runs once per instance and gets the room, a startup service; the
9
- // function it returns runs before every handler and reads the caller of that call.
10
7
  export const authorize = Effect.gen(function* () {
11
8
  const room = yield* Room;
12
9
 
@@ -5,19 +5,12 @@ import { authorize } from "./authorize.js";
5
5
  import { MessagePosted } from "./Chat.js";
6
6
  import { MessageStore } from "./store.js";
7
7
 
8
- // A cursor is the id of the last message a page holds, as `readMessages`' `after` is.
9
8
  const idOf = Schema.decodeUnknownOption(
10
9
  Schema.NumberFromString.pipe(Schema.check(Schema.isInt()))
11
10
  );
12
11
 
13
- // An agent polling over MCP asks again after `nextPoll`, 5 seconds by default: a request that
14
- // often keeps the object from the 10 idle seconds after which the runtime may hibernate it, so it
15
- // asks every 30 seconds, and an agent that needs a message sooner holds a stream open instead.
16
12
  const nextPoll = "30 seconds";
17
13
 
18
- // The room's messages as an event, read from the store that keeps them: a check source.
19
- // `postMessage` notifies after each post, so a page receives it at once: when an object reads a
20
- // check source, and what a write that does not notify misses, is on `ActionDurableObject.handlers`.
21
14
  export const messageEvents = Event.implement(
22
15
  MessagePosted,
23
16
  Effect.gen(function* () {
@@ -33,11 +26,6 @@ export const messageEvents = Event.implement(
33
26
  (id) => id >= 0 && id <= last
34
27
  );
35
28
 
36
- // No cursor starts after the room's last message. One this room never gave, such as
37
- // an id past its last from another copy of its database, is answered `truncated` from
38
- // there: the page learns it missed messages, and reads them with `readMessages`. A
39
- // message deleted or expired after a cursor is simply not read: the store keeps no
40
- // record of either, so no gap marks it.
41
29
  if (Option.isNone(after)) {
42
30
  return {
43
31
  cursor: String(last),
@@ -8,9 +8,6 @@ import { authorize } from "./authorize.js";
8
8
  import { MessagePosted, Messages } from "./Chat.js";
9
9
  import { MessageStore } from "./store.js";
10
10
 
11
- // The builder runs once per instance, when the object is constructed, and again on the
12
- // instance the runtime constructs after evicting one: it is where a handler gets its startup
13
- // services. The caller is read per call, because every message has its own.
14
11
  export const messages = Action.implement(
15
12
  Messages,
16
13
  Effect.gen(function* () {
@@ -21,9 +18,6 @@ export const messages = Action.implement(
21
18
  return {
22
19
  readMessages: ({ after }) =>
23
20
  Effect.map(store.read(after), (read) => ({ messages: read })),
24
- // The message is in the store, which `MessagePosted`'s check reads: notifying wakes the
25
- // pages watching the room to read it now. The lobby is another object, whose event this
26
- // one cannot notify: the room tells it over its stub instead, and the lobby notifies.
27
21
  postMessage: ({ text }) =>
28
22
  Effect.flatMap(CurrentMember, (member) =>
29
23
  store.post(member.id, text)
@@ -1,12 +1,7 @@
1
1
  import { Context } from "effect";
2
2
 
3
- import type { RoomName } from "./Chat.js";
3
+ import type { DemoRoomName } from "./Chat.js";
4
4
 
5
- /**
6
- * The room an instance holds. Each room is one Durable Object, reached by its name, so this is
7
- * a startup service: one value for the instance's whole life, unlike the caller, which every
8
- * message names again.
9
- */
10
- export class Room extends Context.Service<Room, RoomName>()(
5
+ export class Room extends Context.Service<Room, DemoRoomName>()(
11
6
  "chat-rooms/Room"
12
7
  ) {}
@@ -3,16 +3,10 @@ import type { Effect } from "effect";
3
3
 
4
4
  import type { Message, MessageNotFound, NotAuthor } from "./Chat.js";
5
5
 
6
- /**
7
- * The room's messages. That only its author deletes a message is checked here, in the data
8
- * access, so no surface and no handler can skip it. A message expires a day after it was
9
- * posted: `expire` deletes those, and the store sees that it runs.
10
- */
11
6
  export class MessageStore extends Context.Service<
12
7
  MessageStore,
13
8
  {
14
9
  readonly latest: Effect.Effect<Message | null>;
15
- /** The id of the last message ever posted, kept or not, or 0 before the first. */
16
10
  readonly last: Effect.Effect<number>;
17
11
  readonly read: (after: number) => Effect.Effect<readonly Message[]>;
18
12
  readonly post: (author: string, text: string) => Effect.Effect<Message>;
@@ -8,14 +8,8 @@ export const Member = Schema.Struct({
8
8
 
9
9
  export type Member = typeof Member.Type;
10
10
 
11
- /**
12
- * Who sent a message. A protected action declares it, `caller: CurrentMember`; authentication
13
- * provides it for each message, from the token the message carries or the one its socket kept.
14
- */
15
11
  export class CurrentMember extends Context.Service<CurrentMember, Member>()(
16
12
  "chat-rooms/CurrentMember"
17
13
  ) {}
18
14
 
19
- // How a remote caller proves it is CurrentMember: a bearer token, the default scheme. Clients
20
- // import this descriptor with the bindings; its verifier, in verifier.ts, stays on the server.
21
15
  export const Login = Authentication.make("chat-rooms.Login", CurrentMember);
@@ -1,8 +1,6 @@
1
1
  import type { Member } from "./Identity.js";
2
2
 
3
- // DEMO ONLY: fixed members, each token their name. A real application keeps members in its
4
- // identity provider and their rooms in a store.
5
- export const members = {
3
+ export const demoMembers = {
6
4
  ada: { id: "ada", rooms: ["general", "design"] },
7
5
  grace: { id: "grace", rooms: ["general"] },
8
6
  } satisfies Record<string, Member>;
@@ -3,22 +3,19 @@ import * as Authentication from "@gjermundgaraba/effect-actions/Authentication";
3
3
  import { Effect, Redacted } from "effect";
4
4
 
5
5
  import { Login } from "./Identity.js";
6
- import { members } from "./members.js";
6
+ import { demoMembers } from "./members.js";
7
7
 
8
- const isToken = (token: string): token is keyof typeof members =>
9
- Object.hasOwn(members, token);
8
+ const isToken = (token: string): token is keyof typeof demoMembers =>
9
+ Object.hasOwn(demoMembers, token);
10
10
 
11
- // DEMO ONLY: a token is a member's name. A real verifier checks a signed token with your
12
- // authorization server's library, its audience and expiry included: a socket keeps the token
13
- // its page connected with, and this runs on every message, so an expired one is refused.
14
- const verify = (token: Redacted.Redacted) => {
11
+ const demoVerify = (token: Redacted.Redacted) => {
15
12
  const name = Redacted.value(token);
16
13
 
17
14
  return isToken(name)
18
- ? Effect.succeed(members[name])
15
+ ? Effect.succeed(demoMembers[name])
19
16
  : Effect.fail(
20
17
  new Action.Unauthenticated({ message: "Unknown demo token." })
21
18
  );
22
19
  };
23
20
 
24
- export const authenticate = Authentication.layer(Login, verify);
21
+ export const authenticate = Authentication.layer(Login, demoVerify);
@@ -3,11 +3,6 @@ import { Rpc, RpcGroup } from "effect/rpc";
3
3
 
4
4
  import { RoomPreview } from "./Lobby.js";
5
5
 
6
- // The lobby's own API, over its stub: a room tells it its latest activity, and the Worker reads
7
- // the previews. A plain Effect `RpcGroup`, not actions: no page calls it, so it needs no contract
8
- // checks, no authentication and no JSON route, and nothing authenticates a stub call anyway, as
9
- // only a binding reaches it. Why a report heard late never overwrites a later one is at
10
- // `tellLobby`, in lobby-stubs.ts, which sends it.
11
6
  export const LobbyCalls = RpcGroup.make(
12
7
  Rpc.make("roomChanged", { payload: RoomPreview }),
13
8
  Rpc.make("previews", { success: Schema.Array(RoomPreview) })
@@ -2,18 +2,15 @@ import * as Action from "@gjermundgaraba/effect-actions/Action";
2
2
  import * as Event from "@gjermundgaraba/effect-actions/Event";
3
3
  import { Schema } from "effect";
4
4
 
5
- import { RoomName } from "../chat/Chat.js";
5
+ import { DemoRoomName } from "../chat/Chat.js";
6
6
 
7
- // When one room was last active, in milliseconds, or null while it holds no message.
8
7
  export const RoomPreview = Schema.Struct({
9
- room: RoomName,
8
+ room: DemoRoomName,
10
9
  latestAt: Schema.NullOr(Schema.Int),
11
10
  });
12
11
 
13
12
  export type RoomPreview = typeof RoomPreview.Type;
14
13
 
15
- // The Worker's own action, served by the Worker, not by an object: it asks the lobby's object,
16
- // which keeps every room's preview.
17
14
  export const Previews = Action.make("previews", {
18
15
  description:
19
16
  "When each room was last active, in milliseconds, if it holds any message.",
@@ -22,8 +19,6 @@ export const Previews = Action.make("previews", {
22
19
  caller: Action.Anyone,
23
20
  });
24
21
 
25
- // Every room's preview, sent whole each time one changes: a page watches it on its socket to the
26
- // lobby's object. Public, as `previews` is, so a page signed out follows it too.
27
22
  export const PreviewsChanged = Event.make("previews.changed", {
28
23
  description:
29
24
  "When each room was last active, sent whole: first as it is, then on each change.",
@@ -4,11 +4,6 @@ import { Effect } from "effect";
4
4
  import { PreviewsChanged } from "./Lobby.js";
5
5
  import { PreviewStore } from "./store.js";
6
6
 
7
- // Every room's preview as one event, read from the lobby's store: a current source, for a value
8
- // small enough to send whole. A page watching is sent the previews as they are, then again after
9
- // each notify, which `roomChanged` makes after each change, so it needs no read before it and is
10
- // never sent each change it missed, which a whole value makes needless. The object keeps the
11
- // revision a page's cursor holds, so a page resuming at the latest is sent nothing.
12
7
  export const previewEvents = Event.implement(
13
8
  PreviewsChanged,
14
9
  Effect.map(PreviewStore, (store) => ({
@@ -7,7 +7,6 @@ import { LobbyHost } from "./host.js";
7
7
  import { Previews, PreviewsChanged } from "./Lobby.js";
8
8
  import { PreviewStore } from "./store.js";
9
9
 
10
- // The Worker's `previews`, as the lobby's object keeps them.
11
10
  export const lobby = Action.implement(
12
11
  Previews,
13
12
  Effect.map(
@@ -16,8 +15,6 @@ export const lobby = Action.implement(
16
15
  )
17
16
  );
18
17
 
19
- // The lobby's own API, in its object. A change notifies `PreviewsChanged`, which an object
20
- // outside this one could not do itself: its event is this object's.
21
18
  export const calls = LobbyCalls.toLayer(
22
19
  Effect.gen(function* () {
23
20
  const store = yield* PreviewStore;
@@ -3,7 +3,6 @@ import type { Effect } from "effect";
3
3
 
4
4
  import type { RoomPreview } from "./Lobby.js";
5
5
 
6
- /** The lobby's object as the Worker reaches it. */
7
6
  export class LobbyHost extends Context.Service<
8
7
  LobbyHost,
9
8
  { readonly previews: Effect.Effect<readonly RoomPreview[]> }
@@ -1,17 +1,15 @@
1
1
  import { Context } from "effect";
2
2
  import type { Effect } from "effect";
3
3
 
4
- import type { RoomName } from "../chat/Chat.js";
4
+ import type { DemoRoomName } from "../chat/Chat.js";
5
5
  import type { RoomPreview } from "./Lobby.js";
6
6
 
7
- /** Every room's preview, as the room last told the lobby. */
8
7
  export class PreviewStore extends Context.Service<
9
8
  PreviewStore,
10
9
  {
11
10
  readonly read: Effect.Effect<readonly RoomPreview[]>;
12
- /** Keeps `room`'s latest activity, succeeding with whether it changed. */
13
11
  readonly record: (
14
- room: RoomName,
12
+ room: DemoRoomName,
15
13
  latestAt: number | null
16
14
  ) => Effect.Effect<boolean>;
17
15
  }
@@ -1,7 +1,7 @@
1
1
  import * as ActionDurableObject from "@gjermundgaraba/effect-actions-cloudflare/ActionDurableObject";
2
2
  import { Effect, Layer, Schema } from "effect";
3
3
 
4
- import { RoomName } from "../chat/Chat.js";
4
+ import { DemoRoomName } from "../chat/Chat.js";
5
5
  import { RoomPreview } from "../lobby/Lobby.js";
6
6
  import { PreviewStore } from "../lobby/store.js";
7
7
 
@@ -9,16 +9,17 @@ const decodeLatestAt = Schema.decodeUnknownSync(
9
9
  Schema.UndefinedOr(RoomPreview.fields.latestAt)
10
10
  );
11
11
 
12
- // The previews in the lobby's object's synchronous key-value storage: each read and each record
13
- // is one step no other call runs inside, so a record compares and writes what it read.
14
12
  export const layerKvPreviews = Layer.effect(PreviewStore)(
15
13
  Effect.map(ActionDurableObject.State, ({ storage: { kv } }) => {
16
- const latestOf = (room: RoomName) =>
14
+ const latestOf = (room: DemoRoomName) =>
17
15
  decodeLatestAt(kv.get(`preview:${room}`)) ?? null;
18
16
 
19
17
  return PreviewStore.of({
20
18
  read: Effect.sync(() =>
21
- RoomName.literals.map((room) => ({ room, latestAt: latestOf(room) }))
19
+ DemoRoomName.literals.map((room) => ({
20
+ room,
21
+ latestAt: latestOf(room),
22
+ }))
22
23
  ),
23
24
  record: (room, latestAt) =>
24
25
  Effect.sync(() => {
@@ -8,25 +8,14 @@ import { MessageStore } from "../chat/store.js";
8
8
  import { LobbyCalls } from "../lobby/Calls.js";
9
9
  import { LobbyHost } from "../lobby/host.js";
10
10
 
11
- // The lobby is one object, named `lobby`: a new stub for each call, read from `env` as the call
12
- // is sent, never as the module loads.
13
11
  const lobbyStub = () => env.CHAT_LOBBY.getByName("lobby");
14
12
 
15
- // The lobby's object as the Worker reaches it, for the previews: a lobby that cannot be reached
16
- // is the deployment's failure, not the caller's, so it is a defect, the Worker answers 500, and
17
- // the cause is in its logs.
18
13
  export const layerLobbyHost = Layer.effect(LobbyHost)(
19
14
  Effect.map(ActionDurableObject.client(LobbyCalls), (lobby) =>
20
15
  LobbyHost.of({ previews: Effect.orDie(lobby(lobbyStub).previews()) })
21
16
  )
22
17
  );
23
18
 
24
- // The room's task, worker.ts's `lobby`: telling the lobby the room's latest activity. The room's
25
- // alarm runs its tasks one run at a time, each waiting for the lobby's answer, and each run reads
26
- // the activity as it is then: the lobby hears a room's reports in the order the room made them,
27
- // so a report heard late never overwrites a later one, and the last it hears is the room's
28
- // latest. A run repeated after a lost answer sends what the lobby holds, which `record` finds
29
- // unchanged, notifying no page.
30
19
  export const tellLobby = Effect.gen(function* () {
31
20
  const room = yield* Room;
32
21
  const latest = yield* MessageStore.use((store) => store.latest);
@@ -35,10 +24,6 @@ export const tellLobby = Effect.gen(function* () {
35
24
  yield* lobby(lobbyStub).roomChanged({ room, latestAt: latest?.at ?? null });
36
25
  });
37
26
 
38
- // A room's activity, a startup service of the room's: each change runs the `lobby` task after it,
39
- // on the room's alarm once the call has answered, and again until the lobby hears it, so a lobby
40
- // that cannot be reached fails no post and misses no change. `runAfter` marks the task before the
41
- // change and again after it, so a crash at any point leaves the task to the alarm.
42
27
  export const layerActivity = Layer.effect(Activity)(
43
28
  Effect.map(ActionDurableObject.Tasks, (tasks) =>
44
29
  Activity.of({ changing: (change) => tasks.runAfter("lobby", change) })
@@ -12,9 +12,6 @@ const decodeSequence = Schema.decodeUnknownSync(
12
12
  Schema.Array(Schema.Struct({ seq: Schema.Int }))
13
13
  );
14
14
 
15
- // The room's messages in the object's own SQLite database, which outlives every instance: an
16
- // evicted instance loses its memory, never these. The Layer runs each time an instance is
17
- // constructed, so creating the table is idempotent.
18
15
  export const layerSql = Layer.effect(MessageStore)(
19
16
  Effect.gen(function* () {
20
17
  const { storage } = yield* ActionDurableObject.State;
@@ -30,17 +27,10 @@ export const layerSql = Layer.effect(MessageStore)(
30
27
  "CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY AUTOINCREMENT, author TEXT NOT NULL, text TEXT NOT NULL, at INTEGER NOT NULL)"
31
28
  );
32
29
 
33
- // Every post looks up the oldest message: indexed, it reads one row, where a scan would read
34
- // the whole table, and SQLite storage is billed by rows read.
35
30
  storage.sql.exec(
36
31
  "CREATE INDEX IF NOT EXISTS messages_by_at ON messages (at)"
37
32
  );
38
33
 
39
- // The room's alarm is due no later than the oldest message's expiry: `post` and `expire` set
40
- // it for the oldest message, read from the table and set in one step, so posts running at
41
- // once each set it for the oldest they see, and the last to set it has seen them all; reading
42
- // the alarm first would let two posts both see none and the later one win. Removing the
43
- // oldest message leaves its alarm, which then finds nothing due and moves on.
44
34
  const alarmForOldest = Effect.suspend(() => {
45
35
  const [oldest] = query("SELECT * FROM messages ORDER BY at LIMIT 1");
46
36
 
@@ -54,8 +44,6 @@ export const layerSql = Layer.effect(MessageStore)(
54
44
  () =>
55
45
  query("SELECT * FROM messages ORDER BY id DESC LIMIT 1")[0] ?? null
56
46
  ),
57
- // AUTOINCREMENT keeps the highest id it ever gave in `sqlite_sequence`, so the last id
58
- // outlives the message: one that expired or was deleted still counts.
59
47
  last: Effect.sync(
60
48
  () =>
61
49
  decodeSequence(
@@ -82,7 +70,7 @@ export const layerSql = Layer.effect(MessageStore)(
82
70
  .one()
83
71
  );
84
72
 
85
- yield* alarmForOldest;
73
+ yield* alarm.set(DateTime.makeUnsafe(message.at + day));
86
74
 
87
75
  return message;
88
76
  }),
@@ -1,21 +1,13 @@
1
1
  import { WorkerEntrypoint } from "cloudflare:workers";
2
2
  import { Effect, Schema } from "effect";
3
3
 
4
- import { RoomName } from "./chat/Chat.js";
4
+ import { DemoRoomName } from "./chat/Chat.js";
5
5
  import { LobbyHost } from "./lobby/host.js";
6
6
  import { layerLobbyHost } from "./platform/lobby-stubs.js";
7
7
 
8
- const decodeRoom = Schema.decodeUnknownEffect(RoomName);
8
+ const decodeRoom = Schema.decodeUnknownEffect(DemoRoomName);
9
9
 
10
- // The rooms' activity for another Worker, over a service binding to this one's `RoomsEntrypoint`,
11
- // which worker.ts exports, as the lobby keeps it. A method of a `WorkerEntrypoint` is no Effect
12
- // program, so each call runs as one, given the lobby's Layer: its client is built in the request
13
- // that uses it and closed with it, which costs no I/O. Why a client kept across requests strands
14
- // is on `ActionDurableObject.layerStubClient`.
15
10
  export class RoomsEntrypoint extends WorkerEntrypoint {
16
- // The calling Worker is another deployment, so its room is checked as any input is: an unknown
17
- // room rejects the call with the schema's error, as a lobby that cannot be reached rejects it
18
- // with the defect lobby-stubs.ts makes of it.
19
11
  async latestAt(room: string) {
20
12
  return await Effect.runPromise(
21
13
  Effect.flatMap(decodeRoom(room), (name) =>
@@ -25,9 +25,6 @@ const room = [messages, messageEvents];
25
25
 
26
26
  const byRoom = (input: { readonly room: string }) => input.room;
27
27
 
28
- // Where each room's calls and watches are served: in the room's object, the one each contract's
29
- // key names. worker.ts gives it to the room's class, which then refuses an input naming another
30
- // room, on its socket too; the Worker serves it below.
31
28
  export const rooms = ActionDurableObject.placed(RoomHttp, {
32
29
  readMessages: byRoom,
33
30
  postMessage: byRoom,
@@ -35,48 +32,26 @@ export const rooms = ActionDurableObject.placed(RoomHttp, {
35
32
  "message.posted": byRoom,
36
33
  });
37
34
 
38
- // One socket route for each object's pages, refusing a page of another version.
39
35
  const pageSocket = ActionDurableObject.layerWebSocket({
40
36
  path: "/rpc",
41
37
  protocol: { version: protocolVersion, code: unsupportedProtocol },
42
38
  });
43
39
 
44
- // What a room's object serves. Its rpcs on WebSockets the runtime holds while the object
45
- // hibernates: a socket keeps the token its upgrade request carried, and each message is
46
- // authenticated with it, or with the message's own. The socket's route refuses a page naming
47
- // another version in its URL, `?protocol=<n>` as browser.ts sends it, with a close code the page's
48
- // client reads as `SocketCloseError` and stops connecting again at, not a 403, which a browser
49
- // reports as a bare 1006 its page connects again after. Its JSON routes, where the Worker sends
50
- // each call and watch on, the token with it: the object authenticates it again, and authorizes.
51
- // It requires `MessageStore`, `Room` and `Activity` at startup: worker.ts chooses them.
52
40
  export const roomRoutes = Layer.mergeAll(
53
41
  ActionRpc.layer(RoomRpc, room).pipe(Layer.provide(pageSocket)),
54
42
  ActionHttp.layer(RoomHttp, room)
55
43
  ).pipe(Layer.provide(authenticate));
56
44
 
57
- // What the lobby's object serves: `PreviewsChanged` on its pages' sockets, a socket a page
58
- // signed out opens too, as nothing on it is protected. It requires `PreviewStore` at startup.
59
45
  export const lobbyRoutes = ActionRpc.layer(LobbyRpc, [previewEvents]).pipe(
60
46
  Layer.provide(pageSocket)
61
47
  );
62
48
 
63
- // What the lobby's object serves over its stub: its own calls, on Effect's own RpcServer, for
64
- // the rooms and the Worker, which call them with Cloudflare's own RPC. It requires `PreviewStore`
65
- // at startup.
66
49
  export const lobbyCalls = RpcServer.layer(LobbyCalls).pipe(
67
50
  Layer.provide(lobbyHandlers)
68
51
  );
69
52
 
70
- // The rooms as the Worker serves them, each call sent on to its room's object. The room is read
71
- // from `env` as each call is sent.
72
53
  const inRooms = ActionDurableObject.reaching(rooms, () => env.CHAT_ROOM);
73
54
 
74
- // What the Worker serves: the rooms' JSON routes and `previews`, which it asks the lobby's object
75
- // for, at `/api`, and all of them at `/mcp`, the actions as tools and `MessagePosted` as an MCP
76
- // event, so one agent's connection reaches every room. Nothing in a Worker outlives a request, so
77
- // the endpoint is request scoped: MCP 2026-07-28 alone, and events by `events/poll`, a poll every
78
- // 30 seconds as events.ts asks. The Worker authenticates each call, and the room's object again.
79
- // It requires `LobbyHost`.
80
55
  export const workerRoutes = Layer.mergeAll(
81
56
  ActionHttp.layer(LobbyHttp, lobby),
82
57
  ActionHttp.layer(RoomHttp, inRooms),