Skip to content
Merged
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
1 change: 1 addition & 0 deletions .github/workflows/unit-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ jobs:
env:
COVERAGE_ENABLED: ${{ inputs.coverage }}
MCP_DATABASE_CONTAINER: ${{ job.services.mcp-database.id }}
TRASH_TEST_POSTGRES: "1"
run: |
coverage_args=()
if [ "${COVERAGE_ENABLED}" = "true" ]; then
Expand Down
5 changes: 4 additions & 1 deletion app/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,10 @@ button,
.notes-sidebar-controls { flex-direction: row; flex-wrap: wrap; align-items: center; gap: 0.5rem; padding: 0.25rem; }
.notes-sidebar-create { flex: 1; min-width: 0; }
.notes-sidebar-count { flex: none; max-width: 65%; }
.notes-sidebar-selection { flex-basis: 100%; }
.notes-sidebar-selection { flex-basis: 100%; max-width: none; }
.notes-sidebar-selection-toggle { width: 2.75rem; min-width: 2.75rem; padding-inline: 0; }
.notes-sidebar-selection-toggle > span { display: none; }
.notes-sidebar-selection-toggle > svg { display: block; }
.notes-sidebar-list { min-height: 8rem; flex-shrink: 0; }
.notes-sidebar-profile { padding: 0.25rem; }
}
Expand Down
195 changes: 194 additions & 1 deletion core/services/notes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,24 @@
import type { Tables } from '@/supabase/types'

type Note = Tables<'notes'>
export type TrashEntry = Omit<Note, 'id'> & {
trash_id: string
original_note_id: string
deleted_at: string
body_bytes: number
}
export type TrashSummary = Omit<TrashEntry, 'description'> & { preview_html: string }
export const TRASH_CARD_PREVIEW_LENGTH = 2048
export type TrashActionResult = {
trash_id: string
id?: string
status: 'restored' | 'purged' | 'missing' | 'conflict'
}
export type DeleteNoteOptions = {
snapshot?: Partial<Note>
expectedUpdatedAt?: string
operationId?: string
}
export type NoteLookupResult =
| { status: 'found'; note: Note }
| { status: 'not_found' }
Expand Down Expand Up @@ -90,12 +108,187 @@
return data
}

