Repository navigation
cli-sessions: share and fork storage rules #8224
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
Open
iscekic
wants to merge
29
commits into
main
Choose a base branch
from
drain/cli-session-copy-limits
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
29 commits
Select commit
Hold shift + click to select a range
346ed10
cli-sessions: share and fork storage rules
iscekic 25fd57b
cli-sessions: durable fork marker and explicit blob columns
iscekic 0f302dc
cli-sessions: conditional share reservation cleanup
iscekic acd90fd
db: fork flag and share owner index migration
iscekic 3b7ba47
db: regenerate the migration snapshot
iscekic 26ee8e2
cli-sessions: share rows are completed by the next request
iscekic 6302ee8
cli-sessions: completion checks its share row
iscekic 961fdfe
cli-sessions: clear copied objects when the share row is gone
iscekic b250b1e
chore(web): reconcile session lifecycle changes with main
iscekic 28bc51c
chore(web): request review of session lifecycle integration
iscekic d540529
Merge remote-tracking branch 'origin/main' into drain/cli-session-cop…
iscekic 79be98a
chore(cli-sessions): request review of integrated changes
iscekic 794567a
Merge remote-tracking branch 'origin/main' into drain/cli-session-cop…
iscekic 7cee952
Merge main and regenerate session migration metadata
iscekic 42f09b8
Merge remote-tracking branch 'origin/main' into drain/cli-session-cop…
iscekic 136b103
fix(cli-sessions): store a current snapshot with each share
iscekic c5cb7fb
fix(cli-sessions): refresh shared session snapshots
iscekic 45341ef
fix(cli-sessions): serialize share copy updates
iscekic ffb7c00
fix(cli-sessions): stage refreshed session copies
iscekic a458d8f
fix(cli-sessions): retain copy cleanup work through lifecycle calls
iscekic de0f8ab
fix(cli-sessions): hold shared snapshots during fork copies
iscekic 098d00a
fix(cli-sessions): synchronize account copy cleanup
iscekic 5dc93a1
Merge remote-tracking branch 'origin/main' into drain/cli-session-cop…
iscekic fcfab56
Merge remote-tracking branch 'origin/main' into drain/cli-session-cop…
iscekic 8d67288
Merge remote-tracking branch 'origin/main' into drain/cli-session-cop…
iscekic 0fe37ec
Merge remote-tracking branch 'origin/main' into drain/cli-session-cop…
iscekic 61c4ef6
chore(db): renumber the CLI session storage migration after main
iscekic 61938a5
Merge remote-tracking branch 'origin/main' into drain/cli-session-cop…
iscekic c0da2b7
chore(db): place the CLI session storage migration after main's 0301
iscekic 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,323 @@ | ||
| import 'server-only'; | ||
|
|
||
| import { and, count, eq, isNotNull, sql } from 'drizzle-orm'; | ||
| import { TRPCError } from '@trpc/server'; | ||
| import { cliSessions, sharedCliSessions } from '@kilocode/db/schema'; | ||
| import { db, type DrizzleTransaction } from '@kilocode/web-shared/lib/drizzle'; | ||
| import { | ||
| SessionBlobCopyTooLargeError, | ||
| copyBlobs, | ||
| deleteBlobs, | ||
| type BlobUrlKeys, | ||
| type FileName, | ||
| type FolderName, | ||
| } from '@/lib/r2/cli-sessions'; | ||
|
|
||
| export const BLOB_TYPES = [ | ||
| 'api_conversation_history', | ||
| 'task_metadata', | ||
| 'ui_messages', | ||
| 'git_state', | ||
| ] as const satisfies readonly FileName[]; | ||
|
|
||
| /** Largest blob the CLI session upload route accepts, per blob type. */ | ||
| export const CLI_SESSION_BLOB_MAX_BYTES = 5 * 1024 * 1024; | ||
|
|
||
| /** A copy carries every blob type, so it is bounded by the upload cap times the blob count. */ | ||
| export const CLI_SESSION_COPY_MAX_BYTES = BLOB_TYPES.length * CLI_SESSION_BLOB_MAX_BYTES; | ||
|
|
||
| /** Shared sessions one account may hold at a time. */ | ||
| export const CLI_SESSION_SHARE_MAX_PER_OWNER = 200; | ||
|
|
||
| /** Forked sessions one account may hold at a time. */ | ||
| export const CLI_SESSION_FORK_MAX_PER_OWNER = 200; | ||
|
|
||
| /** | ||
| * Every object key of one session folder. Deleting the whole set is idempotent, | ||
| * so callers do not have to know which blob types a session actually has. | ||
| */ | ||
| export function sessionBlobRefs( | ||
| folderName: FolderName | ||
| ): { folderName: FolderName; filename: FileName }[] { | ||
| return BLOB_TYPES.map(filename => ({ folderName, filename })); | ||
| } | ||
|
|
||
| /** | ||
| * Serialize the copy admission of one account. `pg_advisory_xact_lock` releases | ||
| * on commit or rollback, so the lock never outlives the transaction that guards | ||
| * the count-then-insert. A hash collision only serializes two accounts; it | ||
| * never admits a copy that should have been refused. | ||
| */ | ||
| async function lockOwnerCopies(tx: DrizzleTransaction, kiloUserId: string): Promise<void> { | ||
| await tx.execute( | ||
| sql`SELECT pg_advisory_xact_lock(hashtext('cli_session_copy'), hashtext(${kiloUserId}))` | ||
| ); | ||
| } | ||
|
|
||
| export type PublishSharedSessionCopyParams = { | ||
| kiloUserId: string; | ||
| sessionId: string; | ||
| sharedState: string; | ||
| }; | ||
|
|
||
| /** One row per blob type; a missing copy is stored as NULL rather than left out. */ | ||
| export function blobUrlColumns(copiedBlobs: Partial<Record<BlobUrlKeys, string>>) { | ||
| return { | ||
| api_conversation_history_blob_url: copiedBlobs.api_conversation_history_blob_url ?? null, | ||
| task_metadata_blob_url: copiedBlobs.task_metadata_blob_url ?? null, | ||
| ui_messages_blob_url: copiedBlobs.ui_messages_blob_url ?? null, | ||
| git_state_blob_url: copiedBlobs.git_state_blob_url ?? null, | ||
| }; | ||
| } | ||
|
|
||
| type SharedSessionCopyRow = Pick< | ||
| typeof sharedCliSessions.$inferSelect, | ||
| | 'share_id' | ||
| | 'api_conversation_history_blob_url' | ||
| | 'task_metadata_blob_url' | ||
| | 'ui_messages_blob_url' | ||
| | 'git_state_blob_url' | ||
| | 'pending_copy_ids' | ||
| >; | ||
|
|
||
| export function sharedSessionCurrentCopyIds(share: SharedSessionCopyRow): string[] { | ||
| const copyIds = new Set<string>(); | ||
|
|
||
| for (const blobUrl of [ | ||
| share.api_conversation_history_blob_url, | ||
| share.task_metadata_blob_url, | ||
| share.ui_messages_blob_url, | ||
| share.git_state_blob_url, | ||
| ]) { | ||
| const [folderName, copyId] = blobUrl?.split('/') ?? []; | ||
| if (folderName === 'shared-sessions' && copyId) { | ||
| copyIds.add(copyId); | ||
| } | ||
| } | ||
|
|
||
| if (copyIds.size === 0) { | ||
| copyIds.add(share.share_id); | ||
| } | ||
|
|
||
| return [...copyIds]; | ||
| } | ||
|
|
||
| /** Current storage folder for a link, used when copying it into a fork. */ | ||
| export function sharedSessionCurrentCopyId(share: SharedSessionCopyRow): string { | ||
| return sharedSessionCurrentCopyIds(share)[0]; | ||
| } | ||
|
|
||
| /** Current and pending shared-session folders, used by cleanup paths. */ | ||
| export function sharedSessionCopyIds(share: SharedSessionCopyRow): string[] { | ||
| return [...new Set([...sharedSessionCurrentCopyIds(share), ...share.pending_copy_ids])]; | ||
| } | ||
|
|
||
| /** | ||
| * Reserve the session row for a fork, or refuse once the account holds | ||
| * {@link CLI_SESSION_FORK_MAX_PER_OWNER} forks. The row is inserted with no | ||
| * blob urls; the caller adds them once the copy succeeds, so an admitted fork | ||
| * can never publish a row that points at nothing. | ||
| */ | ||
| export async function reserveForkedSession( | ||
| kiloUserId: string, | ||
| values: Omit<typeof cliSessions.$inferInsert, 'session_id' | 'is_fork'> | ||
| ): Promise<string> { | ||
| return db.transaction(async tx => { | ||
| await lockOwnerCopies(tx, kiloUserId); | ||
|
|
||
| const [totals] = await tx | ||
| .select({ forkCount: count() }) | ||
| .from(cliSessions) | ||
| .where(and(eq(cliSessions.kilo_user_id, kiloUserId), eq(cliSessions.is_fork, true))); | ||
|
|
||
| if (totals.forkCount >= CLI_SESSION_FORK_MAX_PER_OWNER) { | ||
| throw new TRPCError({ | ||
| code: 'BAD_REQUEST', | ||
| message: `An account can hold ${CLI_SESSION_FORK_MAX_PER_OWNER} forked sessions. Delete a forked session before forking another.`, | ||
| }); | ||
| } | ||
|
|
||
| const sessionId = crypto.randomUUID(); | ||
| await tx.insert(cliSessions).values({ session_id: sessionId, is_fork: true, ...values }); | ||
| return sessionId; | ||
| }); | ||
| } | ||
|
|
||
| /** Copy every blob of one session into another folder under the copy size limit. */ | ||
| export async function copySessionBlobs( | ||
| sourceId: string, | ||
| sourceFolder: FolderName, | ||
| destinationId: string, | ||
| destinationFolder: FolderName | ||
| ) { | ||
| try { | ||
| return await copyBlobs( | ||
| sourceId, | ||
| sourceFolder, | ||
| destinationId, | ||
| destinationFolder, | ||
| [...BLOB_TYPES], | ||
| { | ||
| maxBytes: CLI_SESSION_COPY_MAX_BYTES, | ||
| } | ||
| ); | ||
| } catch (error) { | ||
| if (error instanceof SessionBlobCopyTooLargeError) { | ||
| throw new TRPCError({ | ||
| code: 'BAD_REQUEST', | ||
| message: `Session blobs are larger than the ${CLI_SESSION_COPY_MAX_BYTES} byte copy limit.`, | ||
| }); | ||
| } | ||
| throw error; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Publish a fresh copy for an existing link or create a link after its first | ||
| * copy completes. The owner lock keeps allowance accounting atomic, while the | ||
| * row lock serializes refreshes and deletion of one published link. | ||
| */ | ||
| export async function publishSharedSessionCopy({ | ||
| kiloUserId, | ||
| sessionId, | ||
| sharedState, | ||
| }: PublishSharedSessionCopyParams): Promise<{ share_id: string; session_id: string }> { | ||
| let copyId: string | undefined; | ||
| let previousCopyIds: string[] = []; | ||
|
|
||
| let shareId: string; | ||
| try { | ||
| shareId = await db.transaction(async tx => { | ||
| await lockOwnerCopies(tx, kiloUserId); | ||
|
|
||
| const [existing] = await tx | ||
| .select({ | ||
| share_id: sharedCliSessions.share_id, | ||
| api_conversation_history_blob_url: sharedCliSessions.api_conversation_history_blob_url, | ||
| task_metadata_blob_url: sharedCliSessions.task_metadata_blob_url, | ||
| ui_messages_blob_url: sharedCliSessions.ui_messages_blob_url, | ||
| git_state_blob_url: sharedCliSessions.git_state_blob_url, | ||
| pending_copy_ids: sharedCliSessions.pending_copy_ids, | ||
| }) | ||
| .from(sharedCliSessions) | ||
| .where( | ||
| and( | ||
| eq(sharedCliSessions.session_id, sessionId), | ||
| eq(sharedCliSessions.kilo_user_id, kiloUserId), | ||
| eq(sharedCliSessions.shared_state, sharedState) | ||
| ) | ||
| ) | ||
| .limit(1) | ||
| .for('update'); | ||
|
|
||
| if (!existing) { | ||
| const [totals] = await tx | ||
| .select({ shareCount: count() }) | ||
| .from(sharedCliSessions) | ||
| .where( | ||
| and( | ||
| eq(sharedCliSessions.kilo_user_id, kiloUserId), | ||
| isNotNull(sharedCliSessions.session_id) | ||
| ) | ||
| ); | ||
|
|
||
| if (totals.shareCount >= CLI_SESSION_SHARE_MAX_PER_OWNER) { | ||
| throw new TRPCError({ | ||
| code: 'BAD_REQUEST', | ||
| message: `An account can hold ${CLI_SESSION_SHARE_MAX_PER_OWNER} shared sessions. Delete a shared session before sharing another.`, | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| if (existing && existing.pending_copy_ids.length > 0) { | ||
| await deleteSharedSessionCopies(existing.pending_copy_ids); | ||
| } | ||
|
|
||
| shareId = existing?.share_id ?? crypto.randomUUID(); | ||
| copyId = crypto.randomUUID(); | ||
| const copiedBlobs = await copySessionBlobs(sessionId, 'sessions', copyId, 'shared-sessions'); | ||
|
iscekic marked this conversation as resolved.
|
||
|
|
||
| if (existing) { | ||
| previousCopyIds = sharedSessionCurrentCopyIds(existing); | ||
| await tx | ||
| .update(sharedCliSessions) | ||
| .set({ | ||
| ...blobUrlColumns(copiedBlobs), | ||
| pending_copy_ids: previousCopyIds, | ||
| }) | ||
| .where(eq(sharedCliSessions.share_id, shareId)); | ||
| } else { | ||
| await tx.insert(sharedCliSessions).values({ | ||
| share_id: shareId, | ||
| session_id: sessionId, | ||
| kilo_user_id: kiloUserId, | ||
| shared_state: sharedState, | ||
| ...blobUrlColumns(copiedBlobs), | ||
| }); | ||
| } | ||
|
|
||
| return shareId; | ||
| }); | ||
| } catch (error) { | ||
| if (copyId) { | ||
| try { | ||
| await deleteSharedSessionCopies([copyId]); | ||
| } catch { | ||
| // A cleanup failure must not replace the error that caused the rollback. | ||
| } | ||
| } | ||
| throw error; | ||
| } | ||
|
|
||
| for (const previousCopyId of previousCopyIds) { | ||
| try { | ||
| await deleteSharedSessionCopies([previousCopyId]); | ||
| await clearPendingSharedSessionCopy(shareId, previousCopyId); | ||
| } catch { | ||
| // The row retains this folder id so a later refresh or account cleanup can retry it. | ||
| } | ||
| } | ||
|
|
||
| return { share_id: shareId, session_id: sessionId }; | ||
| } | ||
|
|
||
| /** | ||
| * Undo a fork reservation whose copy did not complete. The row belongs to the | ||
| * request that inserted it, so removing it together with whatever the copy | ||
| * wrote leaves nothing behind. | ||
| */ | ||
| export async function discardReservedFork(sessionId: string): Promise<void> { | ||
| try { | ||
| await deleteBlobs(sessionId, sessionBlobRefs('sessions')); | ||
| } catch { | ||
| // The row delete below still runs; a cleanup failure must not replace the | ||
| // error that caused the discard. | ||
| } | ||
| await db.delete(cliSessions).where(eq(cliSessions.session_id, sessionId)); | ||
| } | ||
|
|
||
| /** Delete the shared-sessions object copies in the given copy folders. */ | ||
| export async function deleteSharedSessionCopies(copyIds: string[]): Promise<void> { | ||
| for (const copyId of copyIds) { | ||
| await deleteBlobs(copyId, sessionBlobRefs('shared-sessions')); | ||
| } | ||
| } | ||
|
|
||
| async function clearPendingSharedSessionCopy(shareId: string, copyId: string): Promise<void> { | ||
| await db.transaction(async tx => { | ||
| const [share] = await tx | ||
| .select({ pending_copy_ids: sharedCliSessions.pending_copy_ids }) | ||
| .from(sharedCliSessions) | ||
| .where(eq(sharedCliSessions.share_id, shareId)) | ||
| .for('update'); | ||
|
|
||
| if (!share) return; | ||
|
|
||
| await tx | ||
| .update(sharedCliSessions) | ||
| .set({ | ||
| pending_copy_ids: share.pending_copy_ids.filter(pendingId => pendingId !== copyId), | ||
| }) | ||
| .where(eq(sharedCliSessions.share_id, shareId)); | ||
| }); | ||
| } | ||
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.