Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: coordinate concierge import completion

Richie McIlroy1b6cb9dd439f
diff --git a/apps/web/actions/loom-concierge.tsx b/apps/web/actions/loom-concierge.tsx
index b1a91d30f..65835952a 100644
--- a/apps/web/actions/loom-concierge.tsx
+++ b/apps/web/actions/loom-concierge.tsx
@@ -8,7 +8,7 @@ import {
} from "@cap/database/emails/loom-migration";
import { nanoId } from "@cap/database/helpers";
import {
- importedVideos,
+ loomMigrationImports,
loomMigrationRequests,
organizations,
users,
@@ -246,12 +246,14 @@ export async function updateLoomMigrationStatus({
if (nextStatus === "completed") {
const [unfinishedImport] = await db()
.select({ videoId: videoUploads.videoId })
- .from(importedVideos)
- .innerJoin(videoUploads, eq(videoUploads.videoId, importedVideos.id))
+ .from(loomMigrationImports)
+ .innerJoin(
+ videoUploads,
+ eq(videoUploads.videoId, loomMigrationImports.videoId),
+ )
.where(
and(
- eq(importedVideos.orgId, request.organizationId),
- eq(importedVideos.source, "loom"),
+ eq(loomMigrationImports.requestId, requestId),
inArray(videoUploads.phase, [
"uploading",
"processing",
@@ -290,10 +292,16 @@ export async function updateLoomMigrationStatus({
and(
eq(loomMigrationRequests.id, requestId),
eq(loomMigrationRequests.status, request.status),
+ isNotNull(loomMigrationRequests.activeOrganizationId),
+ nextStatus === "completed"
+ ? eq(loomMigrationRequests.activeImportCount, 0)
+ : undefined,
),
);
if (affectedRows(result) === 0) {
- throw new Error("The migration request changed. Refresh and try again.");
+ throw new Error(
+ "The migration request changed or imports are starting. Refresh and try again.",
+ );
}
const [requester] = await db()
diff --git a/apps/web/actions/loom.ts b/apps/web/actions/loom.ts
index 7cb49e13f..2083d85dc 100644
--- a/apps/web/actions/loom.ts
+++ b/apps/web/actions/loom.ts
@@ -7,6 +7,7 @@ import { nanoId } from "@cap/database/helpers";
import {
folders,
importedVideos,
+ loomMigrationImports,
loomMigrationRequests,
organizationMembers,
organizations,
@@ -39,7 +40,11 @@ import {
requireOrganizationSettingsManager,
} from "@/actions/organization/authorization";
import { requireSpaceManager } from "@/actions/organization/space-authorization";
-import { requireMigrationOperator } from "@/lib/loom-concierge";
+import {
+ releaseConciergeImport,
+ requireMigrationOperator,
+ reserveConciergeImport,
+} from "@/lib/loom-concierge";
import type { LoomImportDestination } from "@/lib/loom-import-destination";
import { isOrganizationOwnerPro } from "@/lib/org-pro";
import { provisionOrganizationInvitee } from "@/lib/organization-provisioning";
@@ -104,15 +109,6 @@ const LOOM_CSV_LIMIT_ERROR = `CSV imports are limited to ${MAX_LOOM_CSV_ROWS} ro
const LOOM_CSV_PERMISSION_ERROR =
"Only organization admins and owners can import Loom videos from a CSV.";
-function affectedRows(result: unknown) {
- if (Array.isArray(result)) {
- return (
- (result[0] as { affectedRows?: number } | undefined)?.affectedRows ?? 0
- );
- }
- return (result as { affectedRows?: number } | undefined)?.affectedRows ?? 0;
-}
-
function extractLoomVideoId(url: string): string | null {
try {
const parsed = new URL(url);
@@ -319,11 +315,13 @@ async function importLoomVideoForOwner({
orgId,
ownerId,
destination = {},
+ migrationRequestId,
}: {
loomUrl: string;
orgId: Organisation.OrganisationId;
ownerId: User.UserId;
destination?: LoomImportDestination;
+ migrationRequestId?: string;
}): Promise<LoomImportResult> {
const loomVideoId = extractLoomVideoId(loomUrl.trim());
if (!loomVideoId) {
@@ -442,6 +440,12 @@ async function importLoomVideoForOwner({
source: "loom",
sourceId: loomVideoId,
});
+ if (migrationRequestId) {
+ await tx.insert(loomMigrationImports).values({
+ videoId,
+ requestId: migrationRequestId,
+ });
+ }
if (destination.spaceId === orgId) {
await tx.insert(sharedVideos).values({
@@ -796,10 +800,12 @@ async function processLoomCsvRows({
rows,
orgId,
actorId,
+ migrationRequestId,
}: {
rows: LoomCsvImportRow[];
orgId: Organisation.OrganisationId;
actorId: User.UserId;
+ migrationRequestId?: string;
}): Promise<LoomCsvImportResult> {
const inputRows = Array.isArray(rows) ? rows : [];
const normalizedRows = inputRows
@@ -909,6 +915,7 @@ async function processLoomCsvRows({
loomUrl: row.loomUrl,
orgId,
ownerId: member.userId,
+ migrationRequestId,
});
let spaceName = row.spaceName || undefined;
@@ -1012,52 +1019,31 @@ export async function importFromLoomCsvForConcierge({
if (!(await isOrganizationOwnerPro(request.organizationId))) {
throw new Error("The destination workspace needs Cap Pro.");
}
- const claimed = await db()
- .update(loomMigrationRequests)
- .set({
- status: "in_progress",
- lastOperatorUserId: operator.id,
- lastOperatorAt: new Date(),
- updatedAt: new Date(),
- })
- .where(
- and(
- eq(loomMigrationRequests.id, requestId),
- isNotNull(loomMigrationRequests.activeOrganizationId),
- ),
- );
- if (affectedRows(claimed) === 0) {
- throw new Error("The migration request changed. Refresh and try again.");
- }
- const result = await processLoomCsvRows({
- rows,
- orgId: request.organizationId,
- actorId: request.ownerId,
- });
- if (result.importedCount > 0) {
- const updated = await db()
- .update(loomMigrationRequests)
- .set({
- queuedVideoCount: sql`${loomMigrationRequests.queuedVideoCount} + ${result.importedCount}`,
- lastOperatorUserId: operator.id,
- lastOperatorAt: new Date(),
- updatedAt: new Date(),
- })
- .where(
- and(
- eq(loomMigrationRequests.id, requestId),
- isNotNull(loomMigrationRequests.activeOrganizationId),
- ),
- );
- if (affectedRows(updated) === 0) {
- throw new Error(
- "The migration request changed after jobs started. Review them before retrying.",
- );
+ await reserveConciergeImport(requestId, operator.id);
+ try {
+ const result = await processLoomCsvRows({
+ rows,
+ orgId: request.organizationId,
+ actorId: request.ownerId,
+ migrationRequestId: requestId,
+ });
+ if (result.importedCount > 0) {
+ await db()
+ .update(loomMigrationRequests)
+ .set({
+ queuedVideoCount: sql`${loomMigrationRequests.queuedVideoCount} + ${result.importedCount}`,
+ lastOperatorUserId: operator.id,
+ lastOperatorAt: new Date(),
+ updatedAt: new Date(),
+ })
+ .where(eq(loomMigrationRequests.id, requestId));
}
+ revalidatePath("/dashboard/migrations/loom");
+ revalidatePath("/dashboard/admin/loom-migrations");
+ return result;
+ } finally {
+ await releaseConciergeImport(requestId);
}
- revalidatePath("/dashboard/migrations/loom");
- revalidatePath("/dashboard/admin/loom-migrations");
- return result;
}
export async function createConciergeLoomFileUpload({
@@ -1116,161 +1102,173 @@ export async function createConciergeLoomFileUpload({
if (!(await isOrganizationOwnerPro(request.organizationId))) {
throw new Error("The destination workspace needs Cap Pro.");
}
- const [existing] = await db()
- .select({
- id: importedVideos.id,
- ownerId: videos.ownerId,
- ownerEmail: users.email,
- bucket: videos.bucket,
- storageIntegrationId: videos.storageIntegrationId,
- rawFileKey: videoUploads.rawFileKey,
- phase: videoUploads.phase,
- processingMessage: videoUploads.processingMessage,
- })
- .from(importedVideos)
- .leftJoin(
- videos,
- and(
- eq(videos.id, importedVideos.id),
- eq(videos.orgId, importedVideos.orgId),
- ),
- )
- .leftJoin(users, eq(users.id, videos.ownerId))
- .leftJoin(videoUploads, eq(videoUploads.videoId, importedVideos.id))
- .where(
- and(
- eq(importedVideos.orgId, request.organizationId),
- eq(importedVideos.source, "loom"),
- eq(importedVideos.sourceId, loomVideoId),
- ),
- )
- .limit(1);
- if (existing) {
- if (
- !existing.ownerId ||
- !existing.ownerEmail ||
- normalizeImportEmail(existing.ownerEmail) !== normalizedEmail ||
- !existing.rawFileKey ||
- (existing.phase !== "error" &&
- (existing.phase !== "uploading" ||
- existing.processingMessage !== "Uploading Loom video..."))
- ) {
- throw new Error(
- "This Loom video is already in the Cap import inventory.",
- );
+ await reserveConciergeImport(requestId, operator.id);
+ try {
+ const [existing] = await db()
+ .select({
+ id: importedVideos.id,
+ ownerId: videos.ownerId,
+ ownerEmail: users.email,
+ bucket: videos.bucket,
+ storageIntegrationId: videos.storageIntegrationId,
+ rawFileKey: videoUploads.rawFileKey,
+ phase: videoUploads.phase,
+ processingMessage: videoUploads.processingMessage,
+ })
+ .from(importedVideos)
+ .leftJoin(
+ videos,
+ and(
+ eq(videos.id, importedVideos.id),
+ eq(videos.orgId, importedVideos.orgId),
+ ),
+ )
+ .leftJoin(users, eq(users.id, videos.ownerId))
+ .leftJoin(videoUploads, eq(videoUploads.videoId, importedVideos.id))
+ .where(
+ and(
+ eq(importedVideos.orgId, request.organizationId),
+ eq(importedVideos.source, "loom"),
+ eq(importedVideos.sourceId, loomVideoId),
+ ),
+ )
+ .limit(1);
+ if (existing) {
+ if (
+ !existing.ownerId ||
+ !existing.ownerEmail ||
+ normalizeImportEmail(existing.ownerEmail) !== normalizedEmail ||
+ !existing.rawFileKey ||
+ (existing.phase !== "error" &&
+ (existing.phase !== "uploading" ||
+ existing.processingMessage !== "Uploading Loom video..."))
+ ) {
+ throw new Error(
+ "This Loom video is already in the Cap import inventory.",
+ );
+ }
+ const retryUpload = await Storage.createUploadTargetForUser(
+ existing.ownerId,
+ existing.rawFileKey,
+ {
+ contentType: "video/mp4",
+ videoTitle: normalizedTitle,
+ method: "put",
+ fields: { "x-amz-meta-userid": existing.ownerId },
+ },
+ request.organizationId,
+ ).pipe(runPromise);
+ if (
+ Option.getOrNull(retryUpload.bucketId) !== existing.bucket ||
+ Option.getOrNull(retryUpload.storageIntegrationId) !==
+ existing.storageIntegrationId
+ ) {
+ throw new Error(
+ "The Cap storage destination changed. Review this upload before retrying.",
+ );
+ }
+ const [mapped] = await db()
+ .select({ requestId: loomMigrationImports.requestId })
+ .from(loomMigrationImports)
+ .where(
+ eq(loomMigrationImports.videoId, Video.VideoId.make(existing.id)),
+ )
+ .limit(1);
+ if (mapped && mapped.requestId !== requestId) {
+ throw new Error(
+ "This Loom import belongs to another migration request.",
+ );
+ }
+ if (!mapped) {
+ await db()
+ .insert(loomMigrationImports)
+ .values({
+ videoId: Video.VideoId.make(existing.id),
+ requestId,
+ });
+ }
+ return {
+ videoId: Video.VideoId.make(existing.id),
+ uploadTarget: retryUpload.upload,
+ };
+ }
+ let member = await getOrganizationMemberByEmail(
+ request.organizationId,
+ normalizedEmail,
+ );
+ if (!member) {
+ const provisioned = await provisionOrganizationInvitee({
+ organizationId: request.organizationId,
+ email: normalizedEmail,
+ invitedByUserId: request.ownerId,
+ role: "member",
+ });
+ member = { userId: provisioned.userId, email: normalizedEmail };
}
- const retryUpload = await Storage.createUploadTargetForUser(
- existing.ownerId,
- existing.rawFileKey,
+ const space = normalizedSpaceName
+ ? await getOrCreateImportSpace({
+ orgId: request.organizationId,
+ createdById: request.ownerId,
+ name: normalizedSpaceName,
+ spaceCache: new Map(),
+ })
+ : null;
+ if (space) {
+ await addImportOwnerToSpace({ spaceId: space.id, userId: member.userId });
+ }
+ const videoId = Video.VideoId.make(nanoId());
+ const rawFileKey = `${member.userId}/${videoId}/raw-upload.mp4`;
+ const upload = await Storage.createUploadTargetForUser(
+ member.userId,
+ rawFileKey,
{
contentType: "video/mp4",
videoTitle: normalizedTitle,
method: "put",
- fields: { "x-amz-meta-userid": existing.ownerId },
+ fields: { "x-amz-meta-userid": member.userId },
},
request.organizationId,
).pipe(runPromise);
- if (
- Option.getOrNull(retryUpload.bucketId) !== existing.bucket ||
- Option.getOrNull(retryUpload.storageIntegrationId) !==
- existing.storageIntegrationId
- ) {
- throw new Error(
- "The Cap storage destination changed. Review this upload before retrying.",
- );
- }
- return {
- videoId: Video.VideoId.make(existing.id),
- uploadTarget: retryUpload.upload,
- };
- }
- let member = await getOrganizationMemberByEmail(
- request.organizationId,
- normalizedEmail,
- );
- if (!member) {
- const provisioned = await provisionOrganizationInvitee({
- organizationId: request.organizationId,
- email: normalizedEmail,
- invitedByUserId: request.ownerId,
- role: "member",
- });
- member = { userId: provisioned.userId, email: normalizedEmail };
- }
- const space = normalizedSpaceName
- ? await getOrCreateImportSpace({
+ await db().transaction(async (tx) => {
+ await tx.insert(videos).values({
+ id: videoId,
+ name: normalizedTitle,
+ ownerId: member.userId,
orgId: request.organizationId,
- createdById: request.ownerId,
- name: normalizedSpaceName,
- spaceCache: new Map(),
- })
- : null;
- if (space) {
- await addImportOwnerToSpace({ spaceId: space.id, userId: member.userId });
- }
- const videoId = Video.VideoId.make(nanoId());
- const rawFileKey = `${member.userId}/${videoId}/raw-upload.mp4`;
- const upload = await Storage.createUploadTargetForUser(
- member.userId,
- rawFileKey,
- {
- contentType: "video/mp4",
- videoTitle: normalizedTitle,
- method: "put",
- fields: { "x-amz-meta-userid": member.userId },
- },
- request.organizationId,
- ).pipe(runPromise);
- await db().transaction(async (tx) => {
- await tx.insert(videos).values({
- id: videoId,
- name: normalizedTitle,
- ownerId: member.userId,
- orgId: request.organizationId,
- source: { type: "webMP4" as const },
- bucket: Option.getOrNull(upload.bucketId),
- storageIntegrationId: Option.getOrNull(upload.storageIntegrationId),
- public: serverEnv().CAP_VIDEOS_DEFAULT_PUBLIC,
- });
- await tx.insert(videoUploads).values({
- videoId,
- mode: "singlepart",
- phase: "uploading",
- processingProgress: 0,
- processingMessage: "Uploading Loom video...",
- rawFileKey,
- });
- await tx.insert(importedVideos).values({
- id: videoId,
- orgId: request.organizationId,
- source: "loom",
- sourceId: loomVideoId,
- });
- if (space) {
- await tx.insert(spaceVideos).values({
- id: nanoId(),
+ source: { type: "webMP4" as const },
+ bucket: Option.getOrNull(upload.bucketId),
+ storageIntegrationId: Option.getOrNull(upload.storageIntegrationId),
+ public: serverEnv().CAP_VIDEOS_DEFAULT_PUBLIC,
+ });
+ await tx.insert(videoUploads).values({
videoId,
- spaceId: space.id,
- addedById: request.ownerId,
+ mode: "singlepart",
+ phase: "uploading",
+ processingProgress: 0,
+ processingMessage: "Uploading Loom video...",
+ rawFileKey,
});
- }
- });
- await db()
- .update(loomMigrationRequests)
- .set({
- status: "in_progress",
- lastOperatorUserId: operator.id,
- lastOperatorAt: new Date(),
- updatedAt: new Date(),
- })
- .where(
- and(
- eq(loomMigrationRequests.id, requestId),
- isNotNull(loomMigrationRequests.activeOrganizationId),
- ),
- );
- revalidatePath("/dashboard/admin/loom-migrations");
- return { videoId, uploadTarget: upload.upload };
+ await tx.insert(importedVideos).values({
+ id: videoId,
+ orgId: request.organizationId,
+ source: "loom",
+ sourceId: loomVideoId,
+ });
+ await tx.insert(loomMigrationImports).values({ videoId, requestId });
+ if (space) {
+ await tx.insert(spaceVideos).values({
+ id: nanoId(),
+ videoId,
+ spaceId: space.id,
+ addedById: request.ownerId,
+ });
+ }
+ });
+ revalidatePath("/dashboard/admin/loom-migrations");
+ return { videoId, uploadTarget: upload.upload };
+ } finally {
+ await releaseConciergeImport(requestId);
+ }
}
export async function finishConciergeLoomFileUpload({
@@ -1284,80 +1282,93 @@ export async function finishConciergeLoomFileUpload({
if (typeof requestId !== "string" || !/^[A-Za-z0-9_-]{15}$/.test(requestId)) {
throw new Error("Invalid migration request.");
}
- const [record] = await db()
- .select({
- video: videos,
- rawFileKey: videoUploads.rawFileKey,
- phase: videoUploads.phase,
- processingMessage: videoUploads.processingMessage,
- })
- .from(videos)
- .innerJoin(
- importedVideos,
- and(
- eq(importedVideos.id, videos.id),
- eq(importedVideos.orgId, videos.orgId),
- ),
- )
- .innerJoin(videoUploads, eq(videoUploads.videoId, videos.id))
- .innerJoin(
- loomMigrationRequests,
- eq(loomMigrationRequests.organizationId, importedVideos.orgId),
- )
- .where(
- and(
- eq(videos.id, videoId),
- eq(loomMigrationRequests.id, requestId),
- eq(importedVideos.source, "loom"),
- isNotNull(loomMigrationRequests.activeOrganizationId),
- ),
- )
- .limit(1);
- if (
- !record ||
- !record.rawFileKey ||
- (record.phase !== "error" &&
- (record.phase !== "uploading" ||
- record.processingMessage !== "Uploading Loom video..."))
- ) {
- throw new Error("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,
- );
- if ((head.ContentLength ?? 0) <= 0)
- throw new Error("The uploaded file is empty.");
- const status = await startVideoProcessingWorkflow({
- videoId,
- userId: record.video.ownerId,
- rawFileKey: record.rawFileKey,
- bucketId: record.video.bucket,
- processingMessage: "Processing Loom video...",
- startFailureMessage: "Loom file processing could not start.",
- });
- if (status === "started") {
- await db()
- .update(loomMigrationRequests)
- .set({
- queuedVideoCount: sql`${loomMigrationRequests.queuedVideoCount} + 1`,
- lastOperatorUserId: operator.id,
- lastOperatorAt: new Date(),
- updatedAt: new Date(),
+ await reserveConciergeImport(requestId, operator.id);
+ try {
+ const [record] = await db()
+ .select({
+ video: videos,
+ rawFileKey: videoUploads.rawFileKey,
+ phase: videoUploads.phase,
+ processingMessage: videoUploads.processingMessage,
})
+ .from(videos)
+ .innerJoin(
+ importedVideos,
+ and(
+ eq(importedVideos.id, videos.id),
+ eq(importedVideos.orgId, videos.orgId),
+ ),
+ )
+ .innerJoin(videoUploads, eq(videoUploads.videoId, videos.id))
+ .innerJoin(
+ loomMigrationImports,
+ eq(loomMigrationImports.videoId, videos.id),
+ )
+ .innerJoin(
+ loomMigrationRequests,
+ and(
+ eq(loomMigrationRequests.id, loomMigrationImports.requestId),
+ eq(loomMigrationRequests.organizationId, importedVideos.orgId),
+ ),
+ )
.where(
and(
+ eq(videos.id, videoId),
eq(loomMigrationRequests.id, requestId),
+ eq(importedVideos.source, "loom"),
isNotNull(loomMigrationRequests.activeOrganizationId),
),
- );
+ )
+ .limit(1);
+ if (
+ !record ||
+ !record.rawFileKey ||
+ (record.phase !== "error" &&
+ (record.phase !== "uploading" ||
+ record.processingMessage !== "Uploading Loom video..."))
+ ) {
+ throw new Error("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,
+ );
+ if ((head.ContentLength ?? 0) <= 0)
+ throw new Error("The uploaded file is empty.");
+ const status = await startVideoProcessingWorkflow({
+ videoId,
+ userId: record.video.ownerId,
+ rawFileKey: record.rawFileKey,
+ bucketId: record.video.bucket,
+ processingMessage: "Processing Loom video...",
+ startFailureMessage: "Loom file processing could not start.",
+ });
+ if (status === "started") {
+ await db()
+ .update(loomMigrationRequests)
+ .set({
+ queuedVideoCount: sql`${loomMigrationRequests.queuedVideoCount} + 1`,
+ lastOperatorUserId: operator.id,
+ lastOperatorAt: new Date(),
+ updatedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(loomMigrationRequests.id, requestId),
+ isNotNull(loomMigrationRequests.activeOrganizationId),
+ ),
+ );
+ }
+ revalidatePath("/dashboard/migrations/loom");
+ revalidatePath("/dashboard/admin/loom-migrations");
+ return { status };
+ } finally {
+ await releaseConciergeImport(requestId);
}
- revalidatePath("/dashboard/migrations/loom");
- revalidatePath("/dashboard/admin/loom-migrations");
- return { status };
}
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 d256a9ade..f1cf3806b 100644
--- a/apps/web/app/(org)/dashboard/admin/loom-migrations/LoomMigrationQueue.tsx
+++ b/apps/web/app/(org)/dashboard/admin/loom-migrations/LoomMigrationQueue.tsx
@@ -195,6 +195,7 @@ function QueueItem({ request }: { request: OperatorLoomMigrationView }) {
</p>
<p>Jobs started: {request.queuedVideoCount}</p>
<p>Verified videos: {request.importedVideoCount}</p>
+ <p>Imports starting: {request.activeImportCount}</p>
</div>
{request.customerNote && (
<div className="mt-4 rounded-lg bg-gray-3 p-3 text-sm text-gray-11">
@@ -467,7 +468,8 @@ function QueueItem({ request }: { request: OperatorLoomMigrationView }) {
disabled={
statusMutation.isPending ||
importMutation.isPending ||
- fileMutation.isPending
+ fileMutation.isPending ||
+ (nextStatus === "completed" && request.activeImportCount > 0)
}
size="sm"
type="submit"
diff --git a/apps/web/lib/loom-concierge.ts b/apps/web/lib/loom-concierge.ts
index a8f50bf28..aed27433a 100644
--- a/apps/web/lib/loom-concierge.ts
+++ b/apps/web/lib/loom-concierge.ts
@@ -8,8 +8,18 @@ import {
users,
} from "@cap/database/schema";
import { buildEnv } from "@cap/env";
-import type { Organisation } from "@cap/web-domain";
-import { and, asc, desc, eq, isNull, ne } from "drizzle-orm";
+import type { Organisation, User } from "@cap/web-domain";
+import {
+ and,
+ asc,
+ desc,
+ eq,
+ gt,
+ isNotNull,
+ isNull,
+ ne,
+ sql,
+} from "drizzle-orm";
import { requireOrganizationSettingsManager } from "@/actions/organization/authorization";
import { MESSENGER_ADMIN_EMAIL } from "@/lib/messenger/constants";
import { isOrganizationOwnerPro } from "@/lib/org-pro";
@@ -29,6 +39,7 @@ export type LoomMigrationView = {
expectedVideoCount: number | null;
importedVideoCount: number;
queuedVideoCount: number;
+ activeImportCount: number;
completedAt: string | null;
createdAt: string;
updatedAt: string;
@@ -52,6 +63,7 @@ export function migrationToView(record: MigrationRecord): LoomMigrationView {
expectedVideoCount: record.expectedVideoCount,
importedVideoCount: record.importedVideoCount,
queuedVideoCount: record.queuedVideoCount,
+ activeImportCount: record.activeImportCount,
completedAt: record.completedAt?.toISOString() ?? null,
createdAt: record.createdAt.toISOString(),
updatedAt: record.updatedAt.toISOString(),
@@ -92,6 +104,57 @@ export async function requireMigrationOperator() {
return user;
}
+function affectedRows(result: unknown) {
+ if (Array.isArray(result)) {
+ return (
+ (result[0] as { affectedRows?: number } | undefined)?.affectedRows ?? 0
+ );
+ }
+ return (result as { affectedRows?: number } | undefined)?.affectedRows ?? 0;
+}
+
+export async function reserveConciergeImport(
+ requestId: string,
+ operatorId: User.UserId,
+) {
+ const result = await db()
+ .update(loomMigrationRequests)
+ .set({
+ activeImportCount: sql`${loomMigrationRequests.activeImportCount} + 1`,
+ status: "in_progress",
+ lastOperatorUserId: operatorId,
+ lastOperatorAt: new Date(),
+ updatedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(loomMigrationRequests.id, requestId),
+ isNotNull(loomMigrationRequests.activeOrganizationId),
+ ),
+ );
+ if (affectedRows(result) === 0) {
+ throw new Error("The migration request changed. Refresh and try again.");
+ }
+}
+
+export async function releaseConciergeImport(requestId: string) {
+ const result = await db()
+ .update(loomMigrationRequests)
+ .set({
+ activeImportCount: sql`${loomMigrationRequests.activeImportCount} - 1`,
+ updatedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(loomMigrationRequests.id, requestId),
+ gt(loomMigrationRequests.activeImportCount, 0),
+ ),
+ );
+ if (affectedRows(result) === 0) {
+ throw new Error("Could not release the migration import reservation.");
+ }
+}
+
export async function getCustomerMigrationRequests(
organizationId: Organisation.OrganisationId,
) {
diff --git a/packages/database/migrations/0046_loom_concierge.sql b/packages/database/migrations/0046_loom_concierge.sql
index 778f5ef9a..6e787e429 100644
--- a/packages/database/migrations/0046_loom_concierge.sql
+++ b/packages/database/migrations/0046_loom_concierge.sql
@@ -1,3 +1,10 @@
+CREATE TABLE `loom_migration_imports` (
+ `videoId` varchar(15) NOT NULL,
+ `requestId` varchar(15) NOT NULL,
+ `createdAt` datetime NOT NULL,
+ CONSTRAINT `loom_migration_imports_videoId` PRIMARY KEY(`videoId`)
+);
+--> statement-breakpoint
CREATE TABLE `loom_migration_requests` (
`id` varchar(15) NOT NULL,
`organizationId` varchar(15) NOT NULL,
@@ -12,6 +19,7 @@ CREATE TABLE `loom_migration_requests` (
`expectedVideoCount` int,
`importedVideoCount` int NOT NULL DEFAULT 0,
`queuedVideoCount` int NOT NULL DEFAULT 0,
+ `activeImportCount` int NOT NULL DEFAULT 0,
`lastOperatorUserId` varchar(15),
`lastOperatorAt` datetime,
`completedAt` datetime,
@@ -21,5 +29,6 @@ CREATE TABLE `loom_migration_requests` (
CONSTRAINT `loom_migration_active_org_idx` UNIQUE(`activeOrganizationId`)
);
--> statement-breakpoint
+CREATE INDEX `loom_migration_imports_request_idx` ON `loom_migration_imports` (`requestId`);--> statement-breakpoint
CREATE INDEX `loom_migration_org_created_idx` ON `loom_migration_requests` (`organizationId`,`createdAt`);--> statement-breakpoint
CREATE INDEX `loom_migration_status_created_idx` ON `loom_migration_requests` (`status`,`createdAt`);
\ No newline at end of file
diff --git a/packages/database/migrations/meta/0046_snapshot.json b/packages/database/migrations/meta/0046_snapshot.json
index 26dad24df..20273a730 100644
--- a/packages/database/migrations/meta/0046_snapshot.json
+++ b/packages/database/migrations/meta/0046_snapshot.json
@@ -1,7 +1,7 @@
{
"version": "5",
"dialect": "mysql",
- "id": "e73cfec4-89dd-4fc2-9068-4a86b6e10171",
+ "id": "d78f7c74-5007-4c78-96c3-50bf45012ad1",
"prevId": "0d80e4e5-6d93-4d28-b235-bf1231baa7a9",
"tables": {
"accounts": {
@@ -1694,6 +1694,48 @@
"uniqueConstraints": {},
"checkConstraint": {}
},
+ "loom_migration_imports": {
+ "name": "loom_migration_imports",
+ "columns": {
+ "videoId": {
+ "name": "videoId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "requestId": {
+ "name": "requestId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "loom_migration_imports_request_idx": {
+ "name": "loom_migration_imports_request_idx",
+ "columns": ["requestId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "loom_migration_imports_videoId": {
+ "name": "loom_migration_imports_videoId",
+ "columns": ["videoId"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
"loom_migration_requests": {
"name": "loom_migration_requests",
"columns": {
@@ -1791,6 +1833,14 @@
"autoincrement": false,
"default": 0
},
+ "activeImportCount": {
+ "name": "activeImportCount",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
"lastOperatorUserId": {
"name": "lastOperatorUserId",
"type": "varchar(15)",
diff --git a/packages/database/migrations/meta/_journal.json b/packages/database/migrations/meta/_journal.json
index d8e7a8780..49b1b749d 100644
--- a/packages/database/migrations/meta/_journal.json
+++ b/packages/database/migrations/meta/_journal.json
@@ -327,7 +327,7 @@
{
"idx": 46,
"version": "5",
- "when": 1789985586222,
+ "when": 1789988285195,
"tag": "0046_loom_concierge",
"breakpoints": true
}
diff --git a/packages/database/schema.ts b/packages/database/schema.ts
index d91b21bf2..7f6b03c5c 100644
--- a/packages/database/schema.ts
+++ b/packages/database/schema.ts
@@ -1575,6 +1575,7 @@ export const loomMigrationRequests = mysqlTable(
expectedVideoCount: int("expectedVideoCount"),
importedVideoCount: int("importedVideoCount").notNull().default(0),
queuedVideoCount: int("queuedVideoCount").notNull().default(0),
+ activeImportCount: int("activeImportCount").notNull().default(0),
lastOperatorUserId:
nanoIdNullable("lastOperatorUserId").$type<User.UserId>(),
lastOperatorAt: datetime("lastOperatorAt", { mode: "date" }),
@@ -1599,6 +1600,18 @@ export const loomMigrationRequests = mysqlTable(
],
);
+export const loomMigrationImports = mysqlTable(
+ "loom_migration_imports",
+ {
+ videoId: nanoId("videoId").notNull().primaryKey().$type<Video.VideoId>(),
+ requestId: nanoId("requestId").notNull(),
+ createdAt: datetime("createdAt", { mode: "date" })
+ .notNull()
+ .$defaultFn(() => new Date()),
+ },
+ (table) => [index("loom_migration_imports_request_idx").on(table.requestId)],
+);
+
export const developerApps = mysqlTable(
"developer_apps",
{