@sssb/kit 0.2.0 → 0.3.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.
- package/dist/release.json +1 -1
- package/package.json +4 -1
- package/src/adapters/fake/auth.ts +5 -4
- package/src/adapters/fake/jobs.ts +17 -39
- package/src/adapters/fake/simulator.ts +2 -3
- package/src/adapters/index.ts +33 -6
- package/src/adapters/lazy-jobs.ts +25 -0
- package/src/adapters/proxy.ts +34 -0
- package/src/adapters/real/absent.ts +41 -0
- package/src/adapters/real/clerk-proxy.ts +111 -0
- package/src/adapters/real/db-data-api.ts +1 -1
- package/src/adapters/real/db-port.ts +26 -0
- package/src/adapters/real/db.ts +2 -21
- package/src/adapters/real/index.ts +76 -26
- package/src/adapters/real/jobs-in-process.ts +118 -0
- package/src/adapters/real/jobs.ts +2 -1
- package/src/adapters/real/optional-ports.ts +78 -0
- package/src/adapters/run-mode.ts +11 -0
- package/src/components/app-header.tsx +1 -1
- package/src/components/simulator/simulator-host.tsx +335 -0
- package/src/components/simulator/simulator-panel.tsx +45 -57
- package/src/core/abilities.ts +6 -1
- package/src/core/same-origin-path.ts +20 -0
- package/src/db/keyset.ts +1 -1
- package/src/db/migrations/0015_app_user_grant.ts +1 -1
- package/src/db/org-lookup.ts +1 -1
- package/src/demo-static/world.ts +5 -4
- package/src/guide.md +18 -4
- package/src/jobs/digest-email.ts +32 -17
- package/src/jobs/run-in-process.ts +82 -0
- package/src/observability/scrub.ts +3 -1
- package/src/ports/jobs.ts +25 -4
- package/src/server-lib/defer.ts +4 -0
- package/src/server-lib/scheduled-tick.ts +13 -3
- package/src/server-lib/simulator-api.ts +311 -0
- package/src/service-auth/credential.ts +20 -0
- package/src/service-auth/mailgun.ts +2 -2
- package/src/service-auth/verify.ts +10 -3
- package/src/service-auth/webhook.ts +14 -5
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { InvalidTransitionError } from '../../core/state-machine'
|
|
2
|
+
import { recordJobStatus } from '../../db/jobs'
|
|
3
|
+
import { type JobRunPorts, runJobInProcess } from '../../jobs/run-in-process'
|
|
4
|
+
import type { JobsPort } from '../../ports/jobs'
|
|
5
|
+
|
|
6
|
+
/** A terminal job's notification, as the adapter registry gives it (`notifyJobTerminal`, with the request path's deps). */
|
|
7
|
+
export type NotifyJobTerminal = (input: {
|
|
8
|
+
tenantId: string
|
|
9
|
+
jobId: string
|
|
10
|
+
status: 'completed' | 'failed'
|
|
11
|
+
}) => Promise<void>
|
|
12
|
+
|
|
13
|
+
/** The message on the `running` timeline entry of a job this runner claimed: how `sweep` knows its own jobs. */
|
|
14
|
+
export const IN_PROCESS_CLAIM = 'claimed by the in-process runner'
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* A job this runner claimed that is still `running` this long after its last status change was lost: the invocation
|
|
18
|
+
* that ran it ended (the server's time limit, a crash) before the runner could record an outcome. Many times the
|
|
19
|
+
* 30 seconds @sssb/cdk gives the server, so a job another invocation is still running is not taken for lost there.
|
|
20
|
+
*/
|
|
21
|
+
export const IN_PROCESS_LOST_AFTER_MS = 5 * 60_000
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The jobs port with no job compute of its own (`JOBS_RUNNER=in-process`, ./optional-ports.ts): `start` runs the job's
|
|
25
|
+
* registered handler in the server, now, with the deployment's real ports, and records its terminal status before it
|
|
26
|
+
* returns (`runJobInProcess`, which the simulated adapter runs too). No build project, no completion webhook: the
|
|
27
|
+
* status is written where the work is done.
|
|
28
|
+
*
|
|
29
|
+
* `start` is called after the job's row has committed (`submitJob`, `runDueSchedules`), from the request that
|
|
30
|
+
* submitted it or from the scheduled tick (`/api/webhooks/cron`), so a job shares that invocation's time limit with
|
|
31
|
+
* whatever else it does, and a tick that spawns several runs them one after another. That is the limit of this runner:
|
|
32
|
+
* work that may outrun it belongs on the CodeBuild runner. A job cut off by the limit is left `running`: the
|
|
33
|
+
* invocation is ended with its process, so the job's open transaction rolls back (at once on `pg`; on the Data API
|
|
34
|
+
* when that transaction times out), and `sweep`, which the scheduled tick calls, fails it once
|
|
35
|
+
* `IN_PROCESS_LOST_AFTER_MS` have passed. Only jobs this runner claimed (`IN_PROCESS_CLAIM`) are swept, so a job
|
|
36
|
+
* another runner holds `running` (a service caller's, through its status route, or one the jobs webhook is walking
|
|
37
|
+
* to its end) is left to it.
|
|
38
|
+
*
|
|
39
|
+
* A terminal status notifies the job's org admins as the jobs webhook route does, through `notify`, which the adapter
|
|
40
|
+
* registry passes in (the notification modules import the registry). Best effort: `notifyJobTerminal` swallows its
|
|
41
|
+
* own failures, and anything else `notify` throws is logged; neither fails a job that already finished.
|
|
42
|
+
*/
|
|
43
|
+
export function createInProcessJobs(ports: JobRunPorts, notify: NotifyJobTerminal): JobsPort {
|
|
44
|
+
const notifyBestEffort = async (tenantId: string, jobId: string, status: 'completed' | 'failed') => {
|
|
45
|
+
try {
|
|
46
|
+
await notify({ tenantId, jobId, status })
|
|
47
|
+
} catch (error) {
|
|
48
|
+
// console.warn reaches CloudWatch in Lambda; SSSB has no logger port (./db.ts does the same).
|
|
49
|
+
console.warn(`SSSB jobs: job ${jobId} is ${status}, but notifying its org failed: ${messageOf(error)}`)
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return {
|
|
53
|
+
async start(job) {
|
|
54
|
+
await runJobInProcess(job, ports, (status) => notifyBestEffort(job.tenantId, job.id, status), {
|
|
55
|
+
claimMessage: IN_PROCESS_CLAIM,
|
|
56
|
+
})
|
|
57
|
+
},
|
|
58
|
+
// Fault-isolated per tenant and per job, as `runDueSchedules` is per schedule: one failure is logged and the
|
|
59
|
+
// sweep goes on, and nothing it throws reaches the tick.
|
|
60
|
+
async sweep(now) {
|
|
61
|
+
const before = new Date(now.getTime() - IN_PROCESS_LOST_AFTER_MS).toISOString()
|
|
62
|
+
let failed = 0
|
|
63
|
+
let tenants: { id: string }[]
|
|
64
|
+
try {
|
|
65
|
+
tenants = await ports.db.getDb().selectFrom('tenants').select('id').execute()
|
|
66
|
+
} catch (error) {
|
|
67
|
+
console.warn(`SSSB jobs: the in-process sweep could not list tenants: ${messageOf(error)}`)
|
|
68
|
+
return 0
|
|
69
|
+
}
|
|
70
|
+
for (const tenant of tenants) {
|
|
71
|
+
let lost: { id: string }[]
|
|
72
|
+
try {
|
|
73
|
+
lost = await ports.db.withTenant(tenant.id, (trx) =>
|
|
74
|
+
trx
|
|
75
|
+
.selectFrom('jobs')
|
|
76
|
+
.select('jobs.id')
|
|
77
|
+
.where('jobs.status', '=', 'running')
|
|
78
|
+
.where('jobs.updated_at', '<', before)
|
|
79
|
+
.where(({ exists, selectFrom }) =>
|
|
80
|
+
exists(
|
|
81
|
+
selectFrom('job_status_changes')
|
|
82
|
+
.select('job_status_changes.id')
|
|
83
|
+
.whereRef('job_status_changes.job_id', '=', 'jobs.id')
|
|
84
|
+
.where('job_status_changes.status', '=', 'running')
|
|
85
|
+
.where('job_status_changes.message', '=', IN_PROCESS_CLAIM),
|
|
86
|
+
),
|
|
87
|
+
)
|
|
88
|
+
.execute(),
|
|
89
|
+
)
|
|
90
|
+
} catch (error) {
|
|
91
|
+
console.warn(`SSSB jobs: the in-process sweep skipped tenant ${tenant.id}: ${messageOf(error)}`)
|
|
92
|
+
continue
|
|
93
|
+
}
|
|
94
|
+
for (const { id } of lost) {
|
|
95
|
+
try {
|
|
96
|
+
await recordJobStatus(ports.db, tenant.id, id, 'failed', {
|
|
97
|
+
error: 'lost: the server stopped before the in-process runner recorded an outcome',
|
|
98
|
+
})
|
|
99
|
+
} catch (error) {
|
|
100
|
+
if (!(error instanceof InvalidTransitionError)) {
|
|
101
|
+
console.warn(
|
|
102
|
+
`SSSB jobs: the in-process sweep could not fail job ${id}: ${messageOf(error)}`,
|
|
103
|
+
)
|
|
104
|
+
}
|
|
105
|
+
continue // InvalidTransitionError: it finished, or another sweep failed it, meanwhile
|
|
106
|
+
}
|
|
107
|
+
failed += 1
|
|
108
|
+
await notifyBestEffort(tenant.id, id, 'failed')
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return failed
|
|
112
|
+
},
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function messageOf(error: unknown): string {
|
|
117
|
+
return error instanceof Error ? error.message : String(error)
|
|
118
|
+
}
|
|
@@ -4,7 +4,8 @@ import type { JobsPort } from '../../ports/jobs'
|
|
|
4
4
|
/**
|
|
5
5
|
* AUTHORED — CUTOVER (`job-runner`): typechecked against @aws-sdk/client-codebuild, never run
|
|
6
6
|
* against a real project. Starting the build is ALL this seam does — the job stays 'queued' until
|
|
7
|
-
* the build's FINAL step POSTs /api/webhooks/jobs with `
|
|
7
|
+
* the build's FINAL step POSTs /api/webhooks/jobs with `x-sssb-webhook-secret: $WEBHOOK_SECRET` (never `Authorization`, which
|
|
8
|
+
* the deployment's CloudFront replaces with its own signature) and
|
|
8
9
|
* `{ jobId, tenantId, status: 'completed' | 'failed', resultKey?, error? }`, which records the
|
|
9
10
|
* terminal transition via packages/kit/src/db/jobs.recordWebhookCompletion (idempotent under redelivery). The
|
|
10
11
|
* build receives its context through environment overrides, mirroring the fake handler's args —
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SSSB's optional ports in a real deployment: the ones an app may not use at all. Each has a switch, a deployment
|
|
3
|
+
* parameter each app records under `params.ports` in its `config/params.ts` (@sssb/cdk's `SssbApp` sets the variables
|
|
4
|
+
* from it, as it sets DATABASE_TRANSPORT from `params.database.transport`):
|
|
5
|
+
*
|
|
6
|
+
* - `LLM_PROVIDER`: `anthropic` (the default) or `none`. The `llm` port.
|
|
7
|
+
* - `EMAIL_PROVIDER`: `mailgun` (the default) or `none`. The `email` port, which the framework's invitations and
|
|
8
|
+
* notifications send through too.
|
|
9
|
+
* - `INBOUND_EMAIL_PROVIDER`: `mailgun` (the default) or `none`. The signing key the inbound email route verifies
|
|
10
|
+
* with (`@sssb/kit/service-auth/mailgun`). Without it that route refuses every request, as it always has.
|
|
11
|
+
* - `JOBS_RUNNER`: `codebuild` (the default), `in-process` or `none`. The `jobs` port: a CodeBuild build per job, the
|
|
12
|
+
* job's handler run in the server itself (./jobs-in-process.ts), or no jobs at all.
|
|
13
|
+
*
|
|
14
|
+
* An unset switch is its default, which is what real mode required before the switches existed, so a deployment that
|
|
15
|
+
* sets none of them boots as it did. `none` makes the port ABSENT (./absent.ts): its settings are not required, its
|
|
16
|
+
* SDK is never loaded, and a call through it throws an error that names the switch. Never fill an unused port's
|
|
17
|
+
* settings with placeholder values instead: a placeholder reaches the vendor and fails there, far from the cause.
|
|
18
|
+
*
|
|
19
|
+
* An explicit switch, never inferred from which settings happen to be set (the DATABASE_TRANSPORT rule): a
|
|
20
|
+
* deployment that half-configures a port must fail at boot, not quietly lose it.
|
|
21
|
+
*/
|
|
22
|
+
export const OPTIONAL_PORTS = {
|
|
23
|
+
llm: {
|
|
24
|
+
variable: 'LLM_PROVIDER',
|
|
25
|
+
default: 'anthropic',
|
|
26
|
+
env: { anthropic: { ANTHROPIC_API_KEY: 'llm-key' }, none: {} },
|
|
27
|
+
},
|
|
28
|
+
email: {
|
|
29
|
+
variable: 'EMAIL_PROVIDER',
|
|
30
|
+
default: 'mailgun',
|
|
31
|
+
env: {
|
|
32
|
+
mailgun: {
|
|
33
|
+
MAILGUN_DOMAIN: 'email-outbound',
|
|
34
|
+
MAILGUN_API_KEY: 'email-outbound',
|
|
35
|
+
EMAIL_FROM: 'email-outbound',
|
|
36
|
+
},
|
|
37
|
+
none: {},
|
|
38
|
+
},
|
|
39
|
+
},
|
|
40
|
+
inboundEmail: {
|
|
41
|
+
variable: 'INBOUND_EMAIL_PROVIDER',
|
|
42
|
+
default: 'mailgun',
|
|
43
|
+
// The key Mailgun signs inbound-route webhooks with, verified by the inbound email route at request time.
|
|
44
|
+
env: { mailgun: { MAILGUN_WEBHOOK_SIGNING_KEY: 'email-inbound' }, none: {} },
|
|
45
|
+
},
|
|
46
|
+
jobs: {
|
|
47
|
+
variable: 'JOBS_RUNNER',
|
|
48
|
+
default: 'codebuild',
|
|
49
|
+
env: { codebuild: { JOBS_CODEBUILD_PROJECT: 'job-runner' }, 'in-process': {}, none: {} },
|
|
50
|
+
},
|
|
51
|
+
} as const satisfies Record<
|
|
52
|
+
string,
|
|
53
|
+
{ variable: string; default: string; env: Record<string, Readonly<Record<string, string>>> }
|
|
54
|
+
>
|
|
55
|
+
|
|
56
|
+
export type OptionalPort = keyof typeof OPTIONAL_PORTS
|
|
57
|
+
export type PortChoice<P extends OptionalPort> = keyof (typeof OPTIONAL_PORTS)[P]['env'] & string
|
|
58
|
+
|
|
59
|
+
/** The deployment's choice for one optional port: its switch, or the default when unset. Fails on an unknown value. */
|
|
60
|
+
export function portChoice<P extends OptionalPort>(port: P): PortChoice<P> {
|
|
61
|
+
const { variable, default: fallback, env } = OPTIONAL_PORTS[port]
|
|
62
|
+
const choices = Object.keys(env)
|
|
63
|
+
const value = process.env[variable] || fallback
|
|
64
|
+
if (!choices.includes(value)) {
|
|
65
|
+
throw new Error(`${variable} must be one of ${choices.join(', ')} (got "${value}")`)
|
|
66
|
+
}
|
|
67
|
+
return value as PortChoice<P>
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The variables the deployment's optional-port choices require, each mapped to its cutover row. */
|
|
71
|
+
export function optionalPortsEnv(): Record<string, string> {
|
|
72
|
+
const required: Record<string, string> = {}
|
|
73
|
+
for (const port of Object.keys(OPTIONAL_PORTS) as OptionalPort[]) {
|
|
74
|
+
const env: Record<string, Readonly<Record<string, string>>> = OPTIONAL_PORTS[port].env
|
|
75
|
+
Object.assign(required, env[portChoice(port)])
|
|
76
|
+
}
|
|
77
|
+
return required
|
|
78
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The run mode, read once. Everything imports it from the registry (./index.ts), which re-exports it; this module
|
|
3
|
+
* exists so code that must not load the registry (the request proxy, ./proxy.ts; the digest job handler,
|
|
4
|
+
* ../jobs/digest-email.ts, which the registry itself loads) can ask the mode without its ports and their fakes.
|
|
5
|
+
*
|
|
6
|
+
* `APP_MODE` only ever tests for `'real'`, so an older `APP_MODE=fake` still resolves to `simulated`
|
|
7
|
+
* and no deployed config breaks.
|
|
8
|
+
*/
|
|
9
|
+
export type AppMode = 'simulated' | 'real'
|
|
10
|
+
export const appMode: AppMode = process.env['APP_MODE'] === 'real' ? 'real' : 'simulated'
|
|
11
|
+
export const isSimulated = appMode === 'simulated'
|
|
@@ -23,7 +23,7 @@ export function AppHeader({
|
|
|
23
23
|
* products, so any fallback key here would hold whichever app was written first and render it
|
|
24
24
|
* for every other app — silently, because a default that resolves is indistinguishable from a
|
|
25
25
|
* default that is right. Requiring the prop moves that from a sentence in a docstring to
|
|
26
|
-
* something the compiler checks (ADR-0012, docs/adopting.md).
|
|
26
|
+
* something the compiler checks (ADR-0012, docs/adopting-reference.md).
|
|
27
27
|
*/
|
|
28
28
|
appName: ReactNode
|
|
29
29
|
}) {
|
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
'use client'
|
|
2
|
+
|
|
3
|
+
import { useTranslations } from 'next-intl'
|
|
4
|
+
import type { ReactNode } from 'react'
|
|
5
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
|
6
|
+
import type { SimulatorJobs, SimulatorMail, SimulatorSchedules, SimulatorSummary } from '../../server-lib/simulator-api'
|
|
7
|
+
import { sameOriginPath } from '../../core/same-origin-path'
|
|
8
|
+
import { SimulatorPanel, type SimulatorNotice } from './simulator-panel'
|
|
9
|
+
|
|
10
|
+
const EMPTY_SUMMARY: SimulatorSummary = { viewpoint: null, signedIn: false, people: [] }
|
|
11
|
+
const EMPTY_MAIL: SimulatorMail = { emails: [], mailSeenAt: null, allCount: 0 }
|
|
12
|
+
const EMPTY_JOBS: SimulatorJobs = { jobs: [], held: false }
|
|
13
|
+
const EMPTY_SCHEDULES: SimulatorSchedules = { schedules: [], clockOffsetMs: 0, worldNow: new Date(0).toISOString() }
|
|
14
|
+
const EXPANDED_POLL_MS = 4_000
|
|
15
|
+
const COLLAPSED_POLL_MS = 15_000
|
|
16
|
+
const NOTICE_MS = 6_000
|
|
17
|
+
const MAIL_SCOPE_KEY = 'app-simulator-mail-scope'
|
|
18
|
+
const API = '/api/simulator'
|
|
19
|
+
|
|
20
|
+
/** A POST to the server host. Always JSON, even with no body: the server refuses any other content type. */
|
|
21
|
+
function post(path: string, body: unknown = {}): Promise<Response> {
|
|
22
|
+
return fetch(`${API}/${path}`, {
|
|
23
|
+
method: 'POST',
|
|
24
|
+
headers: { 'content-type': 'application/json' },
|
|
25
|
+
body: JSON.stringify(body),
|
|
26
|
+
})
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function getJson<T>(path: string): Promise<T | null> {
|
|
30
|
+
const response = await fetch(`${API}/${path}`)
|
|
31
|
+
return response.ok ? ((await response.json()) as T) : null
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Polls overlap, and their answers can arrive out of order: each fetch takes a ticket, and its answer is applied only
|
|
36
|
+
* when no later ticket's answer has been. A slow answer is never shown over a newer one, and, unlike "only the latest
|
|
37
|
+
* request's answer", answers slower than the poll still land.
|
|
38
|
+
*/
|
|
39
|
+
function useTickets() {
|
|
40
|
+
const counts = useRef({ issued: 0, applied: 0 })
|
|
41
|
+
return useMemo(
|
|
42
|
+
() => ({
|
|
43
|
+
take: () => (counts.current.issued += 1),
|
|
44
|
+
fresh: (ticket: number) => {
|
|
45
|
+
if (ticket <= counts.current.applied) return false
|
|
46
|
+
counts.current.applied = ticket
|
|
47
|
+
return true
|
|
48
|
+
},
|
|
49
|
+
}),
|
|
50
|
+
[],
|
|
51
|
+
)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function readStoredScope(): 'person' | 'all' | null {
|
|
55
|
+
try {
|
|
56
|
+
const stored = window.localStorage.getItem(MAIL_SCOPE_KEY)
|
|
57
|
+
return stored === 'person' || stored === 'all' ? stored : null
|
|
58
|
+
} catch {
|
|
59
|
+
return null
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The Simulator on an app's own `pnpm dev`: the panel, fed by the kit's server host
|
|
65
|
+
* (`@sssb/kit/server-lib/simulator-api`, which the app mounts at `src/app/api/simulator/[...path]/route.ts`). The app's
|
|
66
|
+
* locale layout renders it around the page, in simulated mode only and through a dynamic import, so no page of a real
|
|
67
|
+
* build loads it.
|
|
68
|
+
*
|
|
69
|
+
* It wires the tabs that host serves: People (switch to anyone, signed in or not), Mail (each person's inbox, or all
|
|
70
|
+
* of it) and Jobs with the world clock (run what is queued, move the clock, run what is due). The panel leaves out
|
|
71
|
+
* every tab it is not given; the rest, the app's own tabs, presets and tours included, are later stages of the same
|
|
72
|
+
* host. An app that needs one of them today keeps a glue of its own instead of this component.
|
|
73
|
+
*
|
|
74
|
+
* Polling, never a stream: the summary (the pill's unread badge) on a slow beat while the panel is collapsed, and
|
|
75
|
+
* the open tab's data on a faster one while it is expanded. Every acknowledgement is a notice inside the panel,
|
|
76
|
+
* never the app's own toast.
|
|
77
|
+
*/
|
|
78
|
+
export function SimulatorHost({ locale, children }: { locale: string; children: ReactNode }) {
|
|
79
|
+
const t = useTranslations('simulator')
|
|
80
|
+
const [summary, setSummary] = useState<SimulatorSummary>(EMPTY_SUMMARY)
|
|
81
|
+
const [expanded, setExpanded] = useState(false)
|
|
82
|
+
const [activeTab, setActiveTab] = useState('people')
|
|
83
|
+
const [mailScope, setMailScope] = useState<'person' | 'all'>('person')
|
|
84
|
+
const [mail, setMail] = useState<SimulatorMail>(EMPTY_MAIL)
|
|
85
|
+
const [jobsData, setJobsData] = useState<SimulatorJobs>(EMPTY_JOBS)
|
|
86
|
+
const [schedulesData, setSchedulesData] = useState<SimulatorSchedules>(EMPTY_SCHEDULES)
|
|
87
|
+
const [notices, setNotices] = useState<SimulatorNotice[]>([])
|
|
88
|
+
const noticeSeq = useRef(0)
|
|
89
|
+
const prevUnread = useRef<Map<string, number> | null>(null)
|
|
90
|
+
const summaryTickets = useTickets()
|
|
91
|
+
const mailTickets = useTickets()
|
|
92
|
+
const jobsTickets = useTickets()
|
|
93
|
+
|
|
94
|
+
const personEmail = summary.people.find((person) => person.key === summary.viewpoint)?.email ?? null
|
|
95
|
+
// Signed out, or no viewpoint yet: there is no one's own inbox to show, so the scope is every inbox.
|
|
96
|
+
const effectiveMailScope: 'person' | 'all' = personEmail ? mailScope : 'all'
|
|
97
|
+
const mailQuery = effectiveMailScope === 'all' ? 'all=1' : `person=${encodeURIComponent(summary.viewpoint ?? '')}`
|
|
98
|
+
// The scope this render shows. An answer for another scope is dropped even when it is the newest to arrive: the
|
|
99
|
+
// summary's first answer turns "all" into one person's inbox, and an action's callback can hold an older render's
|
|
100
|
+
// fetch.
|
|
101
|
+
const shownMailQuery = useRef(mailQuery)
|
|
102
|
+
useEffect(() => {
|
|
103
|
+
shownMailQuery.current = mailQuery
|
|
104
|
+
}, [mailQuery])
|
|
105
|
+
|
|
106
|
+
const pushNotice = useCallback((text: string) => {
|
|
107
|
+
const id = (noticeSeq.current += 1)
|
|
108
|
+
setNotices((prev) => [...prev, { id, text }])
|
|
109
|
+
setTimeout(() => setNotices((prev) => prev.filter((notice) => notice.id !== id)), NOTICE_MS)
|
|
110
|
+
}, [])
|
|
111
|
+
|
|
112
|
+
const refresh = useCallback(async () => {
|
|
113
|
+
const ticket = summaryTickets.take()
|
|
114
|
+
const next = await getJson<SimulatorSummary>('summary')
|
|
115
|
+
if (!next || !summaryTickets.fresh(ticket)) return
|
|
116
|
+
setSummary(next)
|
|
117
|
+
// New mail since the last poll gets a notice; the first load has nothing "new".
|
|
118
|
+
if (prevUnread.current) {
|
|
119
|
+
for (const person of next.people) {
|
|
120
|
+
const before = prevUnread.current.get(person.key) ?? 0
|
|
121
|
+
if (person.unreadMail > before) pushNotice(t('noticeNewMail', { email: person.email }))
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
prevUnread.current = new Map(next.people.map((person) => [person.key, person.unreadMail]))
|
|
125
|
+
}, [pushNotice, t, summaryTickets])
|
|
126
|
+
|
|
127
|
+
const refreshMail = useCallback(async () => {
|
|
128
|
+
const ticket = mailTickets.take()
|
|
129
|
+
const next = await getJson<SimulatorMail>(`mail?${mailQuery}`)
|
|
130
|
+
if (next && mailQuery === shownMailQuery.current && mailTickets.fresh(ticket)) setMail(next)
|
|
131
|
+
}, [mailQuery, mailTickets])
|
|
132
|
+
|
|
133
|
+
const refreshJobs = useCallback(async () => {
|
|
134
|
+
const ticket = jobsTickets.take()
|
|
135
|
+
const [nextJobs, nextSchedules] = await Promise.all([
|
|
136
|
+
getJson<SimulatorJobs>('jobs'),
|
|
137
|
+
getJson<SimulatorSchedules>('schedules'),
|
|
138
|
+
])
|
|
139
|
+
if (!nextJobs || !nextSchedules || !jobsTickets.fresh(ticket)) return
|
|
140
|
+
setJobsData(nextJobs)
|
|
141
|
+
setSchedulesData(nextSchedules)
|
|
142
|
+
}, [jobsTickets])
|
|
143
|
+
|
|
144
|
+
/** The open tab's own data, when the panel is expanded. */
|
|
145
|
+
const refreshOpenTab = useCallback(() => {
|
|
146
|
+
if (!expanded) return
|
|
147
|
+
if (activeTab === 'mail') void refreshMail()
|
|
148
|
+
if (activeTab === 'jobs') void refreshJobs()
|
|
149
|
+
}, [expanded, activeTab, refreshMail, refreshJobs])
|
|
150
|
+
|
|
151
|
+
useEffect(() => {
|
|
152
|
+
// Fetch on mount, and restore the remembered mail scope: syncing with external systems (the server, the
|
|
153
|
+
// browser's storage), which is what setting state from an effect is for.
|
|
154
|
+
// eslint-disable-next-line react-hooks/set-state-in-effect
|
|
155
|
+
void refresh()
|
|
156
|
+
const storedScope = readStoredScope()
|
|
157
|
+
if (storedScope) setMailScope(storedScope)
|
|
158
|
+
// Mount-only.
|
|
159
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
160
|
+
}, [])
|
|
161
|
+
|
|
162
|
+
useEffect(() => {
|
|
163
|
+
const id = setInterval(
|
|
164
|
+
() => {
|
|
165
|
+
void refresh()
|
|
166
|
+
refreshOpenTab()
|
|
167
|
+
},
|
|
168
|
+
expanded ? EXPANDED_POLL_MS : COLLAPSED_POLL_MS,
|
|
169
|
+
)
|
|
170
|
+
return () => clearInterval(id)
|
|
171
|
+
}, [expanded, refresh, refreshOpenTab])
|
|
172
|
+
|
|
173
|
+
useEffect(() => {
|
|
174
|
+
// A tab that opens (or a mail scope that changes) fetches at once rather than on the next poll: the state is
|
|
175
|
+
// set when the server answers, the same external-system sync as the mount effect.
|
|
176
|
+
// eslint-disable-next-line react-hooks/set-state-in-effect
|
|
177
|
+
refreshOpenTab()
|
|
178
|
+
}, [refreshOpenTab])
|
|
179
|
+
|
|
180
|
+
function handleSelect(person: string) {
|
|
181
|
+
void post('viewpoint', { person, locale }).then(async (response) => {
|
|
182
|
+
if (!response.ok) return
|
|
183
|
+
const { redirectTo } = (await response.json()) as { redirectTo: unknown }
|
|
184
|
+
// A full reload: the theme and the header are per-user server output. Only ever to a path on this origin:
|
|
185
|
+
// the server answers no other, and this is the client's own check.
|
|
186
|
+
const path = sameOriginPath(redirectTo)
|
|
187
|
+
if (path) window.location.assign(path)
|
|
188
|
+
})
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function handleMailSeen() {
|
|
192
|
+
if (!summary.viewpoint) return
|
|
193
|
+
void post('mail/seen', { person: summary.viewpoint }).then((response) => {
|
|
194
|
+
if (response.ok) void refresh()
|
|
195
|
+
})
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function handleScopeChange(scope: 'person' | 'all') {
|
|
199
|
+
setMailScope(scope)
|
|
200
|
+
try {
|
|
201
|
+
window.localStorage.setItem(MAIL_SCOPE_KEY, scope)
|
|
202
|
+
} catch {
|
|
203
|
+
// No storage (a private window, say): the scope lasts for this page only.
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function handleOpenLink(href: string) {
|
|
208
|
+
// Same origin only, and never silently. A path is followed; so is an absolute URL on this origin, since a real
|
|
209
|
+
// email carries one. Both go through `sameOriginPath`, which refuses what a browser would read as another
|
|
210
|
+
// origin (`/\host`, a tab inside). A protocol-relative `//host` link is resolved against this page, so it is
|
|
211
|
+
// judged by its host like any absolute URL; one with no origin at all (`mailto:`) is unusable here.
|
|
212
|
+
const path = sameOriginPath(href)
|
|
213
|
+
if (path) {
|
|
214
|
+
window.location.assign(path)
|
|
215
|
+
return
|
|
216
|
+
}
|
|
217
|
+
try {
|
|
218
|
+
const url = href.startsWith('//') ? new URL(href, window.location.href) : new URL(href)
|
|
219
|
+
const local =
|
|
220
|
+
url.origin === window.location.origin ? sameOriginPath(url.pathname + url.search + url.hash) : null
|
|
221
|
+
if (local) {
|
|
222
|
+
window.location.assign(local)
|
|
223
|
+
return
|
|
224
|
+
}
|
|
225
|
+
if (url.origin === window.location.origin || url.origin === 'null') {
|
|
226
|
+
pushNotice(t('noticeLinkUnusable', { href }))
|
|
227
|
+
} else {
|
|
228
|
+
pushNotice(t('noticeLinkOrigin', { origin: url.origin }))
|
|
229
|
+
}
|
|
230
|
+
} catch {
|
|
231
|
+
pushNotice(t('noticeLinkUnusable', { href }))
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function handleCopyLink(href: string) {
|
|
236
|
+
void navigator.clipboard
|
|
237
|
+
.writeText(href)
|
|
238
|
+
.then(() => pushNotice(t('noticeLinkCopied')))
|
|
239
|
+
.catch(() => pushNotice(t('noticeLinkCopyFailed')))
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function handleClearMail() {
|
|
243
|
+
void post('mail/clear').then((response) => {
|
|
244
|
+
if (!response.ok) return
|
|
245
|
+
void refreshMail()
|
|
246
|
+
void refresh()
|
|
247
|
+
pushNotice(t('noticeMailCleared'))
|
|
248
|
+
})
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
async function handleRunPending() {
|
|
252
|
+
const response = await post('jobs/run-pending')
|
|
253
|
+
if (!response.ok) return
|
|
254
|
+
const { ran } = (await response.json()) as { ran: number }
|
|
255
|
+
await refreshJobs()
|
|
256
|
+
pushNotice(t('noticeJobsRan', { count: ran }))
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** After the clock moved or due work ran: the schedules, the jobs a schedule spawned, and any mail they sent. */
|
|
260
|
+
async function afterSchedulesChanged(response: Response, moved: 'advanced' | 'reset' | null) {
|
|
261
|
+
if (!response.ok) return
|
|
262
|
+
const { spawned } = (await response.json()) as { spawned: number }
|
|
263
|
+
await Promise.all([refreshJobs(), refresh()])
|
|
264
|
+
if (spawned > 0) pushNotice(t('noticeScheduleFired', { count: spawned }))
|
|
265
|
+
else if (moved === 'advanced') pushNotice(t('noticeClockAdvanced'))
|
|
266
|
+
else if (moved === 'reset') pushNotice(t('noticeClockReset'))
|
|
267
|
+
else pushNotice(t('noticeNoDue'))
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
async function handleAdvanceClock(deltaMs: number) {
|
|
271
|
+
await afterSchedulesChanged(await post('clock', { action: 'advance', deltaMs }), 'advanced')
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
async function handleResetClock() {
|
|
275
|
+
await afterSchedulesChanged(await post('clock', { action: 'reset' }), 'reset')
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
async function handleRunDue() {
|
|
279
|
+
await afterSchedulesChanged(await post('schedules/run-due'), null)
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function handleLocaleChange(next: string) {
|
|
283
|
+
if (next === locale) return
|
|
284
|
+
// Swap the leading /<locale> segment and reload the same page: the theme and the header are per-request
|
|
285
|
+
// server output, so a client navigation would not re-render them.
|
|
286
|
+
const { pathname, search, hash } = window.location
|
|
287
|
+
const swapped = pathname.replace(new RegExp(`^/${locale}(?=/|$)`), `/${next}`) + search + hash
|
|
288
|
+
window.location.assign(sameOriginPath(swapped) ?? `/${next}`)
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
return (
|
|
292
|
+
<div style={{ display: 'flex', minHeight: '100vh', alignItems: 'stretch' }}>
|
|
293
|
+
<div style={{ flex: 1, minWidth: 0 }}>{children}</div>
|
|
294
|
+
<SimulatorPanel
|
|
295
|
+
people={summary.people}
|
|
296
|
+
viewpoint={summary.viewpoint}
|
|
297
|
+
signedIn={summary.signedIn}
|
|
298
|
+
onSelect={handleSelect}
|
|
299
|
+
onRefresh={refresh}
|
|
300
|
+
onExpandedChange={(value) => {
|
|
301
|
+
setExpanded(value)
|
|
302
|
+
if (value) void refresh()
|
|
303
|
+
}}
|
|
304
|
+
onTabChange={setActiveTab}
|
|
305
|
+
onLocaleChange={handleLocaleChange}
|
|
306
|
+
notices={notices}
|
|
307
|
+
mail={{
|
|
308
|
+
emails: mail.emails,
|
|
309
|
+
scope: effectiveMailScope,
|
|
310
|
+
onScopeChange: handleScopeChange,
|
|
311
|
+
personEmail,
|
|
312
|
+
mailSeenAt: mail.mailSeenAt,
|
|
313
|
+
allCount: mail.allCount,
|
|
314
|
+
onOpenLink: handleOpenLink,
|
|
315
|
+
onSeen: handleMailSeen,
|
|
316
|
+
onClear: handleClearMail,
|
|
317
|
+
onCopyLink: handleCopyLink,
|
|
318
|
+
}}
|
|
319
|
+
jobs={{
|
|
320
|
+
jobs: jobsData.jobs,
|
|
321
|
+
held: jobsData.held,
|
|
322
|
+
onRunPending: handleRunPending,
|
|
323
|
+
schedules: schedulesData.schedules,
|
|
324
|
+
clock: {
|
|
325
|
+
offsetMs: schedulesData.clockOffsetMs,
|
|
326
|
+
worldNow: schedulesData.worldNow,
|
|
327
|
+
onAdvance: handleAdvanceClock,
|
|
328
|
+
onReset: handleResetClock,
|
|
329
|
+
onRunDue: handleRunDue,
|
|
330
|
+
},
|
|
331
|
+
}}
|
|
332
|
+
/>
|
|
333
|
+
</div>
|
|
334
|
+
)
|
|
335
|
+
}
|