Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/answers-are-read-by-their-shape.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@fnndsc/menu": minor
"@fnndsc/argus": patch
---

ARGUS reads listings, a feed's access and tags, runs and games by their shape, keeping the good rows of a mixed answer.

Eleven places took an answer's model as whatever they expected it to be. Each now reads it through a schema in `@fnndsc/menu` (`fsListings_read`, `elements_read` and the shapes beside them), element by element where a list is read: a malformed block, entry or row is left out and named, the rest kept, and an answer of the wrong shape reads as none instead of failing later.
7 changes: 7 additions & 0 deletions .changeset/what-stratus-reads-is-read-by-shape.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@fnndsc/stratus": patch
---

A malformed plan, keep, verify, manifest list or Red Hat answer is refused by name, never cast and failing later.

Every document stratus did not write itself (a plan kept on this host, a keep in the tenancy's vault, the last verify, the platform manifests, ChRIS's secrets, a Terraform state, Red Hat's and GoDaddy's answers, what a program on a VM printed) is now read through a schema in the module that owns it, naming only the fields read and keeping the rest. One that does not read is refused naming the document and the field, never quoting it; a list of hosts, manifests or records is read row by row, a malformed row left out; and the nulls Red Hat answers for a new cluster (no status words, no progress yet) read as absent. A `state.json` kept here that is no JSON object naming what it keeps is refused by its file, never quoted. stratus now depends on zod.
7 changes: 4 additions & 3 deletions apps/argus/src/app/access.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* user and what to refresh once something changed.
*/
import type { WireEnvelope } from '@fnndsc/menu';
import { arg_quote, POSIX_IDENTITY_MODEL_KIND, posixIdentityModelSchema, type PosixGroup } from '@fnndsc/menu';
import { ANSWER_MODEL_KINDS, arg_quote, elements_read, fsAclBlockSchema, POSIX_IDENTITY_MODEL_KIND, posixIdentityModelSchema, type PosixGroup } from '@fnndsc/menu';

