Skip to content

Commit 0da7738

Browse files
fix(effect-atom)!: a kept-alive runtime keeps its Layer alive for every member; document multi-root sharing (#74)
A runtime atom's atom, fn, pull and subscriptionRef members read the runtime they were first built for, so Atom.keepAlive(Atom.context()(layer)) returned a different atom that the members never read and the Layer was still released. Members are now built for the runtime atom they are read from, so every configuration step (keepAlive, setIdleTTL, withLabel, ...) on a runtime yields a runtime whose members use it. Atom.runtime takes members as a function of the runtime (breaking, major). Also documents and tests the multi-root pattern (one module-scope registry, one kept-alive runtime) and adds a type test that a configured runtime keeps its runtime type and members. Evidence: the multi-root browser test passes (1 build, same instance, root A unmounted before root B mounts); with Atom.keepAlive removed it fails with built 2, released 1, sameInstance false. --------- Co-authored-by: systemfsoftware-bot <bot@users.noreply.github.com> Co-authored-by: systemfsoftware-bot <systemfsoftware-bot@users.noreply.github.com>
1 parent 77d91ad commit 0da7738

6 files changed

Lines changed: 279 additions & 13 deletions

File tree

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
"@systemfsoftware/effect-atom": major
3+
"@systemfsoftware/effect-atom-react": patch
4+
---
5+
6+
`Atom.keepAlive`, `Atom.setIdleTTL`, `Atom.withLabel` and every other configuration step applied to a runtime atom now return a runtime whose `atom`, `fn`, `pull` and `subscriptionRef` members read that returned runtime, and each runtime keeps the same member functions on every read. Before, they read the runtime `Atom.context()` first returned, so `Atom.keepAlive(Atom.context()(layer))` did not keep the Layer alive. `Atom.runtime` now takes `members` as a function of the runtime it builds for: `members: (self) => RuntimeMembers`.
7+
8+
The React README documents how a page with several independently mounted roots, such as an island architecture, shares one registry and one built runtime Layer.

‎packages/atom/effect-atom-react/README.md‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ const value = AtomReact.useAtomValue(count)
2323

2424
## Owning the registry
2525

26-
The code that mounts the app owns its registry: an app's entry, an island's module, a per-request server handler, or a Storybook story's loader. It creates the registry before the first render, passes it to `RegistryProvider`, and disposes it at teardown. `RegistryProvider` only provides the registry it is given.
26+
The code that mounts the app owns its registry: an app's entry, an island's module, a per-request server handler, or a Storybook story's loader. It creates the registry before the first render, passes it to `RegistryProvider`, and disposes it when that owner ends. A registry that lives as long as the page is never disposed (see Islands). `RegistryProvider` only provides the registry it is given.
2727

2828
```ts
2929
import { Atom } from '@systemfsoftware/effect-atom'
@@ -62,7 +62,29 @@ An island that takes no server-data props makes its registry at module scope, `A
6262

6363
- **Props.** A supported island seeds no atom from its props: props exist only inside the island's first render. Its server data comes through atoms over the app runtime's services. Props that seed nothing, such as a label or an id, are fine.
6464
- **Server render.** When the island is also rendered on the server, its module-scope registry is shared by every request in that process. Every atom the island reads during a server render carries `Atom.withServerValue` with a request-independent value, or `Atom.withServerValueInitial` for a result atom; otherwise render it client-only.
65-
- **Teardown.** The island's teardown is the document's unload. When a client-side navigation unmounts the island, each atom it no longer reads is released and its fiber interrupted; a `keepAlive` atom stays in the registry for the next page that mounts the island. No island calls `Atom.Registry.dispose`.
65+
- **Teardown.** An island's registry lives as long as the page, and nothing disposes it: a dispose on `unload` or `beforeunload` makes the page ineligible for the back/forward cache, and a restored page would hold a disposed registry. When a client-side navigation unmounts the island, each atom it no longer reads is released and its fiber interrupted; a `keepAlive` atom stays in the registry for the next page that mounts the island. No island calls `Atom.Registry.dispose`.
66+
67+
## Several roots sharing one runtime
68+
69+
A page with several independently mounted React roots, such as an island architecture, shares one registry and one built runtime Layer by owning both at module scope, in a module every root imports:
70+
71+
```ts
72+
import { Atom } from '@systemfsoftware/effect-atom'
73+
import { AtomReact } from '@systemfsoftware/effect-atom-react'
74+
75+
export const registry = Atom.Registry.make({ scheduleTask: AtomReact.scheduleTask })
76+
77+
export const runtime = Atom.keepAlive(Atom.context()(AppLayer))
78+
export const gateway = runtime.atom(Gateway.use((service) => Effect.succeed(service)))
79+
```
80+
81+
Every root renders `<AtomReact.RegistryProvider registry={registry}>` with that registry.
82+
83+
- **Why the registry is shared.** `Atom.context()` with no options scopes its memo map to each registry, so a Layer is built once per registry. Roots on different registries build it once each; roots on one registry build it once.
84+
- **Why the runtime atom is kept alive.** A runtime atom is released when its last subscriber goes. Without `Atom.keepAlive`, the page's first root unmounting drops the subscriber count to 0, the Layer's scope closes, and the next root to mount rebuilds it. `Atom.keepAlive(runtime)` keeps the runtime in the registry, and every atom made from it (`runtime.atom`, `runtime.fn`, and the rest) reads that kept-alive runtime, so a later root receives the same service instance.
85+
- **Why there is no module-level memo map.** `Atom.context({ memoMap })` would share built Layers across every registry, including the fresh one a test or Storybook story makes and disposes per case, so a disposed registry's Layer would leak into the next case. Leave `memoMap` unset: a registry made per case still builds, and on `Atom.Registry.dispose` releases, its own Layer.
86+
87+
Never dispose the shared registry; its lifetime is the page's, as in Islands. A test or story does not import the shared registry; it makes its own, disposes it in its own cleanup, and reads the same atoms through it.
6688

6789
## API
6890

Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
import { Atom } from '@systemfsoftware/effect-atom'
2+
import { AtomReact } from '@systemfsoftware/effect-atom-react'
3+
import { Gherkin, Given, it, makeFeature, Then, When } from '@systemfsoftware/effect-gherkin-spec'
4+
import { vi } from '@systemfsoftware/vitest'
5+
import { render } from '@testing-library/react'
6+
import '@vitest/browser/matchers'
7+
import * as Cause from 'effect/Cause'
8+
import * as Context from 'effect/Context'
9+
import * as Effect from 'effect/Effect'
10+
import * as Layer from 'effect/Layer'
11+
import { createElement } from 'react'
12+
import { ownRegistry, renderCleanupLayer } from './__fixtures__/render-cleanup.js'
13+
14+
const Feature = makeFeature({ it })
15+
16+
interface Gateway {
17+
readonly build: number
18+
}
19+
20+
class GatewayService extends Context.Service<GatewayService, Gateway>()(
21+
'@systemfsoftware/effect-atom-react/tests/multiple-roots-sharing-a-runtime.integration.test/GatewayService',
22+
) {}
23+
24+
const makeGatewayLayer = () => {
25+
const counts = { built: 0, released: 0 }
26+
const layer = Layer.effect(
27+
GatewayService,
28+
Effect.acquireRelease(
29+
Effect.sync((): Gateway => ({ build: ++counts.built })),
30+
() => Effect.sync(() => void counts.released++),
31+
),
32+
)
33+
return { counts, layer }
34+
}
35+
36+
const mountRoot = (
37+
registry: Atom.Registry.Registry,
38+
gateway: Atom.Atom<Atom.AsyncResult.Result<Gateway | Context.Context<GatewayService>, Cause.NoSuchElementError>>,
39+
) => {
40+
const seen: Gateway[] = []
41+
function Island() {
42+
const result = AtomReact.useAtomValue(gateway)
43+
if (!Atom.AsyncResult.isSuccess(result)) {
44+
return createElement('div', { 'data-testid': 'gateway-loading' })
45+
}
46+
if (!Context.isContext(result.value)) {
47+
seen.push(result.value)
48+
}
49+
return createElement('div', { 'data-testid': 'gateway-ready' })
50+
}
51+
const view = render(
52+
createElement(AtomReact.RegistryProvider, { registry }, createElement(Island)),
53+
{ container: document.body.appendChild(document.createElement('div')) },
54+
)
55+
return { seen, view }
56+
}
57+
58+
const registryWorkSettled = Effect.callback<void>((resume) => {
59+
const cancel = AtomReact.scheduleTask(() => resume(Effect.void))
60+
return Effect.sync(cancel)
61+
})
62+
63+
Feature('Several roots on one page sharing one registry and one built layer')
64+
.live('renders real React roots in Chromium')
65+
.withLayer(Layer.empty)
66+
.withScenarioLayer(renderCleanupLayer)
67+
.body(({ scenario }) => {
68+
scenario(
69+
'A second root mounted after the first one unmounted reuses the layer the first root built',
70+
Gherkin.Do.pipe(
71+
Given('a page registry shared by every root and a runtime kept alive')('ctx', () =>
72+
Effect.sync(() => {
73+
const { counts, layer } = makeGatewayLayer()
74+
const runtime = Atom.keepAlive(Atom.context()(layer))
75+
const gateway = runtime.atom((_get) => GatewayService.use((service) => Effect.succeed(service)))
76+
return { counts, gateway, registry: ownRegistry() }
77+
})),
78+
When('root A reads the service and unmounts, and then root B mounts on the same registry')(
79+
'roots',
80+
(s) =>
81+
Effect.gen(function*() {
82+
const a = mountRoot(s.ctx.registry, s.ctx.gateway)
83+
yield* Effect.promise(() => vi.waitFor(() => expectReady(a.seen)))
84+
a.view.unmount()
85+
yield* registryWorkSettled
86+
const b = mountRoot(s.ctx.registry, s.ctx.gateway)
87+
yield* Effect.promise(() => vi.waitFor(() => expectReady(b.seen)))
88+
return { a: a.seen, b: b.seen }
89+
}),
90+
),
91+
Then('both roots hold the identical service and the layer was built exactly once')((s, expect) =>
92+
expect({
93+
built: s.ctx.counts.built,
94+
released: s.ctx.counts.released,
95+
sameInstance: s.roots.a.at(-1) === s.roots.b.at(-1),
96+
instance: s.roots.b.at(-1)?.build,
97+
}).toEqual({ built: 1, released: 0, sameInstance: true, instance: 1 })
98+
),
99+
),
100+
)
101+
102+
scenario(
103+
'A fresh registry per test case builds and releases its own layer',
104+
Gherkin.Do.pipe(
105+
Given('the same kept-alive runtime and a layer that counts its builds and releases')(
106+
'ctx',
107+
() =>
108+
Effect.sync(() => {
109+
const { counts, layer } = makeGatewayLayer()
110+
const runtime = Atom.keepAlive(Atom.context()(layer))
111+
const gateway = runtime.atom((_get) => GatewayService.use((service) => Effect.succeed(service)))
112+
return { counts, gateway }
113+
}),
114+
),
115+
When('two cases each mint a registry, read the service and dispose the registry')(
116+
'cases',
117+
(s) =>
118+
Effect.gen(function*() {
119+
const instances: Gateway[] = []
120+
for (const _case of [1, 2]) {
121+
const registry = Atom.Registry.make({ scheduleTask: AtomReact.scheduleTask })
122+
const mounted = mountRoot(registry, s.ctx.gateway)
123+
yield* Effect.promise(() => vi.waitFor(() => expectReady(mounted.seen)))
124+
const latest = mounted.seen.at(-1)
125+
if (latest !== undefined) {
126+
instances.push(latest)
127+
}
128+
mounted.view.unmount()
129+
Atom.Registry.dispose(registry)
130+
}
131+
yield* Effect.promise(() => vi.waitFor(() => expectReleased(s.ctx.counts)))
132+
return { instances }
133+
}),
134+
),
135+
Then('each case built its own layer and released it on dispose')((s, expect) =>
136+
expect({
137+
counts: s.ctx.counts,
138+
builds: s.cases.instances.map((gateway) => gateway.build),
139+
}).toEqual({ counts: { built: 2, released: 2 }, builds: [1, 2] })
140+
),
141+
),
142+
)
143+
})
144+
145+
const expectReady = (seen: ReadonlyArray<Gateway>) => {
146+
if (seen.length === 0) {
147+
throw new Error('the root has not received the service yet')
148+
}
149+
}
150+
151+
const expectReleased = (counts: { built: number; released: number }) => {
152+
if (counts.released < counts.built) {
153+
throw new Error('a layer is still held')
154+
}
155+
}

‎packages/atom/effect-atom/src/atom.blueprint.ts‎

Lines changed: 33 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,23 @@ export interface SerializableSpec<S extends Schema.Constraint = Schema.Constrain
128128
readonly codecJson: Schema.toCodecJson<S>
129129
}
130130

