mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-25 01:19:45 +00:00
Merge pull request #16 from shumaiOne/feat/move-copy-assets
feat(asset): move/copy assets with storage deduplication and optimized cleanup
This commit is contained in:
@@ -163,6 +163,10 @@ The frontend is built with:
|
||||
|
||||
We use **Vitest** for testing (via `bun run test`). **Do not use `bun test`** as it uses Bun's native test runner which is not compatible with this project's test suite.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- **Mandatory Reproduction**: When fixing a backend bug, you MUST first write a test case that reproduces the bug (demonstrates the failure) before applying the fix. This ensures the bug is truly understood and prevents future regressions.
|
||||
|
||||
### Test Maintenance Rule
|
||||
|
||||
- **Do not delete tests** unless the feature or code being tested is permanently removed from the codebase.
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
Warnings:
|
||||
|
||||
- You are about to drop the column `key` on the `assets` table. All the data in the column will be lost.
|
||||
|
||||
*/
|
||||
-- AlterTable
|
||||
ALTER TABLE "assets" DROP COLUMN "key",
|
||||
ADD COLUMN "storage_key_id" TEXT;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "storage_keys" (
|
||||
"id" TEXT NOT NULL,
|
||||
"key" TEXT NOT NULL,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "storage_keys_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "storage_keys_key_key" ON "storage_keys"("key");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "assets" ADD CONSTRAINT "assets_storage_key_id_fkey" FOREIGN KEY ("storage_key_id") REFERENCES "storage_keys"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
Warnings:
|
||||
|
||||
- The values [purging] on the enum `AssetStatus` will be removed. If these variants are still used in the database, this will fail.
|
||||
|
||||
*/
|
||||
-- CreateEnum
|
||||
CREATE TYPE "StorageKeyStatus" AS ENUM ('active', 'purging');
|
||||
|
||||
-- AlterEnum
|
||||
BEGIN;
|
||||
CREATE TYPE "AssetStatus_new" AS ENUM ('uploading', 'uploaded', 'processing', 'processed', 'trashed', 'pending_purge');
|
||||
ALTER TABLE "assets" ALTER COLUMN "status" TYPE "AssetStatus_new" USING ("status"::text::"AssetStatus_new");
|
||||
ALTER TYPE "AssetStatus" RENAME TO "AssetStatus_old";
|
||||
ALTER TYPE "AssetStatus_new" RENAME TO "AssetStatus";
|
||||
DROP TYPE "public"."AssetStatus_old";
|
||||
COMMIT;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "storage_keys" ADD COLUMN "status" "StorageKeyStatus" NOT NULL DEFAULT 'active';
|
||||
+18
-1
@@ -42,6 +42,10 @@ enum AssetStatus {
|
||||
processed
|
||||
trashed
|
||||
pending_purge
|
||||
}
|
||||
|
||||
enum StorageKeyStatus {
|
||||
active
|
||||
purging
|
||||
}
|
||||
|
||||
@@ -347,7 +351,6 @@ model Asset {
|
||||
id String @id @default(ulid())
|
||||
name String @default("")
|
||||
nameNgram String[] @default([]) @map("name_ngram")
|
||||
key String?
|
||||
type AssetType
|
||||
mediaType String? @map("media_type")
|
||||
fileCount Int @default(0) @map("file_count")
|
||||
@@ -370,6 +373,9 @@ model Asset {
|
||||
target Asset? @relation("SymlinkTarget", fields: [targetId], references: [id])
|
||||
symlinks Asset[] @relation("SymlinkTarget")
|
||||
|
||||
storageKeyId String? @map("storage_key_id")
|
||||
storageKey StorageKey? @relation(fields: [storageKeyId], references: [id])
|
||||
|
||||
metadataValues AssetMetadataValue[] @relation("AssetToMetadataValues")
|
||||
|
||||
creatorId String? @map("creator_id")
|
||||
@@ -403,6 +409,17 @@ model Asset {
|
||||
@@unique([parentId, targetId], name: "parentIdTargetId")
|
||||
}
|
||||
|
||||
model StorageKey {
|
||||
id String @id @default(ulid())
|
||||
key String @unique
|
||||
status StorageKeyStatus @default(active)
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
assets Asset[]
|
||||
|
||||
@@map("storage_keys")
|
||||
}
|
||||
|
||||
model AssetMetadataValue {
|
||||
id String @id @default(ulid())
|
||||
assetId String @map("asset_id")
|
||||
|
||||
@@ -76,7 +76,7 @@ describe('readSkillTool', () => {
|
||||
data: {
|
||||
id: 'asset1',
|
||||
name: 'skill.zip',
|
||||
key: 'skills/skill.zip',
|
||||
storageKey: { create: { key: 'skills/skill.zip' } },
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
},
|
||||
|
||||
@@ -65,15 +65,16 @@ export const createReadSkillTool = (
|
||||
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: skill.assetId },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
|
||||
if (!asset || !asset.key) {
|
||||
if (!asset || !asset.storageKey?.key) {
|
||||
throw new Error('Skill asset not found or has no key')
|
||||
}
|
||||
|
||||
const { buffer: zipBuffer } = await s3Service.getObject(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
asset.key,
|
||||
asset.storageKey.key,
|
||||
)
|
||||
|
||||
const zip = new AdmZip(zipBuffer)
|
||||
|
||||
+28
-1
@@ -3,7 +3,7 @@ import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { projectService } from '@/services/project/project'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { reparentAssetsRequestSchema } from '@/dtos/asset'
|
||||
import { reparentAssetsRequestSchema, copyAssetsRequestSchema } from '@/dtos/asset'
|
||||
import {
|
||||
createProjectRequestSchema,
|
||||
updateProjectRequestSchema,
|
||||
@@ -208,5 +208,32 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
return c.body(null, 204)
|
||||
},
|
||||
)
|
||||
.post('/projects/:projectId/copy', zValidator('json', copyAssetsRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
// Check Edit permission on target folder/project
|
||||
await authzService.hasPermission({
|
||||
assetId: req.newParentId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
// Check Read permission on all source assets
|
||||
for (const assetId of req.assetIds) {
|
||||
await authzService.hasPermission({
|
||||
assetId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
}
|
||||
|
||||
await assetService.copyAssets({
|
||||
...req,
|
||||
creatorId: user.id,
|
||||
})
|
||||
|
||||
return c.body(null, 204)
|
||||
})
|
||||
|
||||
export default route
|
||||
|
||||
@@ -220,6 +220,14 @@ export const reparentAssetsRequestSchema = z.object({
|
||||
})
|
||||
export type ReparentAssetsRequest = z.infer<typeof reparentAssetsRequestSchema>
|
||||
|
||||
export const copyAssetsRequestSchema = z.object({
|
||||
newParentId: z.string(),
|
||||
assetIds: z.array(z.string()),
|
||||
withComments: z.boolean().default(false),
|
||||
creatorId: z.string().optional(),
|
||||
})
|
||||
export type CopyAssetsRequest = z.infer<typeof copyAssetsRequestSchema>
|
||||
|
||||
export const updateFileRequestSchema = z.object({
|
||||
name: z.string(),
|
||||
})
|
||||
|
||||
Generated
+5
@@ -82,6 +82,11 @@ export type ShareLink = Prisma.ShareLinkModel
|
||||
*
|
||||
*/
|
||||
export type Asset = Prisma.AssetModel
|
||||
/**
|
||||
* Model StorageKey
|
||||
*
|
||||
*/
|
||||
export type StorageKey = Prisma.StorageKeyModel
|
||||
/**
|
||||
* Model AssetMetadataValue
|
||||
*
|
||||
|
||||
Generated
+5
@@ -106,6 +106,11 @@ export type ShareLink = Prisma.ShareLinkModel
|
||||
*
|
||||
*/
|
||||
export type Asset = Prisma.AssetModel
|
||||
/**
|
||||
* Model StorageKey
|
||||
*
|
||||
*/
|
||||
export type StorageKey = Prisma.StorageKeyModel
|
||||
/**
|
||||
* Model AssetMetadataValue
|
||||
*
|
||||
|
||||
Generated
+34
@@ -328,6 +328,23 @@ export type EnumAssetStatusWithAggregatesFilter<$PrismaModel = never> = {
|
||||
_max?: Prisma.NestedEnumAssetStatusFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type EnumStorageKeyStatusFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.StorageKeyStatus | Prisma.EnumStorageKeyStatusFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.StorageKeyStatus[] | Prisma.ListEnumStorageKeyStatusFieldRefInput<$PrismaModel>
|
||||
notIn?: $Enums.StorageKeyStatus[] | Prisma.ListEnumStorageKeyStatusFieldRefInput<$PrismaModel>
|
||||
not?: Prisma.NestedEnumStorageKeyStatusFilter<$PrismaModel> | $Enums.StorageKeyStatus
|
||||
}
|
||||
|
||||
export type EnumStorageKeyStatusWithAggregatesFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.StorageKeyStatus | Prisma.EnumStorageKeyStatusFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.StorageKeyStatus[] | Prisma.ListEnumStorageKeyStatusFieldRefInput<$PrismaModel>
|
||||
notIn?: $Enums.StorageKeyStatus[] | Prisma.ListEnumStorageKeyStatusFieldRefInput<$PrismaModel>
|
||||
not?: Prisma.NestedEnumStorageKeyStatusWithAggregatesFilter<$PrismaModel> | $Enums.StorageKeyStatus
|
||||
_count?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
_min?: Prisma.NestedEnumStorageKeyStatusFilter<$PrismaModel>
|
||||
_max?: Prisma.NestedEnumStorageKeyStatusFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type FloatNullableFilter<$PrismaModel = never> = {
|
||||
equals?: number | Prisma.FloatFieldRefInput<$PrismaModel> | null
|
||||
in?: number[] | Prisma.ListFloatFieldRefInput<$PrismaModel> | null
|
||||
@@ -909,6 +926,23 @@ export type NestedEnumAssetStatusWithAggregatesFilter<$PrismaModel = never> = {
|
||||
_max?: Prisma.NestedEnumAssetStatusFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type NestedEnumStorageKeyStatusFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.StorageKeyStatus | Prisma.EnumStorageKeyStatusFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.StorageKeyStatus[] | Prisma.ListEnumStorageKeyStatusFieldRefInput<$PrismaModel>
|
||||
notIn?: $Enums.StorageKeyStatus[] | Prisma.ListEnumStorageKeyStatusFieldRefInput<$PrismaModel>
|
||||
not?: Prisma.NestedEnumStorageKeyStatusFilter<$PrismaModel> | $Enums.StorageKeyStatus
|
||||
}
|
||||
|
||||
export type NestedEnumStorageKeyStatusWithAggregatesFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.StorageKeyStatus | Prisma.EnumStorageKeyStatusFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.StorageKeyStatus[] | Prisma.ListEnumStorageKeyStatusFieldRefInput<$PrismaModel>
|
||||
notIn?: $Enums.StorageKeyStatus[] | Prisma.ListEnumStorageKeyStatusFieldRefInput<$PrismaModel>
|
||||
not?: Prisma.NestedEnumStorageKeyStatusWithAggregatesFilter<$PrismaModel> | $Enums.StorageKeyStatus
|
||||
_count?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
_min?: Prisma.NestedEnumStorageKeyStatusFilter<$PrismaModel>
|
||||
_max?: Prisma.NestedEnumStorageKeyStatusFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type NestedFloatNullableFilter<$PrismaModel = never> = {
|
||||
equals?: number | Prisma.FloatFieldRefInput<$PrismaModel> | null
|
||||
in?: number[] | Prisma.ListFloatFieldRefInput<$PrismaModel> | null
|
||||
|
||||
Generated
+9
-2
@@ -37,13 +37,20 @@ export const AssetStatus = {
|
||||
processing: 'processing',
|
||||
processed: 'processed',
|
||||
trashed: 'trashed',
|
||||
pending_purge: 'pending_purge',
|
||||
purging: 'purging'
|
||||
pending_purge: 'pending_purge'
|
||||
} as const
|
||||
|
||||
export type AssetStatus = (typeof AssetStatus)[keyof typeof AssetStatus]
|
||||
|
||||
|
||||
export const StorageKeyStatus = {
|
||||
active: 'active',
|
||||
purging: 'purging'
|
||||
} as const
|
||||
|
||||
export type StorageKeyStatus = (typeof StorageKeyStatus)[keyof typeof StorageKeyStatus]
|
||||
|
||||
|
||||
export const InviteRole = {
|
||||
editor: 'editor',
|
||||
reviewer: 'reviewer'
|
||||
|
||||
Generated
+14
-4
File diff suppressed because one or more lines are too long
+103
-2
@@ -397,6 +397,7 @@ export const ModelName = {
|
||||
ProjectMember: 'ProjectMember',
|
||||
ShareLink: 'ShareLink',
|
||||
Asset: 'Asset',
|
||||
StorageKey: 'StorageKey',
|
||||
AssetMetadataValue: 'AssetMetadataValue',
|
||||
AssetComment: 'AssetComment',
|
||||
AssetCommentAttachment: 'AssetCommentAttachment',
|
||||
@@ -429,7 +430,7 @@ export type TypeMap<ExtArgs extends runtime.Types.Extensions.InternalArgs = runt
|
||||
omit: GlobalOmitOptions
|
||||
}
|
||||
meta: {
|
||||
modelProps: "user" | "session" | "account" | "verification" | "authToken" | "team" | "sandbox" | "skill" | "teamMember" | "project" | "projectMember" | "shareLink" | "asset" | "assetMetadataValue" | "assetComment" | "assetCommentAttachment" | "assetEmbedding" | "invite" | "metadataField" | "notification" | "systemSettings" | "task" | "workflowTask" | "agent" | "agentSkill" | "agentSession" | "agentSessionEntry" | "userMetadata" | "model" | "provider"
|
||||
modelProps: "user" | "session" | "account" | "verification" | "authToken" | "team" | "sandbox" | "skill" | "teamMember" | "project" | "projectMember" | "shareLink" | "asset" | "storageKey" | "assetMetadataValue" | "assetComment" | "assetCommentAttachment" | "assetEmbedding" | "invite" | "metadataField" | "notification" | "systemSettings" | "task" | "workflowTask" | "agent" | "agentSkill" | "agentSession" | "agentSessionEntry" | "userMetadata" | "model" | "provider"
|
||||
txIsolationLevel: TransactionIsolationLevel
|
||||
}
|
||||
model: {
|
||||
@@ -1395,6 +1396,80 @@ export type TypeMap<ExtArgs extends runtime.Types.Extensions.InternalArgs = runt
|
||||
}
|
||||
}
|
||||
}
|
||||
StorageKey: {
|
||||
payload: Prisma.$StorageKeyPayload<ExtArgs>
|
||||
fields: Prisma.StorageKeyFieldRefs
|
||||
operations: {
|
||||
findUnique: {
|
||||
args: Prisma.StorageKeyFindUniqueArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$StorageKeyPayload> | null
|
||||
}
|
||||
findUniqueOrThrow: {
|
||||
args: Prisma.StorageKeyFindUniqueOrThrowArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$StorageKeyPayload>
|
||||
}
|
||||
findFirst: {
|
||||
args: Prisma.StorageKeyFindFirstArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$StorageKeyPayload> | null
|
||||
}
|
||||
findFirstOrThrow: {
|
||||
args: Prisma.StorageKeyFindFirstOrThrowArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$StorageKeyPayload>
|
||||
}
|
||||
findMany: {
|
||||
args: Prisma.StorageKeyFindManyArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$StorageKeyPayload>[]
|
||||
}
|
||||
create: {
|
||||
args: Prisma.StorageKeyCreateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$StorageKeyPayload>
|
||||
}
|
||||
createMany: {
|
||||
args: Prisma.StorageKeyCreateManyArgs<ExtArgs>
|
||||
result: BatchPayload
|
||||
}
|
||||
createManyAndReturn: {
|
||||
args: Prisma.StorageKeyCreateManyAndReturnArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$StorageKeyPayload>[]
|
||||
}
|
||||
delete: {
|
||||
args: Prisma.StorageKeyDeleteArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$StorageKeyPayload>
|
||||
}
|
||||
update: {
|
||||
args: Prisma.StorageKeyUpdateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$StorageKeyPayload>
|
||||
}
|
||||
deleteMany: {
|
||||
args: Prisma.StorageKeyDeleteManyArgs<ExtArgs>
|
||||
result: BatchPayload
|
||||
}
|
||||
updateMany: {
|
||||
args: Prisma.StorageKeyUpdateManyArgs<ExtArgs>
|
||||
result: BatchPayload
|
||||
}
|
||||
updateManyAndReturn: {
|
||||
args: Prisma.StorageKeyUpdateManyAndReturnArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$StorageKeyPayload>[]
|
||||
}
|
||||
upsert: {
|
||||
args: Prisma.StorageKeyUpsertArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$StorageKeyPayload>
|
||||
}
|
||||
aggregate: {
|
||||
args: Prisma.StorageKeyAggregateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.AggregateStorageKey>
|
||||
}
|
||||
groupBy: {
|
||||
args: Prisma.StorageKeyGroupByArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.StorageKeyGroupByOutputType>[]
|
||||
}
|
||||
count: {
|
||||
args: Prisma.StorageKeyCountArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.StorageKeyCountAggregateOutputType> | number
|
||||
}
|
||||
}
|
||||
}
|
||||
AssetMetadataValue: {
|
||||
payload: Prisma.$AssetMetadataValuePayload<ExtArgs>
|
||||
fields: Prisma.AssetMetadataValueFieldRefs
|
||||
@@ -2863,7 +2938,6 @@ export const AssetScalarFieldEnum = {
|
||||
id: 'id',
|
||||
name: 'name',
|
||||
nameNgram: 'nameNgram',
|
||||
key: 'key',
|
||||
type: 'type',
|
||||
mediaType: 'mediaType',
|
||||
fileCount: 'fileCount',
|
||||
@@ -2878,6 +2952,7 @@ export const AssetScalarFieldEnum = {
|
||||
updatedAt: 'updatedAt',
|
||||
parentId: 'parentId',
|
||||
targetId: 'targetId',
|
||||
storageKeyId: 'storageKeyId',
|
||||
creatorId: 'creatorId',
|
||||
taskId: 'taskId',
|
||||
projectId: 'projectId'
|
||||
@@ -2886,6 +2961,17 @@ export const AssetScalarFieldEnum = {
|
||||
export type AssetScalarFieldEnum = (typeof AssetScalarFieldEnum)[keyof typeof AssetScalarFieldEnum]
|
||||
|
||||
|
||||
export const StorageKeyScalarFieldEnum = {
|
||||
id: 'id',
|
||||
key: 'key',
|
||||
status: 'status',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt'
|
||||
} as const
|
||||
|
||||
export type StorageKeyScalarFieldEnum = (typeof StorageKeyScalarFieldEnum)[keyof typeof StorageKeyScalarFieldEnum]
|
||||
|
||||
|
||||
export const AssetMetadataValueScalarFieldEnum = {
|
||||
id: 'id',
|
||||
assetId: 'assetId',
|
||||
@@ -3321,6 +3407,20 @@ export type ListEnumAssetStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'StorageKeyStatus'
|
||||
*/
|
||||
export type EnumStorageKeyStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'StorageKeyStatus'>
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'StorageKeyStatus[]'
|
||||
*/
|
||||
export type ListEnumStorageKeyStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'StorageKeyStatus[]'>
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'Float'
|
||||
*/
|
||||
@@ -3554,6 +3654,7 @@ export type GlobalOmitConfig = {
|
||||
projectMember?: Prisma.ProjectMemberOmit
|
||||
shareLink?: Prisma.ShareLinkOmit
|
||||
asset?: Prisma.AssetOmit
|
||||
storageKey?: Prisma.StorageKeyOmit
|
||||
assetMetadataValue?: Prisma.AssetMetadataValueOmit
|
||||
assetComment?: Prisma.AssetCommentOmit
|
||||
assetCommentAttachment?: Prisma.AssetCommentAttachmentOmit
|
||||
|
||||
+13
-1
@@ -64,6 +64,7 @@ export const ModelName = {
|
||||
ProjectMember: 'ProjectMember',
|
||||
ShareLink: 'ShareLink',
|
||||
Asset: 'Asset',
|
||||
StorageKey: 'StorageKey',
|
||||
AssetMetadataValue: 'AssetMetadataValue',
|
||||
AssetComment: 'AssetComment',
|
||||
AssetCommentAttachment: 'AssetCommentAttachment',
|
||||
@@ -270,7 +271,6 @@ export const AssetScalarFieldEnum = {
|
||||
id: 'id',
|
||||
name: 'name',
|
||||
nameNgram: 'nameNgram',
|
||||
key: 'key',
|
||||
type: 'type',
|
||||
mediaType: 'mediaType',
|
||||
fileCount: 'fileCount',
|
||||
@@ -285,6 +285,7 @@ export const AssetScalarFieldEnum = {
|
||||
updatedAt: 'updatedAt',
|
||||
parentId: 'parentId',
|
||||
targetId: 'targetId',
|
||||
storageKeyId: 'storageKeyId',
|
||||
creatorId: 'creatorId',
|
||||
taskId: 'taskId',
|
||||
projectId: 'projectId'
|
||||
@@ -293,6 +294,17 @@ export const AssetScalarFieldEnum = {
|
||||
export type AssetScalarFieldEnum = (typeof AssetScalarFieldEnum)[keyof typeof AssetScalarFieldEnum]
|
||||
|
||||
|
||||
export const StorageKeyScalarFieldEnum = {
|
||||
id: 'id',
|
||||
key: 'key',
|
||||
status: 'status',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt'
|
||||
} as const
|
||||
|
||||
export type StorageKeyScalarFieldEnum = (typeof StorageKeyScalarFieldEnum)[keyof typeof StorageKeyScalarFieldEnum]
|
||||
|
||||
|
||||
export const AssetMetadataValueScalarFieldEnum = {
|
||||
id: 'id',
|
||||
assetId: 'assetId',
|
||||
|
||||
Generated
+1
@@ -21,6 +21,7 @@ export type * from './models/Project.ts'
|
||||
export type * from './models/ProjectMember.ts'
|
||||
export type * from './models/ShareLink.ts'
|
||||
export type * from './models/Asset.ts'
|
||||
export type * from './models/StorageKey.ts'
|
||||
export type * from './models/AssetMetadataValue.ts'
|
||||
export type * from './models/AssetComment.ts'
|
||||
export type * from './models/AssetCommentAttachment.ts'
|
||||
|
||||
Generated
+386
-107
File diff suppressed because it is too large
Load Diff
+1335
File diff suppressed because it is too large
Load Diff
@@ -118,6 +118,7 @@ export class AiService {
|
||||
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
|
||||
if (!asset) throw new Error('failed to get asset')
|
||||
@@ -146,11 +147,12 @@ export class AiService {
|
||||
throw new Error(`unsupported media type for embeddings: ${asset.mediaType}`)
|
||||
}
|
||||
|
||||
if (!asset.key) {
|
||||
const key = asset.storageKey?.key
|
||||
if (!key) {
|
||||
throw new Error(`asset has no key`)
|
||||
}
|
||||
|
||||
const { buffer: data } = await s3Service.getObject(process.env.S3_BUCKET || 'shumai', asset.key)
|
||||
const { buffer: data } = await s3Service.getObject(process.env.S3_BUCKET || 'shumai', key)
|
||||
|
||||
if (isImage) {
|
||||
const embVec = await p.generateImageEmbedding(config.model, data)
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { prisma } from '@/db'
|
||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||
|
||||
import { AssetType, AssetStatus } from '@/generated/prisma/client.ts'
|
||||
import { AssetType, AssetStatus, Prisma } from '@/generated/prisma/client.ts'
|
||||
import { AssetService } from './asset'
|
||||
|
||||
vi.mock('@/services/s3/s3', () => ({
|
||||
@@ -11,6 +11,7 @@ vi.mock('@/services/s3/s3', () => ({
|
||||
putObject: vi.fn().mockResolvedValue(undefined),
|
||||
deleteObject: vi.fn().mockResolvedValue(1),
|
||||
deletePrefix: vi.fn().mockResolvedValue(1),
|
||||
copyObject: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
}))
|
||||
|
||||
@@ -355,6 +356,185 @@ describe('AssetService', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('handles copying assets recursively', async () => {
|
||||
const { user, assets } = await setupBasicAssets()
|
||||
|
||||
await assetService.copyAssets({
|
||||
assetIds: [assets.folderA.id],
|
||||
newParentId: assets.root3.id,
|
||||
creatorId: user.id,
|
||||
withComments: false,
|
||||
})
|
||||
|
||||
// Verify root3 now has 1 more folder
|
||||
await verifyAsset(assets.root3.id, {
|
||||
type: AssetType.folder,
|
||||
fileCount: 1,
|
||||
size: 300,
|
||||
})
|
||||
|
||||
// Verify children of folderA were copied
|
||||
const copiedFolders = await prisma.asset.findMany({
|
||||
where: { parentId: assets.root3.id, name: 'folderA' },
|
||||
})
|
||||
expect(copiedFolders.length).toBe(1)
|
||||
const newFolderA = copiedFolders[0]
|
||||
|
||||
const children = await prisma.asset.findMany({
|
||||
where: { parentId: newFolderA.id },
|
||||
})
|
||||
expect(children.length).toBe(2)
|
||||
expect(children.map((c) => c.name)).toContain('fileA1')
|
||||
expect(children.map((c) => c.name)).toContain('fileA2')
|
||||
})
|
||||
|
||||
it('handles copying assets with comments and attachments', async () => {
|
||||
const { user, assets, project } = await setupBasicAssets()
|
||||
|
||||
// Create a comment with attachment on fileA1
|
||||
const attachmentAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'attach.png',
|
||||
type: AssetType.attachment,
|
||||
projectId: project.id,
|
||||
creatorId: user.id,
|
||||
status: 'uploaded',
|
||||
sizeByte: 50,
|
||||
},
|
||||
})
|
||||
|
||||
const comment = await prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: assets.fileA1.id,
|
||||
creatorId: user.id,
|
||||
message: 'Original Comment',
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.assetCommentAttachment.create({
|
||||
data: {
|
||||
commentId: comment.id,
|
||||
assetId: attachmentAsset.id,
|
||||
},
|
||||
})
|
||||
|
||||
await assetService.copyAssets({
|
||||
assetIds: [assets.fileA1.id],
|
||||
newParentId: assets.root3.id,
|
||||
creatorId: user.id,
|
||||
withComments: true,
|
||||
})
|
||||
|
||||
// Find the copied file
|
||||
const copiedFiles = await prisma.asset.findMany({
|
||||
where: { parentId: assets.root3.id, name: 'fileA1' },
|
||||
})
|
||||
expect(copiedFiles.length).toBe(1)
|
||||
const newFileA1 = copiedFiles[0]
|
||||
|
||||
// Verify comments were copied
|
||||
const newComments = await prisma.assetComment.findMany({
|
||||
where: { assetId: newFileA1.id },
|
||||
include: { attachments: { include: { asset: true } } },
|
||||
})
|
||||
expect(newComments.length).toBe(1)
|
||||
expect(newComments[0].message).toBe('Original Comment')
|
||||
expect(newComments[0].attachments.length).toBe(1)
|
||||
|
||||
// Verify attachment asset was deep copied
|
||||
const newAttachmentAsset = newComments[0].attachments[0].asset
|
||||
expect(newAttachmentAsset.id).not.toBe(attachmentAsset.id)
|
||||
expect(newAttachmentAsset.name).toBe('attach.png')
|
||||
expect(newAttachmentAsset.type).toBe(AssetType.attachment)
|
||||
})
|
||||
|
||||
it('rejects copying a folder into its own descendant', async () => {
|
||||
const { user, assets } = await setupBasicAssets()
|
||||
|
||||
// Create a subfolder inside folderA
|
||||
const subfolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'subfolder',
|
||||
type: AssetType.folder,
|
||||
projectId: assets.folderA.projectId,
|
||||
parentId: assets.folderA.id,
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
|
||||
await expect(
|
||||
assetService.copyAssets({
|
||||
assetIds: [assets.folderA.id],
|
||||
newParentId: subfolder.id,
|
||||
creatorId: user.id,
|
||||
withComments: false,
|
||||
}),
|
||||
).rejects.toThrow('Cannot copy a folder into its own descendant')
|
||||
})
|
||||
|
||||
it('uses destination project when copying comment attachments', async () => {
|
||||
const { user, assets, project } = await setupBasicAssets()
|
||||
|
||||
// Set up project 2
|
||||
const project2 = await prisma.project.create({
|
||||
data: { name: 'Project 2', teamId: project.teamId },
|
||||
})
|
||||
const root2 = await prisma.asset.create({
|
||||
data: { name: 'root2', type: AssetType.folder, projectId: project2.id, status: 'uploaded' },
|
||||
})
|
||||
|
||||
// Create a comment with attachment on fileA1
|
||||
const attachmentAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'attach.png',
|
||||
type: AssetType.attachment,
|
||||
projectId: project.id,
|
||||
creatorId: user.id,
|
||||
status: 'uploaded',
|
||||
sizeByte: 50,
|
||||
},
|
||||
})
|
||||
|
||||
const comment = await prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: assets.fileA1.id,
|
||||
creatorId: user.id,
|
||||
message: 'Original Comment',
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.assetCommentAttachment.create({
|
||||
data: {
|
||||
commentId: comment.id,
|
||||
assetId: attachmentAsset.id,
|
||||
},
|
||||
})
|
||||
|
||||
// Copy to project 2
|
||||
await assetService.copyAssets({
|
||||
assetIds: [assets.fileA1.id],
|
||||
newParentId: root2.id,
|
||||
creatorId: user.id,
|
||||
withComments: true,
|
||||
})
|
||||
|
||||
// Find the copied file in project 2
|
||||
const newFileA1 = await prisma.asset.findFirstOrThrow({
|
||||
where: { parentId: root2.id, name: 'fileA1' },
|
||||
})
|
||||
|
||||
// Verify comments were copied
|
||||
const newComments = await prisma.assetComment.findMany({
|
||||
where: { assetId: newFileA1.id },
|
||||
include: { attachments: { include: { asset: true } } },
|
||||
})
|
||||
expect(newComments.length).toBe(1)
|
||||
|
||||
// Verify attachment asset belongs to PROJECT 2
|
||||
const newAttachmentAsset = newComments[0].attachments[0].asset
|
||||
expect(newAttachmentAsset.projectId).toBe(project2.id)
|
||||
})
|
||||
|
||||
it('handles reparenting - Version Stack: move into stack', async () => {
|
||||
const { user, assets } = await setupBasicAssets()
|
||||
await assetService.reparentAssets({
|
||||
@@ -1200,24 +1380,34 @@ describe('AssetService', () => {
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.pending_purge,
|
||||
isDeleted: true,
|
||||
projectId: project.id,
|
||||
parentId: folderA.id,
|
||||
key: `key-${i}`,
|
||||
project: { connect: { id: project.id } },
|
||||
parent: { connect: { id: folderA.id } },
|
||||
storageKey: {
|
||||
create: { key: `key-${i}` },
|
||||
},
|
||||
}))
|
||||
|
||||
await prisma.asset.createMany({ data: childData })
|
||||
for (const data of childData) {
|
||||
const asset = await prisma.asset.create({
|
||||
data: data as unknown as Prisma.AssetCreateInput,
|
||||
include: { storageKey: true },
|
||||
})
|
||||
await prisma.storageKey.update({
|
||||
where: { id: asset.storageKeyId! },
|
||||
data: { createdAt: new Date(Date.now() - 25 * 60 * 60 * 1000) },
|
||||
})
|
||||
}
|
||||
|
||||
// 3. Trigger the purge job for the FIRST batch (100 items)
|
||||
// 3. Trigger the purge job
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await (assetService as any).purgePendingAssets()
|
||||
|
||||
// 4. Verify some items were processed in S3
|
||||
// We don't know the order, but if Folder A was in the first 100,
|
||||
// then its synchronous cascade will have wiped the remaining children.
|
||||
|
||||
// 5. Trigger the purge job for the SECOND batch
|
||||
// 6. Trigger GC job to physically delete files
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await (assetService as any).purgePendingAssets()
|
||||
await (assetService as any).purgeUnreferencedStorageKeys()
|
||||
// Call it again to process the remaining items (batch size is 100)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await (assetService as any).purgeUnreferencedStorageKeys()
|
||||
|
||||
// 6. Verify S3 deletion was called for EVERY child
|
||||
for (let i = 0; i < childCount; i++) {
|
||||
@@ -1241,24 +1431,29 @@ describe('AssetService', () => {
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.pending_purge,
|
||||
isDeleted: true,
|
||||
projectId: project.id,
|
||||
key: 'file/01KSBRJVY3DPK111S2MECFKDQ4/raw',
|
||||
project: { connect: { id: project.id } },
|
||||
storageKey: {
|
||||
create: {
|
||||
key: 'file/01KSBRJVY3DPK111S2MECFKDQ4/raw',
|
||||
createdAt: new Date(Date.now() - 25 * 60 * 60 * 1000),
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// Trigger the purge job
|
||||
// 1. Purge the asset record
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await (assetService as any).purgePendingAssets()
|
||||
|
||||
// 2. Trigger GC job
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await (assetService as any).purgeUnreferencedStorageKeys()
|
||||
|
||||
// Verify deletePrefix was called with the correct prefix instead of just deleteObject
|
||||
expect(s3Service.deletePrefix).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
'file/01KSBRJVY3DPK111S2MECFKDQ4/',
|
||||
)
|
||||
expect(s3Service.deleteObject).not.toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
'file/01KSBRJVY3DPK111S2MECFKDQ4/raw',
|
||||
)
|
||||
|
||||
// Verify record is gone
|
||||
expect(await prisma.asset.findUnique({ where: { id: complexFile.id } })).toBeNull()
|
||||
|
||||
+335
-94
@@ -1,11 +1,11 @@
|
||||
import { prisma } from '@/db'
|
||||
import { logger } from '@/logger'
|
||||
import {
|
||||
AncestorFolder,
|
||||
AssetInfo,
|
||||
AttachmentInfo,
|
||||
ChildPreview,
|
||||
CommentInfo,
|
||||
CopyAssetsRequest,
|
||||
CreateAssetRequest,
|
||||
CreateCommentRequest,
|
||||
FieldValueInfo,
|
||||
@@ -17,7 +17,8 @@ import {
|
||||
UpdateAssetOrderRequest,
|
||||
UserInfo,
|
||||
} from '@/dtos/asset'
|
||||
import { Asset, AssetType, Prisma } from '@/generated/prisma/client.ts'
|
||||
import { Asset, AssetStatus, AssetType, Prisma, StorageKey } from '@/generated/prisma/client.ts'
|
||||
import { logger } from '@/logger'
|
||||
import { PaginatedData, paginateQuery, PaginationParams } from '@/services/pagination'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import { generateKeyBetween } from 'jittered-fractional-indexing'
|
||||
@@ -26,17 +27,19 @@ type AssetWithIncludes = Prisma.AssetGetPayload<{
|
||||
include: {
|
||||
creator: true
|
||||
metadataValues: true
|
||||
storageKey: true
|
||||
target: {
|
||||
include: {
|
||||
creator: true
|
||||
metadataValues: true
|
||||
storageKey: true
|
||||
children: {
|
||||
include: { creator: true; metadataValues: true }
|
||||
include: { creator: true; metadataValues: true; storageKey: true }
|
||||
}
|
||||
}
|
||||
}
|
||||
children: {
|
||||
include: { creator: true; metadataValues: true }
|
||||
include: { creator: true; metadataValues: true; storageKey: true }
|
||||
}
|
||||
}
|
||||
}>
|
||||
@@ -44,11 +47,11 @@ type AssetWithIncludes = Prisma.AssetGetPayload<{
|
||||
type CommentWithIncludes = Prisma.AssetCommentGetPayload<{
|
||||
include: {
|
||||
creator: true
|
||||
attachments: { include: { asset: true } }
|
||||
attachments: { include: { asset: { include: { storageKey: true } } } }
|
||||
replies: {
|
||||
include: {
|
||||
creator: true
|
||||
attachments: { include: { asset: true } }
|
||||
attachments: { include: { asset: { include: { storageKey: true } } } }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -88,19 +91,21 @@ export class AssetService {
|
||||
include: {
|
||||
creator: true,
|
||||
metadataValues: true,
|
||||
storageKey: true,
|
||||
target: {
|
||||
include: {
|
||||
creator: true,
|
||||
metadataValues: true,
|
||||
storageKey: true,
|
||||
children: {
|
||||
include: { creator: true, metadataValues: true },
|
||||
include: { creator: true, metadataValues: true, storageKey: true },
|
||||
take: 3,
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
},
|
||||
},
|
||||
},
|
||||
children: {
|
||||
include: { creator: true, metadataValues: true },
|
||||
include: { creator: true, metadataValues: true, storageKey: true },
|
||||
take: 3,
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
},
|
||||
@@ -266,6 +271,212 @@ export class AssetService {
|
||||
})
|
||||
}
|
||||
|
||||
async copyAssets(req: CopyAssetsRequest): Promise<void> {
|
||||
await this.prismaClient.$transaction(async (tx) => {
|
||||
const newParent = await tx.asset.findUnique({
|
||||
where: { id: req.newParentId },
|
||||
include: { project: { include: { team: true } } },
|
||||
})
|
||||
if (!newParent) throw new Error('New parent not found')
|
||||
if (!newParent.project) throw new Error('New parent folder is not associated with a project')
|
||||
|
||||
const assetsToCopy = await tx.asset.findMany({
|
||||
where: { id: { in: req.assetIds } },
|
||||
include: { project: { include: { team: true } } },
|
||||
})
|
||||
|
||||
if (assetsToCopy.length !== req.assetIds.length) {
|
||||
throw new Error('Not all assets to be copied were found')
|
||||
}
|
||||
|
||||
// Check if newParentId is a descendant of any asset being copied
|
||||
const ancestors = await tx.$queryRaw<{ id: string }[]>`
|
||||
WITH RECURSIVE ancestor AS (
|
||||
SELECT id, parent_id FROM assets WHERE id = ${newParent.id}
|
||||
UNION ALL
|
||||
SELECT a.id, a.parent_id FROM assets a
|
||||
INNER JOIN ancestor d ON a.id = d.parent_id
|
||||
)
|
||||
SELECT id FROM ancestor WHERE id IN (${Prisma.join(req.assetIds)}) LIMIT 1;
|
||||
`
|
||||
if (ancestors.length > 0) {
|
||||
throw new Error('Cannot copy a folder into its own descendant')
|
||||
}
|
||||
|
||||
for (const a of assetsToCopy) {
|
||||
if (!a.project || !a.project.team) {
|
||||
throw new Error(`Asset ${a.id} is not associated with a team`)
|
||||
}
|
||||
if (!newParent.project.team) {
|
||||
throw new Error('New parent folder is not associated with a team')
|
||||
}
|
||||
if (a.project.team.id !== newParent.project.team.id) {
|
||||
throw new Error(`Cannot copy asset ${a.id} to a different team`)
|
||||
}
|
||||
}
|
||||
|
||||
const firstFile = await tx.asset.findFirst({
|
||||
where: { parentId: newParent.id },
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
})
|
||||
let firstSortIndex = firstFile?.sortIndex || null
|
||||
|
||||
let totalSize = 0
|
||||
for (let i = req.assetIds.length - 1; i >= 0; i--) {
|
||||
const assetId = req.assetIds[i]
|
||||
const asset = assetsToCopy.find((a) => a.id === assetId)!
|
||||
const newSortIndex = generateSortIndex(firstSortIndex)
|
||||
const copiedAsset = await this.copyAssetRecursive(
|
||||
tx,
|
||||
asset,
|
||||
newParent.id,
|
||||
newParent.projectId!,
|
||||
newSortIndex,
|
||||
req.creatorId,
|
||||
req.withComments,
|
||||
)
|
||||
totalSize += copiedAsset.sizeByte
|
||||
firstSortIndex = newSortIndex
|
||||
}
|
||||
|
||||
await tx.asset.update({
|
||||
where: { id: newParent.id },
|
||||
data: {
|
||||
fileCount: { increment: assetsToCopy.length },
|
||||
},
|
||||
})
|
||||
await this.updateAncestorsSize(tx, newParent.id, totalSize)
|
||||
})
|
||||
}
|
||||
|
||||
private async copyAssetRecursive(
|
||||
tx: Prisma.TransactionClient,
|
||||
asset: Asset & { storageKey?: StorageKey | null },
|
||||
newParentId: string | null,
|
||||
projectId: string | null,
|
||||
sortIndex: string | null,
|
||||
creatorId?: string,
|
||||
withComments: boolean = false,
|
||||
): Promise<Asset> {
|
||||
const newAsset = await tx.asset.create({
|
||||
data: {
|
||||
name: asset.name,
|
||||
nameNgram: asset.nameNgram,
|
||||
type: asset.type,
|
||||
mediaType: asset.mediaType,
|
||||
fileCount: asset.fileCount,
|
||||
sizeByte: asset.sizeByte,
|
||||
status: asset.status,
|
||||
transcodeTaskId: asset.transcodeTaskId,
|
||||
media: asset.media || undefined,
|
||||
isDeleted: asset.isDeleted,
|
||||
deletedAt: asset.deletedAt,
|
||||
sortIndex: sortIndex,
|
||||
parentId: newParentId,
|
||||
projectId: projectId,
|
||||
creatorId: creatorId || asset.creatorId,
|
||||
taskId: asset.taskId,
|
||||
targetId: asset.targetId,
|
||||
storageKeyId: asset.storageKeyId,
|
||||
},
|
||||
})
|
||||
|
||||
if (withComments) {
|
||||
await this.copyComments(tx, asset.id, newAsset.id, projectId, creatorId)
|
||||
}
|
||||
|
||||
if (asset.type === AssetType.folder) {
|
||||
const children = await tx.asset.findMany({
|
||||
where: { parentId: asset.id },
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
})
|
||||
for (const child of children) {
|
||||
await this.copyAssetRecursive(
|
||||
tx,
|
||||
child,
|
||||
newAsset.id,
|
||||
projectId,
|
||||
child.sortIndex,
|
||||
creatorId,
|
||||
withComments,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return newAsset
|
||||
}
|
||||
|
||||
private async copyComments(
|
||||
tx: Prisma.TransactionClient,
|
||||
oldAssetId: string,
|
||||
newAssetId: string,
|
||||
projectId: string | null,
|
||||
creatorId?: string,
|
||||
) {
|
||||
const comments = await tx.assetComment.findMany({
|
||||
where: { assetId: oldAssetId, replyToId: null },
|
||||
include: {
|
||||
attachments: { include: { asset: true } },
|
||||
replies: {
|
||||
include: {
|
||||
attachments: { include: { asset: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
for (const comment of comments) {
|
||||
await this.copyCommentRecursive(tx, comment, newAssetId, null, projectId, creatorId)
|
||||
}
|
||||
}
|
||||
|
||||
private async copyCommentRecursive(
|
||||
tx: Prisma.TransactionClient,
|
||||
comment: any, // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
newAssetId: string,
|
||||
newReplyToId: string | null,
|
||||
projectId: string | null,
|
||||
creatorId?: string,
|
||||
) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { id, createdAt, updatedAt, assetId, replyToId, attachments, replies, ...data } = comment
|
||||
const newComment = await tx.assetComment.create({
|
||||
data: {
|
||||
...data,
|
||||
assetId: newAssetId,
|
||||
replyToId: newReplyToId,
|
||||
creatorId: creatorId || comment.creatorId,
|
||||
},
|
||||
})
|
||||
|
||||
if (attachments) {
|
||||
for (const attachment of attachments) {
|
||||
// Deep copy attachment asset
|
||||
const copiedAttachmentAsset = await this.copyAssetRecursive(
|
||||
tx,
|
||||
attachment.asset,
|
||||
null, // attachment usually has no parent
|
||||
projectId,
|
||||
attachment.asset.sortIndex,
|
||||
creatorId,
|
||||
false,
|
||||
)
|
||||
await tx.assetCommentAttachment.create({
|
||||
data: {
|
||||
commentId: newComment.id,
|
||||
assetId: copiedAttachmentAsset.id,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (replies) {
|
||||
for (const reply of replies) {
|
||||
await this.copyCommentRecursive(tx, reply, newAssetId, newComment.id, projectId, creatorId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async reparentFileToFile(
|
||||
tx: Prisma.TransactionClient,
|
||||
destFile: AssetWithProjectTeam,
|
||||
@@ -432,19 +643,21 @@ export class AssetService {
|
||||
include: {
|
||||
creator: true,
|
||||
metadataValues: true,
|
||||
storageKey: true,
|
||||
target: {
|
||||
include: {
|
||||
creator: true,
|
||||
metadataValues: true,
|
||||
storageKey: true,
|
||||
children: {
|
||||
include: { creator: true, metadataValues: true },
|
||||
include: { creator: true, metadataValues: true, storageKey: true },
|
||||
take: 3,
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
},
|
||||
},
|
||||
},
|
||||
children: {
|
||||
include: { creator: true, metadataValues: true },
|
||||
include: { creator: true, metadataValues: true, storageKey: true },
|
||||
take: 3,
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
},
|
||||
@@ -496,7 +709,14 @@ export class AssetService {
|
||||
|
||||
if (parent) data.parent = { connect: { id: parent.id } }
|
||||
if (sortIndex) data.sortIndex = sortIndex
|
||||
if (req.key) data.key = req.key
|
||||
if (req.key) {
|
||||
data.storageKey = {
|
||||
connectOrCreate: {
|
||||
where: { key: req.key },
|
||||
create: { key: req.key },
|
||||
},
|
||||
}
|
||||
}
|
||||
if (req.sizeByte) data.sizeByte = req.sizeByte
|
||||
if (req.contentType) data.mediaType = req.contentType
|
||||
if (req.creatorId) data.creator = { connect: { id: req.creatorId } }
|
||||
@@ -506,19 +726,21 @@ export class AssetService {
|
||||
include: {
|
||||
creator: true,
|
||||
metadataValues: true,
|
||||
storageKey: true,
|
||||
target: {
|
||||
include: {
|
||||
creator: true,
|
||||
metadataValues: true,
|
||||
storageKey: true,
|
||||
children: {
|
||||
include: { creator: true, metadataValues: true },
|
||||
include: { creator: true, metadataValues: true, storageKey: true },
|
||||
take: 3,
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
},
|
||||
},
|
||||
},
|
||||
children: {
|
||||
include: { creator: true, metadataValues: true },
|
||||
include: { creator: true, metadataValues: true, storageKey: true },
|
||||
take: 3,
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
},
|
||||
@@ -543,19 +765,21 @@ export class AssetService {
|
||||
include: {
|
||||
creator: true,
|
||||
metadataValues: true,
|
||||
storageKey: true,
|
||||
target: {
|
||||
include: {
|
||||
creator: true,
|
||||
metadataValues: true,
|
||||
storageKey: true,
|
||||
children: {
|
||||
include: { creator: true, metadataValues: true },
|
||||
include: { creator: true, metadataValues: true, storageKey: true },
|
||||
take: 3,
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
},
|
||||
},
|
||||
},
|
||||
children: {
|
||||
include: { creator: true, metadataValues: true },
|
||||
include: { creator: true, metadataValues: true, storageKey: true },
|
||||
take: 3,
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
},
|
||||
@@ -665,21 +889,23 @@ export class AssetService {
|
||||
include: {
|
||||
creator: true,
|
||||
metadataValues: true,
|
||||
storageKey: true,
|
||||
children: {
|
||||
include: { creator: true, metadataValues: true },
|
||||
include: { creator: true, metadataValues: true, storageKey: true },
|
||||
take: 3,
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
},
|
||||
},
|
||||
},
|
||||
children: {
|
||||
include: { creator: true, metadataValues: true },
|
||||
include: { creator: true, metadataValues: true, storageKey: true },
|
||||
take: 3,
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
},
|
||||
storageKey: true,
|
||||
},
|
||||
})
|
||||
const infos = await this.toAssetInfos([asset])
|
||||
const infos = await this.toAssetInfos([asset as unknown as AssetWithIncludes])
|
||||
return infos[0]
|
||||
}
|
||||
|
||||
@@ -767,33 +993,26 @@ export class AssetService {
|
||||
|
||||
private cleanupJobsRunning = false
|
||||
|
||||
startCleanupJob() {
|
||||
async startCleanupJob() {
|
||||
this.cleanupJobsRunning = true
|
||||
|
||||
// Stage 1: Expiration Job - Move expired trashed roots to pending_purge
|
||||
const runExpiration = async () => {
|
||||
const runCleanup = async () => {
|
||||
if (!this.cleanupJobsRunning) return
|
||||
|
||||
try {
|
||||
await this.expireTrashedAssets()
|
||||
} catch (e: unknown) {
|
||||
console.error('Error in asset expiration job:', e)
|
||||
}
|
||||
setTimeout(runExpiration, 5000) // Run every 5 seconds, less frequent
|
||||
}
|
||||
|
||||
// Stage 2: Physical Purge Job - Delete files from S3 and wipe from DB
|
||||
const runPurge = async () => {
|
||||
if (!this.cleanupJobsRunning) return
|
||||
try {
|
||||
await this.purgePendingAssets()
|
||||
await this.purgeUnreferencedStorageKeys()
|
||||
} catch (e: unknown) {
|
||||
console.error('Error in asset purge job:', e)
|
||||
console.error('Error in asset cleanup job:', e)
|
||||
}
|
||||
|
||||
if (this.cleanupJobsRunning) {
|
||||
setTimeout(runCleanup, 5000) // Run every 5 seconds after previous run completion
|
||||
}
|
||||
setTimeout(runPurge, 1000) // Run every 1 second
|
||||
}
|
||||
|
||||
runExpiration()
|
||||
runPurge()
|
||||
runCleanup()
|
||||
}
|
||||
|
||||
stopCleanupJob() {
|
||||
@@ -837,73 +1056,81 @@ export class AssetService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Stage 2: Physically delete files and DB records for assets marked as 'pending_purge'.
|
||||
* Stage 2: Delete DB records for assets marked as 'pending_purge'.
|
||||
*/
|
||||
private async purgePendingAssets() {
|
||||
// 1. Lock 100 assets using raw SQL FOR UPDATE SKIP LOCKED and mark them as 'purging'
|
||||
// We include a timeout check (1 hour) to allow picking up stalled tasks.
|
||||
const lockedAssets = await this.prismaClient.$queryRaw<{ id: string; key: string | null }[]>`
|
||||
const { count } = await this.prismaClient.asset.deleteMany({
|
||||
where: { status: AssetStatus.pending_purge },
|
||||
})
|
||||
|
||||
if (count > 0) {
|
||||
logger.info(
|
||||
{
|
||||
purgedCount: count,
|
||||
},
|
||||
`${count} assets purged from database`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stage 3: Garbage Collection - Physically delete files and StorageKey records
|
||||
* that have no associated logical assets.
|
||||
*/
|
||||
private async purgeUnreferencedStorageKeys() {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
|
||||
// 1. Find storage keys with no associated assets and older than 24 hours
|
||||
// using FOR UPDATE SKIP LOCKED to ensure multiple servers don't pick up the same keys.
|
||||
const lockedKeys = await this.prismaClient.$queryRaw<{ id: string; key: string }[]>`
|
||||
WITH to_purge AS (
|
||||
SELECT id FROM assets
|
||||
WHERE status = 'pending_purge'
|
||||
OR (status = 'purging' AND updated_at < NOW() - INTERVAL '1 hour')
|
||||
SELECT id FROM storage_keys sk
|
||||
WHERE NOT EXISTS (SELECT 1 FROM assets a WHERE a.storage_key_id = sk.id)
|
||||
AND sk.created_at < NOW() - INTERVAL '24 hours'
|
||||
AND (sk.status = 'active' OR (sk.status = 'purging' AND sk.updated_at < NOW() - INTERVAL '1 hour'))
|
||||
LIMIT 100
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
UPDATE assets SET status = 'purging', updated_at = NOW()
|
||||
UPDATE storage_keys SET status = 'purging', updated_at = NOW()
|
||||
WHERE id IN (SELECT id FROM to_purge)
|
||||
RETURNING id, key;
|
||||
`
|
||||
|
||||
if (lockedAssets.length === 0) return
|
||||
if (lockedKeys.length === 0) return
|
||||
|
||||
let physicalFilesDeleted = 0
|
||||
let physicalFoldersDeleted = 0
|
||||
let purgedCount = 0
|
||||
|
||||
// 2. Physical file deletion from storage
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const results = await Promise.all(
|
||||
lockedAssets.map(async (a) => {
|
||||
if (a.key) {
|
||||
try {
|
||||
// Check if this asset has a dedicated directory (e.g., file/ULID/raw)
|
||||
// If it has more than one slash, we delete the entire containing directory
|
||||
// to ensure transcodes/thumbnails are also removed.
|
||||
const parts = a.key.split('/')
|
||||
if (parts.length > 2) {
|
||||
const prefix = parts.slice(0, parts.length - 1).join('/') + '/'
|
||||
const count = await s3Service.deletePrefix(bucket, prefix)
|
||||
physicalFilesDeleted += count
|
||||
physicalFoldersDeleted += 1
|
||||
} else {
|
||||
const count = await s3Service.deleteObject(bucket, a.key)
|
||||
physicalFilesDeleted += count
|
||||
}
|
||||
return a.id
|
||||
} catch (e: unknown) {
|
||||
console.error(`Failed to delete storage object(s) for ${a.key}:`, e)
|
||||
return null
|
||||
}
|
||||
for (const sk of lockedKeys) {
|
||||
try {
|
||||
// Physically delete from S3
|
||||
const parts = sk.key.split('/')
|
||||
if (parts.length > 2) {
|
||||
const prefix = parts.slice(0, parts.length - 1).join('/') + '/'
|
||||
const count = await s3Service.deletePrefix(bucket, prefix)
|
||||
physicalFilesDeleted += count
|
||||
} else {
|
||||
const count = await s3Service.deleteObject(bucket, sk.key)
|
||||
physicalFilesDeleted += count
|
||||
}
|
||||
// Assets without keys (folders, etc.) are considered processed
|
||||
return a.id
|
||||
}),
|
||||
)
|
||||
|
||||
// 3. Hard delete from database ONLY for assets successfully removed from storage
|
||||
const successfulIds = results.filter((id): id is string => id !== null)
|
||||
if (successfulIds.length > 0) {
|
||||
await this.prismaClient.asset.deleteMany({
|
||||
where: { id: { in: successfulIds } },
|
||||
})
|
||||
// Delete from database
|
||||
await this.prismaClient.storageKey.delete({
|
||||
where: { id: sk.id },
|
||||
})
|
||||
purgedCount++
|
||||
} catch (e: unknown) {
|
||||
logger.error(
|
||||
{ key: sk.key, error: e instanceof Error ? e.message : String(e) },
|
||||
'Failed to purge unreferenced storage key',
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (purgedCount > 0) {
|
||||
logger.info(
|
||||
{
|
||||
purgedCount: successfulIds.length,
|
||||
physicalFilesDeleted,
|
||||
physicalFoldersDeleted,
|
||||
},
|
||||
`${successfulIds.length} assets purged, deleted ${physicalFilesDeleted} files in ${physicalFoldersDeleted} folders`,
|
||||
{ purgedCount, physicalFilesDeleted },
|
||||
`Garbage collection: purged ${purgedCount} storage keys and ${physicalFilesDeleted} physical files`,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1077,12 +1304,12 @@ export class AssetService {
|
||||
where: { id: commentId },
|
||||
include: {
|
||||
creator: true,
|
||||
asset: true,
|
||||
attachments: { include: { asset: true } },
|
||||
asset: { include: { storageKey: true } },
|
||||
attachments: { include: { asset: { include: { storageKey: true } } } },
|
||||
replies: {
|
||||
include: {
|
||||
creator: true,
|
||||
attachments: { include: { asset: true } },
|
||||
attachments: { include: { asset: { include: { storageKey: true } } } },
|
||||
},
|
||||
orderBy: { id: 'asc' },
|
||||
},
|
||||
@@ -1104,12 +1331,12 @@ export class AssetService {
|
||||
where: { assetId: resolvedAssetId, replyToId: null },
|
||||
include: {
|
||||
creator: true,
|
||||
asset: true,
|
||||
attachments: { include: { asset: true } },
|
||||
asset: { include: { storageKey: true } },
|
||||
attachments: { include: { asset: { include: { storageKey: true } } } },
|
||||
replies: {
|
||||
include: {
|
||||
creator: true,
|
||||
attachments: { include: { asset: true } },
|
||||
attachments: { include: { asset: { include: { storageKey: true } } } },
|
||||
},
|
||||
orderBy: { id: 'asc' },
|
||||
},
|
||||
@@ -1160,7 +1387,7 @@ export class AssetService {
|
||||
if (stackIds.size > 0) {
|
||||
const allVersions = await this.prismaClient.asset.findMany({
|
||||
where: { parentId: { in: Array.from(stackIds) }, isDeleted: false },
|
||||
include: { creator: true, metadataValues: true },
|
||||
include: { creator: true, metadataValues: true, storageKey: true },
|
||||
})
|
||||
for (const v of allVersions) {
|
||||
const list = versionsMap.get(v.parentId!) || []
|
||||
@@ -1279,6 +1506,16 @@ export class AssetService {
|
||||
)
|
||||
}
|
||||
|
||||
const key = latestVersion.storageKey?.key
|
||||
if (media && key) {
|
||||
media.original = {
|
||||
key,
|
||||
downloadUrl: await s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'GET'),
|
||||
filesizeInBytes: latestVersion.sizeByte,
|
||||
codec: '', // TODO: extract from metadata if needed
|
||||
}
|
||||
}
|
||||
|
||||
result.push({
|
||||
id: a.id,
|
||||
name:
|
||||
@@ -1388,8 +1625,12 @@ export class AssetService {
|
||||
const attachments: AttachmentInfo[] = []
|
||||
if (c.attachments) {
|
||||
for (const a of c.attachments) {
|
||||
if (a.asset?.key) {
|
||||
const url = await s3Service.presign(process.env.S3_BUCKET || 'shumai', a.asset.key, 'GET')
|
||||
if (a.asset?.storageKey?.key) {
|
||||
const url = await s3Service.presign(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
a.asset.storageKey.key,
|
||||
'GET',
|
||||
)
|
||||
attachments.push({
|
||||
id: a.id,
|
||||
assetId: a.asset.id,
|
||||
|
||||
@@ -241,8 +241,13 @@ describe('ProjectService', () => {
|
||||
name: 'Test Asset',
|
||||
type: 'file',
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
key: 'asset-key',
|
||||
project: { connect: { id: project.id } },
|
||||
storageKey: {
|
||||
connectOrCreate: {
|
||||
where: { key: 'asset-key' },
|
||||
create: { key: 'asset-key' },
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
@@ -310,9 +315,14 @@ describe('ProjectService', () => {
|
||||
name: 'File C',
|
||||
type: 'file',
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
parentId: folderB.id,
|
||||
key: 'file-c-key',
|
||||
project: { connect: { id: project.id } },
|
||||
parent: { connect: { id: folderB.id } },
|
||||
storageKey: {
|
||||
connectOrCreate: {
|
||||
where: { key: 'file-c-key' },
|
||||
create: { key: 'file-c-key' },
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
@@ -337,9 +347,19 @@ describe('ProjectService', () => {
|
||||
// Manually trigger the private cleanup methods for testing
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await (assetService as any).expireTrashedAssets()
|
||||
// Trigger the purge job
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await (assetService as any).purgePendingAssets()
|
||||
|
||||
// Manually set storage key createdAt to the past so GC picks it up
|
||||
await prisma.storageKey.updateMany({
|
||||
data: { createdAt: new Date(Date.now() - 25 * 60 * 60 * 1000) },
|
||||
})
|
||||
|
||||
// Trigger GC job
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await (assetService as any).purgeUnreferencedStorageKeys()
|
||||
|
||||
// Verify everything is wiped from DB
|
||||
expect(await prisma.project.findUnique({ where: { id: project.id } })).toBeNull()
|
||||
expect(await prisma.asset.findUnique({ where: { id: folderA.id } })).toBeNull()
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ObjectInfo } from '@/dtos/s3'
|
||||
import {
|
||||
CopyObjectCommand,
|
||||
DeleteObjectCommand,
|
||||
GetObjectCommand,
|
||||
HeadObjectCommand,
|
||||
@@ -49,6 +50,12 @@ export interface S3Service {
|
||||
contentType?: string,
|
||||
): Promise<void>
|
||||
getObject(bucket: string, key: string): Promise<S3Object>
|
||||
copyObject(
|
||||
sourceBucket: string,
|
||||
sourceKey: string,
|
||||
destBucket: string,
|
||||
destKey: string,
|
||||
): Promise<void>
|
||||
downloadToFile(bucket: string, key: string, filePath: string): Promise<void>
|
||||
deleteObject(bucket: string, key: string): Promise<number>
|
||||
deletePrefix(bucket: string, prefix: string): Promise<number>
|
||||
@@ -131,6 +138,21 @@ export class S3StorageService implements S3Service {
|
||||
}
|
||||
}
|
||||
|
||||
async copyObject(
|
||||
sourceBucket: string,
|
||||
sourceKey: string,
|
||||
destBucket: string,
|
||||
destKey: string,
|
||||
): Promise<void> {
|
||||
const command = new CopyObjectCommand({
|
||||
Bucket: destBucket,
|
||||
Key: destKey,
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
CopySource: `${sourceBucket}/${sourceKey}`,
|
||||
})
|
||||
await this.client.send(command)
|
||||
}
|
||||
|
||||
async downloadToFile(bucket: string, key: string, filePath: string): Promise<void> {
|
||||
const command = new GetObjectCommand({
|
||||
Bucket: bucket,
|
||||
@@ -331,6 +353,21 @@ export class LocalStorageService implements S3Service {
|
||||
}
|
||||
}
|
||||
|
||||
async copyObject(
|
||||
sourceBucket: string,
|
||||
sourceKey: string,
|
||||
destBucket: string,
|
||||
destKey: string,
|
||||
): Promise<void> {
|
||||
const srcPath = this.getFilePath(sourceBucket, sourceKey)
|
||||
const destPath = this.getFilePath(destBucket, destKey)
|
||||
const dir = path.dirname(destPath)
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
}
|
||||
await fs.promises.copyFile(srcPath, destPath)
|
||||
}
|
||||
|
||||
async downloadToFile(bucket: string, key: string, filePath: string): Promise<void> {
|
||||
const srcPath = this.getFilePath(bucket, key)
|
||||
await fs.promises.copyFile(srcPath, filePath)
|
||||
|
||||
@@ -39,7 +39,7 @@ describe('SkillService', () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test.zip',
|
||||
key: 'test.zip',
|
||||
storageKey: { create: { key: 'test.zip' } },
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
},
|
||||
|
||||
@@ -25,9 +25,11 @@ export class SkillService {
|
||||
} else if (req.assetId) {
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: req.assetId },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
if (!asset || !asset.key) throw new Error('Asset not found or has no key')
|
||||
const { buffer } = await s3Service.getObject(process.env.S3_BUCKET || 'shumai', asset.key)
|
||||
const key = asset?.storageKey?.key
|
||||
if (!asset || !key) throw new Error('Asset not found or has no key')
|
||||
const { buffer } = await s3Service.getObject(process.env.S3_BUCKET || 'shumai', key)
|
||||
zipBuffer = buffer
|
||||
} else {
|
||||
throw new Error('Either assetId or githubUrl must be provided')
|
||||
@@ -68,7 +70,7 @@ export class SkillService {
|
||||
const skillAsset = await this.prismaClient.asset.create({
|
||||
data: {
|
||||
name: `${name}.zip`,
|
||||
key: assetKey,
|
||||
storageKey: { create: { key: assetKey } },
|
||||
type: 'file',
|
||||
mediaType: 'application/zip',
|
||||
sizeByte: repackedZip.length,
|
||||
|
||||
@@ -101,10 +101,15 @@ describe('UploadService', () => {
|
||||
data: {
|
||||
name: 'video.mp4',
|
||||
type: AssetType.file,
|
||||
projectId,
|
||||
parentId,
|
||||
project: { connect: { id: projectId } },
|
||||
parent: { connect: { id: parentId } },
|
||||
status: AssetStatus.uploading,
|
||||
key: 'test-key',
|
||||
storageKey: {
|
||||
connectOrCreate: {
|
||||
where: { key: 'test-key' },
|
||||
create: { key: 'test-key' },
|
||||
},
|
||||
},
|
||||
mediaType: 'video/mp4',
|
||||
},
|
||||
})
|
||||
@@ -134,10 +139,15 @@ describe('UploadService', () => {
|
||||
data: {
|
||||
name: 'image.png',
|
||||
type: AssetType.file,
|
||||
projectId,
|
||||
parentId,
|
||||
project: { connect: { id: projectId } },
|
||||
parent: { connect: { id: parentId } },
|
||||
status: AssetStatus.uploading,
|
||||
key: 'test-key',
|
||||
storageKey: {
|
||||
connectOrCreate: {
|
||||
where: { key: 'test-key' },
|
||||
create: { key: 'test-key' },
|
||||
},
|
||||
},
|
||||
mediaType: 'image/png',
|
||||
},
|
||||
})
|
||||
@@ -162,10 +172,15 @@ describe('UploadService', () => {
|
||||
data: {
|
||||
name: 'file.txt',
|
||||
type: AssetType.file,
|
||||
projectId,
|
||||
parentId,
|
||||
project: { connect: { id: projectId } },
|
||||
parent: { connect: { id: parentId } },
|
||||
status: AssetStatus.uploading,
|
||||
key: 'test-key',
|
||||
storageKey: {
|
||||
connectOrCreate: {
|
||||
where: { key: 'test-key' },
|
||||
create: { key: 'test-key' },
|
||||
},
|
||||
},
|
||||
mediaType: 'text/plain',
|
||||
},
|
||||
})
|
||||
@@ -259,10 +274,15 @@ describe('UploadService', () => {
|
||||
data: {
|
||||
name: 'v2.txt',
|
||||
type: AssetType.file,
|
||||
projectId,
|
||||
parentId: stack.id,
|
||||
project: { connect: { id: projectId } },
|
||||
parent: { connect: { id: stack.id } },
|
||||
status: AssetStatus.uploading,
|
||||
key: 'v2-key',
|
||||
storageKey: {
|
||||
connectOrCreate: {
|
||||
where: { key: 'v2-key' },
|
||||
create: { key: 'v2-key' },
|
||||
},
|
||||
},
|
||||
sizeByte: 2000,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -127,15 +127,15 @@ export class UploadService {
|
||||
data: {
|
||||
name: file.name,
|
||||
type: assetType,
|
||||
key,
|
||||
storageKey: key ? { create: { key } } : undefined,
|
||||
sortIndex: newSortIndex,
|
||||
mediaType: file.mediaType,
|
||||
status: AssetStatus.uploading,
|
||||
sizeByte: file.size,
|
||||
creatorId: userId,
|
||||
parentId,
|
||||
projectId,
|
||||
taskId,
|
||||
creator: userId ? { connect: { id: userId } } : undefined,
|
||||
parent: parentId ? { connect: { id: parentId } } : undefined,
|
||||
project: { connect: { id: projectId } },
|
||||
task: { connect: { id: taskId } },
|
||||
},
|
||||
})
|
||||
createdIds.push(newAsset.id)
|
||||
@@ -168,11 +168,15 @@ export class UploadService {
|
||||
): Promise<void> {
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: req.fileId },
|
||||
include: { project: { include: { team: true } } },
|
||||
include: {
|
||||
storageKey: true,
|
||||
project: { include: { team: true } },
|
||||
},
|
||||
})
|
||||
if (!asset) throw new Error('Asset not found')
|
||||
if (!asset.project) throw new Error('Project not found for asset')
|
||||
if (!asset.key) throw new Error('Asset has no key')
|
||||
const key = asset.storageKey?.key
|
||||
if (!key) throw new Error('Asset has no key')
|
||||
|
||||
if (req.errorMessage) {
|
||||
await this.prismaClient.asset.delete({ where: { id: asset.id } })
|
||||
@@ -192,7 +196,7 @@ export class UploadService {
|
||||
return
|
||||
}
|
||||
|
||||
const size = await s3Service.getObjectSize(process.env.S3_BUCKET || 'shumai', asset.key)
|
||||
const size = await s3Service.getObjectSize(process.env.S3_BUCKET || 'shumai', key)
|
||||
|
||||
const project = asset.project
|
||||
|
||||
|
||||
@@ -93,7 +93,7 @@ describe('Transcode Activities', () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'v.mp4',
|
||||
key: 'v.mp4',
|
||||
storageKey: { create: { key: 'v.mp4' } },
|
||||
status: 'uploaded',
|
||||
type: 'file',
|
||||
},
|
||||
|
||||
@@ -255,10 +255,14 @@ export interface UpdateAssetMediaActivityParams {
|
||||
|
||||
export async function updateAssetMediaActivity(params: UpdateAssetMediaActivityParams) {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const asset = await prisma.asset.findUnique({ where: { id: params.assetId } })
|
||||
if (!asset || !asset.key) throw new Error('Asset not found')
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
const key = asset?.storageKey?.key
|
||||
if (!asset || !key) throw new Error('Asset not found or has no key')
|
||||
|
||||
const infoKey = path.join(path.dirname(asset.key), 'info.json')
|
||||
const infoKey = path.join(path.dirname(key), 'info.json')
|
||||
const buffer = Buffer.from(JSON.stringify(params.mediaInfo))
|
||||
await s3Service.putObject(bucket, infoKey, buffer, buffer.length, 'application/json')
|
||||
|
||||
|
||||
@@ -90,7 +90,7 @@ describe('Transcode Workflow', () => {
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
key: 'video.mp4',
|
||||
storageKey: { key: 'video.mp4' },
|
||||
mediaType: 'video/mp4',
|
||||
})
|
||||
|
||||
|
||||
@@ -38,14 +38,15 @@ export async function transcodeMedia(task: WorkflowTask): Promise<void> {
|
||||
|
||||
// 2. Get Asset
|
||||
const asset = await executeActivity(TaskQueueDb, getAssetActivity, task.assetId)
|
||||
if (!asset || !asset.key) throw new Error('Asset not found')
|
||||
const key = asset?.storageKey?.key
|
||||
if (!asset || !key) throw new Error('Asset not found or has no key')
|
||||
|
||||
// 3. Get Worker-Specific Queue for Transcode
|
||||
workerQueue = await executeActivity(TaskQueueTranscode, getTranscodeWorkerQueueActivity)
|
||||
|
||||
// 4. Download Media to Tmp
|
||||
const download = await executeActivity(workerQueue, downloadMediaToTmpActivity, {
|
||||
assetKey: asset.key,
|
||||
assetKey: key,
|
||||
})
|
||||
const { filePath } = download
|
||||
tmpDir = download.tmpDir
|
||||
@@ -59,7 +60,7 @@ export async function transcodeMedia(task: WorkflowTask): Promise<void> {
|
||||
})
|
||||
|
||||
mediaInfo.original = {
|
||||
key: asset.key,
|
||||
key,
|
||||
downloadUrl: '',
|
||||
filesizeInBytes: 0,
|
||||
codec: '',
|
||||
@@ -89,7 +90,7 @@ export async function transcodeMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
const videoTranscode = await executeActivity(workerQueue, transcodeVideoActivity, {
|
||||
assetKey: asset.key,
|
||||
assetKey: key,
|
||||
filePath,
|
||||
videoSpec,
|
||||
duration: metadata.duration,
|
||||
@@ -125,7 +126,7 @@ export async function transcodeMedia(task: WorkflowTask): Promise<void> {
|
||||
if (imageSpec.width > metadata.originalWidth) continue
|
||||
|
||||
const imageTranscode = await executeActivity(workerQueue, transcodeImageActivity, {
|
||||
assetKey: asset.key,
|
||||
assetKey: key,
|
||||
filePath,
|
||||
imageSpec,
|
||||
})
|
||||
@@ -143,7 +144,7 @@ export async function transcodeMedia(task: WorkflowTask): Promise<void> {
|
||||
format: 'webp',
|
||||
}
|
||||
const imageTranscode = await executeActivity(workerQueue, transcodeImageActivity, {
|
||||
assetKey: asset.key,
|
||||
assetKey: key,
|
||||
filePath,
|
||||
imageSpec,
|
||||
})
|
||||
@@ -164,7 +165,7 @@ export async function transcodeMedia(task: WorkflowTask): Promise<void> {
|
||||
// 9. System: Thumbnail
|
||||
if (spec.thumbnail) {
|
||||
const thumbTranscode = await executeActivity(workerQueue, transcodeImageActivity, {
|
||||
assetKey: asset.key,
|
||||
assetKey: key,
|
||||
filePath,
|
||||
imageSpec: { width: 480, height: 0, quality: 80, format: 'webp' },
|
||||
})
|
||||
@@ -173,8 +174,8 @@ export async function transcodeMedia(task: WorkflowTask): Promise<void> {
|
||||
|
||||
// 10. System: Sprite/Poster (Video only usually)
|
||||
if (spec.sprite || spec.poster) {
|
||||
const lastSlashIndex = asset.key.lastIndexOf('/')
|
||||
const assetDir = lastSlashIndex === -1 ? '' : asset.key.substring(0, lastSlashIndex)
|
||||
const lastSlashIndex = key.lastIndexOf('/')
|
||||
const assetDir = lastSlashIndex === -1 ? '' : key.substring(0, lastSlashIndex)
|
||||
|
||||
const spriteSpec: PrismaJson.SpriteInfo = {
|
||||
key: assetDir ? `${assetDir}/sprite.webp` : 'sprite.webp',
|
||||
@@ -187,7 +188,7 @@ export async function transcodeMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
const spriteResult = await executeActivity(workerQueue, generateSpriteActivity, {
|
||||
assetKey: asset.key,
|
||||
assetKey: key,
|
||||
filePath,
|
||||
spriteSpec,
|
||||
posterSpec,
|
||||
|
||||
@@ -19,6 +19,8 @@ import {
|
||||
FileText,
|
||||
Link,
|
||||
Plus,
|
||||
ArrowRight,
|
||||
Copy,
|
||||
} from 'lucide-react'
|
||||
|
||||
interface FileBrowserContextMenuProps {
|
||||
@@ -32,6 +34,8 @@ interface FileBrowserContextMenuProps {
|
||||
onUploadFile: () => void
|
||||
onUploadFolder: () => void
|
||||
onNewVersion: (item: AssetInfo) => void
|
||||
onMoveTo: (items: AssetInfo[]) => void
|
||||
onCopyTo: (items: AssetInfo[]) => void
|
||||
folders: AssetInfo[]
|
||||
files: AssetInfo[]
|
||||
isRecentlyDeleted?: boolean
|
||||
@@ -54,6 +58,8 @@ export function FileBrowserContextMenu({
|
||||
onUploadFile,
|
||||
onUploadFolder,
|
||||
onNewVersion,
|
||||
onMoveTo,
|
||||
onCopyTo,
|
||||
folders,
|
||||
files,
|
||||
isRecentlyDeleted,
|
||||
@@ -161,6 +167,14 @@ export function FileBrowserContextMenu({
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
<span>Download</span>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={() => onMoveTo(itemsToModify)}>
|
||||
<ArrowRight className="mr-2 h-4 w-4" />
|
||||
<span>Move to</span>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={() => onCopyTo(itemsToModify)}>
|
||||
<Copy className="mr-2 h-4 w-4" />
|
||||
<span>Copy to</span>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={handleDelete} className="text-destructive">
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
<span>Delete</span>
|
||||
@@ -212,6 +226,15 @@ export function FileBrowserContextMenu({
|
||||
<span>Download</span>
|
||||
</ContextMenuItem>
|
||||
|
||||
<ContextMenuItem onSelect={() => onMoveTo(itemsToModify)}>
|
||||
<ArrowRight className="mr-2 h-4 w-4" />
|
||||
<span>Move to</span>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={() => onCopyTo(itemsToModify)}>
|
||||
<Copy className="mr-2 h-4 w-4" />
|
||||
<span>Copy to</span>
|
||||
</ContextMenuItem>
|
||||
|
||||
{(item.type === 'file' || item.type === 'version_stack') && (
|
||||
<ContextMenuItem onSelect={() => onNewVersion(item)}>
|
||||
<UploadCloud className="mr-2 h-4 w-4" />
|
||||
|
||||
@@ -16,6 +16,7 @@ import { toast } from 'sonner'
|
||||
import type { DragState } from '../dnd-types'
|
||||
import { FileBrowserContextMenu } from './context-menu'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { MoveCopyDialog } from '../move-copy-dialog'
|
||||
|
||||
import { FileBrowserGridView } from './grid-view'
|
||||
import { FileBrowserListView } from './list-view'
|
||||
@@ -110,6 +111,8 @@ export function FileBrowser({
|
||||
fieldVisibility,
|
||||
}: FileBrowserProps) {
|
||||
const [contextMenuItem, setContextMenuItem] = useState<AssetInfo | null>(null)
|
||||
const [moveCopyMode, setMoveCopyMode] = useState<'move' | 'copy' | null>(null)
|
||||
const [itemsToMoveCopy, setItemsToMoveCopy] = useState<AssetInfo[]>([])
|
||||
const queryClient = useQueryClient()
|
||||
const navigate = useNavigate()
|
||||
|
||||
@@ -126,6 +129,97 @@ export function FileBrowser({
|
||||
enabled: !!teamId && !!projectId && !isPublic,
|
||||
})
|
||||
|
||||
const $reparent = client.api.projects[':projectId'].reparent.$post
|
||||
const { mutate: reparentAssets } = useMutation<
|
||||
InferResponseType<typeof $reparent, 204>,
|
||||
Error,
|
||||
InferRequestType<typeof $reparent>
|
||||
>({
|
||||
mutationFn: async (request) => {
|
||||
const res = await $reparent(request)
|
||||
if (!res.ok) throw new Error('Failed to move assets')
|
||||
return null as unknown as InferResponseType<typeof $reparent, 204>
|
||||
},
|
||||
})
|
||||
|
||||
const $copy = client.api.projects[':projectId'].copy.$post
|
||||
const { mutate: copyAssets } = useMutation<
|
||||
InferResponseType<typeof $copy, 204>,
|
||||
Error,
|
||||
InferRequestType<typeof $copy>
|
||||
>({
|
||||
mutationFn: async (request) => {
|
||||
const res = await $copy(request)
|
||||
if (!res.ok) throw new Error('Failed to copy assets')
|
||||
return null as unknown as InferResponseType<typeof $copy, 204>
|
||||
},
|
||||
})
|
||||
|
||||
const handleMoveCopyConfirm = async (targetFolderId: string, withComments: boolean) => {
|
||||
const assetIds = itemsToMoveCopy.map((i) => i.id!)
|
||||
if (moveCopyMode === 'move') {
|
||||
reparentAssets(
|
||||
{
|
||||
param: { projectId },
|
||||
json: { newParentId: targetFolderId, assetIds },
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast.success(`Successfully moved ${assetIds.length} item(s)`, {
|
||||
action: {
|
||||
label: 'Go to folder',
|
||||
onClick: () => {
|
||||
navigate({
|
||||
to: '/projects/$projectId/folders/$folderId',
|
||||
params: { projectId, folderId: targetFolderId },
|
||||
})
|
||||
},
|
||||
},
|
||||
})
|
||||
queryClient.invalidateQueries({ queryKey: ['search', teamId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['folders', teamId] })
|
||||
setMoveCopyMode(null)
|
||||
setItemsToMoveCopy([])
|
||||
onClearSelection()
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(`Error: ${err.message}`)
|
||||
},
|
||||
},
|
||||
)
|
||||
} else {
|
||||
copyAssets(
|
||||
{
|
||||
param: { projectId },
|
||||
json: { newParentId: targetFolderId, assetIds, withComments },
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast.success(`Successfully copied ${assetIds.length} item(s)`, {
|
||||
action: {
|
||||
label: 'Go to folder',
|
||||
onClick: () => {
|
||||
navigate({
|
||||
to: '/projects/$projectId/folders/$folderId',
|
||||
params: { projectId, folderId: targetFolderId },
|
||||
})
|
||||
},
|
||||
},
|
||||
})
|
||||
queryClient.invalidateQueries({ queryKey: ['search', teamId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['folders', teamId] })
|
||||
setMoveCopyMode(null)
|
||||
setItemsToMoveCopy([])
|
||||
onClearSelection()
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(`Error: ${err.message}`)
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const { mutate: createShareLink } = useMutation({
|
||||
mutationFn: async (items: AssetInfo[]) => {
|
||||
const name =
|
||||
@@ -773,6 +867,14 @@ export function FileBrowser({
|
||||
onUploadFile={handleUploadFilesClick}
|
||||
onUploadFolder={handleUploadFolderClick}
|
||||
onNewVersion={handleNewVersionClick}
|
||||
onMoveTo={(items) => {
|
||||
setItemsToMoveCopy(items)
|
||||
setMoveCopyMode('move')
|
||||
}}
|
||||
onCopyTo={(items) => {
|
||||
setItemsToMoveCopy(items)
|
||||
setMoveCopyMode('copy')
|
||||
}}
|
||||
onRestore={handleRestore}
|
||||
isRecentlyDeleted={isRecentlyDeleted}
|
||||
shareLinks={shareLinksData?.data ?? []}
|
||||
@@ -809,6 +911,17 @@ export function FileBrowser({
|
||||
/>
|
||||
{renderContent()}
|
||||
|
||||
{moveCopyMode && (
|
||||
<MoveCopyDialog
|
||||
isOpen={!!moveCopyMode}
|
||||
onClose={() => setMoveCopyMode(null)}
|
||||
onConfirm={handleMoveCopyConfirm}
|
||||
mode={moveCopyMode}
|
||||
teamId={teamId}
|
||||
currentProjectId={projectId}
|
||||
/>
|
||||
)}
|
||||
|
||||
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
|
||||
@@ -28,6 +28,8 @@ interface FolderTreeProps {
|
||||
projectName: string
|
||||
rootFolderId: string
|
||||
dragState?: DragState
|
||||
onSelect?: (folder: AssetInfo) => void
|
||||
selectedFolderId?: string
|
||||
}
|
||||
|
||||
export function FolderTree({
|
||||
@@ -36,6 +38,8 @@ export function FolderTree({
|
||||
projectName,
|
||||
rootFolderId,
|
||||
dragState,
|
||||
onSelect,
|
||||
selectedFolderId,
|
||||
}: FolderTreeProps) {
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
@@ -117,6 +121,8 @@ export function FolderTree({
|
||||
level={0}
|
||||
isRoot={true}
|
||||
dragState={dragState}
|
||||
onSelect={onSelect}
|
||||
selectedFolderId={selectedFolderId}
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
@@ -247,6 +253,8 @@ interface FolderTreeItemProps {
|
||||
level: number
|
||||
isRoot?: boolean
|
||||
dragState?: DragState
|
||||
onSelect?: (folder: AssetInfo) => void
|
||||
selectedFolderId?: string
|
||||
}
|
||||
|
||||
function FolderTreeItem({
|
||||
@@ -256,6 +264,8 @@ function FolderTreeItem({
|
||||
level,
|
||||
isRoot,
|
||||
dragState,
|
||||
onSelect,
|
||||
selectedFolderId,
|
||||
}: FolderTreeItemProps) {
|
||||
const [isExpanded, setIsExpanded] = useState(isRoot || false)
|
||||
const navigate = useNavigate()
|
||||
@@ -321,6 +331,11 @@ function FolderTreeItem({
|
||||
}
|
||||
|
||||
const handleFolderClick = () => {
|
||||
if (onSelect) {
|
||||
onSelect(folder)
|
||||
return
|
||||
}
|
||||
|
||||
if (isRoot) {
|
||||
navigate({
|
||||
to: '/projects/$projectId',
|
||||
@@ -340,7 +355,7 @@ function FolderTreeItem({
|
||||
type: 'folder',
|
||||
item: folder,
|
||||
},
|
||||
disabled: !!isRoot,
|
||||
disabled: !!isRoot || !!onSelect,
|
||||
})
|
||||
|
||||
const { ref: setDroppableRef, isDropTarget: isOver } = useDroppable({
|
||||
@@ -349,7 +364,7 @@ function FolderTreeItem({
|
||||
type: 'folder',
|
||||
item: folder,
|
||||
},
|
||||
disabled: dragState?.draggedIds.has(folder.id!),
|
||||
disabled: dragState?.draggedIds.has(folder.id!) || !!onSelect,
|
||||
})
|
||||
|
||||
const setNodeRef = (node: HTMLDivElement | null) => {
|
||||
@@ -358,20 +373,24 @@ function FolderTreeItem({
|
||||
}
|
||||
|
||||
const isValidDropTarget = useMemo(() => {
|
||||
if (onSelect) return false
|
||||
if (!dragState?.isActive) return false
|
||||
if (dragState.draggedIds.has(folder.id!)) return false
|
||||
return true
|
||||
}, [dragState, folder.id])
|
||||
}, [dragState, folder.id, onSelect])
|
||||
|
||||
const showDropFeedback = isOver && isValidDropTarget
|
||||
|
||||
const isSelected = selectedFolderId === folder.id
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
className={cn(
|
||||
'group flex cursor-pointer items-center gap-1 rounded-md px-2 py-1.5 text-sm transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
|
||||
isActive && 'bg-sidebar-accent text-sidebar-accent-foreground font-medium',
|
||||
(isActive || isSelected) &&
|
||||
'bg-sidebar-accent text-sidebar-accent-foreground font-medium',
|
||||
isDragging && 'opacity-50',
|
||||
showDropFeedback && 'bg-sidebar-accent ring-2 ring-primary ring-inset',
|
||||
)}
|
||||
@@ -415,6 +434,8 @@ function FolderTreeItem({
|
||||
folder={child}
|
||||
level={level + 1}
|
||||
dragState={dragState}
|
||||
onSelect={onSelect}
|
||||
selectedFolderId={selectedFolderId}
|
||||
/>
|
||||
))}
|
||||
{hasNextPage && (
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/ui/components/ui/dialog'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Checkbox } from '@/ui/components/ui/checkbox'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/ui/components/ui/select'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { FolderTree } from './folder-tree'
|
||||
import { AssetInfo } from '@/dtos/asset'
|
||||
import { ProjectInfo } from '@/dtos/project'
|
||||
import { ScrollArea } from './ui/scroll-area'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
|
||||
interface MoveCopyDialogProps {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
onConfirm: (targetFolderId: string, withComments: boolean) => void
|
||||
mode: 'move' | 'copy'
|
||||
teamId: string
|
||||
currentProjectId: string
|
||||
}
|
||||
|
||||
export function MoveCopyDialog({
|
||||
isOpen,
|
||||
onClose,
|
||||
onConfirm,
|
||||
mode,
|
||||
teamId,
|
||||
currentProjectId,
|
||||
}: MoveCopyDialogProps) {
|
||||
const [selectedProjectId, setSelectedProjectId] = useState(currentProjectId)
|
||||
const [selectedFolder, setSelectedFolder] = useState<AssetInfo | null>(null)
|
||||
const [withComments, setWithComments] = useState(false)
|
||||
|
||||
const { data: projectsData, isLoading: isLoadingProjects } = useQuery({
|
||||
queryKey: ['projects', teamId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].projects.$get({
|
||||
param: { teamId },
|
||||
query: { first: '100' },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch projects')
|
||||
return (await res.json()) as unknown as { data: ProjectInfo[] }
|
||||
},
|
||||
enabled: !!teamId && isOpen,
|
||||
})
|
||||
|
||||
const projects = projectsData?.data ?? []
|
||||
const selectedProject = projects.find((p) => p.id === selectedProjectId)
|
||||
|
||||
const handleConfirm = () => {
|
||||
if (selectedFolder) {
|
||||
onConfirm(selectedFolder.id, withComments)
|
||||
} else if (selectedProject?.rootFolder) {
|
||||
onConfirm(selectedProject.rootFolder, withComments)
|
||||
}
|
||||
}
|
||||
|
||||
const title = mode === 'move' ? 'Move to' : 'Copy to'
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||
<DialogContent className="sm:max-w-[425px] flex flex-col h-[600px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex flex-col gap-4 flex-1 overflow-hidden">
|
||||
<div className="flex flex-col gap-2">
|
||||
<label className="text-sm font-medium">Select Project</label>
|
||||
<Select
|
||||
value={selectedProjectId}
|
||||
onValueChange={(val) => {
|
||||
setSelectedProjectId(val)
|
||||
setSelectedFolder(null)
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select a project" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{projects.map((p) => (
|
||||
<SelectItem key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2 flex-1 overflow-hidden">
|
||||
<label className="text-sm font-medium">Select Folder</label>
|
||||
<div className="border rounded-md flex-1 overflow-hidden">
|
||||
<ScrollArea className="h-full">
|
||||
{selectedProject && selectedProject.rootFolder ? (
|
||||
<FolderTree
|
||||
teamId={teamId}
|
||||
projectId={selectedProject.id}
|
||||
projectName={selectedProject.name}
|
||||
rootFolderId={selectedProject.rootFolder}
|
||||
onSelect={setSelectedFolder}
|
||||
selectedFolderId={selectedFolder?.id || selectedProject.rootFolder}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-full p-4">
|
||||
{isLoadingProjects ? (
|
||||
<Loader2 className="animate-spin h-6 w-6" />
|
||||
) : (
|
||||
'Select a project first'
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{mode === 'copy' && (
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="copy-comments"
|
||||
checked={withComments}
|
||||
onCheckedChange={(checked) => setWithComments(!!checked)}
|
||||
/>
|
||||
<label
|
||||
htmlFor="copy-comments"
|
||||
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
|
||||
>
|
||||
Copy comments
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleConfirm} disabled={!selectedProject}>
|
||||
Confirm
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -25,10 +25,10 @@ describe('AI Activities', () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test.png',
|
||||
key: 'test.png',
|
||||
storageKey: { create: { key: 'test.png' } },
|
||||
status: 'uploaded',
|
||||
type: 'file',
|
||||
projectId: project.id,
|
||||
project: { connect: { id: project.id } },
|
||||
},
|
||||
})
|
||||
|
||||
@@ -54,7 +54,7 @@ describe('AI Activities', () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test.png',
|
||||
key: 'test.png',
|
||||
storageKey: { create: { key: 'test.png' } },
|
||||
status: 'uploaded',
|
||||
type: 'file',
|
||||
},
|
||||
|
||||
@@ -11,6 +11,7 @@ export async function getAssetActivity(assetId: string) {
|
||||
return prisma.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
include: {
|
||||
storageKey: true,
|
||||
project: {
|
||||
include: {
|
||||
team: true,
|
||||
@@ -46,7 +47,7 @@ export async function updateAssetMetadataActivity(params: UpdateAssetMetadataPar
|
||||
export async function getCommentActivity(commentId: string) {
|
||||
return prisma.assetComment.findUnique({
|
||||
where: { id: commentId },
|
||||
include: { attachments: { include: { asset: true } } },
|
||||
include: { attachments: { include: { asset: { include: { storageKey: true } } } } },
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { prisma } from '@/db'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import { logger } from '@/logger'
|
||||
|
||||
export async function purgeUnreferencedStorageKeysActivity(): Promise<{
|
||||
purgedCount: number
|
||||
physicalFilesDeleted: number
|
||||
}> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
let purgedCount = 0
|
||||
let physicalFilesDeleted = 0
|
||||
|
||||
// 1. Find storage keys with no associated assets and older than 24 hours
|
||||
// We use 24 hours to avoid race conditions with ongoing uploads or copies.
|
||||
const twentyFourHoursAgo = new Date()
|
||||
twentyFourHoursAgo.setDate(twentyFourHoursAgo.getDate() - 1)
|
||||
|
||||
const unreferencedKeys = await prisma.storageKey.findMany({
|
||||
where: {
|
||||
assets: { none: {} },
|
||||
createdAt: { lt: twentyFourHoursAgo },
|
||||
},
|
||||
take: 100,
|
||||
})
|
||||
|
||||
for (const sk of unreferencedKeys) {
|
||||
try {
|
||||
// Physically delete from S3
|
||||
// Handle complex keys (directories) same as before
|
||||
const parts = sk.key.split('/')
|
||||
if (parts.length > 2) {
|
||||
const prefix = parts.slice(0, parts.length - 1).join('/') + '/'
|
||||
const count = await s3Service.deletePrefix(bucket, prefix)
|
||||
physicalFilesDeleted += count
|
||||
} else {
|
||||
const count = await s3Service.deleteObject(bucket, sk.key)
|
||||
physicalFilesDeleted += count
|
||||
}
|
||||
|
||||
// Delete from database
|
||||
await prisma.storageKey.delete({
|
||||
where: { id: sk.id },
|
||||
})
|
||||
purgedCount++
|
||||
} catch (e: unknown) {
|
||||
logger.error(
|
||||
{ key: sk.key, error: e instanceof Error ? e.message : String(e) },
|
||||
'Failed to purge unreferenced storage key',
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (purgedCount > 0) {
|
||||
logger.info(
|
||||
{ purgedCount, physicalFilesDeleted },
|
||||
`Garbage collection: purged ${purgedCount} storage keys and ${physicalFilesDeleted} physical files`,
|
||||
)
|
||||
}
|
||||
|
||||
return { purgedCount, physicalFilesDeleted }
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import * as aiActivities from './ai'
|
||||
import * as transcodeActivities from '@/transcode/activities/transcode'
|
||||
import * as agentActivities from './agent'
|
||||
import * as dbActivities from './db'
|
||||
import * as gcActivities from './gc'
|
||||
|
||||
export const activities = {
|
||||
...taskActivities,
|
||||
@@ -10,4 +11,5 @@ export const activities = {
|
||||
...transcodeActivities,
|
||||
...agentActivities,
|
||||
...dbActivities,
|
||||
...gcActivities,
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ describe('Task Activities', () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test.mp4',
|
||||
key: 'test.mp4',
|
||||
storageKey: { create: { key: 'test.mp4' } },
|
||||
status: 'uploaded',
|
||||
type: 'file',
|
||||
},
|
||||
|
||||
@@ -56,10 +56,10 @@ describe('WorkflowService', () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test.mp3',
|
||||
key: 'test/test.mp3',
|
||||
storageKey: { create: { key: 'test/test.mp3' } },
|
||||
status: 'uploaded',
|
||||
type: 'file',
|
||||
projectId: project.id,
|
||||
project: { connect: { id: project.id } },
|
||||
},
|
||||
})
|
||||
|
||||
@@ -100,11 +100,11 @@ describe('WorkflowService', () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test.png',
|
||||
key: 'test/test.png',
|
||||
storageKey: { create: { key: 'test/test.png' } },
|
||||
status: 'uploaded',
|
||||
type: 'file',
|
||||
mediaType: 'image/png',
|
||||
projectId: project.id,
|
||||
project: { connect: { id: project.id } },
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@@ -89,7 +89,7 @@ describe('AIAutofill Workflow', () => {
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
key: 'test.mp4',
|
||||
storageKey: { key: 'test.mp4' },
|
||||
mediaType: 'video/mp4',
|
||||
project: { id: 'proj-1', teamId: 'team-1' },
|
||||
})
|
||||
@@ -140,7 +140,7 @@ describe('AIAutofill Workflow', () => {
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
key: 'test.mp4',
|
||||
storageKey: { key: 'test.mp4' },
|
||||
mediaType: 'video/mp4',
|
||||
project: { id: 'proj-1', teamId: 'team-1' },
|
||||
})
|
||||
|
||||
@@ -47,7 +47,8 @@ export async function aiAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
|
||||
// 1. Get Asset
|
||||
const asset = await executeActivity(TaskQueueDb, getAssetActivity, task.assetId)
|
||||
if (!asset || !asset.project) {
|
||||
const key = asset?.storageKey?.key
|
||||
if (!asset || !asset.project || !key) {
|
||||
throw new Error('Asset or project not found')
|
||||
}
|
||||
const teamId = asset.project.teamId
|
||||
@@ -63,13 +64,13 @@ export async function aiAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
)
|
||||
|
||||
const download = await executeActivity(transcodeWorkerQueue, downloadMediaToTmpActivity, {
|
||||
assetKey: asset.key || '',
|
||||
assetKey: key,
|
||||
})
|
||||
const { filePath } = download
|
||||
tmpDir = download.tmpDir
|
||||
|
||||
const generatedFiles = await executeActivity(transcodeWorkerQueue, extractAiMetadataActivity, {
|
||||
assetKey: asset.key || '',
|
||||
assetKey: key,
|
||||
filePath,
|
||||
type: 'autofill',
|
||||
isImage,
|
||||
|
||||
@@ -42,7 +42,8 @@ export async function aiTranscriptionMedia(task: WorkflowTask): Promise<void> {
|
||||
|
||||
// 1. Get Asset
|
||||
const asset = await executeActivity(TaskQueueDb, getAssetActivity, task.assetId)
|
||||
if (!asset || !asset.key) {
|
||||
const key = asset?.storageKey?.key
|
||||
if (!asset || !key) {
|
||||
throw new Error('Asset not found')
|
||||
}
|
||||
|
||||
@@ -53,13 +54,13 @@ export async function aiTranscriptionMedia(task: WorkflowTask): Promise<void> {
|
||||
)
|
||||
|
||||
const download = await executeActivity(transcodeWorkerQueue, downloadMediaToTmpActivity, {
|
||||
assetKey: asset.key,
|
||||
assetKey: key,
|
||||
})
|
||||
const { filePath } = download
|
||||
tmpDir = download.tmpDir
|
||||
|
||||
const generatedFiles = await executeActivity(transcodeWorkerQueue, extractAiMetadataActivity, {
|
||||
assetKey: asset.key,
|
||||
assetKey: key,
|
||||
filePath,
|
||||
type: 'transcription',
|
||||
isImage: false,
|
||||
|
||||
Reference in New Issue
Block a user