forge
Explore
Log in

Don't you dare go Hollow

⚡ bound per-row fan-outs and fix capped list reads

Browse files at this commit

8e51fe0d50358d7a9fe39e5ee93e0f0c2cae9fbbBurak BoduroğluParent: 0630be8
  • perf
    • ⚡ bound per-row fan-outs and fix capped list reads
Show full message
perf: ⚡ bound per-row fan-outs and fix capped list reads
- mapConcurrent keeps at most 6 requests in flight for marks, member counts,
  balances and calendar sessions
- student marks and class member counts say so when the school is past the
  fetch cap instead of silently blanking the column
- calendar reads events/exams from the visible month onward with no row cap
  and refetches only when paging backwards; appointments, homework and
  sessions are no longer cut at 100
- shell notification poll reads 100 homework rows instead of the whole list
- dashboard appointments/homework reads match the shell's so they coalesce
- payments header resolves a student's name from the profile when the
  student is not on the loaded page
src/lib/__tests__/map-concurrent.test.tsadded+34 -0
@@ -0,0 +1,34 @@
1+import { mapConcurrent } from "@/lib/map-concurrent";
2+
3+describe("mapConcurrent", () => {
4+ it("keeps input order", async () => {
5+ const out = await mapConcurrent([30, 10, 20], 2, async (ms, index) => {
6+ await new Promise((resolve) => setTimeout(resolve, ms));
7+ return index;
8+ });
9+ expect(out).toEqual([0, 1, 2]);
10+ });
11+
12+ it("never runs more than `limit` calls at once", async () => {
13+ let active = 0;
14+ let peak = 0;
15+ await mapConcurrent(Array.from({ length: 20 }, (_, i) => i), 3, async () => {
16+ active += 1;
17+ peak = Math.max(peak, active);
18+ await new Promise((resolve) => setTimeout(resolve, 1));
19+ active -= 1;
20+ });
21+ expect(peak).toBe(3);
22+ });
23+
24+ it("returns an empty array for no items", async () => {
25+ expect(await mapConcurrent([], 4, async () => 1)).toEqual([]);
26+ });
27+
28+ it("rejects when a call rejects", async () => {
29+ await expect(mapConcurrent([1, 2], 2, async (n) => {
30+ if (n === 2) throw new Error("boom");
31+ return n;
32+ })).rejects.toThrow("boom");
33+ });
34+});
src/lib/map-concurrent.tsadded+28 -0
@@ -0,0 +1,28 @@
1+/**
2+ * `Promise.all(items.map(fn))` with at most `limit` calls in flight. For the
3+ * per-row fan-outs the backend has no bulk read for (marks, balances, member
4+ * counts): an unbounded burst of a few hundred GETs trips the backend's rate
5+ * limit and stalls every other request the page makes behind it.
6+ *
7+ * Results keep the input order. A rejection rejects the whole call, like
8+ * `Promise.all` — callers that tolerate a failed row catch inside `fn`.
9+ */
10+export async function mapConcurrent<T, R>(
11+ items: readonly T[],
12+ limit: number,
13+ fn: (item: T, index: number) => Promise<R>,
14+): Promise<R[]> {
15+ const results = new Array<R>(items.length);
16+ let next = 0;
17+ const worker = async () => {
18+ while (next < items.length) {
19+ const index = next++;
20+ results[index] = await fn(items[index], index);
21+ }
22+ };
23+ await Promise.all(Array.from({ length: Math.min(Math.max(1, limit), items.length) }, worker));
24+ return results;
25+}
26+
27+/** In-flight cap shared by the page-level fan-outs. */
28+export const FAN_OUT_LIMIT = 6;
src/pages/calendar-page.tsxmodified+21 -8
@@ -1,5 +1,6 @@
1 import { For, Show, Suspense, createMemo, createSignal } from "solid-js";1 import { For, Show, Suspense, createMemo, createSignal } from "solid-js";
2 import { createBoardResources } from "@/lib/board-resources";2 import { createBoardResources } from "@/lib/board-resources";
3+import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent";
3 import { getEvents } from "@/api/events";4 import { getEvents } from "@/api/events";
4 import { getExams } from "@/api/exams";5 import { getExams } from "@/api/exams";
5 import { getHomework } from "@/api/homework";6 import { getHomework } from "@/api/homework";
@@ -31,6 +32,7 @@ const MONTH_NAMES_TR = ["Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran",
31 const SESSION_COURSE_CAP = 25;32 const SESSION_COURSE_CAP = 25;
32 /** Chips a single day cell shows before collapsing the rest into "+N". */33 /** Chips a single day cell shows before collapsing the rest into "+N". */
33 const CHIPS_PER_CELL = 3;34 const CHIPS_PER_CELL = 3;
35+const DAY_MS = 24 * 60 * 60 * 1000;
34 36
35 type CalendarKind = "lesson" | "study" | "exam" | "homework" | "event" | "appointment";37 type CalendarKind = "lesson" | "study" | "exam" | "homework" | "event" | "appointment";
36 38
@@ -152,10 +154,19 @@ function CalendarContent() {
152 // Each feed stands alone: a failed one reads as empty and is named in the154 // Each feed stands alone: a failed one reads as empty and is named in the
153 // notice above the grid, instead of blanking the whole calendar.155 // notice above the grid, instead of blanking the whole calendar.
154 const board = createBoardResources();156 const board = createBoardResources();
155- const [events] = board.createResource(async () => (await getEvents({ limit: 100 })).items);157+ // Events and exams take a schedule window, so they are read from the first
156- const [exams] = board.createResource(async () => (await getExams({ limit: 100 })).items);158+ // day the grid can show (the month's leading week included) onward, with no
157- const [appointments] = board.createResource(async () => (await getAppointments({ limit: 100 })).items);159+ // row cap — a fixed `limit` silently emptied later months once a school had
158- const [homework] = board.createResource(async () => (await getHomework({ limit: 100 })).items);160+ // more rows than the cap. The window only ever widens backwards: paging
161+ // forward stays inside what is loaded, paging to an earlier month refetches.
162+ const viewStart = () => new Date(viewYear(), viewMonth(), 1).getTime() - 7 * DAY_MS;
163+ const loadedFrom = createMemo<number>((prev) => Math.min(prev, viewStart()), viewStart());
164+ const [events] = board.createResource(loadedFrom, async (from) => (await getEvents({ ends_after: from })).items);
165+ const [exams] = board.createResource(loadedFrom, async (from) => (await getExams({ ends_after: from })).items);
166+ // Appointments and homework have no date filter and list newest-created
167+ // first, so a cap would drop rows by creation order, not by date: read all.
168+ const [appointments] = board.createResource(async () => (await getAppointments()).items);
169+ const [homework] = board.createResource(async () => (await getHomework()).items);
159 170
160 // Lessons and study/club meetings both come from course sessions; the course's171 // Lessons and study/club meetings both come from course sessions; the course's
161 // own `kind` is what separates them.172 // own `kind` is what separates them.
@@ -169,18 +180,20 @@ function CalendarContent() {
169 role === "student" ? getMyCourses() : getCourses(),180 role === "student" ? getMyCourses() : getCourses(),
170 ]);181 ]);
171 const byId = new Map<string, Course>(courses.items.map((course) => [course.id, course]));182 const byId = new Map<string, Course>(courses.items.map((course) => [course.id, course]));
172- const pages = await Promise.all(183+ const pages = await mapConcurrent(
173- instances.items.slice(0, SESSION_COURSE_CAP).map(async (instance) => {184+ instances.items.slice(0, SESSION_COURSE_CAP), FAN_OUT_LIMIT, async (instance) => {
174 const course = byId.get(instance.course);185 const course = byId.get(instance.course);
175 if (!course) return [];186 if (!course) return [];
176 try {187 try {
177- const page = await getInstanceSessions(instance.id, { limit: 100 });188+ // No cap: a weekly lesson alone passes 100 sessions in a school
189+ // year, and the rows past a cap were the later months.
190+ const page = await getInstanceSessions(instance.id);
178 return page.items.map((session) => ({ session, course }));191 return page.items.map((session) => ({ session, course }));
179 } catch {192 } catch {
180 // One unreadable section must not empty the whole calendar.193 // One unreadable section must not empty the whole calendar.
181 return [];194 return [];
182 }195 }
183- }),196+ },
184 );197 );
185 return pages.flat();198 return pages.flat();
186 },199 },
src/pages/classes-page.tsxmodified+13 -9
@@ -11,6 +11,7 @@ import { RouteGuard } from "@/components/layout/route-guard";
11 import { DataToolbar } from "@/components/ui/data-toolbar";11 import { DataToolbar } from "@/components/ui/data-toolbar";
12 import { DropdownSelect, Select } from "@/components/ui/select";12 import { DropdownSelect, Select } from "@/components/ui/select";
13 import { Alert } from "@/components/ui/alert";13 import { Alert } from "@/components/ui/alert";
14+import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent";
14 import { Badge } from "@/components/ui/badge";15 import { Badge } from "@/components/ui/badge";
15 import { Button } from "@/components/ui/button";16 import { Button } from "@/components/ui/button";
16 import { DataTableSkeleton } from "@/components/ui/data-table";17 import { DataTableSkeleton } from "@/components/ui/data-table";
@@ -101,17 +102,16 @@ function ClassesContent() {
101 return ids.length > 0 && ids.length <= MEMBER_COUNT_FETCH_CAP ? ids : null;102 return ids.length > 0 && ids.length <= MEMBER_COUNT_FETCH_CAP ? ids : null;
102 });103 });
103 const [memberCounts] = createResource(memberCountIds, async (ids) => {104 const [memberCounts] = createResource(memberCountIds, async (ids) => {
104- const entries = await Promise.all(105+ const entries = await mapConcurrent(ids, FAN_OUT_LIMIT, async (id) => {
105- ids.map(async (id) => {106+ try {
106- try {107+ return [id, (await getClassMembers(id, { limit: 1 })).total] as const;
107- return [id, (await getClassMembers(id, { limit: 1 })).total] as const;108+ } catch {
108- } catch {109+ return [id, null] as const;
109- return [id, null] as const;110+ }
110- }111+ });
111- }),
112- );
113 return new Map(entries);112 return new Map(entries);
114 });113 });
114+ const memberCountsCapped = () => listData().length > MEMBER_COUNT_FETCH_CAP;
115 115
116 const createClass = async (event: SubmitEvent) => {116 const createClass = async (event: SubmitEvent) => {
117 event.preventDefault();117 event.preventDefault();
@@ -254,6 +254,10 @@ function ClassesContent() {
254 />254 />
255 </div>255 </div>
256 256
257+ <Show when={memberCountsCapped()}>
258+ <Alert role="status">{t("classGroups.memberCountCapped", { cap: MEMBER_COUNT_FETCH_CAP })}</Alert>
259+ </Show>
260+
257 <Suspense fallback={<DataTableSkeleton />}>261 <Suspense fallback={<DataTableSkeleton />}>
258 <Show when={searched().length > 0} fallback={<EmptyState kind="people" title={t("classGroups.empty")} />}>262 <Show when={searched().length > 0} fallback={<EmptyState kind="people" title={t("classGroups.empty")} />}>
259 <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3">263 <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3">
src/pages/dashboard-page.tsxmodified+4 -1
@@ -181,6 +181,7 @@ function DashboardContent() {
181 // Unfiltered: `/homework` has no due-date window, so this one read serves both181 // Unfiltered: `/homework` has no due-date window, so this one read serves both
182 // the deadlines table (filtered by `scheduleStatus`) and the backwards-looking182 // the deadlines table (filtered by `scheduleStatus`) and the backwards-looking
183 // heatmap.183 // heatmap.
184+ // `limit: 100` matches the shell's feed read, so the two coalesce.
184 const [homework] = createResource(185 const [homework] = createResource(
185 () => role() === "parent" || !on("homework") ? null : role(),186 () => role() === "parent" || !on("homework") ? null : role(),
186 () => quiet(getHomework({ limit: 100 })),187 () => quiet(getHomework({ limit: 100 })),
@@ -189,9 +190,11 @@ function DashboardContent() {
189 () => role() === "parent" ? true : null,190 () => role() === "parent" ? true : null,
190 () => quiet(getMyStudents({ limit: 12 })),191 () => quiet(getMyStudents({ limit: 12 })),
191 );192 );
193+ // Same page as the shell's notification poll (`limit: 100`), so the two
194+ // concurrent first-paint reads coalesce into one request in `client`.
192 const [appointments] = createResource(195 const [appointments] = createResource(
193 () => (on("appointments") ? true : null),196 () => (on("appointments") ? true : null),
194- () => quiet(getAppointments({ limit: 20 })),197+ () => quiet(getAppointments({ limit: 100 })),
195 );198 );
196 const [menus] = createResource(199 const [menus] = createResource(
197 () => (on("meals") ? clock()?.now : null),200 () => (on("meals") ? clock()?.now : null),
src/pages/payments-page.tsxmodified+26 -13
@@ -20,7 +20,7 @@ import {
20 type PaymentLine,20 type PaymentLine,
21 type StatementEntry,21 type StatementEntry,
22 } from "@/api/payments";22 } from "@/api/payments";
23-import { getUserSearch } from "@/api/users";23+import { getUserProfile, getUserSearch } from "@/api/users";
24 import { formatApiError, type PersonRef } from "@/api/client";24 import { formatApiError, type PersonRef } from "@/api/client";
25 import { RouteGuard } from "@/components/layout/route-guard";25 import { RouteGuard } from "@/components/layout/route-guard";
26 import { Alert } from "@/components/ui/alert";26 import { Alert } from "@/components/ui/alert";
@@ -47,6 +47,7 @@ import { formatDate, formatDateTime } from "@/lib/format";
47 import { formatTry } from "@/lib/meals";47 import { formatTry } from "@/lib/meals";
48 import { PAYMENT_METHOD_KEYS, sortStatementEntries, statementStatus } from "@/lib/payments";48 import { PAYMENT_METHOD_KEYS, sortStatementEntries, statementStatus } from "@/lib/payments";
49 import { matchesSearch } from "@/lib/search-text";49 import { matchesSearch } from "@/lib/search-text";
50+import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent";
50 import { personLabel } from "@/lib/person";51 import { personLabel } from "@/lib/person";
51 import { usePreferences, useT } from "@/stores/preferences-context";52 import { usePreferences, useT } from "@/stores/preferences-context";
52 53
@@ -149,6 +150,15 @@ function PaymentsContent() {
149 const pagedStudents = () => studentsPage()?.items ?? [];150 const pagedStudents = () => studentsPage()?.items ?? [];
150 const studentsTotal = () => studentsPage()?.total ?? 0;151 const studentsTotal = () => studentsPage()?.total ?? 0;
151 152
153+ const [routeProfile] = createResource(
154+ () => {
155+ const routeId = routeStudentId();
156+ if (!routeId || studentsPage.loading) return null;
157+ return pagedStudents().some((user) => user.id === routeId) ? null : routeId;
158+ },
159+ (userId) => getUserProfile(userId).catch(() => null),
160+ );
161+
152 createEffect(() => {162 createEffect(() => {
153 const routeId = routeStudentId();163 const routeId = routeStudentId();
154 if (!routeId) {164 if (!routeId) {
@@ -161,9 +171,14 @@ function PaymentsContent() {
161 return;171 return;
162 }172 }
163 // A direct visit/refresh on /management/payments/$userId whose student173 // A direct visit/refresh on /management/payments/$userId whose student
164- // isn't on the currently loaded page — there's no non-admin "read one174+ // isn't on the currently loaded page. The statement/balance/ledger reads
165- // user" endpoint to resolve a name from, so fall back to the id itself.175+ // below only need the id; the header name comes from the public profile
166- // The statement/balance/ledger reads below only need the id to work.176+ // (readable by any staff account) once it resolves.
177+ const named = routeProfile.latest;
178+ if (named && named.id === routeId) {
179+ setSelectedStudent({ id: named.id, username: named.username, display_name: named.display_name });
180+ return;
181+ }
167 setSelectedStudent((prev) => (prev?.id === routeId ? prev : { id: routeId, username: routeId, display_name: null }));182 setSelectedStudent((prev) => (prev?.id === routeId ? prev : { id: routeId, username: routeId, display_name: null }));
168 });183 });
169 184
@@ -175,15 +190,13 @@ function PaymentsContent() {
175 return users.length > 0 ? users : null;190 return users.length > 0 ? users : null;
176 },191 },
177 async (users): Promise<PaymentStudentRow[]> =>192 async (users): Promise<PaymentStudentRow[]> =>
178- Promise.all(193+ mapConcurrent(users, FAN_OUT_LIMIT, async (user) => {
179- users.map(async (user) => {194+ try {
180- try {195+ return { ...user, balance_minor: (await getPaymentBalanceByUserId(user.id)).balance_minor };
181- return { ...user, balance_minor: (await getPaymentBalanceByUserId(user.id)).balance_minor };196+ } catch {
182- } catch {197+ return { ...user, balance_minor: null };
183- return { ...user, balance_minor: null };198+ }
184- }199+ }),
185- }),
186- ),
187 );200 );
188 201
189 const studentColumns = createMemo<ColumnDef<PaymentStudentRow>[]>(() => [202 const studentColumns = createMemo<ColumnDef<PaymentStudentRow>[]>(() => [
src/pages/student-marks-page.tsxmodified+18 -13
@@ -8,6 +8,7 @@ import { cn } from "@/lib/cn";
8 import { MarksReportView } from "@/components/marks/marks-report-view";8 import { MarksReportView } from "@/components/marks/marks-report-view";
9 import { RouteGuard } from "@/components/layout/route-guard";9 import { RouteGuard } from "@/components/layout/route-guard";
10 import { Alert } from "@/components/ui/alert";10 import { Alert } from "@/components/ui/alert";
11+import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent";
11 import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";12 import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
12 import { ErrorAlert } from "@/components/ui/error-alert";13 import { ErrorAlert } from "@/components/ui/error-alert";
13 import { IconEye } from "@/components/ui/icons";14 import { IconEye } from "@/components/ui/icons";
@@ -31,6 +32,8 @@ export default function StudentMarksPage() {
31 );32 );
32 }33 }
33 34
35+const MARKS_FETCH_CAP = 200;
36+
34 function StudentMarksContent() {37 function StudentMarksContent() {
35 const t = useT();38 const t = useT();
36 const [viewUser, setViewUser] = createSignal<PersonRef | null>(null);39 const [viewUser, setViewUser] = createSignal<PersonRef | null>(null);
@@ -47,28 +50,26 @@ function StudentMarksContent() {
47 }, { initialValue: [] as StudentDirectoryRow[] });50 }, { initialValue: [] as StudentDirectoryRow[] });
48 51
49 // Per-student overall marks for the inline "average" column. No bulk endpoint52 // Per-student overall marks for the inline "average" column. No bulk endpoint
50- // exists, so this is one getUserMarks call per listed student, bounded by cap.53+ // exists, so this is one getUserMarks call per listed student — at most
51- // ponytail: N+1 marks fetch, capped at 200; add a bulk /reports/marks endpoint54+ // FAN_OUT_LIMIT in flight, and skipped past the cap with a visible notice
52- // if whole-school listing is needed. Mirrors the payments roster balance fetch.55+ // instead of a column that silently reads "—" for everyone.
53- const MARKS_FETCH_CAP = 200;
54 const [marksMapRes] = createResource(56 const [marksMapRes] = createResource(
55 () => {57 () => {
56 const ids = list().map((row) => row.person.id);58 const ids = list().map((row) => row.person.id);
57 return ids.length > 0 && ids.length <= MARKS_FETCH_CAP ? ids : null;59 return ids.length > 0 && ids.length <= MARKS_FETCH_CAP ? ids : null;
58 },60 },
59 async (ids) => {61 async (ids) => {
60- const pairs = await Promise.all(62+ const pairs = await mapConcurrent(ids, FAN_OUT_LIMIT, async (id) => {
61- ids.map(async (id) => {63+ try {
62- try {64+ return [id, await getUserMarks(id)] as const;
63- return [id, await getUserMarks(id)] as const;65+ } catch {
64- } catch {66+ return [id, null] as const;
65- return [id, null] as const;67+ }
66- }68+ });
67- }),
68- );
69 return Object.fromEntries(pairs) as Record<string, MarksReport | null>;69 return Object.fromEntries(pairs) as Record<string, MarksReport | null>;
70 },70 },
71 );71 );
72+ const marksCapped = () => list().length > MARKS_FETCH_CAP;
72 const marksOf = (id: string) => marksMapRes()?.[id];73 const marksOf = (id: string) => marksMapRes()?.[id];
73 74
74 const [report, { refetch: refetchReport }] = createResource(75 const [report, { refetch: refetchReport }] = createResource(
@@ -163,6 +164,10 @@ function StudentMarksContent() {
163 <Alert variant="destructive">{error()}</Alert>164 <Alert variant="destructive">{error()}</Alert>
164 </Show>165 </Show>
165 166
167+ <Show when={!listLoading() && marksCapped()}>
168+ <Alert role="status">{t("marks.averageCapped", { cap: MARKS_FETCH_CAP })}</Alert>
169+ </Show>
170+
166 <Show when={!listLoading()} fallback={<DataTableSkeleton columns={4} rows={6} />}>171 <Show when={!listLoading()} fallback={<DataTableSkeleton columns={4} rows={6} />}>
167 <DataTable172 <DataTable
168 title={t("nav.studentMarks")}173 title={t("nav.studentMarks")}
src/stores/shell-feed-context.tsxmodified+7 -1
@@ -46,6 +46,8 @@ type ShellFeedContextValue = {
46 46
47 const ShellFeedContext = createContext<ShellFeedContextValue>();47 const ShellFeedContext = createContext<ShellFeedContextValue>();
48 48
49+const HOMEWORK_FEED_LIMIT = 100;
50+
49 const emptyPage = <T,>(): Page<T> => ({ items: [], total: 0, limit: null, offset: 0 });51 const emptyPage = <T,>(): Page<T> => ({ items: [], total: 0, limit: null, offset: 0 });
50 52
51 type UserFeed = Omit<ShellFeedContextValue, "nowMs">;53 type UserFeed = Omit<ShellFeedContextValue, "nowMs">;
@@ -151,7 +153,11 @@ function createUserFeed(loggedIn: boolean, modulesLoading: () => boolean, isEnab
151 async () => {153 async () => {
152 try {154 try {
153 if (!isEnabled("homework")) return emptyPage<Homework>();155 if (!isEnabled("homework")) return emptyPage<Homework>();
154- return await getHomework();156+ // `/homework` has no due-date filter and lists newest-created first,
157+ // so a page of the most recent rows holds everything still upcoming
158+ // in practice. Unbounded, this poll pulled the school's whole
159+ // homework history every minute on every page.
160+ return await getHomework({ limit: HOMEWORK_FEED_LIMIT });
155 } catch {161 } catch {
156 return emptyPage<Homework>();162 return emptyPage<Homework>();
157 }163 }