131+
/**
132+
* How a runtime atom's members are built for the atom they are read from.
133+
* `bound` builds them once per minted atom, so a member keeps its identity;
134+
* `build` is the unmemoized builder a configured copy rebinds to itself.
135+
*
136+
* @since 4.0.0
137+
*/
138+
export interface RuntimeBinding {
139+
readonly build: (self: Atom) => ErasedRuntime
140+
readonly bound: (self: Atom) => ErasedRuntime
141+
}
142+
143+
const bindRuntime = (build: (self: Atom) => ErasedRuntime): RuntimeBinding => {
144+
let members: ErasedRuntime | undefined
145+
return { build, bound: (self) => (members ??= build(self)) }
146+
}
147+
131148
/**
132149
* The runtime members an atom spec stores, with their service and error types erased.
133150
*
@@ -164,7 +181,7 @@ export interface AtomSpec {
164181
readonly initialValueTarget: Atom | undefined
165182
readonly serializable: SerializableSpec | undefined
166183
readonly serverValue: ((get: <A>(atom: Atom<A>) => A) => Top) | undefined
167-
readonly runtime: ErasedRuntime | undefined
184+
readonly runtime: RuntimeBinding | undefined
168185
}
169186

170187
/**
@@ -498,7 +515,7 @@ const Writables = Blueprint.make<AtomSpec, WritableIndex>()(TypeId).operations<W
498515
targets: { ...targets, write: (self: Atom) => self.spec.write },
499516
})
500517

501-
const runtimeOf = (self: Atom): ErasedRuntime | undefined => self.spec.runtime
518+
const runtimeOf = (self: Atom): ErasedRuntime | undefined => self.spec.runtime?.bound(self)
502519

503520
const Runtimes = Blueprint.make<AtomSpec, AtomIndex>()(TypeId).operations<RuntimeOps>()({
504521
operations,
@@ -519,7 +536,7 @@ function remint(spec: AtomSpec): Atom {
519536
if (spec.runtime === undefined) {
520537
return mintPlain(spec)
521538
}
522-
return Runtimes.of(spec)
539+
return Runtimes.of({ ...spec, runtime: bindRuntime(spec.runtime.build) })
523540
}
524541

525542
/**
@@ -577,19 +594,27 @@ export const writable: {
577594
Writables.of<{ readonly Value: R; readonly Write: (value: W) => void }>({ ...defaults, read, write, refresh }),
578595
)
579596

597+
const failNotRuntime = (): never => {
598+
throw new Error('runtime members were read from an atom that is not a runtime atom')
599+
}
600+
601+
const isRuntimeAtom = <R, ER>(atom: Atom): atom is AtomRuntime<R, ER> => atom.spec.runtime !== undefined
602+
580603
/**
581-
* Creates a runtime atom from its read function and the members its factory builds.
604+
* Creates a runtime atom from its read function and the members its factory builds
605+
* for the runtime atom they are read from, so a configured copy of the runtime
606+
* (`keepAlive`, `withLabel`, ...) builds its members against itself.
582607
*
583608
* @since 4.0.0
584609
*/
585610
export const runtime = <R, ER>(parts: {
586611
readonly read: (get: AtomContext) => AsyncResult.Result<Context.Context<R>, ER>
587-
readonly members: RuntimeMembers<R, ER>
612+
readonly members: (self: () => AtomRuntime<R, ER>) => RuntimeMembers<R, ER>
588613
}): AtomRuntime<R, ER> =>
589614
Runtimes.of<{ readonly Value: AsyncResult.Result<Context.Context<R>, ER> }>({
590615
...defaults,
591616
read: parts.read,
592-
runtime: parts.members,
617+
runtime: bindRuntime((self) => parts.members(() => (isRuntimeAtom<R, ER>(self) ? self : failNotRuntime()))),
593618
})
594619

