Skip to content

Commit 7b8d1e0

Browse files
committed
feat(spec,rest): the record page payload serves the timeline stream's count
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QsR2jSrQVdYaC3GSLbQCFd
1 parent 45efba2 commit 7b8d1e0

4 files changed

Lines changed: 311 additions & 10 deletions

File tree

‎packages/rest/src/record-page-routes.test.ts‎

Lines changed: 143 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,14 +22,17 @@
2222
* - [#28470] a related list's `expand` is its read's own `$expand`, and each
2323
* stream part — the discussion (the thread, then its reactions), the
2424
* activity and the attachments — is the `findData` the console's own read of
25-
* it makes, behind that object's exposure gate, refused on its own.
25+
* it makes, behind that object's exposure gate, refused on its own;
26+
* - [#28737] the timeline part is a count of each source the body names, by
27+
* that source's own read as the caller, summed as the spec's timeline table
28+
* spells it.
2629
*
2730
* The end-to-end half, under row-level and field-level security as a member who
2831
* is not an admin, is `record-page.dogfood.test.ts`.
2932
*/
3033

3134
import { describe, it, expect, vi } from 'vitest';
32-
import { RecordPageResponseSchema } from '@objectstack/spec/api';
35+
import { RECORD_TIMELINE_UNDRAWN_ACTIVITY_TYPES, RecordPageResponseSchema } from '@objectstack/spec/api';
3336
import { RestServer } from './rest-server.js';
3437
import { RECORD_PAGE_PARAMS } from './record-page-routes.js';
3538
import { unknownQueryParamMessage } from './query-allowlist.js';
@@ -522,3 +525,141 @@ describe('[#28470] the record\'s streams and the related rows\' names ride in th
522525
expect(findData).not.toHaveBeenCalled();
523526
});
524527
});
528+
529+
describe('[#28737] the timeline part is the 动态 stream\'s size, counted by the caller\'s own reads', () => {
530+
const items = { ...ITEMS, sys_audit_log: systemObject('sys_audit_log') };
531+
// Each count read answers its own total, so a sum that took one source's
532+
// count for another's would show.
533+
const countOf = (req: any) => {
534+
const where = req.query?.where ?? {};
535+
if (req.object === 'sys_comment') return { records: [], total: 3 };
536+
if (req.object === 'sys_audit_log') return { records: [], total: 40 };
537+
if (req.object === 'sys_activity') return { records: [], total: where.type === 'updated' ? 30 : 250 };
538+
return { records: [], total: 0 };
539+
};
540+
const ofRecord = { object_name: 'account', record_id: 'a1' };
541+
542+
it('counts each named source as the caller, and the updates step aside once a field change is counted', async () => {
543+
const { call, findData } = boot({ items, findData: async (req) => countOf(req) });
544+
const answer = await call({ timeline: { discussion: true, activity: true, fieldChanges: true } });
545+
expect(answer.status).toBe(200);
546+
const data = RecordPageResponseSchema.parse(answer.body.data);
547+
// 3 comments + 40 field changes + 250 drawn activity rows − their 30 updates.
548+
expect(data.timeline).toEqual({ total: 263 });
549+
const reads = findData.mock.calls.map(([req]) => req);
550+
expect(reads).toEqual(expect.arrayContaining([
551+
{ object: 'sys_comment', query: { object: 'sys_comment', where: { thread_id: 'account:a1' }, limit: 0, count: true }, context: CTX },
552+
{
553+
object: 'sys_audit_log',
554+
query: { object: 'sys_audit_log', where: { ...ofRecord, action: { $in: ['create', 'update', 'delete'] } }, limit: 0, count: true },
555+
context: CTX,
556+
},
557+
{
558+
object: 'sys_activity',
559+
query: {
560+
object: 'sys_activity',
561+
where: { ...ofRecord, type: { $nin: [...RECORD_TIMELINE_UNDRAWN_ACTIVITY_TYPES] } },
562+
limit: 0,
563+
count: true,
564+
},
565+
context: CTX,
566+
},
567+
{
568+
object: 'sys_activity',
569+
query: { object: 'sys_activity', where: { ...ofRecord, type: 'updated' }, limit: 0, count: true },
570+
context: CTX,
571+
},
572+
]));
573+
expect(reads).toHaveLength(4);
574+
});
575+
576+
it('counts only the sources named, and no update steps aside without a field change', async () => {
577+
const { call, findData } = boot({ items, findData: async (req) => countOf(req) });
578+
const activityOnly = RecordPageResponseSchema.parse((await call({ timeline: { discussion: false, activity: true, fieldChanges: false } })).body.data);
579+
expect(activityOnly.timeline).toEqual({ total: 250 });
580+
expect(findData.mock.calls.map(([req]) => req.object)).toEqual(['sys_activity']);
581+
582+
const noChanges = boot({
583+
items,
584+
findData: async (req) => (req.object === 'sys_audit_log' ? { records: [], total: 0 } : countOf(req)),
585+
});
586+
const data = RecordPageResponseSchema.parse((await noChanges.call({ timeline: { discussion: true, activity: true, fieldChanges: true } })).body.data);
587+
expect(data.timeline).toEqual({ total: 253 });
588+
});
589+
590+
it('a record with no entry counts 0', async () => {
591+
const { call } = boot({ items, findData: async () => ({ records: [], total: 0 }) });
592+
const data = RecordPageResponseSchema.parse((await call({ timeline: { discussion: true, activity: true, fieldChanges: true } })).body.data);
593+
expect(data.timeline).toEqual({ total: 0 });
594+
});
595+
596+
it('a refused comment or activity count refuses the part; the record and the other parts answer', async () => {
597+
for (const refused of ['sys_comment', 'sys_activity']) {
598+
const { call } = boot({
599+
items,
600+
findData: async (req) => {
601+
if (req.object === refused) throw permissionDenied();
602+
return countOf(req);
603+
},
604+
});
605+
const answer = await call({ attachments: { top: 5 }, timeline: { discussion: true, activity: true, fieldChanges: true } });
606+
expect(answer.status, refused).toBe(200);
607+
const data = RecordPageResponseSchema.parse(answer.body.data);
608+
expect(data.timeline, refused).toEqual({ error: { code: 'PERMISSION_DENIED', status: 403, message: expect.any(String) } });
609+
expect(data.record).toEqual(RECORD);
610+
expect(data.attachments).toEqual({ total: 0, records: [] });
611+
}
612+
});
613+
614+
it('a refused ledger count is no field change, so the updates stay in the count', async () => {
615+
const { call } = boot({
616+
items,
617+
findData: async (req) => {
618+
if (req.object === 'sys_audit_log') throw permissionDenied();
619+
return countOf(req);
620+
},
621+
});
622+
const data = RecordPageResponseSchema.parse((await call({ timeline: { discussion: true, activity: true, fieldChanges: true } })).body.data);
623+
expect(data.timeline).toEqual({ total: 253 });
624+
});
625+
626+
it('a source this deployment does not serve holds no entry', async () => {
627+
const withoutLedger = { ...items };
628+
delete (withoutLedger as Record<string, unknown>).sys_audit_log;
629+
delete (withoutLedger as Record<string, unknown>).sys_comment;
630+
const { call } = boot({
631+
items: withoutLedger,
632+
findData: async (req) => {
633+
if (req.object === 'sys_audit_log' || req.object === 'sys_comment') throw objectNotFound(req.object);
634+
return countOf(req);
635+
},
636+
});
637+
const data = RecordPageResponseSchema.parse((await call({ timeline: { discussion: true, activity: true, fieldChanges: true } })).body.data);
638+
expect(data.timeline).toEqual({ total: 250 });
639+
});
640+
641+
it('a source on an object the API does not expose is refused as its list read is, and never read', async () => {
642+
const hidden = { ...items, sys_activity: { ...items.sys_activity, enable: { apiEnabled: false } } };
643+
const { call, findData } = boot({ items: hidden, findData: async (req) => countOf(req) });
644+
const data = RecordPageResponseSchema.parse((await call({ timeline: { discussion: false, activity: true, fieldChanges: false } })).body.data);
645+
expect(data.timeline).toEqual({ error: expect.objectContaining({ code: 'OBJECT_API_DISABLED', status: 404 }) });
646+
expect(findData).not.toHaveBeenCalled();
647+
});
648+
649+
it('the timeline body is strict: a missing or non-boolean source, or an undeclared key, is a 400 and nothing is read', async () => {
650+
const { call, getData, findData } = boot({ items });
651+
for (const body of [
652+
{ timeline: true },
653+
{ timeline: {} },
654+
{ timeline: { discussion: true, activity: true } },
655+
{ timeline: { discussion: 'yes', activity: true, fieldChanges: true } },
656+
{ timeline: { discussion: true, activity: true, fieldChanges: true, top: 5 } },
657+
]) {
658+
const answer = await call(body);
659+
expect(answer.status, JSON.stringify(body)).toBe(400);
660+
expect(answer.body.error.code).toBe('VALIDATION_FAILED');
661+
}
662+
expect(getData).not.toHaveBeenCalled();
663+
expect(findData).not.toHaveBeenCalled();
664+
});
665+
});