import type { ExecuteOutcome } from '../calypso/client.js';
import type { PaneAskChoice, PaneAskRequest } from '../features/ask/paneAsk.js';
Expand Down Expand Up @@ -59,8 +59,9 @@ export interface AccessVerbs {
*/
export function holders_extract(outcome: ExecuteOutcome): FeedHolders | null {
for (const envelope of outcome.envelopes as ReadonlyArray<WireEnvelope>) {
if (envelope.model?.kind !== 'fs.acl') continue;
const block = (envelope.model.data as Array<{ usernames?: string[]; groups?: string[]; public?: boolean }>)[0];
if (envelope.model?.kind !== ANSWER_MODEL_KINDS.fsAcl) continue;
// Read by shape, block by block: the feed's block, or none when it does not read.
const block = elements_read(envelope.model.data, fsAclBlockSchema).kept[0];
if (block === undefined) return null;
return { users: block.usernames ?? [], groups: block.groups ?? [], public: block.public === true };
}
Expand Down
10 changes: 3 additions & 7 deletions apps/argus/src/app/cycler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
*/
import { pipelineDiagramModelSchema, DAG_MODEL_KINDS, type PipelineDiagramModel, type PipelineDiagramNode, type WireEnvelope, arg_quote } from '@fnndsc/menu';

import { answerListings_extract, type Listed } from '../calypso/answerModel.js';
import type { ArgusClient, ExecuteOutcome } from '../calypso/client.js';
import type { FsListing } from '../features/files/entries.js';
import { ChrisSpace, type SceneNode } from '../scene/chrisSpace.js';

/** How long each pipeline holds the stage. */
Expand Down Expand Up @@ -139,12 +139,8 @@ export class PipelineCycler {
*/
export function cyclerNames_seed(client: Pick<ArgusClient, 'line_execute'>, cycler: Pick<PipelineCycler, 'names_set'>): void {
void client.line_execute('ls /bin', { silent: true, observe: false }).then((outcome: ExecuteOutcome): void => {
const listing: WireEnvelope | undefined = outcome.envelopes.find(
(envelope: WireEnvelope): boolean => envelope.model?.kind === 'fs.listing',
);
const data: FsListing[] | undefined = listing?.model?.data as FsListing[] | undefined;
const names: string[] = (data ?? [])
.flatMap((entry: FsListing) => entry.items)
const names: string[] = answerListings_extract(outcome)
.flatMap((entry: Listed) => entry.items)
.filter((item): boolean => item.type === 'pipeline')
.map((item): string => item.name);
cycler.names_set(names);
Expand Down
21 changes: 7 additions & 14 deletions apps/argus/src/app/dashboardTiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
import type { SessionNotes } from '@fnndsc/menu';

import type { GroupSnapshot } from './dormant.js';
import { answerListings_extract, type Listed } from '../calypso/answerModel.js';
import type { ExecuteOutcome } from '../calypso/client.js';
import { DRAWER_CHORDS, VERB_LINES, type DrawerChord } from '../console/argusLang.js';
import type { FsListingEntry } from '../features/files/entries.js';
import { TILE_ABOUT, type TileAbout } from '../features/launcher/about.js';
import type { LauncherRow, LauncherTile } from '../features/launcher/panel.js';

Expand Down Expand Up @@ -62,24 +62,17 @@ export function dashboardTiles_build(hooks: DashboardHooks): () => Promise<Reado
hooks.notes_latest(),
hooks.contribution?.() ?? Promise.resolve({ afterFiles: [], afterPanes: [] }),
]);
let entries: FsListingEntry[] = [];
let homePath: string = '~';
for (const envelope of home.envelopes) {
if (envelope.model?.kind !== 'fs.listing') continue;
const listings = envelope.model.data as Array<{ path?: unknown; items?: unknown }>;
const first = listings[0];
if (first !== undefined && Array.isArray(first.items)) {
entries = first.items as FsListingEntry[];
if (typeof first.path === 'string') homePath = first.path;
}
}
const folders: FsListingEntry[] = entries.filter((entry: FsListingEntry): boolean => entry.type === 'dir');
// The home listing read by shape: a malformed entry is left out, never cast.
const first: Listed | undefined = answerListings_extract(home)[0];
const entries: Listed['items'] = first?.items ?? [];
const homePath: string = first?.path ?? '~';
const folders: Listed['items'] = entries.filter((entry): boolean => entry.type === 'dir');
const desktops: GroupSnapshot[] = hooks.desktops();

const files: LauncherTile = {
key: 'files', name: 'FILES', hue: '--harvestgold', numeral: '2',
figures: [{ text: `${entries.length} ENTRIES` }],
rows: folders.slice(0, 5).map((entry: FsListingEntry): LauncherRow => ({
rows: folders.slice(0, 5).map((entry): LauncherRow => ({
text: entry.name,
open: (): void => hooks.home_cd(homePath.endsWith('/') ? `${homePath}${entry.name}` : `${homePath}/${entry.name}`),
})),
Expand Down
8 changes: 4 additions & 4 deletions apps/argus/src/app/feedRows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
* A module of the host: the host builds the feed verbs once
* (`feedVerbs_wire`) and hands them to every roster.
*/
import { ansi_strip, type FeedListEntry } from '@fnndsc/menu';
import { ansi_strip, ANSWER_MODEL_KINDS, elements_read, fsXattrBlockSchema, type FeedListEntry } from '@fnndsc/menu';

import type { ExecuteOutcome } from '../calypso/client.js';
import type { ListingAction } from '../features/roster/row.js';
Expand Down Expand Up @@ -63,9 +63,9 @@ export interface FeedRowHandlers {
*/
export function feedTags_extract(outcome: ExecuteOutcome): string[] {
for (const envelope of outcome.envelopes) {
if (envelope.model?.kind !== 'fs.xattr') continue;
const blocks = envelope.model.data as Array<{ tags?: unknown }>;
return (blocks[0]?.tags as string[] | undefined) ?? [];
if (envelope.model?.kind !== ANSWER_MODEL_KINDS.fsXattr) continue;
// Read by shape: the feed's block's tags, or none when it does not read.
return [...(elements_read(envelope.model.data, fsXattrBlockSchema).kept[0]?.tags ?? [])];
}
return [];
}
Expand Down
16 changes: 8 additions & 8 deletions apps/argus/src/app/surfaceHost.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
*
* @module
*/
import { ansi_strip, type WireEnvelope } from '@fnndsc/menu';
import { ansi_strip, ANSWER_MODEL_KINDS, elements_read, pluginInstanceRowSchema, runScheduledSchema, type WireEnvelope } from '@fnndsc/menu';

import { binView_wire } from './binView.js';
import { browser_wire } from './browser.js';
Expand Down Expand Up @@ -341,10 +341,10 @@ export function surfaceRecents_wire(s: Pick<SurfaceState, 'birth_record' | 'clie
.then((outcome: ExecuteOutcome): void => {
const names: string[] = [];
for (const envelope of outcome.envelopes) {
if (envelope.model?.kind !== 'plugininstance.list' || !Array.isArray(envelope.model.data)) continue;
for (const row of envelope.model.data as Array<{ pluginName?: unknown; pluginVersion?: unknown; owner?: unknown }>) {
if (typeof row.pluginName !== 'string' || typeof row.pluginVersion !== 'string') continue;
if (s.promptUser !== null && typeof row.owner === 'string' && row.owner !== s.promptUser) continue;
if (envelope.model?.kind !== ANSWER_MODEL_KINDS.pluginInstanceList) continue;
// Row by row, by shape: a row without a plugin's name and version is left out, the rest kept.
for (const row of elements_read(envelope.model.data, pluginInstanceRowSchema).kept) {
if (s.promptUser !== null && row.owner !== undefined && row.owner !== s.promptUser) continue;
if (row.pluginName === 'pl-dircopy') continue;
const name: string = `${row.pluginName}-v${row.pluginVersion}`;
if (!names.includes(name)) names.push(name);
Expand Down Expand Up @@ -450,9 +450,9 @@ export function surfaceRun_wire(s: Pick<SurfaceState, 'askOnPane_await' | 'catal
const scheduled: WireEnvelope | undefined = outcome.envelopes.find(
(envelope: WireEnvelope): boolean => envelope.model?.kind === 'run.scheduled' || envelope.model?.kind === 'pipeline.scheduled',
);
const data: { feedId?: unknown } | undefined = scheduled?.model?.data as { feedId?: unknown } | undefined;
if (typeof data?.feedId === 'number') {
panel.run_show(data.feedId);
const landed = runScheduledSchema.safeParse(scheduled?.model?.data);
if (landed.success) {
panel.run_show(landed.data.feedId);
return;
}
const refusal: string = ansi_strip(outcome.envelopes
Expand Down
7 changes: 4 additions & 3 deletions apps/argus/src/app/surfaceSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
* @module
*/
import type { ClosingCause, PromptContext, WireEnvelope, WatchState, LaneTelemetry, CubeTelemetry, JobsStateTelemetry } from '@fnndsc/menu';
import { gamesChimeSchema, gamesShowSchema } from '@fnndsc/menu';

import { buildMatch_wire } from './buildMatch.js';
import { consoleZoom_set, consoleZoomSet_install, consoleZoom_toggle, drawer_wire, zoom_wire } from './consoleDrawer.js';
Expand Down Expand Up @@ -76,7 +77,7 @@ export function surfaceInstruments_wire(s: Pick<SurfaceState, 'attached' | 'buil
// chell takes the screen); `--pane`, or the transcript, which has no
// screen to play on, runs it in the GAMES pane.
if (envelope.model?.kind === 'games.show') {
const pane: boolean = (envelope.model.data as { pane?: boolean } | undefined)?.pane === true;
const pane: boolean = gamesShowSchema.safeParse(envelope.model.data).data?.pane === true;
if (pane || s.consoleMode === null || !s.consoleMode.terminal_is()) s.terminal.line_note(s.gamesPane.show(envelope.model.data));
}
}
Expand Down Expand Up @@ -269,8 +270,8 @@ export function surfaceTells_wire(s: Pick<SurfaceState, 'argusHost' | 'buildWatc
ambient_receive: (envelope: WireEnvelope): void => {
// A chime (timer, leave): noted in the console, and spoken.
if (envelope.model?.kind === 'games.chime') {
const text: unknown = (envelope.model.data as { text?: unknown } | null)?.text;
if (typeof text === 'string') { s.terminal.line_note(`🔔 ${text}`); voice_say({ text }); }
const chime = gamesChimeSchema.safeParse(envelope.model.data);
if (chime.success) { s.terminal.line_note(`🔔 ${chime.data.text}`); voice_say({ text: chime.data.text }); }
return;
}
// A task's end, or a joblet's (`[1]+ Done pull …`), or a joblet
Expand Down
9 changes: 2 additions & 7 deletions apps/argus/src/app/tags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
* A module of the host: the host hands in the pane question and a way to
* show the roster again once a tag changed.
*/
import type { WireEnvelope } from '@fnndsc/menu';
import { arg_quote } from '@fnndsc/menu';
import { answerListings_extract } from '../calypso/answerModel.js';
import type { ExecuteOutcome } from '../calypso/client.js';
import type { PaneAskChoice, PaneAskRequest } from '../features/ask/paneAsk.js';
import type { HostContext } from './hostContext.js';
Expand Down Expand Up @@ -41,12 +41,7 @@ export interface TagVerbs {
* @returns The names, in the kernel's order.
*/
export function tagNames_extract(outcome: ExecuteOutcome): string[] {
for (const envelope of outcome.envelopes as ReadonlyArray<WireEnvelope>) {
if (envelope.model?.kind !== 'fs.listing') continue;
const listings = envelope.model.data as Array<{ items?: Array<{ name?: unknown }> }>;
return (listings[0]?.items ?? []).map((item): string => String(item.name ?? '')).filter((name: string): boolean => name !== '');
}
return [];
return (answerListings_extract(outcome)[0]?.items ?? []).map((item): string => item.name).filter((name: string): boolean => name !== '');
}

/**
Expand Down
5 changes: 4 additions & 1 deletion apps/argus/src/app/trekBridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
* A module of the host, shaped as the GAMES pane's: the host hands in its
* context and reads the bridge's verbs.
*/
import { gamesTrekSchema } from '@fnndsc/menu';

import type { SurfaceAsk } from '../calypso/client.js';
import { TrekBridge } from '../features/trek/bridge.js';
import type { BridgeVoice, CueName } from '../features/trek/cues.js';
Expand Down Expand Up @@ -102,7 +104,8 @@ export function trekBridge_wire(context: Pick<HostContext, 'client'>): TrekBridg
// The operator's own command, never instrument traffic: the daemon lets it ask its questions.
const outcome = await context.client.line_execute(line, { operator: true });
const ended = outcome.envelopes.find((envelope) => envelope.model?.kind === 'games.trek');
opened.harness_get().end(typeof (ended?.model?.data as { exit?: number } | undefined)?.exit === 'number' ? (ended?.model?.data as { exit: number }).exit : 0);
// How the game ended, read by shape; an end that does not read is a clean one, as before.
opened.harness_get().end(gamesTrekSchema.safeParse(ended?.model?.data).data?.exit ?? 0);
} catch {
opened.harness_get().end(1);
} finally {
Expand Down
10 changes: 6 additions & 4 deletions apps/argus/src/calypso/answerModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
* @module
*/

import { ansi_strip } from '@fnndsc/menu';
import { ansi_strip, ANSWER_MODEL_KINDS, fsListings_read } from '@fnndsc/menu';

/**
* An answer as these readings see it: its envelopes, each with what it rendered and the model it carries.
Expand Down Expand Up @@ -105,7 +105,9 @@ export function answerModel_extract<T>(answer: AnswerEnvelopes, kind: string, pa
}

/**
* The listings an `ls` answered.
* The listings an `ls` answered, each block and entry read by shape
* (`fsListings_read`): a malformed block or entry is left out, every other
* one kept.
*
* @param answer - The answer.
* @returns Them, or none.
Expand All @@ -117,8 +119,8 @@ export function answerModel_extract<T>(answer: AnswerEnvelopes, kind: string, pa
*/
export function answerListings_extract(answer: AnswerEnvelopes): Listed[] {
for (const envelope of answer.envelopes) {
if (envelope.model?.kind !== 'fs.listing' || !Array.isArray(envelope.model.data)) continue;
return (envelope.model.data as unknown[]).filter((one: unknown): one is Listed => typeof one === 'object' && one !== null && typeof (one as { path?: unknown }).path === 'string' && Array.isArray((one as { items?: unknown }).items));
if (envelope.model?.kind !== ANSWER_MODEL_KINDS.fsListing) continue;
return [...fsListings_read(envelope.model.data).blocks];
}
return [];
}
Expand Down
8 changes: 8 additions & 0 deletions apps/argus/tests/unit/dashboardTiles.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,14 @@ describe('the dashboard tiles', () => {
expect(keys(await dashboardTiles_build(hooks(30, contribution(10)))())).toEqual(['files', 'analyses', 'pacs', 'panes', 'universe', 'help', 'notes', 'console']);
});

it('reads home by shape: a malformed entry is left out, a model of the wrong shape is no listing, never a throw', async () => {
const answer = (data: unknown) => async (): Promise<ExecuteOutcome> => ({ envelopes: [{ status: 'ok', rendered: '', model: { kind: 'fs.listing', data } }] } as unknown as ExecuteOutcome);
const figure = async (data: unknown): Promise<string | undefined> => (await dashboardTiles_build({ ...hooks(0), ask: answer(data) })()).find((t) => t.key === 'files')?.figures[0]?.text;
expect(await figure([{ path: '/home/u', items: [{ name: 'a', type: 'dir' }, { name: 7, type: 'dir' }, { name: 'b', type: 'file' }] }])).toBe('2 ENTRIES');
expect(await figure(null)).toBe('0 ENTRIES');
expect(await figure([{ path: '/home/u', items: 'nonsense' }])).toBe('0 ENTRIES');
});

it('lets a composition say what FILES holds, and says something neutral without one', async () => {
const alone = await dashboardTiles_build(hooks(3))();
expect(alone.find((t) => t.key === 'files')?.about.text).toBe('Your home: the files this session holds.');
Expand Down
2 changes: 1 addition & 1 deletion apps/argus/tests/unit/feedTags.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ describe('the lines a tag is hung by', () => {
});

it('reads the tag names from ls /proc/tags and a feed\'s tags from getfattr', () => {
expect(tagNames_extract(outcome({ kind: 'fs.listing', data: [{ path: '/proc/tags', items: [{ name: 'urgent' }, { name: 'qc' }] }] }))).toEqual(['urgent', 'qc']);
expect(tagNames_extract(outcome({ kind: 'fs.listing', data: [{ path: '/proc/tags', items: [{ name: 'urgent', type: 'dir' }, { name: 'qc', type: 'dir' }] }] }))).toEqual(['urgent', 'qc']);
expect(tagNames_extract(outcome({ kind: 'fs.cwd', data: {} }))).toEqual([]);
expect(feedTags_extract(outcome({ kind: 'fs.xattr', data: [{ path: 'feed_12', feedId: 12, tags: ['urgent'] }] }))).toEqual(['urgent']);
});
Expand Down
Loading
Loading