595620
const refreshThrough = (self: Atom): Refresh => self.spec.refresh ?? ((refresh) => refresh(self))
@@ -2263,9 +2288,7 @@ export function context(options?: {
22632288
| ((get: AtomContext) => Layer.Layer<R, E, RIn>),
22642289
): AtomRuntime<R, E> {
22652290
const layerAtom = keepAlive(runtimeLayerAtom(create, globalLayer))
2266-
let runtimeValue: AtomRuntime<R, E>
2267-
const members = makeRuntimeMembers<R, E>(() => runtimeValue, factory, layerAtom)
2268-
runtimeValue = runtime({
2291+
return runtime<R, E>({
22692292
read: (get) => {
22702293
const layer = get(layerAtom)
22712294
const built = Effect.flatMap(
@@ -2274,9 +2297,8 @@ export function context(options?: {
22742297
)
22752298
return effect(get, built, { uninterruptible: true })
22762299
},
2277-
members,
2300+
members: (self) => makeRuntimeMembers<R, E>(self, factory, layerAtom),
22782301
})
2279-
return runtimeValue
22802302
}
22812303
const factory = assignRuntimeFactory(factoryFn, memoMap, addGlobalLayer, withReactivity)
22822304
return factory

‎packages/atom/effect-atom/test-types/atom.tst.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,3 +116,15 @@ describe('an atom is a blueprint', () => {
116116
expect<Atom.Type<typeof draft>>().type.toBe<number>()
117117
})
118118
})
119+
120+
describe('a runtime atom is a blueprint', () => {
121+
const runtime = Atom.context()(Layer.succeed(NotRegistry, 1))
122+
123+
it('Should_KeepTheRuntimeVariantWithItsMembers_When_ConfigurationStepIsApplied', () => {
124+
expect(runtime.keepAlive()).type.toBe<Atom.AtomRuntime<NotRegistry, never>>()
125+
expect(Atom.keepAlive(runtime)).type.toBe<Atom.AtomRuntime<NotRegistry, never>>()
126+
expect(pipe(runtime, Atom.keepAlive, Atom.withLabel('runtime'))).type.toBe<Atom.AtomRuntime<NotRegistry, never>>()
127+
expect(Atom.keepAlive(runtime).atom).type.toBe<typeof runtime.atom>()
128+
expect(Atom.keepAlive(runtime).fn).type.toBe<typeof runtime.fn>()
129+
})
130+
})
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { Atom } from '@systemfsoftware/effect-atom'
2+
import { Gherkin, Given, it, makeFeature, Then, When } from '@systemfsoftware/effect-gherkin-spec'
3+
import { Effect, Layer } from 'effect'
4+
5+
const Feature = makeFeature({ it })
6+
7+
Feature('Configuring a runtime atom')
8+
.withLayer(Layer.empty)
9+
.body(({ scenario }) => {
10+
scenario(
11+
'A runtime hands out the same constructors on every read, and a configured copy hands out its own',
12+
Gherkin.Do.pipe(
13+
Given('a runtime and a kept-alive copy of it')('ctx', () =>
14+
Effect.sync(() => {
15+
const runtime = Atom.context()(Layer.empty)
16+
return { runtime, kept: Atom.keepAlive(runtime) }
17+
})),
18+
When('each runtime is asked twice for its atom, fn, pull and subscriptionRef constructors')(
19+
'reads',
20+
(s) =>
21+
Effect.sync(() => ({
22+
plain: [
23+
s.ctx.runtime.atom === s.ctx.runtime.atom,
24+
s.ctx.runtime.fn === s.ctx.runtime.fn,
25+
s.ctx.runtime.pull === s.ctx.runtime.pull,
26+
s.ctx.runtime.subscriptionRef === s.ctx.runtime.subscriptionRef,
27+
],
28+
kept: [
29+
s.ctx.kept.atom === s.ctx.kept.atom,
30+
s.ctx.kept.fn === s.ctx.kept.fn,
31+
s.ctx.kept.pull === s.ctx.kept.pull,
32+
s.ctx.kept.subscriptionRef === s.ctx.kept.subscriptionRef,
33+
],
34+
distinct: s.ctx.kept.atom !== s.ctx.runtime.atom,
35+
})),
36+
),
37+
Then('every constructor is the same function on each read, and the copy does not share the original')(
38+
(s, expect) =>
39+
expect(s.reads).toEqual({
40+
plain: [true, true, true, true],
41+
kept: [true, true, true, true],
42+
distinct: true,
43+
}),
44+
),
45+
),
46+
)
47+
})

0 commit comments

Comments
 (0)