-
-
Notifications
You must be signed in to change notification settings - Fork 579
Re-land #76 safely: resilient /skills count + globalStats fallbacks #375
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,153 @@ | ||
| import type { Doc } from '../_generated/dataModel' | ||
| import type { MutationCtx, QueryCtx } from '../_generated/server' | ||
|
|
||
| export const GLOBAL_STATS_KEY = 'default' | ||
| const GLOBAL_STATS_PAGE_SIZE = 500 | ||
|
|
||
| type SkillVisibilityFields = Pick< | ||
| Doc<'skills'>, | ||
| 'softDeletedAt' | 'moderationStatus' | 'moderationFlags' | ||
| > | ||
|
|
||
| type DbCtx = Pick<MutationCtx | QueryCtx, 'db'> | ||
|
|
||
| export function isPublicSkillDoc(skill: SkillVisibilityFields | null | undefined) { | ||
| if (!skill || skill.softDeletedAt) return false | ||
| if (skill.moderationStatus && skill.moderationStatus !== 'active') return false | ||
| if (skill.moderationFlags?.includes('blocked.malware')) return false | ||
| return true | ||
| } | ||
|
|
||
| export function getPublicSkillVisibilityDelta( | ||
| before: SkillVisibilityFields | null | undefined, | ||
| after: SkillVisibilityFields | null | undefined, | ||
| ) { | ||
| const beforePublic = isPublicSkillDoc(before) | ||
| const afterPublic = isPublicSkillDoc(after) | ||
| if (beforePublic === afterPublic) return 0 | ||
| return afterPublic ? 1 : -1 | ||
| } | ||
|
|
||
| function getErrorMessage(error: unknown) { | ||
| if (typeof error === 'string') return error | ||
| if (error && typeof error === 'object' && 'message' in error) { | ||
| const message = (error as { message?: unknown }).message | ||
| if (typeof message === 'string') return message | ||
| } | ||
| return '' | ||
| } | ||
|
|
||
| export function isGlobalStatsStorageNotReadyError(error: unknown) { | ||
| const message = getErrorMessage(error).toLowerCase() | ||
| if (!message) return false | ||
| const referencesGlobalStats = message.includes('globalstats') || message.includes('by_key') | ||
| if (!referencesGlobalStats) return false | ||
| return ( | ||
| message.includes('table') || | ||
| message.includes('index') || | ||
| message.includes('schema') || | ||
| message.includes('not found') || | ||
| message.includes('does not exist') || | ||
| message.includes('unknown') | ||
| ) | ||
| } | ||
|
|
||
| export async function countPublicSkillsForGlobalStats(ctx: DbCtx) { | ||
| let count = 0 | ||
| let cursor: string | null = null | ||
|
|
||
| while (true) { | ||
| const { page, isDone, continueCursor } = await ctx.db | ||
| .query('skills') | ||
| .withIndex('by_active_updated', (q) => q.eq('softDeletedAt', undefined)) | ||
| .order('asc') | ||
| .paginate({ cursor, numItems: GLOBAL_STATS_PAGE_SIZE }) | ||
|
|
||
| for (const skill of page) { | ||
| if (isPublicSkillDoc(skill)) { | ||
| count += 1 | ||
| } | ||
| } | ||
|
|
||
| if (isDone) break | ||
| cursor = continueCursor | ||
| } | ||
|
|
||
| return count | ||
| } | ||
|
|
||
| export async function setGlobalPublicSkillsCount( | ||
| ctx: DbCtx, | ||
| count: number, | ||
| now = Date.now(), | ||
| ) { | ||
| const normalizedCount = Math.max(0, Math.trunc(Number.isFinite(count) ? count : 0)) | ||
| try { | ||
| const existing = await ctx.db | ||
| .query('globalStats') | ||
| .withIndex('by_key', (q) => q.eq('key', GLOBAL_STATS_KEY)) | ||
| .unique() | ||
|
|
||
| if (existing) { | ||
| await ctx.db.patch(existing._id, { activeSkillsCount: normalizedCount, updatedAt: now }) | ||
| } else { | ||
| await ctx.db.insert('globalStats', { | ||
| key: GLOBAL_STATS_KEY, | ||
| activeSkillsCount: normalizedCount, | ||
| updatedAt: now, | ||
| }) | ||
| } | ||
| } catch (error) { | ||
| if (isGlobalStatsStorageNotReadyError(error)) return | ||
| throw error | ||
| } | ||
| } | ||
|
|
||
| export async function adjustGlobalPublicSkillsCount( | ||
| ctx: DbCtx, | ||
| delta: number, | ||
| now = Date.now(), | ||
| ) { | ||
| const normalizedDelta = Math.trunc(Number.isFinite(delta) ? delta : 0) | ||
| if (normalizedDelta === 0) return | ||
|
|
||
| let existing: | ||
| | { | ||
| _id: Doc<'globalStats'>['_id'] | ||
| activeSkillsCount: number | ||
| } | ||
| | null | ||
| | undefined | ||
| try { | ||
| existing = await ctx.db | ||
| .query('globalStats') | ||
| .withIndex('by_key', (q) => q.eq('key', GLOBAL_STATS_KEY)) | ||
| .unique() | ||
| } catch (error) { | ||
| if (isGlobalStatsStorageNotReadyError(error)) return | ||
| throw error | ||
| } | ||
|
|
||
| if (!existing) { | ||
| // No baseline yet (e.g. fresh deploy). Initialize via full recount once. | ||
| const count = await countPublicSkillsForGlobalStats(ctx) | ||
| await setGlobalPublicSkillsCount(ctx, count, now) | ||
| return | ||
| } | ||
|
|
||
| const nextCount = Math.max(0, existing.activeSkillsCount + normalizedDelta) | ||
| await ctx.db.patch(existing._id, { activeSkillsCount: nextCount, updatedAt: now }) | ||
| } | ||
|
|
||
| export async function readGlobalPublicSkillsCount(ctx: DbCtx) { | ||
| try { | ||
| const stats = await ctx.db | ||
| .query('globalStats') | ||
| .withIndex('by_key', (q) => q.eq('key', GLOBAL_STATS_KEY)) | ||
| .unique() | ||
| return stats?.activeSkillsCount ?? null | ||
| } catch (error) { | ||
| if (isGlobalStatsStorageNotReadyError(error)) return null | ||
| throw error | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| import { describe, expect, it, vi } from 'vitest' | ||
| import { countPublicSkills } from './skills' | ||
|
|
||
| type WrappedHandler<TArgs, TResult> = { | ||
| _handler: (ctx: unknown, args: TArgs) => Promise<TResult> | ||
| } | ||
|
|
||
| const countPublicSkillsHandler = ( | ||
| countPublicSkills as unknown as WrappedHandler<Record<string, never>, number> | ||
| )._handler | ||
|
|
||
| function makeSkillsQuery(skills: Array<{ softDeletedAt?: number; moderationStatus?: string | null }>) { | ||
| return { | ||
| withIndex: (name: string) => { | ||
| if (name !== 'by_active_updated') throw new Error(`unexpected skills index ${name}`) | ||
| return { | ||
| order: (dir: string) => { | ||
| if (dir !== 'asc') throw new Error(`unexpected skills order ${dir}`) | ||
| return { | ||
| paginate: async () => ({ | ||
| page: skills, | ||
| isDone: true, | ||
| continueCursor: null, | ||
| pageStatus: null, | ||
| splitCursor: null, | ||
| }), | ||
| } | ||
| }, | ||
| } | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| describe('skills.countPublicSkills', () => { | ||
| it('returns precomputed global stats count when available', async () => { | ||
| const ctx = { | ||
| db: { | ||
| query: vi.fn((table: string) => { | ||
| if (table === 'globalStats') { | ||
| return { | ||
| withIndex: () => ({ | ||
| unique: async () => ({ _id: 'globalStats:1', activeSkillsCount: 123 }), | ||
| }), | ||
| } | ||
| } | ||
| if (table === 'skills') { | ||
| return makeSkillsQuery([]) | ||
| } | ||
| throw new Error(`unexpected table ${table}`) | ||
| }), | ||
| }, | ||
| } | ||
|
|
||
| const result = await countPublicSkillsHandler(ctx, {}) | ||
| expect(result).toBe(123) | ||
| }) | ||
|
|
||
| it('falls back to live count when global stats row is missing', async () => { | ||
| const ctx = { | ||
| db: { | ||
| query: vi.fn((table: string) => { | ||
| if (table === 'globalStats') { | ||
| return { | ||
| withIndex: () => ({ | ||
| unique: async () => null, | ||
| }), | ||
| } | ||
| } | ||
| if (table === 'skills') { | ||
| return makeSkillsQuery([ | ||
| { softDeletedAt: undefined, moderationStatus: 'active' }, | ||
| { softDeletedAt: undefined, moderationStatus: 'hidden' }, | ||
| { softDeletedAt: undefined, moderationStatus: 'active' }, | ||
| ]) | ||
| } | ||
| throw new Error(`unexpected table ${table}`) | ||
| }), | ||
| }, | ||
| } | ||
|
|
||
| const result = await countPublicSkillsHandler(ctx, {}) | ||
| expect(result).toBe(2) | ||
| }) | ||
|
|
||
| it('falls back to live count when globalStats table is unavailable', async () => { | ||
| const ctx = { | ||
| db: { | ||
| query: vi.fn((table: string) => { | ||
| if (table === 'globalStats') { | ||
| throw new Error('unexpected table globalStats') | ||
| } | ||
| if (table === 'skills') { | ||
| return makeSkillsQuery([ | ||
| { softDeletedAt: undefined, moderationStatus: 'active' }, | ||
| { softDeletedAt: undefined, moderationStatus: 'active' }, | ||
| ]) | ||
| } | ||
| throw new Error(`unexpected table ${table}`) | ||
| }), | ||
| }, | ||
| } | ||
|
|
||
| const result = await countPublicSkillsHandler(ctx, {}) | ||
| expect(result).toBe(2) | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Global stats key allows duplicate rows
Medium Severity
globalStatsuses a plainby_keyindex, but writes and reads assume a single row via.unique(). Concurrent initialization paths can insert multiplekey: 'default'rows, after which.unique()can throw and breakcountPublicSkillsand mutations that calladjustGlobalPublicSkillsCount.Additional Locations (2)
convex/lib/globalStats.ts#L85-L90convex/lib/globalStats.ts#L121-L126