Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: show Loom concierge errors in production and keep open customer questions

Richie McIlroy7185eec9e0fd
diff --git a/apps/web/actions/loom-concierge.tsx b/apps/web/actions/loom-concierge.tsx
index 007584ce8..66f5e4c11 100644
--- a/apps/web/actions/loom-concierge.tsx
+++ b/apps/web/actions/loom-concierge.tsx
@@ -24,9 +24,11 @@ import {
requireCustomerMigrationAccess,
requireMigrationOperator,
requireProCustomerMigrationAccess,
+ toLoomMigrationResult,
} from "@/lib/loom-concierge";
import {
LOOM_MIGRATION_STATUS_LABELS,
+ LoomMigrationError,
type LoomMigrationStatus,
normalizeMigrationText,
validateOperatorMigrationUpdate,
@@ -51,14 +53,14 @@ function refreshMigrationPages() {
async function findMigration(requestId: string) {
if (typeof requestId !== "string" || !/^[A-Za-z0-9_-]{15}$/.test(requestId)) {
- throw new Error("Invalid migration request.");
+ throw new LoomMigrationError("Invalid migration request.");
}
const [request] = await db()
.select()
.from(loomMigrationRequests)
.where(eq(loomMigrationRequests.id, requestId))
.limit(1);
- if (!request) throw new Error("Migration request not found.");
+ if (!request) throw new LoomMigrationError("Migration request not found.");
return request;
}
@@ -73,15 +75,21 @@ export async function getLoomMigrationDashboard(
return { isPro, requests };
}
-export async function requestLoomMigration({
- organizationId,
- workspaceName,
- note,
-}: {
+type LoomMigrationRequestInput = {
organizationId: Organisation.OrganisationId;
workspaceName: string;
note: string;
-}) {
+};
+
+export async function requestLoomMigration(input: LoomMigrationRequestInput) {
+ return toLoomMigrationResult(() => createMigrationRequest(input));
+}
+
+async function createMigrationRequest({
+ organizationId,
+ workspaceName,
+ note,
+}: LoomMigrationRequestInput) {
const user = await requireProCustomerMigrationAccess(organizationId);
const normalizedWorkspaceName = normalizeMigrationText(
workspaceName,
@@ -154,10 +162,14 @@ export async function requestLoomMigration({
}
export async function confirmLoomMigrationInvite(requestId: string) {
+ return toLoomMigrationResult(() => markMigrationInviteSent(requestId));
+}
+
+async function markMigrationInviteSent(requestId: string) {
const request = await findMigration(requestId);
await requireCustomerMigrationAccess(request.organizationId);
if (request.status === "completed") {
- throw new Error("This migration is already complete.");
+ throw new LoomMigrationError("This migration is already complete.");
}
if (request.invitedAt) return;
const result = await db()
@@ -170,23 +182,30 @@ export async function confirmLoomMigrationInvite(requestId: string) {
),
);
if (affectedRows(result) === 0) {
- throw new Error("The migration request changed. Refresh and try again.");
+ throw new LoomMigrationError(
+ "The migration request changed. Refresh and try again.",
+ );
}
refreshMigrationPages();
}
-export async function answerLoomMigrationQuestion({
+type LoomMigrationAnswerInput = { requestId: string; answer: string };
+
+export async function answerLoomMigrationQuestion(
+ input: LoomMigrationAnswerInput,
+) {
+ return toLoomMigrationResult(() => saveMigrationAnswer(input));
+}
+
+async function saveMigrationAnswer({
requestId,
answer,
-}: {
- requestId: string;
- answer: string;
-}) {
+}: LoomMigrationAnswerInput) {
const request = await findMigration(requestId);
await requireCustomerMigrationAccess(request.organizationId);
const normalizedAnswer = normalizeMigrationText(answer, "Answer", 2000);
if (!normalizedAnswer)
- throw new Error("Enter the information Cap asked for.");
+ throw new LoomMigrationError("Enter the information Cap asked for.");
const result = await db()
.update(loomMigrationRequests)
.set({
@@ -201,7 +220,9 @@ export async function answerLoomMigrationQuestion({
),
);
if (affectedRows(result) === 0) {
- throw new Error("The migration request changed. Refresh and try again.");
+ throw new LoomMigrationError(
+ "The migration request changed. Refresh and try again.",
+ );
}
refreshMigrationPages();
}
@@ -210,21 +231,29 @@ export async function getLoomMigrationOperatorQueue() {
return getOperatorMigrationQueue();
}
-export async function updateLoomMigrationStatus({
- requestId,
- nextStatus,
- message,
- verified,
- expectedVideoCount,
- importedVideoCount,
-}: {
+type LoomMigrationStatusInput = {
requestId: string;
nextStatus: LoomMigrationStatus;
message: string;
verified: boolean;
expectedVideoCount: number | null;
importedVideoCount: number;
-}) {
+};
+
+export async function updateLoomMigrationStatus(
+ input: LoomMigrationStatusInput,
+) {
+ return toLoomMigrationResult(() => saveMigrationStatus(input));
+}
+
+async function saveMigrationStatus({
+ requestId,
+ nextStatus,
+ message,
+ verified,
+ expectedVideoCount,
+ importedVideoCount,
+}: LoomMigrationStatusInput) {
const operator = await requireMigrationOperator();
const request = await findMigration(requestId);
const normalizedMessage = validateOperatorMigrationUpdate({
@@ -264,7 +293,7 @@ export async function updateLoomMigrationStatus({
)
.limit(1);
if (unfinishedImport) {
- throw new Error(
+ throw new LoomMigrationError(
"Loom imports are still processing or have errors. Resolve them before completion.",
);
}
@@ -305,16 +334,21 @@ export async function updateLoomMigrationStatus({
),
);
if (affectedRows(result) === 0) {
- throw new Error(
+ throw new LoomMigrationError(
"The migration request changed or imports are starting. Refresh and try again.",
);
}
- const [requester] = await db()
- .select({ email: users.email })
- .from(users)
- .where(eq(users.id, request.requestedByUserId))
- .limit(1);
+ const customerVisibleChange =
+ nextStatus !== request.status ||
+ (normalizedMessage || null) !== request.capMessage;
+ const [requester] = customerVisibleChange
+ ? await db()
+ .select({ email: users.email })
+ .from(users)
+ .where(eq(users.id, request.requestedByUserId))
+ .limit(1)
+ : [];
if (requester) {
try {
const delivery = await sendEmail({
diff --git a/apps/web/actions/loom.ts b/apps/web/actions/loom.ts
index a89a6676c..9d3acc866 100644
--- a/apps/web/actions/loom.ts
+++ b/apps/web/actions/loom.ts
@@ -46,8 +46,13 @@ import {
renewConciergeImport,
requireMigrationOperator,
reserveConciergeImport,
+ toLoomMigrationResult,
} from "@/lib/loom-concierge";
import type { LoomImportDestination } from "@/lib/loom-import-destination";
+import {
+ LoomMigrationError,
+ type LoomMigrationResult,
+} from "@/lib/loom-migration-state";
import { isOrganizationOwnerPro } from "@/lib/org-pro";
import { provisionOrganizationInvitee } from "@/lib/organization-provisioning";
import { canManageOrganizationSettings } from "@/lib/permissions/roles";
@@ -438,7 +443,9 @@ async function importLoomVideoForOwner({
!reservation.leaseUntil ||
reservation.leaseUntil <= new Date()
) {
- throw new Error("The concierge import expired. Retry this video.");
+ throw new LoomMigrationError(
+ "The concierge import expired. Retry this video.",
+ );
}
}
await tx.insert(videos).values({
@@ -891,7 +898,9 @@ async function processLoomCsvRows({
for (const row of normalizedRows) {
if (migrationRequestId) {
if (!migrationLeaseToken) {
- throw new Error("The concierge import is missing its reservation.");
+ throw new LoomMigrationError(
+ "The concierge import is missing its reservation.",
+ );
}
await renewConciergeImport(migrationRequestId, migrationLeaseToken);
}
@@ -1028,7 +1037,14 @@ async function processLoomCsvRows({
};
}
-export async function importFromLoomCsvForConcierge({
+export async function importFromLoomCsvForConcierge(input: {
+ requestId: string;
+ rows: LoomCsvImportRow[];
+}): Promise<LoomMigrationResult<LoomCsvImportResult>> {
+ return toLoomMigrationResult(() => importConciergeCsvRows(input));
+}
+
+async function importConciergeCsvRows({
requestId,
rows,
}: {
@@ -1037,7 +1053,7 @@ export async function importFromLoomCsvForConcierge({
}): Promise<LoomCsvImportResult> {
const operator = await requireMigrationOperator();
if (typeof requestId !== "string" || !/^[A-Za-z0-9_-]{15}$/.test(requestId)) {
- throw new Error("Invalid migration request.");
+ throw new LoomMigrationError("Invalid migration request.");
}
const [request] = await db()
.select({
@@ -1059,13 +1075,15 @@ export async function importFromLoomCsvForConcierge({
)
.limit(1);
if (!request || request.status === "completed") {
- throw new Error("The migration request is no longer active.");
+ throw new LoomMigrationError("The migration request is no longer active.");
}
if (!(await isOrganizationOwnerPro(request.organizationId))) {
- throw new Error("The destination workspace needs Cap Pro.");
+ throw new LoomMigrationError("The destination workspace needs Cap Pro.");
}
if (!Array.isArray(rows) || rows.length > 10) {
- throw new Error("Concierge CSV imports run in batches of 10 videos.");
+ throw new LoomMigrationError(
+ "Concierge CSV imports run in batches of 10 videos.",
+ );
}
const leaseToken = await reserveConciergeImport(requestId, operator.id);
try {
@@ -1084,39 +1102,52 @@ export async function importFromLoomCsvForConcierge({
}
}
-export async function createConciergeLoomFileUpload({
- requestId,
- loomUrl,
- userEmail,
- spaceName,
- videoTitle,
-}: {
+type ConciergeLoomFileUploadInput = {
requestId: string;
loomUrl: string;
userEmail: string;
spaceName: string;
videoTitle: string;
-}): Promise<{
+};
+
+type ConciergeLoomFileUpload = {
videoId: Video.VideoId;
uploadTarget: StorageDomain.UploadTarget;
-}> {
+};
+
+export async function createConciergeLoomFileUpload(
+ input: ConciergeLoomFileUploadInput,
+): Promise<LoomMigrationResult<ConciergeLoomFileUpload>> {
+ return toLoomMigrationResult(() => prepareConciergeLoomFileUpload(input));
+}
+
+async function prepareConciergeLoomFileUpload({
+ requestId,
+ loomUrl,
+ userEmail,
+ spaceName,
+ videoTitle,
+}: ConciergeLoomFileUploadInput): Promise<ConciergeLoomFileUpload> {
const operator = await requireMigrationOperator();
if (typeof requestId !== "string" || !/^[A-Za-z0-9_-]{15}$/.test(requestId)) {
- throw new Error("Invalid migration request.");
+ throw new LoomMigrationError("Invalid migration request.");
}
const loomVideoId = extractLoomVideoId(loomUrl.trim());
- if (!loomVideoId) throw new Error("Enter a valid Loom video URL.");
+ if (!loomVideoId)
+ throw new LoomMigrationError("Enter a valid Loom video URL.");
const normalizedEmail = normalizeImportEmail(userEmail);
if (!isValidImportEmail(normalizedEmail)) {
- throw new Error("Enter a valid destination owner email.");
+ throw new LoomMigrationError("Enter a valid destination owner email.");
}
const normalizedSpaceName = normalizeImportSpaceName(spaceName);
if (!isValidImportSpaceName(normalizedSpaceName)) {
- throw new Error("Space name is too long.");
+ throw new LoomMigrationError("Space name is too long.");
}
const normalizedTitle = videoTitle.trim();
if (!normalizedTitle || normalizedTitle.length > 255) {
- throw new Error("Enter a video title of 255 characters or fewer.");
+ throw new LoomMigrationError(
+ "Enter a video title of 255 characters or fewer.",
+ );
}
const [request] = await db()
.select({
@@ -1136,9 +1167,10 @@ export async function createConciergeLoomFileUpload({
),
)
.limit(1);
- if (!request) throw new Error("The migration request is no longer active.");
+ if (!request)
+ throw new LoomMigrationError("The migration request is no longer active.");
if (!(await isOrganizationOwnerPro(request.organizationId))) {
- throw new Error("The destination workspace needs Cap Pro.");
+ throw new LoomMigrationError("The destination workspace needs Cap Pro.");
}
const leaseToken = await reserveConciergeImport(requestId, operator.id);
try {
@@ -1181,7 +1213,7 @@ export async function createConciergeLoomFileUpload({
(existing.phase !== "uploading" ||
existing.processingMessage !== "Uploading Loom video..."))
) {
- throw new Error(
+ throw new LoomMigrationError(
"This Loom video is already in the Cap import inventory.",
);
}
@@ -1201,7 +1233,7 @@ export async function createConciergeLoomFileUpload({
Option.getOrNull(retryUpload.storageIntegrationId) !==
existing.storageIntegrationId
) {
- throw new Error(
+ throw new LoomMigrationError(
"The Cap storage destination changed. Review this upload before retrying.",
);
}
@@ -1213,7 +1245,7 @@ export async function createConciergeLoomFileUpload({
)
.limit(1);
if (mapped && mapped.requestId !== requestId) {
- throw new Error(
+ throw new LoomMigrationError(
"This Loom import belongs to another migration request.",
);
}
@@ -1235,7 +1267,9 @@ export async function createConciergeLoomFileUpload({
!reservation.leaseUntil ||
reservation.leaseUntil <= new Date()
) {
- throw new Error("The concierge import expired. Retry this video.");
+ throw new LoomMigrationError(
+ "The concierge import expired. Retry this video.",
+ );
}
await tx.insert(loomMigrationImports).values({
videoId: Video.VideoId.make(existing.id),
@@ -1310,7 +1344,9 @@ export async function createConciergeLoomFileUpload({
!reservation.leaseUntil ||
reservation.leaseUntil <= new Date()
) {
- throw new Error("The concierge import expired. Retry this video.");
+ throw new LoomMigrationError(
+ "The concierge import expired. Retry this video.",
+ );
}
await tx.insert(videos).values({
id: videoId,
@@ -1360,7 +1396,14 @@ export async function createConciergeLoomFileUpload({
}
}
-export async function finishConciergeLoomFileUpload({
+export async function finishConciergeLoomFileUpload(input: {
+ requestId: string;
+ videoId: Video.VideoId;
+}) {
+ return toLoomMigrationResult(() => startConciergeLoomFileProcessing(input));
+}
+
+async function startConciergeLoomFileProcessing({
requestId,
videoId,
}: {
@@ -1369,7 +1412,7 @@ export async function finishConciergeLoomFileUpload({
}) {
const operator = await requireMigrationOperator();
if (typeof requestId !== "string" || !/^[A-Za-z0-9_-]{15}$/.test(requestId)) {
- throw new Error("Invalid migration request.");
+ throw new LoomMigrationError("Invalid migration request.");
}
const leaseToken = await reserveConciergeImport(requestId, operator.id);
try {
@@ -1416,20 +1459,27 @@ export async function finishConciergeLoomFileUpload({
(record.phase !== "uploading" ||
record.processingMessage !== "Uploading Loom video..."))
) {
- throw new Error("This Loom upload is no longer available.");
+ throw new LoomMigrationError("This Loom upload is no longer available.");
}
const [bucket] = await Storage.getAccessForVideo(
decodeStorageVideo(record.video),
).pipe(runPromise);
- const head = await bucket.headObject(record.rawFileKey).pipe(
- Effect.retry({
- times: 3,
- schedule: Schedule.exponential("100 millis"),
- }),
- runPromise,
- );
+ const head = await bucket
+ .headObject(record.rawFileKey)
+ .pipe(
+ Effect.retry({
+ times: 3,
+ schedule: Schedule.exponential("100 millis"),
+ }),
+ runPromise,
+ )
+ .catch(() => {
+ throw new LoomMigrationError(
+ "The uploaded file was not found in storage. Upload it again.",
+ );
+ });
if ((head.ContentLength ?? 0) <= 0)
- throw new Error("The uploaded file is empty.");
+ throw new LoomMigrationError("The uploaded file is empty.");
const status = await startVideoProcessingWorkflow({
videoId,
userId: record.video.ownerId,
diff --git a/apps/web/app/(org)/dashboard/admin/loom-migrations/LoomMigrationQueue.tsx b/apps/web/app/(org)/dashboard/admin/loom-migrations/LoomMigrationQueue.tsx
index 34f6f5e2c..b7c6b1ea9 100644
--- a/apps/web/app/(org)/dashboard/admin/loom-migrations/LoomMigrationQueue.tsx
+++ b/apps/web/app/(org)/dashboard/admin/loom-migrations/LoomMigrationQueue.tsx
@@ -21,6 +21,7 @@ import { parseConciergeLoomCsv } from "@/lib/loom-csv";
import {
LOOM_MIGRATION_STATUS_LABELS,
type LoomMigrationStatus,
+ unwrapLoomMigrationResult,
} from "@/lib/loom-migration-state";
import { uploadWithTarget } from "@/utils/upload-target";
@@ -71,16 +72,20 @@ function QueueItem({ request }: { request: OperatorLoomMigrationView }) {
const refresh = () =>
queryClient.invalidateQueries({ queryKey: ["loom-migration-queue"] });
const statusMutation = useMutation({
- mutationFn: () =>
- updateLoomMigrationStatus({
- requestId: request.id,
- nextStatus,
- message,
- verified,
- expectedVideoCount:
- expectedVideoCount.trim() === "" ? null : Number(expectedVideoCount),
- importedVideoCount: Number(importedVideoCount),
- }),
+ mutationFn: async () =>
+ unwrapLoomMigrationResult(
+ await updateLoomMigrationStatus({
+ requestId: request.id,
+ nextStatus,
+ message,
+ verified,
+ expectedVideoCount:
+ expectedVideoCount.trim() === ""
+ ? null
+ : Number(expectedVideoCount),
+ importedVideoCount: Number(importedVideoCount),
+ }),
+ ),
onSuccess: async () => {
await refresh();
toast.success("Migration status updated.");
@@ -97,10 +102,12 @@ function QueueItem({ request }: { request: OperatorLoomMigrationView }) {
const failures: LoomCsvImportRowResult[] = [];
for (let index = 0; index < csvRows.length; index += BATCH_SIZE) {
const batch = csvRows.slice(index, index + BATCH_SIZE);
- const result = await importFromLoomCsvForConcierge({
- requestId: request.id,
- rows: batch,
- });
+ const result = unwrapLoomMigrationResult(
+ await importFromLoomCsvForConcierge({
+ requestId: request.id,
+ rows: batch,
+ }),
+ );
started += result.importedCount;
failures.push(...result.results.filter((row) => !row.success));
setProcessedRows(index + batch.length);
@@ -132,13 +139,15 @@ function QueueItem({ request }: { request: OperatorLoomMigrationView }) {
throw new Error("Choose an MP4 downloaded from Loom.");
}
if (file.size === 0) throw new Error("The MP4 file is empty.");
- const prepared = await createConciergeLoomFileUpload({
- requestId: request.id,
- loomUrl: fileLoomUrl,
- userEmail: fileOwnerEmail,
- spaceName: fileSpaceName,
- videoTitle: fileTitle.trim() || file.name.replace(/\.mp4$/i, ""),
- });
+ const prepared = unwrapLoomMigrationResult(
+ await createConciergeLoomFileUpload({
+ requestId: request.id,
+ loomUrl: fileLoomUrl,
+ userEmail: fileOwnerEmail,
+ spaceName: fileSpaceName,
+ videoTitle: fileTitle.trim() || file.name.replace(/\.mp4$/i, ""),
+ }),
+ );
setUploadPercent(0);
await uploadWithTarget({
target: prepared.uploadTarget,
@@ -148,10 +157,12 @@ function QueueItem({ request }: { request: OperatorLoomMigrationView }) {
if (total > 0) setUploadPercent(Math.round((loaded / total) * 100));
},
});
- return finishConciergeLoomFileUpload({
- requestId: request.id,
- videoId: prepared.videoId,
- });
+ return unwrapLoomMigrationResult(
+ await finishConciergeLoomFileUpload({
+ requestId: request.id,
+ videoId: prepared.videoId,
+ }),
+ );
},
onSuccess: async (result) => {
await refresh();
diff --git a/apps/web/app/(org)/dashboard/migrations/loom/LoomMigrationPage.tsx b/apps/web/app/(org)/dashboard/migrations/loom/LoomMigrationPage.tsx
index 63129848c..9bcbb0ffb 100644
--- a/apps/web/app/(org)/dashboard/migrations/loom/LoomMigrationPage.tsx
+++ b/apps/web/app/(org)/dashboard/migrations/loom/LoomMigrationPage.tsx
@@ -17,6 +17,7 @@ import type { LoomMigrationView } from "@/lib/loom-concierge";
import {
LOOM_MIGRATION_STATUS_LABELS,
type LoomMigrationStatus,
+ unwrapLoomMigrationResult,
} from "@/lib/loom-migration-state";
const STATUS_STYLE: Record<LoomMigrationStatus, string> = {
@@ -117,9 +118,11 @@ export function LoomMigrationPage() {
queryKey: ["loom-concierge", organizationId],
});
const requestMutation = useMutation({
- mutationFn: () => {
+ mutationFn: async () => {
if (!organizationId) throw new Error("Select a Cap workspace.");
- return requestLoomMigration({ organizationId, workspaceName, note });
+ return unwrapLoomMigrationResult(
+ await requestLoomMigration({ organizationId, workspaceName, note }),
+ );
},
onSuccess: async (result) => {
await refresh();
@@ -133,7 +136,8 @@ export function LoomMigrationPage() {
onError: (error) => toast.error(error.message),
});
const inviteMutation = useMutation({
- mutationFn: confirmLoomMigrationInvite,
+ mutationFn: async (requestId: string) =>
+ unwrapLoomMigrationResult(await confirmLoomMigrationInvite(requestId)),
onSuccess: async () => {
await refresh();
toast.success("Thanks. Cap can now review your Loom invite.");
@@ -141,7 +145,8 @@ export function LoomMigrationPage() {
onError: (error) => toast.error(error.message),
});
const answerMutation = useMutation({
- mutationFn: answerLoomMigrationQuestion,
+ mutationFn: async (input: { requestId: string; answer: string }) =>
+ unwrapLoomMigrationResult(await answerLoomMigrationQuestion(input)),
onSuccess: async () => {
setAnswer("");
await refresh();
diff --git a/apps/web/lib/loom-concierge.ts b/apps/web/lib/loom-concierge.ts
index 7bd62cf69..27538802f 100644
--- a/apps/web/lib/loom-concierge.ts
+++ b/apps/web/lib/loom-concierge.ts
@@ -26,7 +26,11 @@ import {
import { requireOrganizationSettingsManager } from "@/actions/organization/authorization";
import { MESSENGER_ADMIN_EMAIL } from "@/lib/messenger/constants";
import { isOrganizationOwnerPro } from "@/lib/org-pro";
-import type { LoomMigrationStatus } from "./loom-migration-state";
+import {
+ LoomMigrationError,
+ type LoomMigrationResult,
+ type LoomMigrationStatus,
+} from "./loom-migration-state";
type MigrationRecord = typeof loomMigrationRequests.$inferSelect;
const IMPORT_LEASE_MS = 60 * 60 * 1000;
@@ -54,6 +58,19 @@ export type OperatorLoomMigrationView = LoomMigrationView & {
requestedByEmail: string;
};
+export async function toLoomMigrationResult<T>(
+ run: () => Promise<T>,
+): Promise<LoomMigrationResult<T>> {
+ try {
+ return { ok: true, value: await run() };
+ } catch (error) {
+ if (error instanceof LoomMigrationError) {
+ return { ok: false, error: error.message };
+ }
+ throw error;
+ }
+}
+
export function migrationToView(record: MigrationRecord): LoomMigrationView {
return {
id: record.id,
@@ -82,7 +99,7 @@ export async function requireCustomerMigrationAccess(
organizationId: Organisation.OrganisationId,
) {
const user = await getCurrentUser();
- if (!user) throw new Error("Unauthorized");
+ if (!user) throw new LoomMigrationError("Unauthorized");
await requireOrganizationSettingsManager(user.id, organizationId);
return user;
}
@@ -92,10 +109,12 @@ export async function requireProCustomerMigrationAccess(
) {
const user = await requireCustomerMigrationAccess(organizationId);
if (!buildEnv.NEXT_PUBLIC_IS_CAP) {
- throw new Error("Concierge migration is available on Cap Cloud.");
+ throw new LoomMigrationError(
+ "Concierge migration is available on Cap Cloud.",
+ );
}
if (!(await isOrganizationOwnerPro(organizationId))) {
- throw new Error("Concierge Loom migration requires Cap Pro.");
+ throw new LoomMigrationError("Concierge Loom migration requires Cap Pro.");
}
return user;
}
@@ -107,7 +126,7 @@ export async function requireMigrationOperator() {
!user ||
user.email.toLowerCase() !== MESSENGER_ADMIN_EMAIL
) {
- throw new Error("Unauthorized");
+ throw new LoomMigrationError("Unauthorized");
}
return user;
}
@@ -133,7 +152,7 @@ export async function reserveConciergeImport(
activeImportCount: 1,
activeImportLeaseToken: token,
activeImportLeaseUntil: new Date(now.getTime() + IMPORT_LEASE_MS),
- status: "in_progress",
+ status: sql`CASE WHEN ${loomMigrationRequests.status} = 'pending' THEN 'in_progress' ELSE ${loomMigrationRequests.status} END`,
lastOperatorUserId: operatorId,
lastOperatorAt: now,
updatedAt: now,
@@ -149,7 +168,7 @@ export async function reserveConciergeImport(
),
);
if (affectedRows(result) === 0) {
- throw new Error(
+ throw new LoomMigrationError(
"The migration request changed or another import is starting. Refresh and try again.",
);
}
@@ -191,7 +210,9 @@ export async function renewConciergeImport(requestId: string, token: string) {
),
);
if (affectedRows(result) === 0) {
- throw new Error("The concierge import expired. Refresh and retry.");
+ throw new LoomMigrationError(
+ "The concierge import expired. Refresh and retry.",
+ );
}
}
diff --git a/apps/web/lib/loom-migration-state.ts b/apps/web/lib/loom-migration-state.ts
index 1e2791df9..79ab2a6c4 100644
--- a/apps/web/lib/loom-migration-state.ts
+++ b/apps/web/lib/loom-migration-state.ts
@@ -7,6 +7,19 @@ export const LOOM_MIGRATION_STATUSES = [
export type LoomMigrationStatus = (typeof LOOM_MIGRATION_STATUSES)[number];
+export class LoomMigrationError extends Error {
+ override name = "LoomMigrationError";
+}
+
+export type LoomMigrationResult<T> =
+ | { ok: true; value: T }
+ | { ok: false; error: string };
+
+export function unwrapLoomMigrationResult<T>(result: LoomMigrationResult<T>) {
+ if (!result.ok) throw new Error(result.error);
+ return result.value;
+}
+
export const LOOM_MIGRATION_STATUS_LABELS: Record<LoomMigrationStatus, string> =
{
pending: "Pending",
@@ -20,10 +33,13 @@ export function normalizeMigrationText(
label: string,
maxLength: number,
) {
- if (typeof value !== "string") throw new Error(`${label} is invalid.`);
+ if (typeof value !== "string")
+ throw new LoomMigrationError(`${label} is invalid.`);
const normalized = value.trim().replace(/\s+/g, " ");
if (normalized.length > maxLength) {
- throw new Error(`${label} must be ${maxLength} characters or fewer.`);
+ throw new LoomMigrationError(
+ `${label} must be ${maxLength} characters or fewer.`,
+ );
}
return normalized;
}
@@ -44,20 +60,26 @@ export function validateOperatorMigrationUpdate({
importedVideoCount: number;
}) {
if (currentStatus === "completed") {
- throw new Error("A completed migration cannot be changed.");
+ throw new LoomMigrationError("A completed migration cannot be changed.");
}
if (!LOOM_MIGRATION_STATUSES.includes(nextStatus)) {
- throw new Error("Invalid migration status.");
+ throw new LoomMigrationError("Invalid migration status.");
}
const normalizedMessage = normalizeMigrationText(message, "Message", 2000);
if (nextStatus === "needs_information" && !normalizedMessage) {
- throw new Error("Tell the customer what information you need.");
+ throw new LoomMigrationError(
+ "Tell the customer what information you need.",
+ );
}
if (nextStatus === "completed" && !verified) {
- throw new Error("Verify the migrated library before marking it complete.");
+ throw new LoomMigrationError(
+ "Verify the migrated library before marking it complete.",
+ );
}
if (nextStatus === "completed" && expectedVideoCount === null) {
- throw new Error("Enter the agreed source video count before completion.");
+ throw new LoomMigrationError(
+ "Enter the agreed source video count before completion.",
+ );
}
if (
!Number.isInteger(importedVideoCount) ||
@@ -67,14 +89,16 @@ export function validateOperatorMigrationUpdate({
expectedVideoCount < 0 ||
importedVideoCount > expectedVideoCount))
) {
- throw new Error("Enter valid video counts.");
+ throw new LoomMigrationError("Enter valid video counts.");
}
if (
nextStatus === "completed" &&
expectedVideoCount !== null &&
importedVideoCount !== expectedVideoCount
) {
- throw new Error("Reconcile the expected video count before completion.");
+ throw new LoomMigrationError(
+ "Reconcile the expected video count before completion.",
+ );
}
return normalizedMessage;
}