‎packages/rest/src/record-page-routes.ts‎

Lines changed: 55 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,11 @@
1818
* streams — `discussion`, `activity`, `attachments` — are `findData` over
1919
* `sys_comment` (then `sys_comment_reaction`), `sys_activity` and
2020
* `sys_attachment`, each after that object's own exposure gate, scoped to this
21-
* record and ordered as the spec module's stream table spells it. Object
21+
* record and ordered as the spec module's stream table spells it. [#28737]
22+
* The `timeline` part is the size of the record's 动态 stream: a `findData`
23+
* count (`limit: 0`, `count: true`) of each source the request names, over
24+
* the same objects behind the same gates, as the spec's timeline table spells
25+
* it — so the count is of rows the caller could read, and of no other. Object
2226
* permissions, row-level security, sharing and field-level security are
2327
* therefore whatever those calls apply, by construction.
2428
*
@@ -30,6 +34,8 @@
3034
*/
3135

3236
import {
37+
RECORD_TIMELINE_UNDRAWN_ACTIVITY_TYPES,
38+
RECORD_TIMELINE_UPDATE_ACTIVITY_TYPE,
3339
RecordPageRequestSchema,
3440
zodIssuesToFields,
3541
type GetDataRequest,
@@ -56,6 +62,10 @@ const COMMENT_OBJECT = 'sys_comment';
5662
const COMMENT_REACTION_OBJECT = 'sys_comment_reaction';
5763
const ACTIVITY_OBJECT = 'sys_activity';
5864
const ATTACHMENT_OBJECT = 'sys_attachment';
65+
/** [#28737] The record's field changes the timeline counts: the ledger's own object. */
66+
const AUDIT_LOG_OBJECT = 'sys_audit_log';
67+
/** [#28737] The ledger's write actions — the entries the 动态 stream draws as field changes. */
68+
const FIELD_CHANGE_ACTIONS = ['create', 'update', 'delete'];
5969

6070
/**
6171
* A `$expand` list spelled as the relation map the QueryAST declares, as the
@@ -163,11 +173,15 @@ export function registerRecordPageEndpoints(this: RecordPageRouteHost, basePath:
163173
const related = body.related ?? [];
164174
// [#28470] The stream objects' items too, for their exposure
165175
// gates — read in the same metadata wave as the children's.
166-
const streamObjects = [
176+
// [#28737] And the timeline's sources, each object read once.
177+
const streamObjects = [...new Set([
167178
...(body.discussion ? [COMMENT_OBJECT, COMMENT_REACTION_OBJECT] : []),
168179
...(body.activity ? [ACTIVITY_OBJECT] : []),
169180
...(body.attachments ? [ATTACHMENT_OBJECT] : []),
170-
];
181+
...(body.timeline?.discussion ? [COMMENT_OBJECT] : []),
182+
...(body.timeline?.activity ? [ACTIVITY_OBJECT] : []),
183+
...(body.timeline?.fieldChanges ? [AUDIT_LOG_OBJECT] : []),
184+
])];
171185
const [childItems, streamItemList] = await measureServerTiming('meta', () => Promise.all([
172186
Promise.all(related.map((entry) => this.loadObjectItem(p, environmentId, entry.object))),
173187
Promise.all(streamObjects.map((name) => this.loadObjectItem(p, environmentId, name))),
@@ -322,6 +336,40 @@ export function registerRecordPageEndpoints(this: RecordPageRouteHost, basePath:
322336
return 'error' in answer ? answer : { total: answer.total, records: answer.records };
323337
};
324338

339+
// [#28737] The 动态 stream's size: each named source counted by
340+
// its read as the caller (`readStream`, so behind that object's
341+
// gate), as the spec's timeline table spells it. A source this
342+
// deployment does not serve holds no entry, as the page reads
343+
// such a stream as an empty one; a refused comment or activity
344+
// count refuses the part, and a refused ledger count is no
345+
// field change, as the stream then merges none.
346+
const answerTimeline = async (
347+
sources: NonNullable<RecordPageRequest['timeline']>,
348+
): Promise<{ total: number } | { error: PartRefusal }> => {
349+
const count = async (name: string, where: Record<string, unknown>): Promise<number | { error: PartRefusal }> => {
350+
const answer = await readStream(name, { where, limit: 0, count: true });
351+
if (!('error' in answer)) return answer.total;
352+
return answer.error.code === 'OBJECT_NOT_FOUND' ? 0 : answer;
353+
};
354+
const ofRecord = { object_name: object, record_id: id };
355+
const [comments, fieldChanges, activity, updates] = await Promise.all([
356+
sources.discussion ? count(COMMENT_OBJECT, { thread_id: `${object}:${id}` }) : 0,
357+
sources.fieldChanges ? count(AUDIT_LOG_OBJECT, { ...ofRecord, action: { $in: FIELD_CHANGE_ACTIONS } }) : 0,
358+
sources.activity
359+
? count(ACTIVITY_OBJECT, { ...ofRecord, type: { $nin: [...RECORD_TIMELINE_UNDRAWN_ACTIVITY_TYPES] } })
360+
: 0,
361+
// The updates that step aside once a field change is counted.
362+
sources.activity && sources.fieldChanges
363+
? count(ACTIVITY_OBJECT, { ...ofRecord, type: RECORD_TIMELINE_UPDATE_ACTIVITY_TYPE })
364+
: 0,
365+
]);
366+
if (typeof comments !== 'number') return comments;
367+
if (typeof activity !== 'number') return activity;
368+
if (typeof updates !== 'number') return updates;
369+
const changes = typeof fieldChanges === 'number' ? fieldChanges : 0;
370+
return { total: comments + changes + activity - (changes > 0 ? updates : 0) };
371+
};
372+
325373
const answerFieldAccess = async () => {
326374
try {
327375
const security = await this.resolveSecurityService(environmentId, req);
@@ -386,14 +434,15 @@ export function registerRecordPageEndpoints(this: RecordPageRouteHost, basePath:
386434
}
387435
};
388436

389-
const [relatedAnswers, fieldAccess, explain, approvals, discussion, activity, attachments] = await Promise.all([
437+
const [relatedAnswers, fieldAccess, explain, approvals, discussion, activity, attachments, timeline] = await Promise.all([
390438
Promise.all(related.map(answerRelated)),
391439
body.fieldAccess ? answerFieldAccess() : Promise.resolve(undefined),
392440
body.explain && body.explain.length > 0 ? answerExplain() : Promise.resolve(undefined),
393441
body.approvals ? answerApprovals() : Promise.resolve(undefined),
394442
body.discussion ? answerDiscussion() : Promise.resolve(undefined),
395443
body.activity ? answerActivity(body.activity.top) : Promise.resolve(undefined),
396444
body.attachments ? answerAttachments(body.attachments.top) : Promise.resolve(undefined),
445+
body.timeline ? answerTimeline(body.timeline) : Promise.resolve(undefined),
397446
]);
398447

399448
sendOk(res, {
@@ -407,6 +456,7 @@ export function registerRecordPageEndpoints(this: RecordPageRouteHost, basePath:
407456
...(discussion !== undefined ? { discussion } : {}),
408457
...(activity !== undefined ? { activity } : {}),
409458
...(attachments !== undefined ? { attachments } : {}),
459+
...(timeline !== undefined ? { timeline } : {}),
410460
});
411461
} catch (error: any) {
412462
const mapped = mapDataError(error, object);
@@ -415,7 +465,7 @@ export function registerRecordPageEndpoints(this: RecordPageRouteHost, basePath:
415465
}
416466
},
417467
metadata: {
418-
summary: 'Record page payload: the record, its related lists\' counts and first rows, its field projection, access verdicts, approval state, discussion, activity and attachments in one request',
468+
summary: 'Record page payload: the record, its related lists\' counts and first rows, its field projection, access verdicts, approval state, discussion, activity, attachments and timeline count in one request',
419469
tags: ['data'],
420470
},
421471
});

‎packages/spec/src/api/record-page.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
22

33
import { describe, expect, it } from 'vitest';
4+
import { SYS_ACTIVITY_BUILTIN_TYPES } from '../data/feed.zod';
45
import {
56
RECORD_PAGE_MAX_ACTIVITY_ROWS,
7+
RECORD_TIMELINE_UNDRAWN_ACTIVITY_TYPES,
8+
RECORD_TIMELINE_UPDATE_ACTIVITY_TYPE,
69
RECORD_PAGE_MAX_ATTACHMENT_ROWS,
710
RecordPageDiscussionSchema,
811
RecordPageExplainOperationSchema,
@@ -112,3 +115,34 @@ describe('[#28470] a stream part answers its rows or its refusal, never both and
112115
}
113116
});
114117
});
118+
119+
describe('[#28737] the timeline part names its sources strictly and answers the stream\'s size or a refusal', () => {
120+
const base = { object: 'account', id: 'a1', record: { id: 'a1' }, related: [] };
121+
const all = { discussion: true, activity: true, fieldChanges: true };
122+
123+
it('takes the three sources, each a boolean, and nothing else', () => {
124+
expect(RecordPageRequestSchema.safeParse({ timeline: all }).success).toBe(true);
125+
expect(RecordPageRequestSchema.safeParse({ timeline: { ...all, fieldChanges: false } }).success).toBe(true);
126+
for (const timeline of [true, {}, { discussion: true, activity: true }, { ...all, discussion: 'yes' }, { ...all, top: 5 }]) {
127+
expect(RecordPageRequestSchema.safeParse({ timeline }).success, JSON.stringify(timeline)).toBe(false);
128+
}
129+
});
130+
131+
it('answers a non-negative whole count, or a refusal alone', () => {
132+
const parses = (timeline: unknown) => RecordPageResponseSchema.safeParse({ ...base, timeline }).success;
133+
expect(parses({ total: 0 })).toBe(true);
134+
expect(parses({ total: 263 })).toBe(true);
135+
expect(parses({ error: refusal })).toBe(true);
136+
for (const timeline of [{ total: -1 }, { total: 1.5 }, {}, { total: 1, error: refusal }, { total: 1, records: [] }]) {
137+
expect(parses(timeline), JSON.stringify(timeline)).toBe(false);
138+
}
139+
});
140+
141+
it('leaves out only built-in activity types, and an update is not one of them', () => {
142+
for (const type of RECORD_TIMELINE_UNDRAWN_ACTIVITY_TYPES) {
143+
expect(SYS_ACTIVITY_BUILTIN_TYPES as readonly string[], type).toContain(type);
144+
}
145+
expect(SYS_ACTIVITY_BUILTIN_TYPES as readonly string[]).toContain(RECORD_TIMELINE_UPDATE_ACTIVITY_TYPE);
146+
expect(RECORD_TIMELINE_UNDRAWN_ACTIVITY_TYPES as readonly string[]).not.toContain(RECORD_TIMELINE_UPDATE_ACTIVITY_TYPE);
147+
});
148+
});

0 commit comments

Comments
 (0)