Repository navigation
Expand file tree
/
Copy pathdemo.ts
More file actions
403 lines (367 loc) · 16 KB
/
Copy pathdemo.ts
File metadata and controls
403 lines (367 loc) · 16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
/**
* A worked Remote + Surface + Mixins trace. `ProjectPage` is a Surface that
* selects a project out of the Remote store; a SurfaceView renders the
* `RemoteData` through Style and Behavior. The demo runs the real path — plan,
* prefetch, select, a stale-while-revalidate refresh, render, mutate,
* retention, and a decode failure — against an in-process `RemoteClient`.
*/
import { Effect, Layer, Match, Option, Schema, Stream } from 'effect'
import { TestClock } from 'effect/testing'
import { defineMessageUnion } from 'foldkit/message'
import {
Attributes,
Behavior,
Capability,
Slot,
Slots,
Style,
type SlotAttributes,
} from 'foldkit-mixins'
import { SurfaceView } from 'foldkit-mixins-surface'
import {
Entity,
Mutation,
Query,
Remote,
RemoteClient,
RemoteData,
RemotePolicy,
entityKey,
writeEntity,
type EntityStore,
type Page,
} from 'foldkit-remote'
import { why } from 'foldkit-remote/why'
import { Surface } from 'foldkit-surface'
const Project = Entity.make(
'Project',
Schema.Struct({ id: Schema.String, name: Schema.String, status: Schema.String }),
)
const ProjectSummary = Project.select({ id: true, name: true, status: true })
const RenameInput = Schema.Struct({ id: Schema.String, name: Schema.String })
const RenameProject = Mutation.make('RenameProject', {
Input: RenameInput.fields,
Output: { id: Schema.String },
})
const ProjectsByOwner = Query.make('ProjectsByOwner', {
Input: { ownerId: Schema.String },
Result: Project,
})
// The Remote submodel's schema is the same for every domain, so the Model
// embeds it before the domain is bound; Remote's Messages are cases of the
// application's own union, and `update` hands them to `Data.reduce` by tag.
const Model = Schema.Struct({ remote: Remote.Model, projectId: Schema.String })
type Model = typeof Model.Type
const Message = defineMessageUnion({ ...Remote.messages, Ping: {} })
// `update` names its result: `Data` is bound to `App`, and `App` is built
// from `update`, so the annotation is what keeps the types acyclic.
const App = Surface.application({
Model,
Message,
initial: { remote: Remote.initial, projectId: 'p1' },
update: (model, message): { readonly model: Model } =>
Remote.reduces(message) ? { model: Data.reduce(model, message) } : { model },
})
const Data = Remote.make({
model: App.model.remote,
entities: [Project],
mutations: [RenameProject],
queries: [ProjectsByOwner],
// A script run by tsx and Vitest, never built for a reader: always verified.
verifyPredictions: true,
})
// Params are plain fields and the model an object of Projections; `App.surface`
// lifts both into the Schema.Struct and Projection.struct `Surface.make` takes.
const ProjectPage = App.surface('ProjectPage', {
params: { projectId: Schema.String },
model: ({ params }) => ({ project: Data.get(ProjectSummary, params.projectId) }),
messages: [Message.Ping],
})
type ProjectValue = { readonly id: string; readonly name: string; readonly status: string }
type Projected = { readonly project: RemoteData<ProjectValue> }
type PageMessage = typeof Message.Ping.Type
const ProjectSlots = Slots.define({
root: Slot.make({ capability: Capability.Container }),
name: Slot.make({ capability: Capability.Container }),
status: Slot.make({ capability: Capability.Container }),
})
const ProjectStyle = Style.forSlots(ProjectSlots)(
{
root: Style.compose(
Style.class('project-card'),
Style.inline({ display: 'grid', gap: '0.25rem' }),
),
status: Style.whenInput<Projected>(
input => input.project._tag === 'Ready' && input.project.value.status === 'archived',
Style.class('project-card-archived'),
),
},
{ name: 'ProjectStyle' },
)
const StatusBehavior = Behavior.forSlots(ProjectSlots)<Projected, PageMessage>(
{
status: Behavior.slot({
attributes: ({ input, h }) =>
Match.value(input.project).pipe(
Match.tag('Ready', ({ value }) => [h.DataAttribute('status', value.status)]),
Match.orElse(() => []),
),
}),
},
{ name: 'StatusBehavior' },
)
const describeData = (data: RemoteData<ProjectValue>): string =>
RemoteData.match(data, {
Initial: () => 'Initial',
Loading: () => 'Loading',
Ready: value => `Ready ${JSON.stringify(value)}`,
Refreshing: value => `Refreshing ${JSON.stringify(value)}`,
Failed: error => `Failed ${error._tag}`,
NotFound: () => 'NotFound',
})
const describePage = (data: RemoteData<Page<ProjectValue>>): string =>
RemoteData.match(data, {
Initial: () => 'Initial',
Loading: () => 'Loading',
Ready: page => `Ready ${page.items.map(item => `${item.id} ${item.name}`).join(', ')}`,
Refreshing: page => `Refreshing ${page.items.map(item => item.id).join(', ')}`,
Failed: error => `Failed ${error._tag}`,
NotFound: () => 'NotFound',
})
const statusText = (data: RemoteData<ProjectValue>): string =>
RemoteData.match(data, {
Initial: () => '...',
Loading: () => '...',
Ready: value => value.status,
Refreshing: value => value.status,
Failed: () => 'error',
NotFound: () => 'missing',
})
const classTokens = (attributes: SlotAttributes<PageMessage>): ReadonlyArray<string> =>
Attributes.find(attributes, 'Class')?.value.split(/\s+/) ?? []
const dataAttribute = (attributes: SlotAttributes<PageMessage>, key: string): string | undefined =>
Attributes.filter(attributes, 'DataAttribute').find(attribute => attribute.key === key)?.value
const withStore = (model: typeof App.initial, store: EntityStore): typeof App.initial => ({
...model,
remote: { ...model.remote, entities: store },
})
// The server's facts, which the refresh step changes behind the client's back.
const server: { names: Record<string, string>; owned: ReadonlyArray<string> } = {
names: { p1: 'Apollo' },
owned: ['p1'],
}
/** An in-process `RemoteClient`; no server, but the whole path is the real one. */
const FakeClient = Layer.succeed(RemoteClient, {
read: batch =>
Effect.sync(() => ({
entities: batch.requests.map(request => ({
entity: request.entity,
id: request.id,
values: { id: request.id, name: server.names[request.id], status: 'active' },
})),
settled: [],
})),
// Like a real server since payload planning: the page carries the selected
// fields of its items with the edges, so one response populates both.
query: request =>
Effect.sync(() => ({
edges: server.owned.map(id => ({ entity: 'Project', id, key: `Project:${id}` })),
start: { _tag: 'Terminal' as const },
end: { _tag: 'Terminal' as const },
entities: server.owned.map(id => ({
entity: 'Project',
id,
values: {
id,
...Object.fromEntries(
['name', 'status'].flatMap(field =>
(request.select?.fields ?? ['id', 'name', 'status']).includes(field)
? [[field, field === 'name' ? server.names[id] : 'active'] as const]
: [],
),
),
},
})),
settled: [],
})),
mutate: request =>
Effect.sync(() => {
const input = Schema.decodeUnknownSync(RenameInput)(request.input)
return {
output: { id: input.id },
entities: [{ entity: 'Project', id: input.id, values: { name: input.name } }],
}
}),
live: () => Stream.empty,
})
const projects = Data.query(
ProjectsByOwner,
{ ownerId: 'u1' },
{ select: ProjectSummary, first: 25 },
)
// A Surface without params, so `Data.refresh` takes it directly.
const Dashboard = App.surface('Dashboard', {
model: () => ({ project: Data.get(ProjectSummary, 'p1'), projects }),
})
/** Runs the Dashboard's read entry, as the mounted Subscription would, until it plans nothing. */
const observeDashboard = async (
model: Model,
): Promise<{ readonly model: Model; readonly tags: ReadonlyArray<string> }> => {
const entry = Data.subscriptions({ dashboard: Dashboard })['dashboard.read']
let current = model
const tags: string[] = []
// The page first, then the items it newly references; the cap only stops a runaway loop.
for (let pass = 0; pass < 3; pass += 1) {
const dependencies = entry.modelToDependencies(current)
if (dependencies.requirements.length === 0 && dependencies.queries.length === 0) break
const messages = await Effect.runPromise(
Stream.runCollect(entry.dependenciesToStream(dependencies)).pipe(Effect.provide(FakeClient)),
)
tags.push(...Array.from(messages, message => message._tag))
current = messages.reduce(Data.reduce, current)
}
return { model: current, tags }
}
export const runDemo = async (): Promise<ReadonlyArray<string>> => {
server.names = { p1: 'Apollo' }
server.owned = ['p1']
const lines: string[] = ['surface: ProjectPage']
const initial = App.initial
const projection = Data.get(ProjectSummary, 'p1')
const requirements = Data.plan(initial, ProjectPage.projection({ projectId: 'p1' }))
lines.push(
`plan: ${requirements.map(entry => `${entry.entity}:${entry.id} [${entry.fields.join(',')}]`).join(', ')}`,
)
lines.push(`before fetch: ${describeData(projection.read(initial))}`)
// `why` tells the two reasons for `Initial` apart: nothing reads it, or
// something does and nothing fetches. Here the page is active, and nothing has
// fetched yet: the step below is the I/O.
const said = why(Data, initial, projection, {
surfaces: { page: Surface.at(ProjectPage, { projectId: 'p1' }) },
})
lines.push(`why: ${said.because.map(reason => reason._tag).join(', ')}`)
// The store stamps each write with the clock it is given, so the refresh
// below can decide staleness without waiting.
const loaded = await Effect.runPromise(
Data.prefetch(initial, projection, { now: () => 1_000 }).pipe(Effect.provide(FakeClient)),
)
lines.push(`after fetch: ${describeData(projection.read(loaded))}`)
// A refreshing policy keeps the value visible while it refetches: the
// Subscription emits RefreshStarted (the projection reads Refreshing) and
// then the read result (Ready again). `Data.subscriptions` derives the entry
// from the active Surface; it emits `RemoteMessage`s that `Data.reduce` takes.
const refreshing = Data.subscriptions(
{ page: Surface.at(ProjectPage, { projectId: 'p1' }) },
{ policy: RemotePolicy.staleWhileRevalidate({ maxAge: 30_000 }), now: () => 60_000 },
)['page.read']
const refreshMessages = await Effect.runPromise(
Stream.runCollect(refreshing.dependenciesToStream(refreshing.modelToDependencies(loaded))).pipe(
Effect.provide(FakeClient),
),
)
// The announcements first: `ReadStarted` marks what is being fetched and
// `RefreshStarted` marks the present fields stale, so the value reads
// `Refreshing` until the result lands.
const midRefresh = refreshMessages
.filter(message => message._tag !== 'ReadReceived')
.reduce(Data.reduce, loaded)
const refreshed = refreshMessages.reduce(Data.reduce, loaded)
lines.push(
`stale-while-revalidate: ${refreshMessages.map(message => message._tag).join(', ')}; ${describeData(projection.read(midRefresh))} -> ${describeData(projection.read(refreshed))}`,
)
// A query is a Projection too: the connection read as a page of the selected
// items. The prefetch runs the query, whose response already carries the
// selected fields with the edges; a read follows only for what the page
// left out (nothing here: the payload names every selected field, and p1
// is already known besides). `Data.more` is the Model with one page more,
// or nothing when every row is shown.
const queried = await Effect.runPromise(
Data.prefetch(loaded, projects, { now: () => 2_000 }).pipe(Effect.provide(FakeClient)),
)
lines.push(
`query page: ${describePage(projects.read(queried))}; next page: ${
Option.isNone(Data.more(queried, projects)) ? 'none' : 'available'
}`,
)
const meta = Data.meta(queried, projects)
lines.push(
`meta: updatedAt ${meta.updatedAt ?? 'never'}, stale ${meta.stale}, loading ${meta.loading}`,
)
const inspection = Data.inspect(queried)
lines.push(
`inspect: ${inspection.entities.length} entities, ${inspection.connections.length} connection, ${Data.registry.queries.size} registered queries`,
)
let resolved: Option.Option<{
readonly root: SlotAttributes<PageMessage>
readonly status: SlotAttributes<PageMessage>
}> = Option.none()
const ProjectView = SurfaceView.define(ProjectPage, ProjectSlots, (model, slots, h) => {
const root = slots.root.attrs()
const status = slots.status.attrs()
resolved = Option.some({ root, status })
return h.article(root, [
h.h2(slots.name.attrs(), [describeData(model.project)]),
h.span(status, [statusText(model.project)]),
])
}).pipe(Style.attach(ProjectStyle), Behavior.attach(StatusBehavior))
SurfaceView.render(ProjectView, ProjectPage, { projectId: 'p1' }, loaded)
const view = Option.getOrThrowWith(resolved, () => new Error('the view was not drawn'))
lines.push(`rendered classes: ${classTokens(view.root).join(' ')}`)
lines.push(`rendered status: ${String(dataAttribute(view.status, 'status'))}`)
// `Data.mutate` is what `update` calls: the request starts in the Model with
// an id from the Model's own sequence, and the returned Command's Message
// settles it. Here the Command runs and its Message is reduced in place.
// The answer is dated by Effect's clock when it lands, as a read is, but it
// carries only `name`: `status` is still the read's, at 1,000, so the
// stale-while-revalidate entry above (whose clock reads 60,000) asks for the
// row again, whole. A row is as fresh as its oldest field.
const rename = Data.mutate(loaded, RenameProject, { id: 'p1', name: 'Apollo II' })
const settled = await Effect.runPromise(
Effect.andThen(TestClock.setTime(59_000), rename.command.effect).pipe(
Effect.provide(TestClock.layer()),
Effect.provide(FakeClient),
),
)
const renamed = Data.reduce(rename.model, settled)
lines.push(`mutation RenameProject (${rename.requestId}): ${settled._tag}`)
lines.push(`after mutation: ${describeData(projection.read(renamed))}`)
const due = refreshing.modelToDependencies(renamed).requirements.length
lines.push(
`refetch after mutation: ${due === 0 ? 'none' : `${due} requirement${due === 1 ? '' : 's'}`}`,
)
// Retention: the roots are what the active Surfaces reach. A project the page
// does not select, and a connection nobody lists, are collected; the page's
// project stays.
const crowded = withStore(
queried,
writeEntity(renamed.remote.entities, entityKey('Project', 'p2'), { name: 'Borealis' }),
)
const retain = Remote.retain([ProjectPage.projection({ projectId: 'p1' })])
const retention = await Effect.runPromise(
Stream.runHead(retain.dependenciesToStream(retain.modelToDependencies(crowded))),
)
const kept = Data.inspect(Data.reduce(crowded, Option.getOrThrow(retention)))
const before = Data.inspect(crowded)
lines.push(
`retained: ${kept.entities.map(entry => entry.key).join(', ')}; ${before.entities.length - kept.entities.length} entity and ${before.connections.length - kept.connections.length} connection collected`,
)
const corrupted = withStore(
loaded,
writeEntity(Data.storeOf(loaded), entityKey('Project', 'p1'), { status: 42 }),
)
lines.push(`corrupt store: ${describeData(projection.read(corrupted))}`)
// The server renames p1 and moves the list to p2 alone. `Data.refresh` is what
// a ClickedRefresh branch of `update` returns: no I/O, only marks. The read
// entry then refetches the marked fields and the invalidated connection.
server.names = { p1: 'Artemis', p2: 'Borealis' }
server.owned = ['p2']
const marked = Data.refresh(queried, Dashboard)
lines.push(
`refresh: ${describeData(projection.read(marked))}; list ${describePage(projects.read(marked))}; again unchanged: ${Data.refresh(marked, Dashboard) === marked}`,
)
const reloaded = await observeDashboard(marked)
lines.push(
`after refresh: ${reloaded.tags.join(', ')}; ${describeData(projection.read(reloaded.model))}; list ${describePage(projects.read(reloaded.model))}`,
)
return lines
}