async deleteNote(id: string) {
async deleteNote(id: string, options?: DeleteNoteOptions) {

Check failure on line 111 in core/services/notes.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 16 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=koreyba_EverFreeNote&issues=AaGtRcxg3-ZIvfMI4L-c&open=AaGtRcxg3-ZIvfMI4L-c&pullRequest=214
if (
options?.snapshot ||
options?.expectedUpdatedAt ||
options?.operationId
) {
const { data, error } = await this.supabase.rpc('trash_notes', {
p_notes: [
{
id,
...(options.snapshot ? { snapshot: options.snapshot } : {}),
...(options.expectedUpdatedAt
? { expected_updated_at: options.expectedUpdatedAt }
: {}),
...(options.operationId
? { operation_id: options.operationId }
: {}),
},
],
})
if (error) throw error
const outcome = Array.isArray(data)
? data.find((row) => row.id === id)
: undefined
if (outcome?.status === 'conflict')
throw new Error(
'The note changed on another device. Your local draft remains in Trash pending sync.',
)
if (!outcome || !['trashed', 'already_trashed'].includes(outcome.status))
throw new Error(
'The server could not confirm that the note was saved in Trash.',
)
return id
}
// Older ID-only callers are protected by the archive-before-delete database trigger.
const { error } = await this.supabase.from('notes').delete().eq('id', id)
if (error) throw error
return id
}

async getTrash(userId: string, page = 0) {
const { data, error, count } = await this.supabase
.from('notes_trash_list')
.select(
'trash_id, original_note_id, user_id, title, tags, created_at, updated_at, deleted_at, body_bytes, preview_html',
{ count: 'exact' },
)
.eq('user_id', userId)
.order('deleted_at', { ascending: false })
.order('trash_id', { ascending: false })
.range(page * 50, page * 50 + 49)
if (error) throw error
return {
notes: (data ?? []) as TrashSummary[],
totalCount: count ?? 0,
hasMore: (page + 1) * 50 < (count ?? 0),
}
}

async trashNotesBatch(
ids: string[],
): Promise<{ succeeded: string[]; failed: string[] }> {
if (ids.length > 100)
throw new Error('Process at most 100 notes at a time.')
const { data, error } = await this.supabase.rpc('trash_notes', {
p_notes: ids.map((id) => ({ id })),
})
if (error) throw error
const succeeded: string[] = [],
failed: string[] = []
for (const id of ids) {
const row = Array.isArray(data)
? data.find((item) => item.id === id)
: undefined
if (
!row ||
!['trashed', 'already_trashed', 'missing', 'conflict'].includes(
row.status,
)
)
throw new Error('Incomplete Trash confirmation.')
if (row.status === 'conflict') failed.push(id)
else succeeded.push(id)
}
return { succeeded, failed }
}

async getTrashedNote(trashId: string, userId: string): Promise<TrashEntry> {
const { data, error } = await this.supabase
.from('notes_trash')
.select('*')
.eq('trash_id', trashId)
.eq('user_id', userId)
.single()
if (error) throw error
return { ...data, description: data.description ?? '' } as TrashEntry
}

async getAllTrashIds(userId: string): Promise<string[]> {
const ids = new Set<string>()
let cursor: { trash_id: string; deleted_at: string } | undefined
while (true) {
let query = this.supabase
.from('notes_trash')
.select('trash_id, deleted_at')
.eq('user_id', userId)
.order('deleted_at', { ascending: false })
.order('trash_id', { ascending: false })
.limit(500)
if (cursor)
query = query.or(
`deleted_at.lt.${cursor.deleted_at},and(deleted_at.eq.${cursor.deleted_at},trash_id.lt.${cursor.trash_id})`,
)
const { data, error } = await query
if (error) throw error
if (!data) throw new Error('Could not load the complete Trash selection.')
const size = ids.size
for (const row of data) ids.add(row.trash_id)
if (data.length < 500) return [...ids]
if (size === ids.size)
throw new Error('Trash pagination did not advance. Refresh and retry.')
cursor = data[data.length - 1]
}
}

async restoreTrashedNotes(ids: string[]): Promise<TrashActionResult[]> {
return this.trashEntryAction('restore_notes', ids)
}

async cleanupExpiredTrash(
run: string,
isCurrent: () => boolean = () => true,
): Promise<number> {
const started = Date.now()
let removed = 0
for (
let batch = 0;
batch < 5 && isCurrent() && Date.now() - started < 2000;
batch++
) {
const { data, error } = await this.supabase.rpc('cleanup_my_trash', {
p_run: run,
})
if (error) throw error
if (typeof data !== 'number' || data < 0 || data > 100)
throw new Error('Invalid cleanup confirmation.')
removed += data
if (data < 100) break
}
return removed
}

async purgeTrashedNotes(ids: string[]): Promise<TrashActionResult[]> {
return this.trashEntryAction('purge_notes', ids)
}

private async trashEntryAction(
action: 'restore_notes' | 'purge_notes',
ids: string[],
): Promise<TrashActionResult[]> {
if (ids.length > 100)
throw new Error('Process at most 100 Trash entries at a time.')
const { data, error } = await this.supabase.rpc(action, { p_ids: ids })
if (error) throw error
const statuses =
action === 'restore_notes'
? ['restored', 'missing', 'conflict']
: ['purged', 'missing']
if (
!Array.isArray(data) ||
data.length !== new Set(ids).size ||
data.some(
(row) =>
!row || !ids.includes(row.trash_id) || !statuses.includes(row.status),
) ||
ids.some((id) => !data.some((row) => row.trash_id === id))
)
throw new Error('Incomplete Trash confirmation. Refresh before retrying.')
return data as TrashActionResult[]
}

async getNote(id: string) {
const { data, error } = await this.supabase
.from('notes')
Expand Down
65 changes: 65 additions & 0 deletions core/services/trashMediaCleanup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
export type MediaClaim = { object_path: string; lease_id: string }
export type TrashMediaCleanupDeps = {
cronSecret?: string
userForToken: (token: string) => Promise<string | null>
claim: (owner: string | null) => Promise<MediaClaim[]>
remove: (paths: string[]) => Promise<void>
complete: (claims: MediaClaim[], success: boolean) => Promise<void>
}
const headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers':
'authorization, apikey, content-type, x-client-info',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Content-Type': 'application/json',
}
export function createTrashMediaCleanupHandler(deps: TrashMediaCleanupDeps) {
return async (request: Request): Promise<Response> => {
const json = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status, headers })
if (request.method === 'OPTIONS')
return new Response(null, { status: 204, headers })
if (request.method !== 'POST')
return json({ error: 'Method not allowed' }, 405)
try {
const scheduled = Boolean(
deps.cronSecret &&
request.headers.get('x-trash-cleanup-secret') === deps.cronSecret,
)
const token = request.headers
.get('authorization')
?.match(/^Bearer\s+(.+)$/i)?.[1]

Check warning on line 31 in core/services/trashMediaCleanup.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Simplify this regular expression to reduce its runtime, as it has super-linear performance due to backtracking.

See more on https://sonarcloud.io/project/issues?id=koreyba_EverFreeNote&issues=AaGtRcxh3-ZIvfMI4L-d&open=AaGtRcxh3-ZIvfMI4L-d&pullRequest=214
const owner = scheduled
? null
: token
? await deps.userForToken(token)
: null

Check warning on line 36 in core/services/trashMediaCleanup.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Extract this nested ternary operation into an independent statement.

See more on https://sonarcloud.io/project/issues?id=koreyba_EverFreeNote&issues=AaGtRcxh3-ZIvfMI4L-e&open=AaGtRcxh3-ZIvfMI4L-e&pullRequest=214
if (!scheduled && !owner) return json({ error: 'Unauthorized' }, 401)
const claims = await deps.claim(owner)
if (
claims.length > 100 ||
claims.some(
(row) =>
!row.lease_id ||
!/^[\da-f-]{36}\//i.test(row.object_path) ||
(owner && !row.object_path.startsWith(`${owner}/`)),
)
)
throw new Error('Invalid media cleanup scope')
if (!claims.length) return json({ removed: 0 })
try {
await deps.remove(claims.map((row) => row.object_path))
} catch {
await deps.complete(claims, false)
return json({ error: 'File cleanup is pending and will retry.' }, 503)
}
await deps.complete(claims, true)
return json({ removed: claims.length })
} catch {
return json(
{ error: 'Cleanup could not finish. It will retry later.' },
503,
)
}
}
}
Loading
Loading