refactor: extract core service domain layer to @shumai/core

This commit is contained in:
yiling
2026-06-01 23:16:22 +08:00
parent 2362a7f373
commit cb80822637
163 changed files with 328 additions and 67608 deletions
+223
View File
@@ -0,0 +1,223 @@
import { describe, expect, test } from 'vitest'
import { AgentService } from './agent'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
describe('AgentService', () => {
setupTestDbHooks()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function setupTestData(db: any) {
const team = await db.team.create({
data: {
name: 'Test Team',
},
})
const provider = await db.provider.create({
data: {
name: 'Google',
teamId: team.id,
config: {
api: 'openai-completions',
},
},
})
const model = await db.model.create({
data: {
modelId: 'gemini-pro',
name: 'Gemini Pro',
providerId: provider.id,
config: {},
},
})
const skill = await db.skill.create({
data: {
name: 'Test Skill',
teamId: team.id,
assetId: 'asset1',
hash: 'hash1',
},
})
const user = await db.user.create({
data: {
name: 'Bot 1',
email: 'bot1@shumai.ai',
type: 'agent',
},
})
const agent = await db.agent.create({
data: {
id: user.id,
teamId: team.id,
type: 'chat',
providerId: provider.id,
modelId: model.id,
soul: 'Test soul',
config: {
provider: provider.id,
model: model.id,
},
},
})
await db.teamMember.create({
data: {
teamId: team.id,
userId: user.id,
role: 'owner',
},
})
return { team, provider, model, skill, agent }
}
describe('create, update, delete agents', () => {
test('Create Agent with Provider and Model', async () => {
const db = prisma
const svc = new AgentService()
const { team, provider, model } = await setupTestData(db)
const agent = await svc.createAgent({
teamId: team.id,
name: 'New Agent',
type: 'chat',
enabled: true,
providerId: provider.id,
modelId: model.id,
thinkingLevel: 'medium',
systemPrompt: 'You are helpful',
soul: 'I am a soul',
})
expect(agent?.id).toBeDefined()
expect(agent?.user.name).toBe('New Agent')
expect(agent?.providerId).toBe(provider.id)
expect(agent?.modelId).toBe(model.id)
expect(agent?.soul).toBe('I am a soul')
const teamMember = await db.teamMember.findFirst({
where: { userId: agent?.id, teamId: team.id },
})
expect(teamMember).toBeDefined()
})
test('Create Agent with Skills', async () => {
const db = prisma
const svc = new AgentService()
const { team, provider, model, skill } = await setupTestData(db)
const agent = await svc.createAgent({
teamId: team.id,
name: 'Skill Agent',
type: 'chat',
enabled: true,
providerId: provider.id,
modelId: model.id,
thinkingLevel: 'medium',
skills: [skill.id],
})
expect(agent?.skills?.length).toBe(1)
expect(agent?.skills?.[0].skillId).toBe(skill.id)
})
test('Create Agent validation fails if model mismatch', async () => {
const db = prisma
const svc = new AgentService()
const { team, model } = await setupTestData(db)
const otherProvider = await db.provider.create({
data: {
name: 'Other',
teamId: team.id,
config: {
api: 'openai-completions',
},
},
})
await expect(
svc.createAgent({
teamId: team.id,
name: 'Fail Agent',
type: 'chat',
enabled: true,
providerId: otherProvider.id,
modelId: model.id,
thinkingLevel: 'medium',
}),
).rejects.toThrow('model does not belong to provider')
})
test('Update Agent and Skills', async () => {
const db = prisma
const svc = new AgentService()
const { agent, skill } = await setupTestData(db)
const updated = await svc.updateAgent({
agentId: agent.id,
name: 'Updated Agent',
type: 'autofill',
enabled: true,
providerId: agent.providerId!,
modelId: agent.modelId!,
thinkingLevel: 'high',
soul: 'New soul',
skills: [], // Disable all skills
})
expect(updated.user.name).toBe('Updated Agent')
expect(updated.type).toBe('autofill')
expect(updated.soul).toBe('New soul')
expect(updated.skills?.length).toBe(0)
const reUpdated = await svc.updateAgent({
agentId: agent.id,
name: 'Updated Agent',
type: 'autofill',
enabled: true,
providerId: agent.providerId!,
modelId: agent.modelId!,
thinkingLevel: 'high',
soul: 'New soul',
skills: [skill.id], // Re-enable one
})
expect(reUpdated.skills?.length).toBe(1)
})
test('Delete Agent', async () => {
const db = prisma
const svc = new AgentService()
const { agent } = await setupTestData(db)
await svc.deleteAgent({ agentId: agent.id })
const deletedAgent = await db.agent.findUnique({
where: { id: agent.id },
})
expect(deletedAgent).toBeNull()
const deletedUser = await db.user.findUnique({
where: { id: agent.id },
})
expect(deletedUser).toBeNull()
})
test('List Agents', async () => {
const db = prisma
const svc = new AgentService()
const { team } = await setupTestData(db)
const agents = await svc.listAgents({ teamId: team.id })
expect(agents.length).toBe(1)
expect(agents[0].user.name).toBe('Bot 1')
expect(agents[0].provider).toBeDefined()
expect(agents[0].modelRef).toBeDefined()
})
})
})
+330
View File
@@ -0,0 +1,330 @@
import { prisma } from '@shumai/db'
import {
CreateAgentParams,
DeleteAgentParams,
ListAgentsParams,
UpdateAgentParams,
} from '@shumai/dtos'
import '@shumai/db/src/prisma-json-types'
import { s3Service } from '@shumai/core/src/s3/s3'
import AdmZip from 'adm-zip'
import * as fs from 'fs'
import * as path from 'path'
export class AgentService {
constructor(private readonly prismaClient: typeof prisma = prisma) {}
async getSkillContent(skillId: string): Promise<string> {
const skill = await this.prismaClient.skill.findUnique({
where: { id: skillId },
})
if (!skill) {
throw new Error(`Skill with ID ${skillId} not found.`)
}
const skillDir = path.join(process.cwd(), '.pi', 'skills', skill.id)
const hashFile = path.join(skillDir, '.hash')
let needsDownload = true
if (fs.existsSync(hashFile)) {
const localHash = fs.readFileSync(hashFile, 'utf8')
if (localHash === skill.hash) {
needsDownload = false
}
}
if (needsDownload) {
if (fs.existsSync(skillDir)) {
fs.rmSync(skillDir, { recursive: true, force: true })
}
fs.mkdirSync(skillDir, { recursive: true })
const asset = await this.prismaClient.asset.findUnique({
where: { id: skill.assetId },
include: { storageKey: true },
})
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.storageKey.key,
)
const zip = new AdmZip(zipBuffer)
zip.extractAllTo(skillDir, true)
fs.writeFileSync(hashFile, skill.hash)
}
// Read SKILL.md
let skillMdPath = path.join(skillDir, 'SKILL.md')
if (!fs.existsSync(skillMdPath)) {
skillMdPath = path.join(skillDir, 'skill.md')
}
if (!fs.existsSync(skillMdPath)) {
throw new Error(`Skill downloaded but SKILL.md not found in ${skillDir}`)
}
return fs.readFileSync(skillMdPath, 'utf8')
}
async getSkillEnvs(skillId: string): Promise<Record<string, string>> {
const skill = await this.prismaClient.skill.findUnique({
where: { id: skillId },
})
if (!skill) return {}
const config = skill.config as unknown as PrismaJson.SkillConfig
const envs: Record<string, string> = {}
if (config?.environmentVariables && Array.isArray(config.environmentVariables)) {
for (const envVar of config.environmentVariables) {
const value =
envVar.default !== undefined && envVar.default !== null && envVar.default !== ''
? envVar.default
: process.env[envVar.name]
if (value !== undefined) {
envs[envVar.name] = value
}
}
}
return envs
}
async createAgent(params: CreateAgentParams) {
const {
teamId,
name,
type,
enabled,
avatar,
providerId,
modelId,
thinkingLevel,
systemPrompt,
soul,
skills,
} = params
if (type === 'embedding' || type === 'autofill') {
const existing = await this.prismaClient.agent.findFirst({
where: {
type,
teamId,
},
})
if (existing) {
throw new Error(`Agent of type ${type} already exists for this team`)
}
}
if (type === 'chat' || type === 'autofill') {
if (!providerId || !modelId) {
throw new Error('providerId and modelId are required for chat/autofill agents')
}
const model = await this.prismaClient.model.findUnique({
where: { id: modelId },
})
if (!model) throw new Error('model not found')
if (model.providerId !== providerId) {
throw new Error('model does not belong to provider')
}
}
return this.prismaClient.$transaction(async (tx) => {
const team = await tx.team.findUnique({
where: { id: teamId },
})
if (!team) throw new Error('team not found')
const agentConfig: PrismaJson.AgentConfig = {
provider: providerId || '',
model: modelId || '',
thinkingLevel,
systemPrompt,
}
const user = await tx.user.create({
data: {
name,
email: `agent-${Date.now()}-${Math.random().toString(36).substring(7)}@shumai.ai`,
type: 'agent',
image: avatar,
},
})
const agent = await tx.agent.create({
data: {
id: user.id,
teamId,
type,
enabled: enabled ?? true,
providerId: providerId || null,
modelId: modelId || null,
soul,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config: agentConfig as any,
skills: {
create:
skills?.map((skillId) => ({
skillId,
})) || [],
},
},
})
await tx.teamMember.create({
data: {
teamId,
userId: user.id,
role: 'reviewer', // Default role for agents
},
})
return tx.agent.findUnique({
where: { id: agent.id },
include: { user: true, skills: { include: { skill: true } } },
})
})
}
async updateAgent(params: UpdateAgentParams) {
const {
agentId,
name,
type,
enabled,
avatar,
providerId,
modelId,
thinkingLevel,
systemPrompt,
soul,
skills,
} = params
const agent = await this.prismaClient.agent.findUnique({
where: { id: agentId },
include: { user: { include: { teamMembers: true } } },
})
if (!agent) throw new Error('agent not found')
if (type === 'embedding' || type === 'autofill') {
const existing = await this.prismaClient.agent.findFirst({
where: {
type,
id: { not: agentId },
teamId: agent.teamId,
},
})
if (existing) {
throw new Error(`Agent of type ${type} already exists for this team`)
}
}
if (type === 'chat' || type === 'autofill') {
if (!providerId || !modelId) {
throw new Error('providerId and modelId are required for chat/autofill agents')
}
const model = await this.prismaClient.model.findUnique({
where: { id: modelId },
})
if (!model) throw new Error('model not found')
if (model.providerId !== providerId) {
throw new Error('model does not belong to provider')
}
}
const agentConfig: PrismaJson.AgentConfig = {
provider: providerId || '',
model: modelId || '',
thinkingLevel,
systemPrompt,
}
return this.prismaClient.$transaction(async (tx) => {
await tx.user.update({
where: { id: agentId },
data: {
name,
image: avatar,
},
})
// Update skills: easier to delete all and recreate
await tx.agentSkill.deleteMany({
where: { agentId },
})
return tx.agent.update({
where: { id: agentId },
data: {
type,
enabled: enabled ?? true,
providerId: providerId || null,
modelId: modelId || null,
soul,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config: agentConfig as any,
skills: {
create:
skills?.map((skillId) => ({
skillId,
})) || [],
},
},
include: { user: true, skills: { include: { skill: true } } },
})
})
}
async deleteAgent(params: DeleteAgentParams) {
const { agentId } = params
const agent = await this.prismaClient.agent.findUnique({
where: { id: agentId },
})
if (!agent) throw new Error('agent not found')
// Deleting user will cascade to agent and teamMember due to schema definition
await this.prismaClient.user.delete({
where: { id: agentId },
})
}
async listAgents(params: ListAgentsParams) {
return this.prismaClient.agent.findMany({
where: {
teamId: params.teamId,
},
orderBy: {
id: 'desc',
},
include: {
user: true,
provider: true,
modelRef: true,
skills: {
include: {
skill: true,
},
},
},
})
}
async getSessionEntries(params: { sessionId: string }) {
return this.prismaClient.agentSessionEntry.findMany({
where: { sessionId: params.sessionId },
orderBy: { id: 'asc' },
})
}
}
export const agentService = new AgentService()
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+96
View File
@@ -0,0 +1,96 @@
import { betterAuth } from 'better-auth'
import { prismaAdapter } from 'better-auth/adapters/prisma'
import { prisma } from '@shumai/db'
import { teamService } from '@shumai/core/src/team/team'
import { inviteService } from '@shumai/core/src/invite/invite'
import { createAuthMiddleware } from 'better-auth/api'
export const auth = betterAuth({
database: prismaAdapter(prisma, {
provider: 'postgresql',
}),
emailAndPassword: {
enabled: true,
minPasswordLength: 3,
},
secret: process.env.BETTER_AUTH_SECRET,
// eslint-disable-next-line @typescript-eslint/naming-convention
baseURL: process.env.BETTER_AUTH_URL,
basePath: '/api/auth',
trustedOrigins: ['http://localhost:3000', 'http://127.0.0.1:3000'],
advanced: {
disableCSRFCheck: true,
},
hooks: {
before: createAuthMiddleware(async (ctx) => {
if (ctx.path === '/sign-up/email') {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const body = ctx.body as any
const inviteCode = body?.inviteCode
const info = await teamService.getSignupInfo()
if (info.userCount > 0) {
if (!inviteCode && !info.enablePublicSignup) {
console.log('[Better Auth Hook] Public signup is disabled')
return ctx.json(
{
error: 'Public signup is disabled',
},
{
status: 403,
},
)
}
}
}
}),
after: createAuthMiddleware(async (ctx) => {
if (ctx.path === '/sign-up/email') {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result = ctx.context.returned as any
// Only proceed if the signup was successful and we have a user
if (result && result.user && result.user.id) {
const user = result.user
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const body = ctx.body as any
const inviteCode = body?.inviteCode
try {
const info = await teamService.getSignupInfo()
const defaultTeam = await teamService.ensureDefaultTeam()
// If this is the very first user, make them owner
if (info.userCount === 1) {
await prisma.teamMember.create({
data: {
teamId: defaultTeam.id,
userId: user.id,
role: 'owner',
scope: 'team',
},
})
} else if (!inviteCode) {
// If public signup is enabled and no invite code, add as editor
await prisma.teamMember.create({
data: {
teamId: defaultTeam.id,
userId: user.id,
role: 'editor',
scope: 'team',
},
})
}
if (inviteCode) {
await inviteService.consumeInvite(inviteCode, user.id)
}
} catch (err) {
console.error(`[Better Auth Hook] Error in after hook: ${err}`)
}
}
}
}),
},
})
+400
View File
@@ -0,0 +1,400 @@
import { setupTestDbHooks } from '@shumai/db'
import { describe, expect, it } from 'vitest'
import { prisma } from '@shumai/db'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
describe('AuthzService', () => {
setupTestDbHooks()
it('should test authorization permissions correctly', async () => {
// Setup Data
// Users
const userOwner = await prisma.user.create({
data: { name: 'owner', email: 'owner@example.com', password: 'pass' },
})
const userEditor = await prisma.user.create({
data: { name: 'editor', email: 'editor@example.com', password: 'pass' },
})
const userReviewer = await prisma.user.create({
data: { name: 'reviewer', email: 'reviewer@example.com', password: 'pass' },
})
const userOther = await prisma.user.create({
data: { name: 'other', email: 'other@example.com', password: 'pass' },
})
// Team
const team = await prisma.team.create({
data: { name: 'Team A' },
})
// Memberships
await prisma.teamMember.create({
data: { teamId: team.id, userId: userOwner.id, role: 'owner' },
})
await prisma.teamMember.create({
data: { teamId: team.id, userId: userEditor.id, role: 'editor' },
})
await prisma.teamMember.create({
data: { teamId: team.id, userId: userReviewer.id, role: 'reviewer' },
})
// Project & Asset
const project = await prisma.project.create({
data: { name: 'Project A', teamId: team.id },
})
const asset = await prisma.asset.create({
data: {
name: 'File A',
projectId: project.id,
type: 'file',
status: 'processed',
},
})
// Collection
const collection = await prisma.collection.create({
data: {
name: 'Collection A',
projectId: project.id,
filter: {
sourceFolderId: 'root',
searchFilter: { conditions: [], operator: 'AND', recursively: true, isSemantic: false },
},
},
})
// Project Scope User
const userProjectEditor = await prisma.user.create({
data: { name: 'p_editor', email: 'p_editor@example.com', password: 'pass' },
})
const tmPe = await prisma.teamMember.create({
data: {
teamId: team.id,
userId: userProjectEditor.id,
role: 'reviewer',
scope: 'project',
},
})
await prisma.projectMember.create({
data: { projectId: project.id, teamMemberId: tmPe.id, role: 'editor' },
})
const tests = [
{
name: 'Owner can Admin Project',
req: {
type: ResourceType.Project,
id: project.id,
user: userOwner,
permission: Permission.Admin,
},
wantErr: false,
},
{
name: 'Editor cannot Admin Project',
req: {
type: ResourceType.Project,
id: project.id,
user: userEditor,
permission: Permission.Admin,
},
wantErr: true,
},
{
name: 'Editor can Edit Project',
req: {
type: ResourceType.Project,
id: project.id,
user: userEditor,
permission: Permission.Edit,
},
wantErr: false,
},
{
name: 'Reviewer cannot Edit Project',
req: {
type: ResourceType.Project,
id: project.id,
user: userReviewer,
permission: Permission.Edit,
},
wantErr: true,
},
{
name: 'Reviewer can Read Project',
req: {
type: ResourceType.Project,
id: project.id,
user: userReviewer,
permission: Permission.Read,
},
wantErr: false,
},
{
name: 'Non-member cannot Read Project',
req: {
type: ResourceType.Project,
id: project.id,
user: userOther,
permission: Permission.Read,
},
wantErr: true,
errMessage: 'is not a member of the team',
},
{
name: 'Project Editor can Edit Project',
req: {
type: ResourceType.Project,
id: project.id,
user: userProjectEditor,
permission: Permission.Edit,
},
wantErr: false,
},
{
name: 'Project Editor cannot Admin Project',
req: {
type: ResourceType.Project,
id: project.id,
user: userProjectEditor,
permission: Permission.Admin,
},
wantErr: true,
},
{
name: 'Project Scope User can Read Team',
req: {
type: ResourceType.Team,
id: team.id,
user: userProjectEditor,
permission: Permission.Read,
},
wantErr: false,
},
{
name: 'Project Scope User cannot Edit Team',
req: {
type: ResourceType.Team,
id: team.id,
user: userProjectEditor,
permission: Permission.Edit,
},
wantErr: true,
errMessage: 'User has only project scope',
},
{
name: 'Resolve Context from Asset',
req: {
type: ResourceType.Asset,
id: asset.id,
user: userOwner,
permission: Permission.Edit,
},
wantErr: false,
},
{
name: 'Resolve Context from Collection',
req: {
type: ResourceType.Collection,
id: collection.id,
user: userOwner,
permission: Permission.Edit,
},
wantErr: false,
},
{
name: 'Asset Not Found',
req: {
type: ResourceType.Asset,
id: '01HJXXW6A61234567890ABCDEF',
user: userOwner,
permission: Permission.Read,
},
wantErr: true,
errMessage: 'Asset not found',
},
]
for (const tt of tests) {
if (tt.wantErr) {
let err
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await authzService.hasPermission(tt.req as any)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
err = e
}
expect(err, tt.name).toBeDefined()
if (tt.errMessage) {
expect(err.message).include(tt.errMessage)
}
} else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await expect(authzService.hasPermission(tt.req as any), tt.name).resolves.toBeUndefined()
}
}
})
it('should resolve context correctly for each ResourceType', async () => {
// Setup complete data graph for all types
const team = await prisma.team.create({ data: { name: 'Team X' } })
const project = await prisma.project.create({ data: { name: 'Project X', teamId: team.id } })
// Asset (Project-scoped)
const assetProject = await prisma.asset.create({
data: { name: 'Asset P', projectId: project.id, type: 'file', status: 'processed' },
})
// Asset (Team-scoped root folder fallback)
const assetTeam = await prisma.asset.create({
data: { name: 'Team Root', type: 'root', status: 'processed' },
})
await prisma.team.update({
where: { id: team.id },
data: { rootFolderId: assetTeam.id },
})
// Collection
const collection = await prisma.collection.create({
data: {
name: 'Coll',
projectId: project.id,
filter: {
sourceFolderId: 'root',
searchFilter: { conditions: [], operator: 'AND', recursively: true, isSemantic: false },
},
},
})
// Agent & Session
const user = await prisma.user.create({
data: { name: 'BotUser2', email: 'bot2@example.com', password: 'p' },
})
const agent = await prisma.agent.create({
data: {
id: user.id,
teamId: team.id,
type: 'chat',
enabled: true,
config: { provider: 'openai', model: 'gpt-4o' },
},
})
const agentSession = await prisma.agentSession.create({
data: { agentId: agent.id, cwd: '/tmp' },
})
// Share
const share = await prisma.shareLink.create({
data: { name: 'Share1', rootFolderId: assetProject.id, projectId: project.id },
})
// Metadata Field
const teamField = await prisma.metadataField.create({
data: {
key: 'field_t',
scope: 'TEAM',
teamId: team.id,
config: { name: 'Field T', type: 'text' },
},
})
const projectField = await prisma.metadataField.create({
data: {
key: 'field_p',
scope: 'PROJECT',
projectId: project.id,
config: { name: 'Field P', type: 'text' },
},
})
// Skill
const skill = await prisma.skill.create({
data: { name: 'Skill 1', teamId: team.id, hash: '123', assetId: assetProject.id },
})
// Provider
const provider = await prisma.provider.create({
data: { name: 'Prov 1', teamId: team.id, config: { api: 'openai' } },
})
// Invite
const inviteTeam = await prisma.invite.create({
data: { code: 'inv_t', teamId: team.id, role: 'editor', inviterId: user.id },
})
const inviteProject = await prisma.invite.create({
data: {
code: 'inv_p',
teamId: team.id,
projectId: project.id,
role: 'editor',
inviterId: user.id,
},
})
// Comment
const comment = await prisma.assetComment.create({
data: { assetId: assetProject.id, creatorId: user.id, message: 'hello' },
})
// Test execution via cast
const resolveContext = (type: ResourceType, id: string) =>
(
authzService as unknown as {
resolveContext: (
type: ResourceType,
id: string,
) => Promise<{ teamId: string; projectId?: string }>
}
).resolveContext(type, id)
// Tests
await expect(resolveContext(ResourceType.Team, team.id)).resolves.toEqual({ teamId: team.id })
await expect(resolveContext(ResourceType.Project, project.id)).resolves.toEqual({
teamId: team.id,
projectId: project.id,
})
await expect(resolveContext(ResourceType.Asset, assetProject.id)).resolves.toEqual({
teamId: team.id,
projectId: project.id,
})
await expect(resolveContext(ResourceType.Asset, assetTeam.id)).resolves.toEqual({
teamId: team.id,
})
await expect(resolveContext(ResourceType.Collection, collection.id)).resolves.toEqual({
teamId: team.id,
projectId: project.id,
})
await expect(resolveContext(ResourceType.Agent, agent.id)).resolves.toEqual({ teamId: team.id })
await expect(resolveContext(ResourceType.AgentSession, agentSession.id)).resolves.toEqual({
teamId: team.id,
})
await expect(resolveContext(ResourceType.Share, share.id)).resolves.toEqual({
teamId: team.id,
projectId: project.id,
})
await expect(resolveContext(ResourceType.MetadataField, teamField.key)).resolves.toEqual({
teamId: team.id,
})
await expect(resolveContext(ResourceType.MetadataField, projectField.key)).resolves.toEqual({
teamId: team.id,
projectId: project.id,
})
await expect(resolveContext(ResourceType.Skill, skill.id)).resolves.toEqual({ teamId: team.id })
await expect(resolveContext(ResourceType.Provider, provider.id)).resolves.toEqual({
teamId: team.id,
})
await expect(resolveContext(ResourceType.Invite, inviteTeam.id)).resolves.toEqual({
teamId: team.id,
projectId: undefined,
})
await expect(resolveContext(ResourceType.Invite, inviteProject.id)).resolves.toEqual({
teamId: team.id,
projectId: project.id,
})
await expect(resolveContext(ResourceType.Comment, comment.id)).resolves.toEqual({
teamId: team.id,
projectId: project.id,
})
})
})
+236
View File
@@ -0,0 +1,236 @@
import { prisma } from '@shumai/db'
import type { Prisma } from '@shumai/db'
type User = Prisma.UserGetPayload<Record<string, never>>
export enum Permission {
Read = 'Read',
Edit = 'Edit',
Admin = 'Admin',
}
export enum ResourceType {
Team = 'team',
Project = 'project',
Asset = 'asset',
Collection = 'collection',
Agent = 'agent',
Share = 'share',
MetadataField = 'metadataField',
Skill = 'skill',
Provider = 'provider',
Invite = 'invite',
Comment = 'comment',
AgentSession = 'agentSession',
}
export interface AuthzRequest {
user: User
permission: Permission
type: ResourceType
id: string
}
export class AuthzService {
async hasPermission(req: AuthzRequest): Promise<void> {
if (!req.user) throw new Error('User is required')
const { teamId, projectId } = await this.resolveContext(req.type, req.id)
// 1. Check Team Membership
const member = await prisma.teamMember.findUnique({
where: {
teamIdUserId: {
teamId: teamId,
userId: req.user.id,
},
},
})
if (!member) throw new Error('User is not a member of the team')
// 2. Check Scope
if (member.scope === 'team') {
return this.checkRole(member.role, req.permission)
}
// 3. Scope is Project
if (!projectId) {
// User has project scope but no project context provided (e.g. Team-level resource)
// If it's a team-level resource, project-scoped users shouldn't have access except for Read maybe?
// But usually team resources like Skills/Providers are managed by Team Owners/Editors.
// For now, let's keep the logic: project-scoped users can't access team-level resources unless it's Read (like ListProjects).
if (req.permission === Permission.Read) {
return
}
throw new Error('User has only project scope')
}
// Check Project Membership
const pm = await prisma.projectMember.findUnique({
where: {
projectIdTeamMemberId: {
projectId: projectId,
teamMemberId: member.id,
},
},
})
if (!pm) throw new Error(`User is not a member of project ${projectId}`)
return this.checkRole(pm.role, req.permission)
}
private async resolveContext(
type: ResourceType,
id: string,
): Promise<{ teamId: string; projectId?: string }> {
switch (type) {
case ResourceType.Team:
return { teamId: id }
case ResourceType.Project: {
const proj = await prisma.project.findUnique({
where: { id },
select: { teamId: true },
})
if (!proj) throw new Error('Project not found')
return { teamId: proj.teamId, projectId: id }
}
case ResourceType.Asset: {
const asset = await prisma.asset.findUnique({
where: { id },
select: {
parentId: true,
teamRootFolder: { select: { id: true } },
project: { select: { id: true, teamId: true } },
},
})
if (!asset) throw new Error('Asset not found')
if (asset.project) {
return { teamId: asset.project.teamId, projectId: asset.project.id }
}
if (asset.teamRootFolder) {
return { teamId: asset.teamRootFolder.id }
}
if (asset.parentId) {
// If it's a nested asset, we might need recursive lookup.
// However, in this project, assets typically have projectId if they are in a project.
// If parentId is set but no project, it might be in a team root folder.
// For now, let's try to get context from parent.
return this.resolveContext(ResourceType.Asset, asset.parentId)
}
throw new Error('Could not resolve context for asset')
}
case ResourceType.Collection: {
const coll = await prisma.collection.findUnique({
where: { id },
include: { project: true },
})
if (!coll) throw new Error('Collection not found')
return { teamId: coll.project.teamId, projectId: coll.projectId }
}
case ResourceType.Agent: {
const agent = await prisma.agent.findUnique({
where: { id },
select: { teamId: true },
})
if (!agent) throw new Error('Agent not found')
return { teamId: agent.teamId }
}
case ResourceType.AgentSession: {
const session = await prisma.agentSession.findUnique({
where: { id },
include: { agent: true },
})
if (!session) throw new Error('Agent session not found')
return { teamId: session.agent.teamId }
}
case ResourceType.Share: {
const share = await prisma.shareLink.findUnique({
where: { id },
include: { project: true },
})
if (!share) throw new Error('Share not found')
return { teamId: share.project.teamId, projectId: share.projectId }
}
case ResourceType.MetadataField: {
const field = await prisma.metadataField.findUnique({
where: { key: id },
select: { teamId: true, projectId: true },
})
if (!field) throw new Error('Metadata field not found')
if (field.projectId) {
const proj = await prisma.project.findUnique({
where: { id: field.projectId },
select: { teamId: true },
})
return { teamId: proj!.teamId, projectId: field.projectId }
}
if (!field.teamId) throw new Error('Metadata field has no context')
return { teamId: field.teamId }
}
case ResourceType.Skill: {
const skill = await prisma.skill.findUnique({
where: { id },
select: { teamId: true },
})
if (!skill) throw new Error('Skill not found')
return { teamId: skill.teamId }
}
case ResourceType.Provider: {
const provider = await prisma.provider.findUnique({
where: { id },
select: { teamId: true },
})
if (!provider) throw new Error('Provider not found')
return { teamId: provider.teamId }
}
case ResourceType.Invite: {
const invite = await prisma.invite.findUnique({
where: { id },
select: { teamId: true, projectId: true },
})
if (!invite) throw new Error('Invite not found')
return { teamId: invite.teamId, projectId: invite.projectId ?? undefined }
}
case ResourceType.Comment: {
const comment = await prisma.assetComment.findUnique({
where: { id },
include: { asset: { include: { project: true } } },
})
if (!comment) throw new Error('Comment not found')
if (!comment.asset.project) throw new Error('Comment asset has no project')
return { teamId: comment.asset.project.teamId, projectId: comment.asset.projectId! }
}
default:
throw new Error(`Unsupported resource type: ${type}`)
}
}
private checkRole(role: string, permission: Permission): void {
switch (permission) {
case Permission.Read:
return
case Permission.Edit:
if (role === 'owner' || role === 'editor') return
break
case Permission.Admin:
if (role === 'owner') return
break
}
throw new Error('Permission denied')
}
}
export const authzService = new AuthzService()
@@ -0,0 +1,149 @@
import { describe, it, expect } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import { collectionService } from './collection'
import { projectService } from '../project/project'
describe('CollectionService', () => {
setupTestDbHooks()
async function setupProject() {
const user = await prisma.user.create({
data: { name: 'Test User', email: 'test@example.com' },
})
const team = await prisma.team.create({
data: {
name: 'Test Team',
settings: {
enablePublicSignup: true,
transcode: { videoStrategy: 'best_match' },
},
sandbox: { create: {} },
},
})
await prisma.teamMember.create({
data: {
teamId: team.id,
userId: user.id,
role: 'owner',
scope: 'team',
},
})
const project = await projectService.createProject(user, {
teamId: team.id,
name: 'Test Project',
})
return { team, project }
}
it('can create, get, update, and delete a collection', async () => {
const { project } = await setupProject()
// Create
const collection = await collectionService.createCollection(project.id, {
name: 'Test Collection',
filter: {
sourceFolderId: project.rootFolder!,
searchFilter: {
operator: 'AND',
conditions: [{ field: 'name', operator: 'contains', value: 'test' }],
recursively: true,
isSemantic: false,
},
},
})
expect(collection.name).toBe('Test Collection')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((collection.filter as any).searchFilter.conditions[0].value).toBe('test')
// Get
const fetched = await collectionService.getCollection(collection.id)
expect(fetched?.id).toBe(collection.id)
// Update
const updated = await collectionService.updateCollection(collection.id, {
name: 'Updated Name',
filter: {
sourceFolderId: project.rootFolder!,
searchFilter: {
operator: 'AND',
conditions: [{ field: 'rating', operator: 'eq', value: 5 }],
recursively: true,
isSemantic: false,
},
},
})
expect(updated.name).toBe('Updated Name')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((updated.filter as any).searchFilter.conditions[0].field).toBe('rating')
// Delete
await collectionService.deleteCollection(collection.id)
const deleted = await collectionService.getCollection(collection.id)
expect(deleted).toBeNull()
})
it('can list collections for a project with pagination', async () => {
const { project } = await setupProject()
// Create multiple collections
for (let i = 0; i < 5; i++) {
await collectionService.createCollection(project.id, {
name: `Collection ${i}`,
filter: {
sourceFolderId: project.rootFolder!,
searchFilter: { operator: 'AND', conditions: [], recursively: true, isSemantic: false },
},
})
}
// List first page
const list1 = await collectionService.listCollections(project.id, {
first: 2,
includeCount: true,
})
expect(list1.data.length).toBe(2)
expect(list1.pageInfo.total).toBe(5)
expect(list1.pageInfo.cursor).toBeDefined()
// List second page
const list2 = await collectionService.listCollections(project.id, {
first: 2,
after: list1.pageInfo.cursor,
})
expect(list2.data.length).toBe(2)
expect(list2.data[0].name).not.toBe(list1.data[0].name)
// List last page
const list3 = await collectionService.listCollections(project.id, {
first: 2,
after: list2.pageInfo.cursor,
})
expect(list3.data.length).toBe(1)
expect(list3.pageInfo.cursor).toBeUndefined()
})
it('cascades delete when project is deleted', async () => {
const { project } = await setupProject()
await collectionService.createCollection(project.id, {
name: 'To be deleted',
filter: {
sourceFolderId: project.rootFolder!,
searchFilter: { operator: 'AND', conditions: [], recursively: true, isSemantic: false },
},
})
const countBefore = await prisma.collection.count({
where: { projectId: project.id },
})
expect(countBefore).toBe(1)
await projectService.deleteProject(project.id)
const countAfter = await prisma.collection.count({
where: { projectId: project.id },
})
expect(countAfter).toBe(0)
})
})
@@ -0,0 +1,59 @@
import { prisma } from '@shumai/db'
import { paginateQuery } from '../pagination'
import {
CreateCollectionRequest,
UpdateCollectionRequest,
ListCollectionsRequest,
} from '@shumai/dtos'
export class CollectionService {
async createCollection(projectId: string, req: CreateCollectionRequest) {
return await prisma.collection.create({
data: {
name: req.name,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
filter: req.filter as any,
projectId,
},
})
}
async updateCollection(collectionId: string, req: UpdateCollectionRequest) {
return await prisma.collection.update({
where: { id: collectionId },
data: {
...(req.name && { name: req.name }),
// eslint-disable-next-line @typescript-eslint/no-explicit-any
...(req.filter && { filter: req.filter as any }),
},
})
}
async deleteCollection(collectionId: string) {
return await prisma.collection.delete({
where: { id: collectionId },
})
}
async getCollection(collectionId: string) {
return await prisma.collection.findUnique({
where: { id: collectionId },
})
}
async listCollections(projectId: string, req: ListCollectionsRequest) {
return await paginateQuery(
(skip, take) =>
prisma.collection.findMany({
where: { projectId },
orderBy: { id: 'desc' },
skip,
take,
}),
() => prisma.collection.count({ where: { projectId } }),
req,
)
}
}
export const collectionService = new CollectionService()
+27
View File
@@ -0,0 +1,27 @@
import { describe, expect, it } from 'vitest'
import { marshal, unmarshal } from './hyrumtoken'
const testkey = new Uint8Array([
24, 12, 15, 90, 143, 133, 171, 28, 34, 75, 185, 194, 102, 93, 165, 183, 235, 96, 135, 135, 165, 1,
129, 91, 32, 7, 139, 135, 130, 2, 241, 168,
])
describe('hyrumtoken', () => {
it('encodes and decodes', () => {
const data = { Foo: 'foo', Bar: 'bar' }
const encoded = marshal(testkey, data)
const out = unmarshal(testkey, encoded)
expect(out).toEqual(data)
})
it('unmarshals empty string to null', () => {
const out = unmarshal(testkey, '')
expect(out).toBeNull()
})
it('unmarshals known string', () => {
const token = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAULRUMRVA4GIqe5Y8N_z8B4J7hw'
const out = unmarshal(testkey, token)
expect(out).toBe(123)
})
})
+35
View File
@@ -0,0 +1,35 @@
import { Buffer } from 'buffer'
import nacl from 'tweetnacl'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function marshal(key: Uint8Array, v: any): string {
const b = Buffer.from(JSON.stringify(v), 'utf8')
const nonce = nacl.randomBytes(nacl.secretbox.nonceLength)
const d = nacl.secretbox(b, nonce, key)
const combined = Buffer.concat([nonce, d])
return combined.toString('base64url')
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function unmarshal(key: Uint8Array, s: string): any {
if (!s) {
return null
}
const combined = Buffer.from(s, 'base64url')
if (combined.length < nacl.secretbox.nonceLength) {
throw new Error('token too short')
}
const nonce = combined.subarray(0, nacl.secretbox.nonceLength)
const d = combined.subarray(nacl.secretbox.nonceLength)
const b = nacl.secretbox.open(d, nonce, key)
if (!b) {
throw new Error('decrypt token failed')
}
const jsonStr = Buffer.from(b).toString('utf8')
return JSON.parse(jsonStr)
}
+20
View File
@@ -0,0 +1,20 @@
export * from './agent/agent'
export * from './asset/asset'
export * from './auth/auth'
export * from './authz/authz'
export * from './collection/collection'
export * from './invite/invite'
export * from './metadata/metadata'
export * from './notification/notification'
export * from './project/project'
export * from './provider/provider'
export * from './s3/s3'
export * from './search/search'
export * from './share/share'
export * from './skill/skill'
export * from './team/team'
export * from './upload/upload'
export * from './user-metadata/user-metadata'
export * from './versionStack/versionStack'
export * from './hyrumtoken'
export * from './pagination'
+144
View File
@@ -0,0 +1,144 @@
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import { inviteService } from '@shumai/core/src/invite/invite'
import { beforeEach, describe, expect, it } from 'vitest'
describe('Invite Service', () => {
setupTestDbHooks()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let admin: any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let team: any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let project: any
beforeEach(async () => {
admin = await prisma.user.create({
data: { name: 'admin', email: 'admin-invite@example.com', password: 'pass' },
})
team = await prisma.team.create({
data: { name: 'Team A' },
})
await prisma.teamMember.create({
data: {
teamId: team.id,
userId: admin.id,
role: 'owner',
scope: 'team',
},
})
project = await prisma.project.create({
data: { name: 'Project A', teamId: team.id },
})
})
it('handles Team Invite', async () => {
const inv = await inviteService.createTeamInvite({
teamId: team.id,
role: 'editor',
inviterId: admin.id,
})
expect(inv.code).toBeDefined()
expect(inv.teamId).toBe(team.id)
const newUser = await prisma.user.create({
data: { name: 'user1', email: 'user1-invite@example.com', password: 'password' },
})
await inviteService.consumeInvite(inv.code, newUser.id)
const tm = await prisma.teamMember.findUnique({
where: {
teamIdUserId: { teamId: team.id, userId: newUser.id },
},
})
expect(tm).toBeDefined()
expect(tm?.role).toBe('editor')
expect(tm?.scope).toBe('team')
const dbInv = await prisma.invite.findUnique({ where: { code: inv.code } })
expect(dbInv?.used).toBe(true)
await expect(inviteService.consumeInvite(inv.code, newUser.id)).rejects.toThrow(
'invite code already used',
)
})
it('handles Project Invite', async () => {
const inv = await inviteService.createProjectInvite({
projectId: project.id,
role: 'editor',
inviterId: admin.id,
})
expect(inv.code).toBeDefined()
expect(inv.projectId).toBe(project.id)
const newUser = await prisma.user.create({
data: { name: 'user2', email: 'user2-invite@example.com', password: 'password' },
})
await inviteService.consumeInvite(inv.code, newUser.id)
const tm = await prisma.teamMember.findUnique({
where: {
teamIdUserId: { teamId: team.id, userId: newUser.id },
},
include: { projectMembers: true },
})
expect(tm).toBeDefined()
expect(tm?.role).toBe('reviewer')
expect(tm?.scope).toBe('project')
expect(tm?.projectMembers.length).toBe(1)
expect(tm?.projectMembers[0].projectId).toBe(project.id)
expect(tm?.projectMembers[0].role).toBe('editor')
const dbInv = await prisma.invite.findUnique({ where: { code: inv.code } })
expect(dbInv?.used).toBe(true)
})
it('handles Upgrade Scope', async () => {
const user3 = await prisma.user.create({
data: { name: 'user3', email: 'user3-invite@example.com', password: 'pass' },
})
const tm = await prisma.teamMember.create({
data: {
teamId: team.id,
userId: user3.id,
role: 'reviewer',
scope: 'project',
},
})
await prisma.projectMember.create({
data: {
projectId: project.id,
teamMemberId: tm.id,
role: 'editor',
},
})
const inv = await inviteService.createTeamInvite({
teamId: team.id,
role: 'editor',
inviterId: admin.id,
})
await inviteService.consumeInvite(inv.code, user3.id)
const updatedTm = await prisma.teamMember.findUnique({
where: { id: tm.id },
})
expect(updatedTm?.scope).toBe('team')
expect(updatedTm?.role).toBe('editor')
})
})
+151
View File
@@ -0,0 +1,151 @@
import { prisma } from '@shumai/db'
import { InviteRole, ProjectMemberRole, TeamMemberRole } from '@shumai/db'
import { ulid } from 'ulid'
export interface CreateTeamInviteRequest {
teamId: string
role: InviteRole
inviterId: string
}
export interface CreateProjectInviteRequest {
projectId: string
role: InviteRole
inviterId: string
}
export class InviteService {
async createTeamInvite(req: CreateTeamInviteRequest) {
const code = ulid()
const inv = await prisma.invite.create({
data: {
code,
teamId: req.teamId,
inviterId: req.inviterId,
role: req.role,
},
})
return this.getInvite(inv.code)
}
async createProjectInvite(req: CreateProjectInviteRequest) {
const project = await prisma.project.findUniqueOrThrow({
where: { id: req.projectId },
include: { team: true },
})
const code = ulid()
const inv = await prisma.invite.create({
data: {
code,
teamId: project.teamId,
projectId: project.id,
inviterId: req.inviterId,
role: req.role,
},
})
return this.getInvite(inv.code)
}
async getInvite(code: string) {
const inv = await prisma.invite.findUniqueOrThrow({
where: { code },
include: {
team: true,
project: true,
inviter: true,
},
})
return inv
}
async consumeInvite(code: string, userId: string): Promise<void> {
await prisma.$transaction(async (tx) => {
const inv = await tx.invite.findUniqueOrThrow({
where: { code },
include: { team: true, project: true },
})
if (inv.used) {
throw new Error('invite code already used')
}
const user = await tx.user.findUniqueOrThrow({
where: { id: userId },
})
let tm = await tx.teamMember.findUnique({
where: {
teamIdUserId: {
teamId: inv.teamId,
userId: user.id,
},
},
})
if (!inv.projectId) {
// Team Invite
if (tm) {
if (tm.scope === 'project') {
await tx.teamMember.update({
where: { id: tm.id },
data: {
scope: 'team',
role: inv.role as unknown as TeamMemberRole,
},
})
}
} else {
await tx.teamMember.create({
data: {
teamId: inv.teamId,
userId: user.id,
role: inv.role as unknown as TeamMemberRole,
scope: 'team',
},
})
}
} else {
// Project Invite
if (!tm) {
tm = await tx.teamMember.create({
data: {
teamId: inv.teamId,
userId: user.id,
role: 'reviewer', // default fallback for project scope TeamMember
scope: 'project',
},
})
}
const pm = await tx.projectMember.findUnique({
where: {
projectIdTeamMemberId: {
projectId: inv.projectId,
teamMemberId: tm.id,
},
},
})
if (!pm) {
await tx.projectMember.create({
data: {
projectId: inv.projectId,
teamMemberId: tm.id,
role: inv.role as unknown as ProjectMemberRole,
},
})
}
}
await tx.invite.update({
where: { id: inv.id },
data: { used: true },
})
})
}
}
export const inviteService = new InviteService()
+207
View File
@@ -0,0 +1,207 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { MetadataService } from './metadata'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
describe('MetadataService', () => {
setupTestDbHooks()
let metadataService: MetadataService
beforeEach(() => {
metadataService = new MetadataService()
})
it('should initialize system fields', async () => {
await metadataService.syncSystemFields()
const fields = await prisma.metadataField.findMany({
where: { scope: 'SYSTEM' },
})
expect(fields.length).toBeGreaterThan(0)
// Test idempotency
await metadataService.syncSystemFields()
const fields2 = await prisma.metadataField.findMany({
where: { scope: 'SYSTEM' },
})
expect(fields2.length).toBe(fields.length)
})
it('ProjectFieldsOrder', async () => {
const user = await prisma.user.create({
data: { name: 'test-user', email: 'test-user@example.com', password: 'password' },
})
const team = await prisma.team.create({
data: { name: 'test-team' },
})
const project = await prisma.project.create({
data: { name: 'test-project', teamId: team.id },
})
const field1 = await prisma.metadataField.create({
data: {
key: 'field1',
scope: 'PROJECT',
project: { connect: { id: project.id } },
config: { name: 'Field A', type: 'text' },
},
})
const field2 = await prisma.metadataField.create({
data: {
key: 'field2',
scope: 'PROJECT',
project: { connect: { id: project.id } },
config: { name: 'Field B', type: 'text' },
},
})
const field3 = await prisma.metadataField.create({
data: {
key: 'field3',
scope: 'PROJECT',
project: { connect: { id: project.id } },
config: { name: 'Field C', type: 'text' },
},
})
const order = [
{ fieldId: field3.key, visible: true },
{ fieldId: field1.key, visible: false },
]
await metadataService.updateProjectFieldsOrder(user.id, project.id, order)
const fields = await metadataService.listProjectFields(user.id, project.id)
// Filter out system and team fields for simple comparison
const projectFields = fields.filter((f) => f.field.scope === 'PROJECT')
expect(projectFields.length).toBe(3)
// Check order and visibility
expect(projectFields[0].field.key).toBe(field3.key)
expect(projectFields[0].visible).toBe(true)
expect(projectFields[1].field.key).toBe(field1.key)
expect(projectFields[1].visible).toBe(false)
expect(projectFields[2].field.key).toBe(field2.key)
expect(projectFields[2].visible).toBe(false)
})
it('AIAutofillAndDescription', async () => {
const team = await prisma.team.create({
data: { name: 'test-team' },
})
await prisma.project.create({
data: { name: 'test-project', teamId: team.id },
})
const desc = 'This is a test description'
// Instead of testing service create method which failed due to connection scope, we test service update
const teamField = await prisma.metadataField.create({
data: {
key: 'teamfield1',
scope: 'TEAM',
team: { connect: { id: team.id } },
config: { name: 'Test Team Field', type: 'text' },
aiAutofill: true,
description: desc,
},
})
const newDesc = 'Updated description'
const updatedTeamField = await metadataService.updateTeamField(team.id, teamField.key, {
config: { name: 'Test Team Field', type: 'text' },
aiAutofill: false,
description: newDesc,
})
expect(updatedTeamField.aiAutofill).toBe(false)
expect(updatedTeamField.description).toBe(newDesc)
// IDOR test
await expect(
metadataService.updateTeamField('wrong-team-id', teamField.key, {
config: { name: 'Hack', type: 'text' },
}),
).rejects.toThrow('Field does not belong to this team')
})
it('UpdateAssetMetadata', async () => {
const team = await prisma.team.create({
data: { name: 'test-team' },
})
const project = await prisma.project.create({
data: { name: 'test-project', teamId: team.id },
})
const asset = await prisma.asset.create({
data: {
name: 'test-asset',
project: { connect: { id: project.id } },
type: 'file',
status: 'uploaded',
sizeByte: 100,
},
})
const reqs = [
{ key: 'resolution_width', value: 1920 },
{ key: 'resolution_height', value: 1080 },
]
await metadataService.updateAssetMetadata(asset.id, reqs)
const values = await prisma.assetMetadataValue.findMany({
where: { assetId: asset.id },
})
expect(values).toHaveLength(2)
const width = values.find((v) => v.fieldKey === 'resolution_width')
expect(width?.numberValue).toBe(1920)
const height = values.find((v) => v.fieldKey === 'resolution_height')
expect(height?.numberValue).toBe(1080)
})
it('should reject updating read-only fields', async () => {
const team = await prisma.team.create({
data: { name: 'test-team' },
})
const project = await prisma.project.create({
data: { name: 'test-project', teamId: team.id },
})
const asset = await prisma.asset.create({
data: {
name: 'test-asset',
project: { connect: { id: project.id } },
type: 'file',
status: 'uploaded',
sizeByte: 100,
},
})
// Create a read-only metadata field
const field = await prisma.metadataField.create({
data: {
key: 'readonly-field',
scope: 'PROJECT',
project: { connect: { id: project.id } },
config: { name: 'Readonly Field', type: 'text' },
readOnly: true,
},
})
const reqs = [{ key: field.key, value: 'some value' }]
await expect(metadataService.updateAssetMetadata(asset.id, reqs)).rejects.toThrow(
'Field readonly-field is read-only',
)
// With allowReadOnly=true, it should successfully update
await metadataService.updateAssetMetadata(asset.id, reqs, true)
const val = await prisma.assetMetadataValue.findUnique({
where: {
// eslint-disable-next-line @typescript-eslint/naming-convention
assetId_fieldKey: {
assetId: asset.id,
fieldKey: field.key,
},
},
})
expect(val?.stringValue).toBe('some value')
})
})
+347
View File
@@ -0,0 +1,347 @@
import { prisma } from '@shumai/db'
import {
CreateFieldRequest,
ProjectFieldOrder,
UpdateAssetMetadataRequest,
UpdateFieldRequest,
} from '@shumai/dtos'
import type { Prisma } from '@shumai/db'
import { ulid } from 'ulid'
import { assetService } from '../asset/asset'
import { systemFields } from './system_fields'
export class MetadataService {
constructor(private client: typeof prisma = prisma) {}
async syncSystemFields(): Promise<void> {
await this.client.$transaction(async (tx) => {
for (const field of systemFields) {
await tx.metadataField.upsert({
where: { key: field.key },
update: {
scope: field.scope,
readOnly: field.readOnly,
config: field.config,
},
create: {
key: field.key,
scope: field.scope,
readOnly: field.readOnly ?? false,
config: field.config,
},
})
}
})
}
async createTeamField(
teamId: string,
req: CreateFieldRequest,
): Promise<Prisma.MetadataFieldGetPayload<Record<string, never>>> {
const f = await this.client.metadataField.create({
data: {
key: ulid(),
scope: 'TEAM',
teamId: teamId,
config: req.config,
aiAutofill: req.aiAutofill,
description: req.description,
},
})
return f
}
async listTeamFields(
teamId: string,
): Promise<Prisma.MetadataFieldGetPayload<Record<string, never>>[]> {
const fields = await this.client.metadataField.findMany({
where: {
OR: [
{ scope: 'SYSTEM' },
{
AND: [{ scope: 'TEAM' }, { teamId: teamId }],
},
],
},
})
return fields
}
async getFieldByKey(
key: string,
): Promise<Prisma.MetadataFieldGetPayload<Record<string, never>> | null> {
return this.client.metadataField.findUnique({
where: { key },
})
}
async updateTeamField(
teamId: string,
fieldId: string,
req: UpdateFieldRequest,
): Promise<Prisma.MetadataFieldGetPayload<Record<string, never>>> {
const field = await this.client.metadataField.findUnique({
where: { key: fieldId },
})
if (!field) throw new Error('Field not found')
if (field.teamId !== teamId) throw new Error('Field does not belong to this team')
const updated = await this.client.metadataField.update({
where: { id: field.id },
data: {
config: req.config,
aiAutofill: req.aiAutofill ?? field.aiAutofill,
description: req.description ?? field.description,
},
})
return updated
}
async deleteTeamField(teamId: string, fieldId: string): Promise<void> {
const field = await this.client.metadataField.findUnique({
where: { key: fieldId },
})
if (!field) throw new Error('Field not found')
if (field.teamId !== teamId) throw new Error('Field does not belong to this team')
await this.client.metadataField.delete({
where: { key: fieldId },
})
}
async createProjectField(
projectId: string,
req: CreateFieldRequest,
): Promise<Prisma.MetadataFieldGetPayload<Record<string, never>>> {
const p = await this.client.project.findUnique({
where: { id: projectId },
select: { teamId: true },
})
if (!p) throw new Error('Project not found')
const f = await this.client.metadataField.create({
data: {
key: ulid(),
scope: 'PROJECT',
projectId: projectId,
teamId: p.teamId,
config: req.config,
aiAutofill: req.aiAutofill,
description: req.description,
},
})
return f
}
async listProjectFields(
userId: string | null,
projectId: string,
): Promise<{ field: Prisma.MetadataFieldGetPayload<Record<string, never>>; visible: boolean }[]> {
const p = await this.client.project.findUnique({
where: { id: projectId },
select: { teamId: true },
})
if (!p) throw new Error('Project not found')
const fields = await this.client.metadataField.findMany({
where: {
OR: [
{ scope: 'SYSTEM' },
{
AND: [{ scope: 'TEAM' }, { teamId: p.teamId }],
},
{
AND: [{ scope: 'PROJECT' }, { projectId: projectId }],
},
],
},
})
const order = userId ? await this.getProjectFieldsOrder(userId, projectId) : []
const orderMap = new Map<string, number>()
order.forEach((o, index) => {
orderMap.set(o.fieldId, index)
})
const visibleMap = new Map<string, boolean>()
order.forEach((o) => {
visibleMap.set(o.fieldId, o.visible)
})
const res = fields.map((f) => ({
field: f,
visible: visibleMap.has(f.key) ? visibleMap.get(f.key)! : userId === null, // All fields visible by default for public if not ordered
}))
res.sort((a, b) => {
const aOrder = orderMap.get(a.field.key)
const bOrder = orderMap.get(b.field.key)
if (aOrder !== undefined && bOrder !== undefined) {
return aOrder - bOrder
}
if (aOrder !== undefined) return -1
if (bOrder !== undefined) return 1
const aName = a.field.config?.name || ''
const bName = b.field.config?.name || ''
return aName.localeCompare(bName)
})
return res
}
private async getProjectFieldsOrder(
userId: string,
projectId: string,
): Promise<ProjectFieldOrder[]> {
const key = this.getProjectFieldOrderKey(userId, projectId)
const m = await this.client.systemSettings.findUnique({
where: { key },
})
if (!m || !m.value) return []
const order = m.value as ProjectFieldOrder[]
return order
}
async updateProjectFieldsOrder(
userId: string,
projectId: string,
order: ProjectFieldOrder[],
): Promise<void> {
const key = this.getProjectFieldOrderKey(userId, projectId)
await this.client.systemSettings.upsert({
where: { key },
create: {
key,
value: order,
},
update: {
value: order,
},
})
}
private getProjectFieldOrderKey(userId: string, projectId: string): string {
return `project_field_order:${userId}:${projectId}`
}
async updateProjectField(
projectId: string,
fieldId: string, // actually 'key'
req: UpdateFieldRequest,
): Promise<Prisma.MetadataFieldGetPayload<Record<string, never>>> {
const field = await this.client.metadataField.findUnique({
where: { key: fieldId },
})
if (!field) throw new Error('Field not found')
if (field.projectId !== projectId) throw new Error('Field does not belong to this project')
const updated = await this.client.metadataField.update({
where: { id: field.id },
data: {
config: req.config,
aiAutofill: req.aiAutofill ?? field.aiAutofill,
description: req.description ?? field.description,
},
})
return updated
}
async deleteProjectField(projectId: string, fieldId: string): Promise<void> {
const field = await this.client.metadataField.findUnique({
where: { key: fieldId },
})
if (!field) throw new Error('Field not found')
if (field.projectId !== projectId) throw new Error('Field does not belong to this project')
await this.client.metadataField.delete({
where: { key: fieldId },
})
}
async updateAssetMetadata(
assetId: string,
reqs: UpdateAssetMetadataRequest[],
allowReadOnly = false,
): Promise<void> {
const resolvedAssetId = await assetService.resolveLatestVersionId(assetId)
await this.client.$transaction(async (tx) => {
for (const req of reqs) {
const field = await tx.metadataField.findUnique({
where: { key: req.key },
})
if (field?.readOnly && !allowReadOnly) {
throw new Error(`Field ${field.key} is read-only`)
}
const value = req.value
let stringValue: string | null = null
let numberValue: number | null = null
let booleanValue: boolean | null = null
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let jsonValue: any = null
let dateValue: Date | null = null
if (typeof value === 'string') {
// Check if it's a valid ISO date string
const date = new Date(value)
if (!isNaN(date.getTime()) && value.includes('T') && value.includes('-')) {
dateValue = date
} else {
stringValue = value
}
} else if (typeof value === 'number') {
numberValue = value
} else if (typeof value === 'boolean') {
booleanValue = value
} else if (value instanceof Date) {
dateValue = value
} else if (Array.isArray(value)) {
jsonValue = value
} else if (value === null) {
// all null
} else if (typeof value === 'object') {
jsonValue = value
} else {
stringValue = String(value)
}
await tx.assetMetadataValue.upsert({
where: {
// eslint-disable-next-line @typescript-eslint/naming-convention
assetId_fieldKey: {
assetId: resolvedAssetId,
fieldKey: req.key,
},
},
create: {
assetId: resolvedAssetId,
fieldKey: req.key,
stringValue,
numberValue,
booleanValue,
jsonValue,
dateValue,
},
update: {
stringValue,
numberValue,
booleanValue,
jsonValue,
dateValue,
},
})
}
// Touch asset
await tx.asset.update({
where: { id: resolvedAssetId },
data: {
updatedAt: new Date(),
},
})
})
}
}
export const metadataService = new MetadataService()
+191
View File
@@ -0,0 +1,191 @@
import type { Prisma } from '@shumai/db'
import '@shumai/db/src/prisma-json-types'
export const systemFields: Prisma.MetadataFieldCreateInput[] = [
{
key: 'file_size',
scope: 'SYSTEM',
readOnly: true,
config: {
name: 'File Size',
type: 'number',
number: { scale: 0 },
},
},
{
key: 'resolution_width',
scope: 'SYSTEM',
readOnly: true,
config: {
name: 'Resolution Width',
type: 'number',
number: { scale: 0 },
},
},
{
key: 'resolution_height',
scope: 'SYSTEM',
readOnly: true,
config: {
name: 'Resolution Height',
type: 'number',
number: { scale: 0 },
},
},
{
key: 'name',
scope: 'SYSTEM',
readOnly: true,
config: {
name: 'Name',
type: 'text',
text: {},
},
},
{
key: 'rating',
scope: 'SYSTEM',
readOnly: false,
config: {
name: 'Rating',
type: 'rating',
rating: { maxValue: 5 },
},
},
{
key: 'duration',
scope: 'SYSTEM',
readOnly: true,
config: {
name: 'Duration',
type: 'number',
number: { scale: 0 },
},
},
{
key: 'bitRate',
scope: 'SYSTEM',
readOnly: true,
config: {
name: 'Bit Rate',
type: 'number',
number: { scale: 1 },
},
},
{
key: 'frame_rate',
scope: 'SYSTEM',
readOnly: true,
config: {
name: 'Frame Rate',
type: 'number',
number: { scale: 3 },
},
},
{
key: 'keywords',
scope: 'SYSTEM',
readOnly: false,
config: {
name: 'Keywords',
type: 'selectMulti',
selectMulti: {
options: [],
},
},
},
{
key: 'file_type',
scope: 'SYSTEM',
readOnly: true,
config: {
name: 'File Type',
type: 'select',
select: {
options: [
{ id: 'video', displayName: 'Video', color: 'system' },
{ id: 'audio', displayName: 'Audio', color: 'system' },
{ id: 'image', displayName: 'Image', color: 'system' },
{ id: 'document', displayName: 'Document', color: 'system' },
{ id: 'file', displayName: 'File', color: 'system' },
],
},
},
},
{
key: 'audio_bit_depth',
scope: 'SYSTEM',
readOnly: true,
config: {
name: 'Audio Bit Depth',
type: 'number',
number: { scale: 0 },
},
},
{
key: 'audio_channels',
scope: 'SYSTEM',
readOnly: true,
config: {
name: 'Audio Channels',
type: 'number',
number: { scale: 0 },
},
},
{
key: 'audio_codec',
scope: 'SYSTEM',
readOnly: true,
config: {
name: 'Audio Codec',
type: 'text',
text: {},
},
},
{
key: 'audio_sample_rate',
scope: 'SYSTEM',
readOnly: true,
config: {
name: 'Audio Sample Rate',
type: 'number',
number: { scale: 0 },
},
},
{
key: 'video_codec',
scope: 'SYSTEM',
readOnly: true,
config: {
name: 'Video Codec',
type: 'text',
text: {},
},
},
{
key: 'format',
scope: 'SYSTEM',
readOnly: true,
config: {
name: 'Format',
type: 'text',
text: {},
},
},
{
key: 'status',
scope: 'SYSTEM',
readOnly: false,
config: {
name: 'Status',
type: 'select',
select: {
options: [
{ id: 'needs_review', displayName: 'Needs Review', color: 'red' },
{ id: 'in_progress', displayName: 'In Progress', color: 'yellow' },
{ id: 'approved', displayName: 'Approved', color: 'green' },
],
},
},
},
]
@@ -0,0 +1,365 @@
import { describe, expect, it } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import { NotificationType } from '@shumai/db'
import { notificationService } from './notification'
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
describe('NotificationService', () => {
setupTestDbHooks()
it('Create basic notification', async () => {
const tm = await prisma.team.create({ data: { name: 'Team 1' } })
const u1 = await prisma.user.create({
data: { name: 'u1', email: `u1-${Date.now()}@example.com`, password: 'p' },
})
const p = await prisma.project.create({ data: { name: 'Project 1', teamId: tm.id } })
const svc = notificationService
await svc['createAsync']({
type: NotificationType.comment_created,
teamId: tm.id,
projectId: p.id,
creatorId: u1.id,
})
const count = await prisma.notification.count()
expect(count).toBe(1)
const n = await prisma.notification.findFirst()
expect(n?.type).toBe(NotificationType.comment_created)
expect(n?.teamId).toBe(tm.id)
expect(n?.projectId).toBe(p.id)
expect(n?.creatorId).toBe(u1.id)
})
it('Create mention notification', async () => {
const tm = await prisma.team.create({ data: { name: 'Team 1' } })
const u1 = await prisma.user.create({
data: { name: 'u1', email: 'u1-mention@example.com', password: 'p' },
})
const u2 = await prisma.user.create({
data: { name: 'u2', email: 'u2-mention@example.com', password: 'p' },
})
const p = await prisma.project.create({ data: { name: 'Project 1', teamId: tm.id } })
const svc = notificationService
const msg = `Hello <@${u2.id}>`
await svc['createAsync']({
type: NotificationType.comment_created,
teamId: tm.id,
projectId: p.id,
creatorId: u1.id,
commentMessage: msg,
})
const count = await prisma.notification.count()
expect(count).toBe(2) // 1 comment, 1 mention
const mentions = await prisma.notification.findMany({
where: { type: NotificationType.mention },
})
expect(mentions).toHaveLength(1)
expect(mentions[0].userId).toBe(u2.id)
})
it('Disabled project notification', async () => {
const tm = await prisma.team.create({ data: { name: 'Team 1' } })
const u1 = await prisma.user.create({
data: { name: 'u1', email: 'u1-disabled@example.com', password: 'p' },
})
const p2 = await prisma.project.create({
data: { name: 'Project 2', teamId: tm.id, enableNotification: false },
})
const svc = notificationService
await svc['createAsync']({
type: NotificationType.comment_created,
teamId: tm.id,
projectId: p2.id,
creatorId: u1.id,
})
const count = await prisma.notification.count({ where: { projectId: p2.id } })
expect(count).toBe(0)
})
it('List all and Mark Read', async () => {
const tm = await prisma.team.create({ data: { name: 'Team 1' } })
const u1 = await prisma.user.create({
data: { name: 'u1', email: 'u1-list@example.com', password: 'p' },
})
const member = await prisma.teamMember.create({
data: { teamId: tm.id, userId: u1.id, role: 'owner' },
})
// Create notifications directly
// Using string IDs that are sorted correctly
const n1 = await prisma.notification.create({
data: {
id: '001',
teamId: tm.id,
type: NotificationType.comment_created,
createdAt: new Date(Date.now() - 3000),
},
})
const n2 = await prisma.notification.create({
data: {
id: '002',
teamId: tm.id,
type: NotificationType.reply_created,
createdAt: new Date(Date.now() - 2000),
},
})
const n3 = await prisma.notification.create({
data: {
id: '003',
teamId: tm.id,
type: NotificationType.mention,
userId: u1.id,
createdAt: new Date(Date.now() - 1000),
},
})
const svc = notificationService
// List all
const resAll = await svc.list(tm.id, u1.id, {})
expect(resAll.data).toHaveLength(3)
// Ordered by desc createdAt
expect(resAll.data[0].id).toBe(n3.id)
expect(resAll.data[1].id).toBe(n2.id)
expect(resAll.data[2].id).toBe(n1.id)
expect(resAll.data[0].isRead).toBe(false)
// Mark Read
await svc.markRead(tm.id, u1.id, n2.id)
const m = await prisma.teamMember.findUnique({
where: { id: member.id },
include: { lastReadNotification: true },
})
expect(m?.lastReadNotification?.id).toBe(n2.id)
// List again
const resRead = await svc.list(tm.id, u1.id, {})
expect(resRead.data[0].isRead).toBe(false) // n3
expect(resRead.data[1].isRead).toBe(true) // n2
expect(resRead.data[2].isRead).toBe(true) // n1 (read because n2 is newer)
})
it('List Unread Only', async () => {
const tm = await prisma.team.create({ data: { name: 'Team 1' } })
const u1 = await prisma.user.create({
data: { name: 'u1', email: `u1-${Date.now()}@example.com`, password: 'p' },
})
await prisma.teamMember.create({
data: { teamId: tm.id, userId: u1.id, role: 'owner' },
})
await prisma.notification.create({
data: {
id: '001',
teamId: tm.id,
type: NotificationType.comment_created,
createdAt: new Date(Date.now() - 3000),
},
})
const n2 = await prisma.notification.create({
data: {
id: '002',
teamId: tm.id,
type: NotificationType.reply_created,
createdAt: new Date(Date.now() - 2000),
},
})
const n3 = await prisma.notification.create({
data: {
id: '003',
teamId: tm.id,
type: NotificationType.mention,
userId: u1.id,
createdAt: new Date(Date.now() - 1000),
},
})
const svc = notificationService
await svc.markRead(tm.id, u1.id, n2.id)
const resUnread = await svc.list(tm.id, u1.id, { unreadOnly: true })
expect(resUnread.data).toHaveLength(1)
expect(resUnread.data[0].id).toBe(n3.id)
})
it('Filter Self Notifications', async () => {
const tm = await prisma.team.create({ data: { name: 'Team 1' } })
const u1 = await prisma.user.create({
data: { name: 'u1', email: `u1-${Date.now()}@example.com`, password: 'p' },
})
await prisma.teamMember.create({
data: { teamId: tm.id, userId: u1.id, role: 'owner' },
})
const nSelf = await prisma.notification.create({
data: { id: '004', teamId: tm.id, type: NotificationType.comment_created, creatorId: u1.id },
})
const svc = notificationService
const res = await svc.list(tm.id, u1.id, {})
const containsSelf = res.data.some((n) => n.id === nSelf.id)
expect(containsSelf).toBe(false)
})
it('Project Member scoping', async () => {
const tm = await prisma.team.create({ data: { name: 'Team 1' } })
const p1 = await prisma.project.create({ data: { name: 'p1', teamId: tm.id } })
const p2 = await prisma.project.create({ data: { name: 'p2', teamId: tm.id } })
const u1 = await prisma.user.create({
data: { name: 'u1', email: `u1-${Date.now()}@example.com`, password: 'p' },
})
const member = await prisma.teamMember.create({
data: { teamId: tm.id, userId: u1.id, role: 'reviewer', scope: 'project' },
})
await prisma.projectMember.create({
data: { projectId: p1.id, teamMemberId: member.id, role: 'editor' },
})
await prisma.notification.create({
data: { id: '001', teamId: tm.id, projectId: p1.id, type: NotificationType.comment_created },
})
await prisma.notification.create({
data: { id: '002', teamId: tm.id, projectId: p2.id, type: NotificationType.comment_created },
})
await prisma.notification.create({
data: { id: '003', teamId: tm.id, type: NotificationType.mention, userId: u1.id },
})
const svc = notificationService
const res = await svc.list(tm.id, u1.id, {})
// Should see p1 and the targeted mention, but not p2
expect(res.data).toHaveLength(2)
const p2Notification = res.data.find((n) => n.id === '002')
expect(p2Notification).toBeUndefined()
})
it('Respects user metadata notification settings', async () => {
const tm = await prisma.team.create({ data: { name: 'Team 1' } })
const u1 = await prisma.user.create({
data: { name: 'u1', email: `u1-${Date.now()}@example.com`, password: 'p' },
})
const u2 = await prisma.user.create({
data: { name: 'u2', email: `u2-${Date.now()}@example.com`, password: 'p' },
})
await prisma.teamMember.create({
data: { teamId: tm.id, userId: u1.id, role: 'owner' },
})
// Create comments, replies, mentions, uploads, etc.
const commentNotif = await prisma.notification.create({
data: { id: '001', teamId: tm.id, type: NotificationType.comment_created },
})
const replyNotif = await prisma.notification.create({
data: { id: '002', teamId: tm.id, type: NotificationType.reply_created, userId: u1.id },
})
const uploadNotifOther = await prisma.notification.create({
data: {
id: '003',
teamId: tm.id,
type: NotificationType.successful_file_uploaded,
creatorId: u2.id,
},
})
const uploadNotifSelf = await prisma.notification.create({
data: {
id: '004',
teamId: tm.id,
type: NotificationType.successful_file_uploaded,
creatorId: u1.id,
},
})
const svc = notificationService
// Default settings: comments=true, replies=true, mentions=true, yourUploads=false, otherUploads=true
const resDefault = await svc.list(tm.id, u1.id, {})
expect(resDefault.data.some((n) => n.id === commentNotif.id)).toBe(true)
expect(resDefault.data.some((n) => n.id === replyNotif.id)).toBe(true)
expect(resDefault.data.some((n) => n.id === uploadNotifOther.id)).toBe(true)
expect(resDefault.data.some((n) => n.id === uploadNotifSelf.id)).toBe(false) // yourUploads is false by default
// Disable comments and replies, but enable yourUploads
await userMetadataService.upsertMetadata(u1.id, tm.id, 'notification_settings', {
comments: false,
replies: false,
mentions: true,
yourUploads: true,
otherUploads: false,
statusUpdates: true,
})
const resCustom = await svc.list(tm.id, u1.id, {})
expect(resCustom.data.some((n) => n.id === commentNotif.id)).toBe(false)
expect(resCustom.data.some((n) => n.id === replyNotif.id)).toBe(false)
expect(resCustom.data.some((n) => n.id === uploadNotifOther.id)).toBe(false) // otherUploads is now false
expect(resCustom.data.some((n) => n.id === uploadNotifSelf.id)).toBe(true) // yourUploads is now true
})
it('getUnreadCount retrieves correct count of unread notifications', async () => {
const tm = await prisma.team.create({ data: { name: 'Team 2' } })
const u1 = await prisma.user.create({
data: { name: 'u3', email: `u3-${Date.now()}@example.com`, password: 'p' },
})
const u2 = await prisma.user.create({
data: { name: 'u4', email: `u4-${Date.now()}@example.com`, password: 'p' },
})
const member = await prisma.teamMember.create({
data: { teamId: tm.id, userId: u1.id, role: 'owner' },
})
// No notifications initially
let count = await notificationService.getUnreadCount(tm.id, u1.id)
expect(count).toBe(0)
// Create unread notifications from other user
const n1 = await prisma.notification.create({
data: { id: '101', teamId: tm.id, type: NotificationType.comment_created, creatorId: u2.id },
})
const n2 = await prisma.notification.create({
data: {
id: '102',
teamId: tm.id,
type: NotificationType.reply_created,
userId: u1.id,
creatorId: u2.id,
},
})
count = await notificationService.getUnreadCount(tm.id, u1.id)
expect(count).toBe(2)
// Mark up to n1 as read
await prisma.teamMember.update({
where: { id: member.id },
data: { lastReadNotificationId: n1.id },
})
count = await notificationService.getUnreadCount(tm.id, u1.id)
expect(count).toBe(1) // n2 is still unread
// Mark all as read (up to n2)
await prisma.teamMember.update({
where: { id: member.id },
data: { lastReadNotificationId: n2.id },
})
count = await notificationService.getUnreadCount(tm.id, u1.id)
expect(count).toBe(0)
})
})
@@ -0,0 +1,403 @@
import { prisma } from '@shumai/db'
import type { Prisma } from '@shumai/db'
import { NotificationType } from '@shumai/db'
import {
NotificationInfo,
CreateNotificationRequest,
ListNotificationParams,
NotificationSettings,
} from '@shumai/dtos'
import { paginateQuery, PaginatedData } from '@shumai/core/src/pagination'
import '@shumai/db/src/prisma-json-types'
import { s3Service } from '@shumai/core/src/s3/s3'
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
const mentionRegex = /<@([^>]+)>/g
export class NotificationService {
async create(req: CreateNotificationRequest) {
// Note: Do not await this, we fire and forget similarly to Go
this.createAsync(req).catch((err) => {
console.error('Failed to create notification asynchronously:', err)
})
}
private async createAsync(req: CreateNotificationRequest) {
let projectId = req.projectId
// Resolve ProjectID from AssetID if missing
if (!projectId && req.assetId) {
const asset = await prisma.asset.findUnique({
where: { id: req.assetId },
include: { project: true },
})
if (asset?.projectId) {
projectId = asset.projectId
}
}
// Check project notification settings
if (projectId) {
const project = await prisma.project.findUnique({
where: { id: projectId },
})
if (project && !project.enableNotification) {
return
}
}
// Helper to create a notification
const create = async (t: NotificationType, targetUserId?: string) => {
try {
await prisma.notification.create({
data: {
type: t,
teamId: req.teamId,
projectId: projectId,
creatorId: req.creatorId,
assetId: req.assetId,
taskId: req.taskId,
userId: targetUserId,
},
})
} catch (err) {
console.error('Failed to save notification', { type: t, err })
}
}
// 1. Create the primary notification
await create(req.type, req.userId)
// 2. Handle Mentions for Comment/Reply types
if (
(req.type === NotificationType.comment_created ||
req.type === NotificationType.reply_created) &&
req.commentMessage
) {
const matches = [...req.commentMessage.matchAll(mentionRegex)]
const mentionedIds = new Set<string>()
for (const match of matches) {
if (match.length > 1) {
const userId = match[1]
if (mentionedIds.has(userId)) {
continue
}
mentionedIds.add(userId)
// Don't notify self
if (req.creatorId === userId) {
continue
}
// Create mention notification
await create(NotificationType.mention, userId)
}
}
}
}
private async getListWhere(
teamId: string,
userId: string,
teamMember: Prisma.TeamMemberGetPayload<{ include: { lastReadNotification: true } }>,
unreadOnly: boolean,
): Promise<Prisma.NotificationWhereInput> {
// Permission Filtering based on Scope
let projectFilter: string[] = []
if (teamMember.scope === 'project') {
const pms = await prisma.projectMember.findMany({
where: { teamMemberId: teamMember.id },
include: { project: true },
})
projectFilter = pms.filter((pm) => pm.project).map((pm) => pm.projectId)
}
// Load notification settings
const settingsMeta = await userMetadataService.getMetadata(
userId,
teamId,
'notification_settings',
)
const settings: NotificationSettings = settingsMeta
? (settingsMeta.value as NotificationSettings)
: {
comments: true,
replies: true,
mentions: true,
yourUploads: false,
otherUploads: true,
statusUpdates: true,
}
const typeConditions: Prisma.NotificationWhereInput[] = []
// 1. Comments
if (settings.comments) {
typeConditions.push({ type: NotificationType.comment_created, userId: null })
}
// 2. Replies
if (settings.replies) {
typeConditions.push({ type: NotificationType.reply_created, userId: userId })
typeConditions.push({ type: NotificationType.reply_created, userId: null })
}
// 3. Mentions
if (settings.mentions) {
typeConditions.push({ type: NotificationType.mention, userId: userId })
}
// 4. Uploads
if (settings.yourUploads && settings.otherUploads) {
typeConditions.push({ type: NotificationType.successful_file_uploaded })
} else if (settings.yourUploads) {
typeConditions.push({ type: NotificationType.successful_file_uploaded, creatorId: userId })
} else if (settings.otherUploads) {
typeConditions.push({
type: NotificationType.successful_file_uploaded,
creatorId: { not: userId },
})
}
// 5. Status Updates
if (settings.statusUpdates) {
typeConditions.push({ type: NotificationType.metadata_field_updated_status })
}
// 6. Always include team/project join notifications
typeConditions.push({ type: NotificationType.new_user_join_team })
typeConditions.push({ type: NotificationType.new_user_join_project })
const where: Prisma.NotificationWhereInput = {
teamId,
OR: typeConditions,
AND: [
{
OR: [
...(settings.yourUploads
? [{ type: NotificationType.successful_file_uploaded, creatorId: userId }]
: []),
{ creatorId: null },
{ creatorId: { not: userId } },
],
},
],
}
if (teamMember.scope === 'project') {
// Must be AND applied after the general rules
const currentAnd = Array.isArray(where.AND) ? where.AND : where.AND ? [where.AND] : []
where.AND = [
...currentAnd,
{
OR: [
{ type: NotificationType.mention }, // Always allow mentions (targeted)
{ projectId: { in: projectFilter } }, // Only show notifications for projects user is member of
],
},
] as Prisma.NotificationWhereInput[]
}
if (unreadOnly && teamMember.lastReadNotification) {
// We want notifications NEWER than the last read one.
// String comparison works for ULID/KSUID.
const currentAnd = Array.isArray(where.AND) ? where.AND : where.AND ? [where.AND] : []
where.AND = [
...currentAnd,
{ id: { gt: teamMember.lastReadNotification.id } },
] as Prisma.NotificationWhereInput[]
}
return where
}
async getUnreadCount(teamId: string, userId: string): Promise<number> {
const teamMember = await prisma.teamMember.findUnique({
where: {
teamIdUserId: {
teamId,
userId,
},
},
include: {
lastReadNotification: true,
},
})
if (!teamMember) {
return 0
}
const where = await this.getListWhere(teamId, userId, teamMember, true)
return prisma.notification.count({ where })
}
async list(
teamId: string,
userId: string,
params: ListNotificationParams,
): Promise<PaginatedData<NotificationInfo[]>> {
// Get user's last read notification
const teamMember = await prisma.teamMember.findUnique({
where: {
teamIdUserId: {
teamId,
userId,
},
},
include: {
lastReadNotification: true,
},
})
if (!teamMember) {
throw new Error('failed to get team member')
}
const where = await this.getListWhere(teamId, userId, teamMember, !!params.unreadOnly)
return paginateQuery<NotificationInfo>(
async (skip, take) => {
const notifications = await prisma.notification.findMany({
where,
orderBy: { id: 'desc' },
skip,
take,
include: {
creator: true,
team: true,
project: true,
asset: true,
user: true,
},
})
return Promise.all(
notifications.map(async (n) => {
return this.toNotificationInfo(n, teamMember.lastReadNotification)
}),
)
},
null, // we don't need count
{
after: params.after,
first: params.pageSize,
includeCount: false,
},
)
}
async markRead(teamId: string, userId: string, notificationId: string) {
const teamMember = await prisma.teamMember.findUnique({
where: {
teamIdUserId: {
teamId,
userId,
},
},
include: {
lastReadNotification: true,
},
})
if (!teamMember) {
throw new Error('failed to get team member')
}
const notificationExists = await prisma.notification.findUnique({
where: { id: notificationId },
})
if (!notificationExists) {
throw new Error('notification not found')
}
let shouldUpdate = true
if (teamMember.lastReadNotification) {
if (notificationId <= teamMember.lastReadNotification.id) {
shouldUpdate = false
}
}
if (shouldUpdate) {
await prisma.teamMember.update({
where: { id: teamMember.id },
data: { lastReadNotificationId: notificationId },
})
}
}
private async toNotificationInfo(
n: Prisma.NotificationGetPayload<{
include: { creator: true; team: true; project: true; asset: true; user: true }
}>,
lastRead: Prisma.NotificationGetPayload<Record<string, never>> | null,
): Promise<NotificationInfo> {
const info: NotificationInfo = {
id: n.id,
type: n.type || undefined,
createdAt: n.createdAt.toISOString(),
isRead: lastRead !== null && n.id <= lastRead.id,
}
if (n.creator) {
info.creator = {
id: n.creator.id,
name: n.creator.name,
}
}
if (n.team) {
info.team = {
id: n.team.id,
name: n.team.name,
}
}
if (n.project) {
info.project = {
id: n.project.id,
name: n.project.name,
}
}
if (n.user) {
info.user = {
id: n.user.id,
name: n.user.name,
}
}
if (n.asset) {
const a = n.asset
let previewUrl = ''
const media = a.media as PrismaJson.MediaInfo | null
if (media) {
const bucket = process.env.S3_BUCKET || 'shumai'
try {
if (media.sprite) {
previewUrl = await s3Service.presign(bucket, media.sprite.key, 'GET')
} else if (media.thumbnail) {
previewUrl = await s3Service.presign(bucket, media.thumbnail.key || '', 'GET')
}
} catch (e) {
console.error('Failed to generate presigned url for notification asset preview:', e)
}
}
info.asset = {
id: a.id,
name: a.name,
mediaType: a.mediaType || undefined,
preview: previewUrl || undefined,
}
}
return info
}
}
export const notificationService = new NotificationService()
+67
View File
@@ -0,0 +1,67 @@
import { marshal, unmarshal } from '@shumai/core/src/hyrumtoken'
const key = new Uint8Array([
0x38, 0x9c, 0xf5, 0xe7, 0xfe, 0xa5, 0x6a, 0xe7, 0xbe, 0x0e, 0x6a, 0x47, 0x19, 0x9f, 0xb1, 0x81,
0xcc, 0x83, 0xb8, 0x94, 0x62, 0xd7, 0xb0, 0x22, 0x18, 0xa6, 0x36, 0x57, 0xde, 0xfa, 0x70, 0xe9,
])
export interface PaginationParams {
first?: number
after?: string
includeCount?: boolean
}
export interface PageInfo {
total?: number
cursor?: string
}
export interface PaginatedData<T> {
data: T
pageInfo: PageInfo
}
export function encodeCursor(offset: number): string {
return marshal(key, offset.toString())
}
export function decodeCursor(cursor: string): number {
const decoded = unmarshal(key, cursor)
return parseInt(decoded, 10)
}
/**
* Helper function to handle cursor pagination using skip/take logic
* with encoded cursors.
*/
export async function paginateQuery<T>(
queryFn: (skip: number, take: number) => Promise<T[]>,
countFn: (() => Promise<number>) | null,
params: PaginationParams,
): Promise<PaginatedData<T[]>> {
const info: PageInfo = {}
if (params.includeCount && countFn) {
info.total = await countFn()
}
let limit = params.first || 20
if (limit <= 0 || limit > 200) {
limit = 20
}
let offset = 0
if (params.after) {
offset = decodeCursor(params.after)
}
// Request one extra item to check if there is a next page
const results = await queryFn(offset, limit + 1)
if (results.length > limit) {
info.cursor = encodeCursor(offset + limit)
return { data: results.slice(0, limit), pageInfo: info }
}
return { data: results, pageInfo: info }
}
+382
View File
@@ -0,0 +1,382 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import { ProjectService } from './project'
import { s3Service } from '@shumai/core/src/s3/s3'
import { assetService } from '@shumai/core/src/asset/asset'
vi.mock('@shumai/core/src/s3/s3', () => ({
s3Service: {
presign: vi.fn(),
deleteObject: vi.fn().mockResolvedValue(1),
deletePrefix: vi.fn().mockResolvedValue(1),
},
}))
describe('ProjectService', () => {
setupTestDbHooks()
let projectService: ProjectService
beforeEach(() => {
projectService = new ProjectService()
vi.mocked(s3Service.presign).mockResolvedValue('http://s3/presigned')
})
describe('listProjects scoping', () => {
it('team scope user sees all projects', async () => {
const team = await prisma.team.create({ data: { name: 'Team A' } })
await prisma.project.create({ data: { name: 'P1', teamId: team.id } })
await prisma.project.create({ data: { name: 'P2', teamId: team.id } })
await prisma.project.create({ data: { name: 'P3', teamId: team.id } })
const u1 = await prisma.user.create({ data: { name: 'u1', email: 'u1@example.com' } })
await prisma.teamMember.create({
data: { teamId: team.id, userId: u1.id, role: 'editor', scope: 'team' },
})
const res = await projectService.listProjects({
teamId: team.id,
userId: u1.id,
pagination: {},
})
expect(res.data).toHaveLength(3)
const names = res.data.map((p) => p.name).sort()
expect(names).toEqual(['P1', 'P2', 'P3'])
})
it('project scope user sees only assigned projects', async () => {
const team = await prisma.team.create({ data: { name: 'Team B' } })
const p1 = await prisma.project.create({ data: { name: 'P1', teamId: team.id } })
const p2 = await prisma.project.create({ data: { name: 'P2', teamId: team.id } })
await prisma.project.create({ data: { name: 'P3', teamId: team.id } })
const u2 = await prisma.user.create({ data: { name: 'u2', email: 'u2@example.com' } })
const tm2 = await prisma.teamMember.create({
data: { teamId: team.id, userId: u2.id, role: 'reviewer', scope: 'project' },
})
await prisma.projectMember.create({
data: { projectId: p1.id, teamMemberId: tm2.id, role: 'reviewer' },
})
await prisma.projectMember.create({
data: { projectId: p2.id, teamMemberId: tm2.id, role: 'reviewer' },
})
const res = await projectService.listProjects({
teamId: team.id,
userId: u2.id,
pagination: {},
})
expect(res.data).toHaveLength(2)
const names = res.data.map((p) => p.name).sort()
expect(names).toEqual(['P1', 'P2'])
})
it('user not in team fails', async () => {
const team = await prisma.team.create({ data: { name: 'Team C' } })
const u3 = await prisma.user.create({ data: { name: 'u3', email: 'u3@example.com' } })
await expect(
projectService.listProjects({ teamId: team.id, userId: u3.id, pagination: {} }),
).rejects.toThrow('failed to get team member')
})
})
describe('listProjects sorting', () => {
it('sorts projects by name and creation time', async () => {
const team = await prisma.team.create({ data: { name: 'Team Sort' } })
const now = new Date()
const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000)
const twoHoursAgo = new Date(now.getTime() - 2 * 60 * 60 * 1000)
const thirtyMinsAgo = new Date(now.getTime() - 30 * 60 * 1000)
await prisma.project.create({ data: { name: 'A', teamId: team.id, createdAt: twoHoursAgo } })
await prisma.project.create({ data: { name: 'C', teamId: team.id, createdAt: oneHourAgo } })
await prisma.project.create({
data: { name: 'B', teamId: team.id, createdAt: thirtyMinsAgo },
})
const u = await prisma.user.create({ data: { name: 'u', email: 'u@example.com' } })
await prisma.teamMember.create({
data: { teamId: team.id, userId: u.id, role: 'editor', scope: 'team' },
})
// Default Sort (Name ASC)
let res = await projectService.listProjects({ teamId: team.id, userId: u.id, pagination: {} })
expect(res.data).toHaveLength(3)
expect(res.data[0].name).toBe('A')
expect(res.data[1].name).toBe('B')
expect(res.data[2].name).toBe('C')
// Sort by CreatedAt DESC
res = await projectService.listProjects({
teamId: team.id,
userId: u.id,
sortBy: 'created_at',
sortDirection: 'desc',
pagination: {},
})
expect(res.data).toHaveLength(3)
expect(res.data[0].name).toBe('B') // Newest
expect(res.data[1].name).toBe('C')
expect(res.data[2].name).toBe('A') // Oldest
// Sort by CreatedAt ASC
res = await projectService.listProjects({
teamId: team.id,
userId: u.id,
sortBy: 'created_at',
sortDirection: 'asc',
pagination: {},
})
expect(res.data).toHaveLength(3)
expect(res.data[0].name).toBe('A') // Oldest
expect(res.data[1].name).toBe('C')
expect(res.data[2].name).toBe('B') // Newest
})
})
describe('listProjectMembers', () => {
it('should filter bots in project members', async () => {
const team = await prisma.team.create({ data: { name: 'Team Bot' } })
const project = await prisma.project.create({ data: { name: 'P1', teamId: team.id } })
const human = await prisma.user.create({
data: { name: 'Human', email: `human-${Date.now()}@example.com`, password: 'pw' },
})
const bot = await prisma.user.create({
data: {
name: 'Bot',
email: `bot-${Date.now()}@example.com`,
password: 'pw',
type: 'agent',
agent: {
create: {
teamId: team.id,
type: 'chat',
enabled: true,
config: {
provider: 'google',
model: 'gemini',
},
},
},
},
})
const tmHuman = await prisma.teamMember.create({
data: { teamId: team.id, userId: human.id, role: 'editor', scope: 'team' },
})
const tmBot = await prisma.teamMember.create({
data: { teamId: team.id, userId: bot.id, role: 'editor', scope: 'team' },
})
await prisma.projectMember.create({
data: { projectId: project.id, teamMemberId: tmHuman.id, role: 'editor' },
})
await prisma.projectMember.create({
data: { projectId: project.id, teamMemberId: tmBot.id, role: 'editor' },
})
// Should hide bots by default
const members = await projectService.listProjectMembers({
projectId: project.id,
})
expect(members).toHaveLength(1)
expect(members[0].id).toBe(human.id)
// Should include bots if requested
const allMembers = await projectService.listProjectMembers({
projectId: project.id,
includeAgents: true,
})
expect(allMembers).toHaveLength(2)
})
})
describe('createProject', () => {
it('creates a project with a share_root folder', async () => {
const team = await prisma.team.create({ data: { name: 'Team Share' } })
const u = await prisma.user.create({ data: { name: 'u', email: 'share@example.com' } })
await prisma.teamMember.create({
data: { teamId: team.id, userId: u.id, role: 'owner' },
})
const project = await projectService.createProject(u, {
name: 'Project with Share',
teamId: team.id,
})
expect(project.id).toBeDefined()
const p = await prisma.project.findUnique({
where: { id: project.id },
include: { shareRoot: true },
})
expect(p?.shareRootId).toBeDefined()
expect(p?.shareRoot?.type).toBe('share_root')
expect(p?.shareRoot?.name).toBe('share_root')
})
})
describe('deleteProject', () => {
it('detaches and soft-deletes project assets', async () => {
const team = await prisma.team.create({ data: { name: 'Delete Team' } })
const u = await prisma.user.create({ data: { name: 'u', email: 'delete@example.com' } })
await prisma.teamMember.create({
data: { teamId: team.id, userId: u.id, role: 'owner' },
})
const project = await projectService.createProject(u, {
name: 'Project to Delete',
teamId: team.id,
})
// Add some related data
const asset = await prisma.asset.create({
data: {
name: 'Test Asset',
type: 'file',
status: 'processed',
project: { connect: { id: project.id } },
storageKey: {
connectOrCreate: {
where: { key: 'asset-key' },
create: { key: 'asset-key' },
},
},
},
})
// Set cover image key
await prisma.project.update({
where: { id: project.id },
data: { coverImageKey: 'cover-key' },
})
// Delete project
await projectService.deleteProject(project.id)
// Verify project is deleted
const p = await prisma.project.findUnique({ where: { id: project.id } })
expect(p).toBeNull()
// Verify asset is soft-deleted and detached
const a = await prisma.asset.findUnique({ where: { id: asset.id } })
expect(a).toBeDefined()
expect(a?.isDeleted).toBe(true)
expect(a?.projectId).toBeNull()
expect(a?.parentId).toBeNull()
// Verify S3 project cover cleanup (synchronous)
expect(s3Service.deleteObject).toHaveBeenCalledWith(expect.any(String), 'cover-key')
// S3 asset key cleanup is NOT called synchronously
expect(s3Service.deleteObject).not.toHaveBeenCalledWith(expect.any(String), 'asset-key')
})
it('cleans up nested hierarchy asynchronously in background job', async () => {
const team = await prisma.team.create({ data: { name: 'Nested Team' } })
const u = await prisma.user.create({ data: { name: 'u', email: 'nested@example.com' } })
await prisma.teamMember.create({
data: { teamId: team.id, userId: u.id, role: 'owner' },
})
const project = await projectService.createProject(u, {
name: 'Nested Project',
teamId: team.id,
})
const projectDb = await prisma.project.findUnique({ where: { id: project.id } })
// Create hierarchy: Folder A -> Folder B -> File C
const folderA = await prisma.asset.create({
data: {
name: 'Folder A',
type: 'folder',
status: 'processed',
projectId: project.id,
parentId: projectDb!.rootFolderId,
},
})
const folderB = await prisma.asset.create({
data: {
name: 'Folder B',
type: 'folder',
status: 'processed',
projectId: project.id,
parentId: folderA.id,
},
})
const fileC = await prisma.asset.create({
data: {
name: 'File C',
type: 'file',
status: 'processed',
project: { connect: { id: project.id } },
parent: { connect: { id: folderB.id } },
storageKey: {
connectOrCreate: {
where: { key: 'file-c-key' },
create: { key: 'file-c-key' },
},
},
},
})
// Add metadata and comments to verify cascade
await prisma.assetMetadataValue.create({
data: {
assetId: fileC.id,
fieldKey: 'test-field',
stringValue: 'test-value',
},
})
const comment = await prisma.assetComment.create({
data: {
assetId: fileC.id,
message: 'Test comment',
},
})
// Delete project
await projectService.deleteProject(project.id)
// 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()
expect(await prisma.asset.findUnique({ where: { id: folderB.id } })).toBeNull()
expect(await prisma.asset.findUnique({ where: { id: fileC.id } })).toBeNull()
// Verify cascade
expect(
await prisma.assetMetadataValue.findUnique({
// eslint-disable-next-line @typescript-eslint/naming-convention
where: { assetId_fieldKey: { assetId: fileC.id, fieldKey: 'test-field' } },
}),
).toBeNull()
expect(await prisma.assetComment.findUnique({ where: { id: comment.id } })).toBeNull()
// Verify S3 cleanup for file
expect(s3Service.deleteObject).toHaveBeenCalledWith(expect.any(String), 'file-c-key')
})
})
})
+332
View File
@@ -0,0 +1,332 @@
import { prisma } from '@shumai/db'
import { Prisma } from '@shumai/db'
import { s3Service } from '@shumai/core/src/s3/s3'
import { paginateQuery, PaginatedData } from '@shumai/core/src/pagination'
import {
ServiceCreateProjectRequest,
ServiceUpdateProjectRequest,
ServiceListProjectsRequest,
ServiceAddProjectMemberRequest,
ServiceListProjectMembersRequest,
ProjectInfo,
ProjectUserInfo,
} from '@shumai/dtos'
export class ProjectService {
async createProject(
user: { id: string },
req: ServiceCreateProjectRequest,
): Promise<ProjectInfo> {
const team = await prisma.team.findUnique({ where: { id: req.teamId } })
if (!team) throw new Error('Team not found')
const teamMember = await prisma.teamMember.findUnique({
where: {
teamIdUserId: { teamId: req.teamId, userId: user.id },
},
})
if (!teamMember) throw new Error('creator is not a team member')
const project = await prisma.$transaction(async (tx) => {
const proj = await tx.project.create({
data: {
name: req.name,
teamId: req.teamId,
enableNotification: req.enableNotification ?? true,
coverImageKey: req.coverImageKey,
},
})
const rootFolder = await tx.asset.create({
data: {
name: 'root',
type: 'root',
status: 'processed',
projectId: proj.id,
},
})
const shareRootFolder = await tx.asset.create({
data: {
name: 'share_root',
type: 'share_root',
status: 'processed',
projectId: proj.id,
},
})
const updatedProj = await tx.project.update({
where: { id: proj.id },
data: {
rootFolderId: rootFolder.id,
shareRootId: shareRootFolder.id,
},
include: { rootFolder: true },
})
await tx.projectMember.create({
data: {
projectId: proj.id,
teamMemberId: teamMember.id,
role: 'owner',
},
})
return updatedProj
})
return this.toProjectInfo(project)
}
async getProject(projectId: string): Promise<ProjectInfo> {
const project = await prisma.project.findUnique({
where: { id: projectId },
include: { rootFolder: true },
})
if (!project) throw new Error('Project not found')
return this.toProjectInfo(project)
}
async updateProject(req: ServiceUpdateProjectRequest): Promise<ProjectInfo> {
const project = await prisma.project.findUnique({
where: { id: req.projectId },
include: { team: true },
})
if (!project) throw new Error('Project not found')
if (!project.team) throw new Error('Project has no team')
const updatedProject = await prisma.project.update({
where: { id: req.projectId },
data: {
name: req.name,
coverImageKey: req.coverImageKey,
enableNotification: req.enableNotification,
},
include: { rootFolder: true },
})
return this.toProjectInfo(updatedProject)
}
async listProjects(req: ServiceListProjectsRequest): Promise<PaginatedData<ProjectInfo[]>> {
const teamMember = await prisma.teamMember.findUnique({
where: {
teamIdUserId: { teamId: req.teamId, userId: req.userId },
},
})
if (!teamMember) throw new Error('failed to get team member')
const where: Prisma.ProjectWhereInput = {
teamId: req.teamId,
}
if (teamMember.scope === 'project') {
where.members = {
some: { teamMemberId: teamMember.id },
}
}
const orderBy: Prisma.ProjectOrderByWithRelationInput = {}
const direction = req.sortDirection === 'desc' ? 'desc' : 'asc'
if (req.sortBy) {
if (req.sortBy === 'created_at') {
orderBy.createdAt = direction
} else if (req.sortBy === 'updated_at') {
orderBy.updatedAt = direction
} else {
orderBy.name = direction
}
} else {
orderBy.name = 'asc'
}
const res = await paginateQuery(
async (skip, take) => {
const projects = await prisma.project.findMany({
where,
orderBy,
skip,
take,
include: { rootFolder: true },
})
const infos = await Promise.all(projects.map((p) => this.toProjectInfo(p)))
return infos
},
null,
req.pagination,
)
return res
}
async addProjectMember(req: ServiceAddProjectMemberRequest): Promise<void> {
const user = await prisma.user.findUnique({ where: { id: req.userId } })
if (!user) throw new Error('User not found')
const project = await prisma.project.findUnique({
where: { id: req.projectId },
include: { team: true },
})
if (!project) throw new Error('Project not found')
const tm = await prisma.teamMember.findUnique({
where: {
teamIdUserId: { teamId: project.teamId, userId: req.userId },
},
})
if (!tm) throw new Error('user is not a team member')
await prisma.projectMember.create({
data: {
projectId: req.projectId,
teamMemberId: tm.id,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
role: req.role as any,
},
})
}
async listProjectMembers(req: ServiceListProjectMembersRequest): Promise<ProjectUserInfo[]> {
const members = await prisma.projectMember.findMany({
where: {
projectId: req.projectId,
...(req.includeAgents
? {
teamMember: {
user: {
OR: [
{ type: 'human' },
{
type: 'agent',
agent: {
type: 'chat',
enabled: true,
},
},
],
},
},
}
: { teamMember: { user: { type: { not: 'agent' } } } }),
},
include: {
teamMember: {
include: { user: true },
},
},
})
return members
.filter((pm) => pm.teamMember && pm.teamMember.user)
.map((pm) => ({
id: pm.teamMember.user.id,
name: pm.teamMember.user.name,
role: pm.role,
}))
}
async deleteProject(projectId: string): Promise<void> {
const project = await prisma.project.findUnique({
where: { id: projectId },
})
if (!project) throw new Error('Project not found')
const immediateCleanupDate = new Date(0)
await prisma.$transaction(async (tx) => {
// 1. Mark ALL project assets as isDeleted and detach projectId
// We keep parentId intact so the folder structure remains for Stage 1 cleanup.
await tx.asset.updateMany({
where: { projectId },
data: {
isDeleted: true,
projectId: null,
},
})
// 2. Mark root folders as 'trashed' with deletedAt = 0 to trigger immediate background purge
const rootIds = [project.rootFolderId, project.shareRootId].filter(
(id): id is string => id !== null,
)
if (rootIds.length > 0) {
await tx.asset.updateMany({
where: { id: { in: rootIds } },
data: {
status: 'trashed',
deletedAt: immediateCleanupDate,
},
})
}
// 3. Unlink root folders from project record to avoid FK cycles during project deletion
await tx.project.update({
where: { id: projectId },
data: { rootFolderId: null, shareRootId: null },
})
// 4. Delete the project itself
// Cascade deletes will handle project members, invites, notifications, etc.
await tx.project.delete({
where: { id: projectId },
})
})
// Synchronously delete the project's cover image if it exists
if (project.coverImageKey) {
const bucket = process.env.S3_BUCKET || 'shumai'
try {
await s3Service.deleteObject(bucket, project.coverImageKey)
} catch (e: unknown) {
console.error(`Failed to delete project cover image ${project.coverImageKey}:`, e)
}
}
}
async getProjectRootFolder(projectId: string): Promise<string> {
const project = await prisma.project.findUnique({
where: { id: projectId },
include: { rootFolder: true },
})
if (!project) throw new Error('Project not found')
if (!project.rootFolderId) return ''
return project.rootFolderId
}
async getProjectTeam(projectId: string): Promise<string> {
const project = await prisma.project.findUnique({
where: { id: projectId },
})
if (!project) throw new Error('Project not found')
return project.teamId
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private async toProjectInfo(p: any): Promise<ProjectInfo> {
const pi: ProjectInfo = {
id: p.id,
name: p.name,
enableNotification: p.enableNotification ?? true,
coverImageKey: p.coverImageKey || undefined,
updatedAt: p.updatedAt,
}
if (p.rootFolderId) {
pi.rootFolder = p.rootFolderId
} else if (p.rootFolder) {
pi.rootFolder = p.rootFolder.id
}
if (p.coverImageKey) {
try {
const bucket = process.env.S3_BUCKET || 'shumai'
const url = await s3Service.presign(bucket, p.coverImageKey, 'GET')
pi.coverImage = url
} catch (e: unknown) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const ignored = e
}
}
return pi
}
}
export const projectService = new ProjectService()
+151
View File
@@ -0,0 +1,151 @@
import { setupTestDbHooks } from '@shumai/db'
import { teamService } from '@shumai/core/src/team/team'
import { providerService } from './provider'
import { describe, expect, it } from 'vitest'
import { ProviderConfigSerializable, providerModelSchema } from '@shumai/dtos'
import { builtinProviders } from '@/generated/providers.generated'
import { z } from 'zod'
type ProviderModel = z.infer<typeof providerModelSchema>
describe('ProviderService', () => {
setupTestDbHooks()
it('should initialize builtin providers', async () => {
const team = await teamService.ensureDefaultTeam()
// Server startup/init logic
await providerService.initBuiltinProviders(team.id)
const providers = await providerService.listByTeam(team.id)
expect(providers.length).toBeGreaterThan(0)
const anthropic = providers.find((p) => p.name === 'anthropic')
expect(anthropic).toBeDefined()
expect(anthropic?.isBuiltin).toBe(true)
expect(anthropic?.modelsCount).toBeGreaterThan(0)
})
it('should initialize builtin providers in correct order', async () => {
const team = await teamService.ensureDefaultTeam()
await providerService.initBuiltinProviders(team.id)
const providers = await providerService.listByTeam(team.id)
// The first provider in generated file is 'openai'
// Since we use id: 'desc', 'openai' should be first in the list
const firstInGenerated = Object.keys(builtinProviders)[0]
expect(providers[0].name).toBe(firstInGenerated)
})
it('should prevent deletion of builtin providers', async () => {
const team = await teamService.ensureDefaultTeam()
await providerService.initBuiltinProviders(team.id)
const providers = await providerService.listByTeam(team.id)
const builtin = providers.find((p) => p.isBuiltin)
expect(builtin).toBeDefined()
await expect(providerService.delete(team.id, builtin!.id)).rejects.toThrow(
'Cannot delete builtin provider',
)
})
it('should allow editing builtin providers', async () => {
const team = await teamService.ensureDefaultTeam()
await providerService.initBuiltinProviders(team.id)
const providers = await providerService.listByTeam(team.id)
const builtin = providers.find((p) => p.name === 'openai')
const builtinModels = await providerService.listModelsByProvider(team.id, builtin!.id)
const newConfig: ProviderConfigSerializable = {
...builtin!.config,
apiKey: 'new-key',
}
const updated = await providerService.update(team.id, builtin!.id, newConfig, builtinModels)
expect(updated.config.apiKey).toBe('new-key')
expect(updated.models.length).toBe(builtin!.modelsCount)
const sortedUpdatedModels = [...updated.models].sort((a, b) =>
a.modelId.localeCompare(b.modelId),
)
const sortedBuiltinModels = [...builtinModels].sort((a, b) =>
a.modelId.localeCompare(b.modelId),
)
sortedUpdatedModels.forEach((model, i) => {
expect(model.modelId).toBe(sortedBuiltinModels[i].modelId)
expect(model.config).toEqual(sortedBuiltinModels[i].config)
})
})
it('should create, list, update and delete custom providers', async () => {
const team = await teamService.ensureDefaultTeam()
// 1. Create
const config: ProviderConfigSerializable = {
baseUrl: 'https://api.openai.com/v1',
api: 'openai-completions',
apiKey: 'test-key',
}
const models: ProviderModel[] = [
{
modelId: 'gpt-4',
name: 'GPT-4',
config: {
api: 'openai-completions',
reasoning: false,
input: ['text'],
contextWindow: 128000,
maxTokens: 4096,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
},
},
]
const provider = await providerService.create(team.id, 'my-openai', config, models)
expect(provider.id).toBeDefined()
expect(provider.name).toBe('my-openai')
expect(provider.config).toEqual(config)
expect(provider.models).toHaveLength(1)
expect(provider.models[0].modelId).toBe('gpt-4')
// 2. List
const providers = await providerService.listByTeam(team.id)
const myProvider = providers.find((p) => p.id === provider.id)
expect(myProvider).toBeDefined()
expect(myProvider!.id).toBe(provider.id)
expect(myProvider!.modelsCount).toBe(1)
// 3. Update
const newConfig: ProviderConfigSerializable = {
...config,
apiKey: 'new-key',
}
const currentModels = await providerService.listModelsByProvider(team.id, provider.id)
const newModels: ProviderModel[] = [
...currentModels,
{
modelId: 'gpt-4-turbo',
name: 'GPT-4 Turbo',
config: {
api: 'openai-completions',
reasoning: false,
input: ['text', 'image'],
contextWindow: 128000,
maxTokens: 4096,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
},
},
]
const updated = await providerService.update(team.id, provider.id, newConfig, newModels)
expect(updated.config.apiKey).toBe('new-key')
expect(updated.models).toHaveLength(2)
// 4. Delete
await providerService.delete(team.id, provider.id)
const afterDelete = await providerService.listByTeam(team.id)
expect(afterDelete.find((p) => p.id === provider.id)).toBeUndefined()
})
})
+156
View File
@@ -0,0 +1,156 @@
import { prisma } from '@shumai/db'
import { ProviderConfigSerializable, providerModelSchema } from '@shumai/dtos'
import { builtinProviders } from '@/generated/providers.generated'
import { z } from 'zod'
type ProviderModel = z.infer<typeof providerModelSchema>
export class ProviderService {
constructor(private readonly prismaClient: typeof prisma = prisma) {}
async initBuiltinProviders(teamId: string) {
const team = await this.prismaClient.team.findUnique({
where: { id: teamId },
include: {
_count: {
select: { providers: true },
},
},
})
if (team && team._count.providers === 0) {
// We insert them one by one in reverse order to ensure that the
// popular providers (first in builtinProviders) get the highest ULIDs
// and appear first when sorted by id DESC.
const entries = Object.entries(builtinProviders).reverse()
for (const [name, data] of entries) {
const typedData = data as unknown as {
config: ProviderConfigSerializable
models: ProviderModel[]
}
await this.prismaClient.provider.create({
data: {
teamId: team.id,
name,
config: typedData.config,
isBuiltin: true,
models: {
create: typedData.models.map((m) => ({
modelId: m.modelId,
name: m.name,
config: m.config,
})),
},
},
})
}
}
}
async listByTeam(teamId: string) {
const providers = await this.prismaClient.provider.findMany({
where: { teamId },
include: {
_count: {
select: { models: true },
},
},
orderBy: { id: 'desc' },
})
return providers.map((p) => ({
...p,
modelsCount: p._count.models,
_count: undefined,
}))
}
async getById(id: string) {
return this.prismaClient.provider.findUnique({
where: { id },
})
}
async listModelsByProvider(teamId: string, providerId: string) {
return this.prismaClient.model.findMany({
where: {
providerId,
provider: { teamId },
},
orderBy: { id: 'asc' },
})
}
async create(
teamId: string,
name: string,
config: ProviderConfigSerializable,
models: ProviderModel[],
) {
return this.prismaClient.provider.create({
data: {
teamId,
name,
config,
models: {
create: models.map((m) => ({
modelId: m.modelId,
name: m.name,
config: m.config,
})),
},
},
include: { models: true },
})
}
async update(
teamId: string,
id: string,
config: ProviderConfigSerializable,
models: ProviderModel[],
) {
return this.prismaClient.$transaction(async (tx) => {
// Delete all existing models for this provider
await tx.model.deleteMany({
where: { providerId: id },
})
// Update provider and recreate models
return tx.provider.update({
where: { id, teamId },
data: {
config,
models: {
create: models.map((m) => ({
modelId: m.modelId,
name: m.name,
config: m.config,
})),
},
},
include: { models: true },
})
})
}
async delete(teamId: string, id: string) {
const provider = await this.prismaClient.provider.findUnique({
where: { id, teamId },
})
if (!provider) {
throw new Error('Provider not found')
}
if (provider.isBuiltin) {
throw new Error('Cannot delete builtin provider')
}
return this.prismaClient.provider.delete({
where: { id, teamId },
})
}
}
export const providerService = new ProviderService()
+118
View File
@@ -0,0 +1,118 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import * as fs from 'fs'
import * as path from 'path'
import { LocalStorageService, S3StorageService } from './s3'
// Mock the AWS SDK
const s3ClientConstructorSpy = vi.fn()
vi.mock('@aws-sdk/client-s3', () => {
return {
S3Client: class {
constructor(params: unknown) {
s3ClientConstructorSpy(params)
}
send = vi.fn().mockResolvedValue({})
},
HeadObjectCommand: class {},
PutObjectCommand: class {},
GetObjectCommand: class {},
ListObjectsV2Command: class {},
}
})
vi.mock('@aws-sdk/s3-request-presigner', () => {
return {
getSignedUrl: vi.fn().mockResolvedValue('http://presigned-url'),
}
})
describe('S3Service implementations', () => {
describe('S3StorageService', () => {
it('should correctly build standard endpoints', () => {
const s3 = new S3StorageService('s3.example.com', 'key', 'secret', 'test-bucket', true)
expect(s3).toBeDefined()
expect(s3ClientConstructorSpy).toHaveBeenCalledWith(
expect.objectContaining({ region: 'auto' }),
)
})
it('should use provided region', () => {
s3ClientConstructorSpy.mockClear()
const s3 = new S3StorageService(
's3.example.com',
'key',
'secret',
'test-bucket',
true,
'ap-singapore',
)
expect(s3).toBeDefined()
expect(s3ClientConstructorSpy).toHaveBeenCalledWith(
expect.objectContaining({ region: 'ap-singapore' }),
)
})
it('should implement presign correctly', async () => {
const s3 = new S3StorageService('localhost:9000', 'key', 'secret', 'test-bucket', false)
const url = await s3.presign('bucket', 'key', 'GET')
expect(url).toBe('http://presigned-url')
})
})
describe('LocalStorageService', () => {
const TEST_BASE_PATH = path.join(process.cwd(), 'data-test', 's3', 'data')
let localS3: LocalStorageService
beforeEach(() => {
if (fs.existsSync(TEST_BASE_PATH)) {
fs.rmSync(TEST_BASE_PATH, { recursive: true, force: true })
}
fs.mkdirSync(TEST_BASE_PATH, { recursive: true })
localS3 = new LocalStorageService('http://localhost:3000', TEST_BASE_PATH)
})
afterEach(() => {
if (fs.existsSync(TEST_BASE_PATH)) {
fs.rmSync(TEST_BASE_PATH, { recursive: true, force: true })
}
})
it('should implement putObject and getObjectSize correctly', async () => {
await localS3.putObject('test-bucket', 'test.txt', 'hello world', 11)
const size = await localS3.getObjectSize('test-bucket', 'test.txt')
expect(size).toBe(11)
})
it('should list objects', async () => {
await localS3.putObject('test-bucket', 'dir1/file1.txt', 'abc', 3)
await localS3.putObject('test-bucket', 'dir1/file2.txt', 'def', 3)
await localS3.putObject('test-bucket', 'dir2/file3.txt', 'ghi', 3)
const keys1 = await localS3.listObjects('test-bucket', 'dir1')
expect(keys1.length).toBe(2)
expect(keys1).toContain('dir1/file1.txt')
expect(keys1).toContain('dir1/file2.txt')
const keysAll = await localS3.listObjects('test-bucket', '')
expect(keysAll.length).toBe(3)
})
it('should handle headObject correctly', async () => {
await localS3.putObject('test-bucket', 'test.txt', 'hello world', 11)
const head = await localS3.headObject('test-bucket', 'test.txt')
expect(head.key).toBe('test.txt')
expect(head.size).toBe(11)
expect(head.eTag).toContain('"')
})
it('should generate a local presign URL', async () => {
const url = await localS3.presign('my-bucket', 'dir/file.txt', 'GET')
expect(url).toBe('http://localhost:3000/files/my-bucket/dir/file.txt')
})
it('should throw an error for unsupported presign methods', async () => {
await expect(localS3.presign('b', 'k', 'POST')).rejects.toThrow()
})
})
})
+512
View File
@@ -0,0 +1,512 @@
import { ObjectInfo } from '@shumai/dtos'
import {
CopyObjectCommand,
DeleteObjectCommand,
GetObjectCommand,
HeadObjectCommand,
ListObjectsV2Command,
PutObjectCommand,
S3Client,
} from '@aws-sdk/client-s3'
import { getSignedUrl } from '@aws-sdk/s3-request-presigner'
import * as crypto from 'crypto'
import * as fs from 'fs'
import { readFileSync, statSync } from 'fs'
import * as path from 'path'
import { ulid } from 'ulid'
export function signLocalUrl(bucket: string, key: string): string {
const secret = process.env.BETTER_AUTH_SECRET || 'shumai-local-storage-secret'
const hmac = crypto.createHmac('sha256', secret)
hmac.update(`${bucket}/${key}`)
const signature = hmac.digest('hex')
return `/api/upload/local?bucket=${encodeURIComponent(bucket)}&key=${encodeURIComponent(key)}&Signature=${signature}`
}
export function verifyLocalUrlSignature(bucket: string, key: string, signature: string): boolean {
const secret = process.env.BETTER_AUTH_SECRET || 'shumai-local-storage-secret'
const hmac = crypto.createHmac('sha256', secret)
hmac.update(`${bucket}/${key}`)
const expected = hmac.digest('hex')
try {
return crypto.timingSafeEqual(Buffer.from(signature, 'hex'), Buffer.from(expected, 'hex'))
} catch {
return false
}
}
export interface S3Object {
buffer: Buffer
contentType: string
}
export interface S3Service {
getObjectSize(bucket: string, key: string): Promise<number>
putObject(
bucket: string,
key: string,
body: Buffer | Uint8Array | string,
size: number,
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>
headObject(bucket: string, key: string): Promise<ObjectInfo>
listObjects(bucket: string, prefix: string): Promise<string[]>
uploadFile(filePath: string, contentType: string): Promise<string>
uploadFileToKey(filePath: string, key: string, contentType: string): Promise<void>
presign(bucket: string, key: string, method: string): Promise<string>
}
export class S3StorageService implements S3Service {
private client: S3Client
private bucket: string
constructor(
endpoint: string,
accessKeyId: string,
secretAccessKey: string,
bucket: string,
useSsl: boolean,
region: string = 'auto',
) {
let fullEndpoint = endpoint
if (!fullEndpoint.startsWith('http://') && !fullEndpoint.startsWith('https://')) {
const scheme = useSsl ? 'https' : 'http'
fullEndpoint = `${scheme}://${endpoint}`
}
this.client = new S3Client({
region,
endpoint: fullEndpoint,
credentials: {
accessKeyId,
secretAccessKey,
},
forcePathStyle: false,
})
this.bucket = bucket
}
async getObjectSize(bucket: string, key: string): Promise<number> {
const command = new HeadObjectCommand({
Bucket: bucket,
Key: key,
})
const response = await this.client.send(command)
return response.ContentLength || 0
}
async putObject(
bucket: string,
key: string,
body: Buffer | Uint8Array | string,
size: number,
contentType?: string,
): Promise<void> {
const command = new PutObjectCommand({
Bucket: bucket,
Key: key,
Body: body,
ContentLength: size,
ContentType: contentType,
})
await this.client.send(command)
}
async getObject(bucket: string, key: string): Promise<S3Object> {
const command = new GetObjectCommand({
Bucket: bucket,
Key: key,
})
const response = await this.client.send(command)
if (!response.Body) {
throw new Error('Empty response body')
}
const byteArray = await response.Body.transformToByteArray()
return {
buffer: Buffer.from(byteArray),
contentType: response.ContentType || 'application/octet-stream',
}
}
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,
Key: key,
})
const response = await this.client.send(command)
if (!response.Body) {
throw new Error('Empty response body')
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const stream = response.Body as any
const writeStream = fs.createWriteStream(filePath)
await new Promise((resolve, reject) => {
stream
.pipe(writeStream)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.on('error', (err: any) => {
writeStream.close()
reject(err)
})
.on('finish', () => {
writeStream.close()
resolve(null)
})
})
}
async deleteObject(bucket: string, key: string): Promise<number> {
const command = new DeleteObjectCommand({
Bucket: bucket,
Key: key,
})
try {
await this.client.send(command)
return 1
} catch {
// If object doesn't exist, we return 0
return 0
}
}
async deletePrefix(bucket: string, prefix: string): Promise<number> {
const keys = await this.listObjects(bucket, prefix)
if (keys.length > 0) {
await Promise.all(keys.map((key) => this.deleteObject(bucket, key)))
}
return keys.length
}
async headObject(bucket: string, key: string): Promise<ObjectInfo> {
const command = new HeadObjectCommand({
Bucket: bucket,
Key: key,
})
const response = await this.client.send(command)
return {
key,
size: response.ContentLength || 0,
lastModified: response.LastModified || new Date(),
contentType: response.ContentType || 'application/octet-stream',
eTag: response.ETag || '',
}
}
async listObjects(bucket: string, prefix: string): Promise<string[]> {
const keys: string[] = []
let isTruncated = true
let continuationToken: string | undefined = undefined
while (isTruncated) {
const command: ListObjectsV2Command = new ListObjectsV2Command({
Bucket: bucket,
Prefix: prefix,
ContinuationToken: continuationToken,
})
const response = await this.client.send(command)
if (response.Contents) {
for (const item of response.Contents) {
if (item.Key) {
keys.push(item.Key)
}
}
}
isTruncated = response.IsTruncated || false
continuationToken = response.NextContinuationToken
}
return keys
}
async uploadFile(filePath: string, contentType: string): Promise<string> {
const key = ulid() + path.extname(filePath)
await this.uploadFileToKey(filePath, key, contentType)
return key
}
async uploadFileToKey(filePath: string, key: string, contentType: string): Promise<void> {
const fileStats = statSync(filePath)
const fileContent = readFileSync(filePath)
const command = new PutObjectCommand({
Bucket: this.bucket,
Key: key,
Body: fileContent,
ContentLength: fileStats.size,
ContentType: contentType,
})
await this.client.send(command)
}
async presign(bucket: string, key: string, method: string): Promise<string> {
let command: GetObjectCommand | PutObjectCommand
if (method === 'GET') {
command = new GetObjectCommand({
Bucket: bucket,
Key: key,
})
} else if (method === 'PUT') {
command = new PutObjectCommand({
Bucket: bucket,
Key: key,
})
} else {
throw new Error(`Invalid method: ${method}`)
}
// 1 hour expiration
return await getSignedUrl(this.client, command, { expiresIn: 3600 })
}
}
export class LocalStorageService implements S3Service {
private basePath: string
private endpoint: string
constructor(endpoint: string, basePath: string = 'data') {
this.endpoint = endpoint.replace(/\/$/, '')
this.basePath = path.resolve(basePath)
if (!fs.existsSync(this.basePath)) {
fs.mkdirSync(this.basePath, { recursive: true })
}
}
private getFilePath(bucket: string, key: string): string {
const filePath = path.join(this.basePath, bucket, key)
if (!filePath.startsWith(this.basePath)) {
throw new Error(`Invalid path: potential path traversal detected`)
}
return filePath
}
async getObjectSize(bucket: string, key: string): Promise<number> {
const filePath = this.getFilePath(bucket, key)
try {
const stats = await fs.promises.stat(filePath)
return stats.size
} catch (e: unknown) {
if (e instanceof Error && (e as NodeJS.ErrnoException).code === 'ENOENT') {
throw new Error(`NoSuchKey: The specified key does not exist.`)
}
throw e
}
}
async putObject(
bucket: string,
key: string,
body: Buffer | Uint8Array | string,
_size: number, // eslint-disable-line @typescript-eslint/no-unused-vars
_contentType?: string, // eslint-disable-line @typescript-eslint/no-unused-vars
): Promise<void> {
const filePath = this.getFilePath(bucket, key)
const dir = path.dirname(filePath)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
await fs.promises.writeFile(filePath, body)
}
async getObject(bucket: string, key: string): Promise<S3Object> {
const filePath = this.getFilePath(bucket, key)
try {
const buffer = await fs.promises.readFile(filePath)
return {
buffer,
contentType: Bun.file(filePath).type || 'application/octet-stream',
}
} catch (e: unknown) {
if (e instanceof Error && (e as NodeJS.ErrnoException).code === 'ENOENT') {
throw new Error(`NoSuchKey: The specified key does not exist.`)
}
throw e
}
}
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)
}
async deleteObject(bucket: string, key: string): Promise<number> {
const filePath = this.getFilePath(bucket, key)
try {
await fs.promises.unlink(filePath)
return 1
} catch (e: unknown) {
if (e instanceof Error && (e as NodeJS.ErrnoException).code === 'ENOENT') {
// Ignore if file doesn't exist
return 0
}
throw e
}
}
async deletePrefix(bucket: string, prefix: string): Promise<number> {
// Get count of files before deleting
const keys = await this.listObjects(bucket, prefix)
if (keys.length === 0) return 0
const dirPath = this.getFilePath(bucket, prefix)
try {
await fs.promises.rm(dirPath, { recursive: true, force: true })
return keys.length
} catch (e: unknown) {
if (e instanceof Error && (e as NodeJS.ErrnoException).code === 'ENOENT') {
return 0
}
throw e
}
}
async headObject(bucket: string, key: string): Promise<ObjectInfo> {
const filePath = this.getFilePath(bucket, key)
try {
const stats = await fs.promises.stat(filePath)
// Simple hash to simulate ETag
const hash = crypto
.createHash('md5')
.update(filePath + stats.mtimeMs)
.digest('hex')
return {
key,
size: stats.size,
lastModified: stats.mtime,
contentType: Bun.file(key).type || 'application/octet-stream',
eTag: `"${hash}"`,
}
} catch (e: unknown) {
if (e instanceof Error && (e as NodeJS.ErrnoException).code === 'ENOENT') {
throw new Error(`NoSuchKey: The specified key does not exist.`)
}
throw e
}
}
async listObjects(bucket: string, prefix: string): Promise<string[]> {
const bucketDir = path.join(this.basePath, bucket)
const keys: string[] = []
if (!fs.existsSync(bucketDir)) {
return keys
}
const walkDir = async (currentDir: string) => {
const files = await fs.promises.readdir(currentDir)
for (const file of files) {
const fullPath = path.join(currentDir, file)
const stat = await fs.promises.stat(fullPath)
if (stat.isDirectory()) {
await walkDir(fullPath)
} else {
// Get relative path from bucket dir
const relPath = path.relative(bucketDir, fullPath)
// Normalise separators
const key = relPath.split(path.sep).join('/')
if (key.startsWith(prefix)) {
keys.push(key)
}
}
}
}
await walkDir(bucketDir)
return keys
}
async uploadFile(filePath: string, contentType: string): Promise<string> {
const key = ulid() + path.extname(filePath)
await this.uploadFileToKey(filePath, key, contentType)
return key
}
async uploadFileToKey(
filePath: string,
key: string,
_contentType: string, // eslint-disable-line @typescript-eslint/no-unused-vars
): Promise<void> {
// using a default bucket for direct upload, or the user has to supply it
// S3StorageService uses this.bucket
const bucket = process.env.S3_BUCKET || 'shumai'
const destPath = this.getFilePath(bucket, key)
const dir = path.dirname(destPath)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
await fs.promises.copyFile(filePath, destPath)
}
async presign(bucket: string, key: string, method: string): Promise<string> {
if (method !== 'GET' && method !== 'PUT') {
throw new Error(`Invalid method: ${method}`)
}
if (method === 'PUT') {
return `${this.endpoint}${signLocalUrl(bucket, key)}`
}
return `${this.endpoint}/files/${bucket}/${key}`
}
}
const storageBackend = process.env.STORAGE_BACKEND || 'local'
const s3Endpoint = process.env.AWS_ENDPOINT_URL_S3 || 'http://localhost:3000'
export const s3Service: S3Service =
storageBackend === 's3'
? new S3StorageService(
s3Endpoint,
process.env.S3_ACCESS_KEY_ID || 'minioadmin',
process.env.S3_SECRET_ACCESS_KEY || 'minioadmin',
process.env.S3_BUCKET || 'shumai',
process.env.S3_USE_SSL === 'true',
process.env.S3_REGION || 'auto',
)
: new LocalStorageService(s3Endpoint)
@@ -0,0 +1,286 @@
import { describe, expect, it, beforeEach } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import { SearchService } from './search'
import { AssetType } from '@shumai/db'
describe('N-gram Search Integration', () => {
setupTestDbHooks()
let searchService: SearchService
beforeEach(() => {
searchService = new SearchService()
})
it('should automatically populate nameNgram on asset creation', async () => {
const asset = await prisma.asset.create({
data: {
name: 'Apple Pie',
type: AssetType.file,
status: 'uploaded',
sizeByte: 100,
},
})
expect(asset.nameNgram).toContain('app')
expect(asset.nameNgram).toContain('pie')
expect(asset.nameNgram).toContain('ple')
})
it('should automatically update nameNgram on asset update', async () => {
const asset = await prisma.asset.create({
data: {
name: 'Apple',
type: AssetType.file,
status: 'uploaded',
},
})
const updated = await prisma.asset.update({
where: { id: asset.id },
data: { name: 'Banana' },
})
expect(updated.nameNgram).toContain('ban')
expect(updated.nameNgram).not.toContain('app')
})
it('should find assets using n-gram search', async () => {
const root = await prisma.asset.create({
data: { name: 'root', type: AssetType.folder, status: 'uploaded' },
})
await prisma.asset.create({
data: { name: '北京大学', type: AssetType.file, status: 'uploaded', parentId: root.id },
})
await prisma.asset.create({
data: { name: '清华大学', type: AssetType.file, status: 'uploaded', parentId: root.id },
})
const result = await searchService.search(root.id, {
operator: 'AND',
recursively: true,
isSemantic: false,
conditions: [
{
field: 'name',
operator: 'contains',
value: '北京',
},
],
})
expect(result.data).toHaveLength(1)
expect(result.data[0].name).toBe('北京大学')
})
it('should handle false positives correctly using the recheck', async () => {
const root = await prisma.asset.create({
data: { name: 'root', type: AssetType.folder, status: 'uploaded' },
})
await prisma.asset.create({
data: { name: 'hello world', type: AssetType.file, status: 'uploaded', parentId: root.id },
})
await prisma.asset.create({
data: { name: 'hellXello', type: AssetType.file, status: 'uploaded', parentId: root.id },
})
const result = await searchService.search(root.id, {
operator: 'AND',
recursively: true,
isSemantic: false,
conditions: [
{
field: 'name',
operator: 'contains',
value: 'hello',
},
],
})
expect(result.data).toHaveLength(1)
expect(result.data[0].name).toBe('hello world')
})
describe('N-gram Search Matrix', () => {
let rootId: string
beforeEach(async () => {
const root = await prisma.asset.create({
data: { name: 'matrix-root', type: AssetType.folder, status: 'uploaded' },
})
rootId = root.id
const names = [
'apple.png',
'banana_v2.mp4',
'北京大学-最终版.docx',
'清华大学-final.pdf',
'project-2026-05-10',
'123456789.txt',
'hellXello',
'hello world',
'my-awesome-asset',
'我的资源',
'foo-bar',
'foo bar',
]
for (const name of names) {
await prisma.asset.create({
data: {
name,
type: AssetType.file,
status: 'uploaded',
parentId: rootId,
},
})
}
})
it.each([
{ val: 'apple', expected: ['apple.png'] },
{ val: 'v2', expected: ['banana_v2.mp4'] },
{ val: '北京', expected: ['北京大学-最终版.docx'] },
{ val: '大学', expected: ['北京大学-最终版.docx', '清华大学-final.pdf'] },
{ val: 'final', expected: ['清华大学-final.pdf'] },
{ val: '2026', expected: ['project-2026-05-10'] },
{ val: 'hello', expected: ['hello world'] },
{ val: 'awesome', expected: ['my-awesome-asset'] },
{ val: '资源', expected: ['我的资源'] },
{ val: '123', expected: ['123456789.txt'] },
{ val: 'docx', expected: ['北京大学-最终版.docx'] },
{ val: 'none-match', expected: [] },
// Hyphen/Space sensitivity tests
{ val: 'foo-bar', expected: ['foo-bar'] },
{ val: 'foo bar', expected: ['foo bar'] },
])('should match "$val" with names $expected', async ({ val, expected }) => {
const result = await searchService.search(rootId, {
operator: 'AND',
recursively: true,
isSemantic: false,
conditions: [
{
field: 'name',
operator: 'contains',
value: val,
},
],
})
const actualNames = result.data.map((a) => a.name).sort()
expect(actualNames).toEqual(expected.sort())
})
})
describe('Switching Search Probe Logic', () => {
let rootId: string
beforeEach(async () => {
const root = await prisma.asset.create({
data: { name: 'probe-root', type: AssetType.folder, status: 'uploaded' },
})
rootId = root.id
})
it('should use GIN index when probe count is less than 10001', async () => {
const queries: string[] = []
const mockPrisma = new Proxy(prisma, {
get(target, prop) {
if (prop === '$queryRaw') {
return (prismaSql: unknown) => {
const sqlStr = (prismaSql as { text?: string })?.text || ''
if (sqlStr) {
queries.push(sqlStr)
}
let result: { id: string }[] = []
if (!sqlStr.includes('as "assetId"')) {
// Probe query: return 5 matches
result = Array(5).fill({ id: '1' })
}
const promise = Promise.resolve(result)
Object.defineProperty(promise, Symbol.toStringTag, {
value: 'PrismaPromise',
configurable: true,
writable: true,
})
return promise as unknown as ReturnType<typeof prisma.$queryRaw>
}
}
const val = Reflect.get(target, prop)
if (typeof val === 'function') {
return val.bind(target)
}
return val
},
})
const localSearchService = new SearchService(mockPrisma)
await localSearchService.search(rootId, {
operator: 'AND',
recursively: true,
isSemantic: false,
conditions: [{ field: 'name', operator: 'contains', value: 'rareterm' }],
})
// Verify probe and main query were executed
expect(queries).toHaveLength(2)
// Check that main query used GIN index
const mainQuery = queries.find((q) => q.includes('as "assetId"'))
expect(mainQuery).toBeDefined()
expect(mainQuery).toContain('name_ngram @>')
expect(mainQuery).toContain('name ILIKE')
})
it('should fallback to simple ILIKE when probe count is 10001 or more', async () => {
const queries: string[] = []
const mockPrisma = new Proxy(prisma, {
get(target, prop) {
if (prop === '$queryRaw') {
return (prismaSql: unknown) => {
const sqlStr = (prismaSql as { text?: string })?.text || ''
if (sqlStr) {
queries.push(sqlStr)
}
let result: { id: string }[] = []
if (!sqlStr.includes('as "assetId"')) {
// Probe query: return 10001 matches
result = Array(10001).fill({ id: '1' })
}
const promise = Promise.resolve(result)
Object.defineProperty(promise, Symbol.toStringTag, {
value: 'PrismaPromise',
configurable: true,
writable: true,
})
return promise as unknown as ReturnType<typeof prisma.$queryRaw>
}
}
const val = Reflect.get(target, prop)
if (typeof val === 'function') {
return val.bind(target)
}
return val
},
})
const localSearchService = new SearchService(mockPrisma)
await localSearchService.search(rootId, {
operator: 'AND',
recursively: true,
isSemantic: false,
conditions: [{ field: 'name', operator: 'contains', value: 'commonterm' }],
})
// Verify probe and main query were executed
expect(queries).toHaveLength(2)
// Check that main query did NOT use GIN index but used ILIKE
const mainQuery = queries.find((q) => q.includes('as "assetId"'))
expect(mainQuery).toBeDefined()
expect(mainQuery).not.toContain('name_ngram @>')
expect(mainQuery).toContain('name ILIKE')
})
})
})
+834
View File
@@ -0,0 +1,834 @@
import { describe, expect, it, beforeEach, vi } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import { SearchService } from './search'
import { SearchConditionOperator } from '@shumai/dtos'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { workflowService } from '@/workflow/workflow'
import { AssetType } from '@shumai/db'
describe('SearchService', () => {
setupTestDbHooks()
let searchService: SearchService
beforeEach(() => {
searchService = new SearchService()
})
const setupBasicAssets = async () => {
const user = await prisma.user.create({
data: { name: 'test-user-search', email: 'search-user@example.com', type: 'human' },
})
const team = await prisma.team.create({
data: { name: 'test-team' },
})
const project = await prisma.project.create({
data: { name: 'test-project', teamId: team.id },
})
const rootFolder = await prisma.asset.create({
data: {
name: 'root',
type: AssetType.folder,
projectId: project.id,
creatorId: user.id,
sizeByte: 0,
status: 'uploaded',
},
})
const subFolder = await prisma.asset.create({
data: {
name: 'subfolder',
type: AssetType.folder,
projectId: project.id,
parentId: rootFolder.id,
creatorId: user.id,
sizeByte: 0,
status: 'uploaded',
},
})
const file1 = await prisma.asset.create({
data: {
name: 'file1',
type: AssetType.file,
projectId: project.id,
parentId: rootFolder.id,
creatorId: user.id,
sizeByte: 100,
status: 'uploaded',
createdAt: new Date('2023-01-01T00:00:00Z'),
},
})
const file2 = await prisma.asset.create({
data: {
name: 'file2',
type: AssetType.file,
projectId: project.id,
parentId: subFolder.id,
creatorId: user.id,
sizeByte: 200,
status: 'uploaded',
createdAt: new Date('2023-01-01T00:00:01Z'),
},
})
await prisma.assetMetadataValue.create({
data: {
assetId: file2.id,
fieldKey: 'status',
stringValue: 'approved',
},
})
return { rootFolder, subFolder, file1, file2 }
}
const setupMatrixAssets = async () => {
const user = await prisma.user.create({
data: { name: 'matrix-user', email: 'matrix@example.com', type: 'human' },
})
const team = await prisma.team.create({ data: { name: 'matrix-team' } })
const project = await prisma.project.create({ data: { name: 'matrix-proj', teamId: team.id } })
const root = await prisma.asset.create({
data: {
name: 'matrix-root',
type: AssetType.folder,
projectId: project.id,
creatorId: user.id,
status: 'uploaded',
},
})
const createWithMeta = async (name: string, meta: Record<string, unknown>) => {
const asset = await prisma.asset.create({
data: {
name,
type: AssetType.file,
projectId: project.id,
parentId: root.id,
creatorId: user.id,
status: 'uploaded',
sizeByte: 100,
},
})
const reqs = Object.entries(meta).map(([key, value]) => ({ key, value }))
await metadataService.updateAssetMetadata(asset.id, reqs)
return asset
}
// String fields
await createWithMeta('str-apple', { text: 'apple' })
await createWithMeta('str-banana', { text: 'banana' })
// Number fields
await createWithMeta('num-10', { num: 10 })
await createWithMeta('num-20', { num: 20 })
// Bool fields
await createWithMeta('bool-true', { bool: true })
await createWithMeta('bool-false', { bool: false })
// SelectMulti
await createWithMeta('multi-a-b', { multi: ['a', 'b'] })
await createWithMeta('multi-b-c', { multi: ['b', 'c'] })
// Date
await createWithMeta('date-today', { date: new Date().toISOString() })
const yesterday = new Date()
yesterday.setDate(yesterday.getDate() - 1)
await createWithMeta('date-yesterday', { date: yesterday.toISOString() })
// Name field specific tests
await createWithMeta('name-contains-test', {})
// One with nothing
await prisma.asset.create({
data: {
name: 'nothing',
type: AssetType.file,
projectId: project.id,
parentId: root.id,
creatorId: user.id,
status: 'uploaded',
sizeByte: 100,
},
})
return { root }
}
describe('Exhaustive Operator Matrix', () => {
let rootId: string
beforeEach(async () => {
const { root } = await setupMatrixAssets()
rootId = root.id
})
it.each([
// Name field (System)
{ field: 'name', op: 'eq', val: 'str-apple', expected: ['str-apple'] },
{
field: 'name',
op: 'neq',
val: 'str-apple',
expected: [
'str-banana',
'num-10',
'num-20',
'bool-true',
'bool-false',
'multi-a-b',
'multi-b-c',
'date-today',
'date-yesterday',
'name-contains-test',
'nothing',
],
},
{ field: 'name', op: 'contains', val: 'apple', expected: ['str-apple'] },
{
field: 'name',
op: 'notContains',
val: 'apple',
expected: [
'str-banana',
'num-10',
'num-20',
'bool-true',
'bool-false',
'multi-a-b',
'multi-b-c',
'date-today',
'date-yesterday',
'name-contains-test',
'nothing',
],
},
{ field: 'name', op: 'isEmpty', val: '', expected: [] }, // name is never empty in this setup
{
field: 'name',
op: 'isNotEmpty',
val: '',
expected: [
'str-apple',
'str-banana',
'num-10',
'num-20',
'bool-true',
'bool-false',
'multi-a-b',
'multi-b-c',
'date-today',
'date-yesterday',
'name-contains-test',
'nothing',
],
},
// String Metadata
{ field: 'text', op: 'eq', val: 'apple', expected: ['str-apple'] },
{
field: 'text',
op: 'neq',
val: 'apple',
expected: [
'str-banana',
'num-10',
'num-20',
'bool-true',
'bool-false',
'multi-a-b',
'multi-b-c',
'date-today',
'date-yesterday',
'name-contains-test',
'nothing',
],
},
{
field: 'text',
op: 'isEmpty',
val: null,
expected: [
'num-10',
'num-20',
'bool-true',
'bool-false',
'multi-a-b',
'multi-b-c',
'date-today',
'date-yesterday',
'name-contains-test',
'nothing',
],
},
{ field: 'text', op: 'isNotEmpty', val: null, expected: ['str-apple', 'str-banana'] },
// Number Metadata
{ field: 'num', op: 'eq', val: 10, expected: ['num-10'] },
{
field: 'num',
op: 'neq',
val: 10,
expected: [
'str-apple',
'str-banana',
'num-20',
'bool-true',
'bool-false',
'multi-a-b',
'multi-b-c',
'date-today',
'date-yesterday',
'name-contains-test',
'nothing',
],
},
{ field: 'num', op: 'gt', val: 15, expected: ['num-20'] },
{ field: 'num', op: 'lt', val: 15, expected: ['num-10'] },
{ field: 'num', op: 'gte', val: 20, expected: ['num-20'] },
{ field: 'num', op: 'lte', val: 10, expected: ['num-10'] },
// Boolean Metadata
{ field: 'bool', op: 'eq', val: true, expected: ['bool-true'] },
{ field: 'bool', op: 'eq', val: false, expected: ['bool-false'] },
// SelectMulti Metadata
{ field: 'multi', op: 'hasAny', val: ['a'], expected: ['multi-a-b'] },
{ field: 'multi', op: 'hasAny', val: ['b'], expected: ['multi-a-b', 'multi-b-c'] },
{ field: 'multi', op: 'hasAll', val: ['a', 'b'], expected: ['multi-a-b'] },
{ field: 'multi', op: 'hasAll', val: ['a', 'c'], expected: [] },
{
field: 'multi',
op: 'hasNone',
val: ['a'],
expected: [
'str-apple',
'str-banana',
'num-10',
'num-20',
'bool-true',
'bool-false',
'multi-b-c',
'date-today',
'date-yesterday',
'name-contains-test',
'nothing',
],
},
{ field: 'multi', op: 'eq', val: ['a', 'b'], expected: ['multi-a-b'] },
// Date Metadata
{ field: 'date', op: 'eq', val: 'today', expected: ['date-today'] },
{ field: 'date', op: 'isWithin', val: 'today', expected: ['date-today'] },
{ field: 'date', op: 'lt', val: 'today', expected: ['date-yesterday'] },
{ field: 'date', op: 'gt', val: 'yesterday', expected: ['date-today'] },
// System Fields (native columns)
{
field: 'sizeByte',
op: 'gt',
val: 50,
expected: [
'str-apple',
'str-banana',
'num-10',
'num-20',
'bool-true',
'bool-false',
'multi-a-b',
'multi-b-c',
'date-today',
'date-yesterday',
'name-contains-test',
'nothing',
],
},
{ field: 'name', op: 'contains', val: 'apple', expected: ['str-apple'] },
{
field: 'createdAt',
op: 'gt',
val: 'one week ago',
expected: [
'str-apple',
'str-banana',
'num-10',
'num-20',
'bool-true',
'bool-false',
'multi-a-b',
'multi-b-c',
'date-today',
'date-yesterday',
'name-contains-test',
'nothing',
],
},
])('filters $field with $op $val', async ({ field, op, val, expected }) => {
const result = await searchService.search(rootId, {
conditions: [{ field, operator: op as SearchConditionOperator, value: val }],
recursively: true,
assetType: 'file',
operator: 'AND',
isSemantic: false,
})
const names = result.data.map((a) => a.name).sort()
expect(names).toEqual(expected.sort())
})
})
it('searches for assets by name (equals)', async () => {
const { rootFolder, file1 } = await setupBasicAssets()
const result = await searchService.search(rootFolder.id, {
conditions: [{ field: 'name', operator: 'eq', value: 'file1' }],
recursively: true,
assetType: 'file',
operator: 'AND',
isSemantic: false,
})
expect(result.data).toHaveLength(1)
expect(result.data[0].id).toBe(file1.id)
})
it('searches for assets by name (contains)', async () => {
const { rootFolder, file1, file2 } = await setupBasicAssets()
const result = await searchService.search(rootFolder.id, {
conditions: [{ field: 'name', operator: 'contains', value: 'file' }],
recursively: true,
assetType: 'file',
operator: 'AND',
isSemantic: false,
})
expect(result.data).toHaveLength(2)
const ids = result.data.map((a) => a.id)
expect(ids).toContain(file1.id)
expect(ids).toContain(file2.id)
})
it('searches for assets by metadata (equals)', async () => {
const { rootFolder, file2 } = await setupBasicAssets()
const result = await searchService.search(rootFolder.id, {
conditions: [{ field: 'status', operator: 'eq', value: 'approved' }],
recursively: true,
assetType: 'file',
operator: 'AND',
isSemantic: false,
})
expect(result.data).toHaveLength(1)
expect(result.data[0].id).toBe(file2.id)
})
it('searches only in the specified folder if recursively is false', async () => {
const { rootFolder, file1 } = await setupBasicAssets()
const result = await searchService.search(rootFolder.id, {
conditions: [{ field: 'name', operator: 'contains', value: 'file' }],
recursively: false,
assetType: 'file',
operator: 'AND',
isSemantic: false,
})
// Should only find file1, as file2 is in subfolder
expect(result.data).toHaveLength(1)
expect(result.data[0].id).toBe(file1.id)
})
it('sorts by createdAt', async () => {
const { rootFolder } = await setupBasicAssets()
// file1 was created before file2, but file2 is in subfolder.
// wait, I need to be sure about the creation order.
// setupBasicAssets creates file1 then file2.
const resultAsc = await searchService.search(rootFolder.id, {
sort: { field: 'createdAt', order: 'asc' },
recursively: true,
assetType: 'file',
operator: 'AND',
conditions: [],
isSemantic: false,
})
expect(resultAsc.data[0].name).toBe('file1')
expect(resultAsc.data[1].name).toBe('file2')
const resultDesc = await searchService.search(rootFolder.id, {
sort: { field: 'createdAt', order: 'desc' },
recursively: true,
assetType: 'file',
operator: 'AND',
conditions: [],
isSemantic: false,
})
expect(resultDesc.data[0].name).toBe('file2')
expect(resultDesc.data[1].name).toBe('file1')
})
it('sorts by sizeByte', async () => {
const { rootFolder } = await setupBasicAssets()
// file1 size 100, file2 size 200
const resultAsc = await searchService.search(rootFolder.id, {
sort: { field: 'sizeByte', order: 'asc' },
recursively: true,
assetType: 'file',
operator: 'AND',
conditions: [],
isSemantic: false,
})
expect(resultAsc.data[0].sizeByte).toBe(100)
expect(resultAsc.data[1].sizeByte).toBe(200)
const resultDesc = await searchService.search(rootFolder.id, {
sort: { field: 'sizeByte', order: 'desc' },
recursively: true,
assetType: 'file',
operator: 'AND',
conditions: [],
isSemantic: false,
})
expect(resultDesc.data[0].sizeByte).toBe(200)
expect(resultDesc.data[1].sizeByte).toBe(100)
})
it('includes symlinks when showSymlink is true', async () => {
const { rootFolder, file1 } = await setupBasicAssets()
// Create a symlink in the root folder pointing to file2
const symlink = await prisma.asset.create({
data: {
name: 'symlink-to-file2',
type: AssetType.symlink,
projectId: file1.projectId,
parentId: rootFolder.id,
targetId: file1.id, // Pointing to file1 for simplicity
status: 'uploaded',
},
})
// Search without showSymlink
const resultNormal = await searchService.search(rootFolder.id, {
recursively: false,
assetType: 'file',
operator: 'AND',
conditions: [],
isSemantic: false,
})
expect(resultNormal.data.find((a) => a.id === symlink.id)).toBeUndefined()
// Search with showSymlink
const resultWithSymlink = await searchService.search(rootFolder.id, {
recursively: false,
assetType: 'file',
operator: 'AND',
conditions: [],
showSymlink: true,
isSemantic: false,
})
expect(resultWithSymlink.data.find((a) => a.id === symlink.id)).toBeDefined()
})
describe('Semantic Search with multiple chunks and distance ordering', () => {
it('returns multiple matching segments from the same asset and orders by distance', async () => {
const user = await prisma.user.create({
data: { name: 'semantic-user', email: 'semantic-user@example.com', type: 'human' },
})
const team = await prisma.team.create({
data: { name: 'semantic-team' },
})
const project = await prisma.project.create({
data: { name: 'semantic-project', teamId: team.id },
})
// We need an embedding agent that is enabled for semantic search to be allowed
const botUser = await prisma.user.create({
data: { name: 'Embedding Bot', email: 'emb@example.com', type: 'agent' },
})
const provider = await prisma.provider.create({
data: {
name: 'google',
teamId: team.id,
config: { api: 'google', apiKey: 'key' } as unknown as PrismaJson.ProviderConfig,
},
})
const model = await prisma.model.create({
data: {
modelId: 'gemini',
name: 'Gemini',
providerId: provider.id,
config: {
reasoning: false,
input: ['text'],
contextWindow: 1000,
maxTokens: 1000,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
} as unknown as PrismaJson.ModelConfig,
},
})
await prisma.agent.create({
data: {
id: botUser.id,
teamId: team.id,
type: 'embedding',
enabled: true,
providerId: provider.id,
modelId: model.id,
config: { provider: 'google', model: 'gemini' },
},
})
const rootFolder = await prisma.asset.create({
data: {
name: 'root',
type: AssetType.folder,
projectId: project.id,
creatorId: user.id,
status: 'uploaded',
},
})
const videoAssetA = await prisma.asset.create({
data: {
name: 'videoA.mp4',
type: AssetType.file,
projectId: project.id,
parentId: rootFolder.id,
creatorId: user.id,
status: 'uploaded',
},
})
const videoAssetB = await prisma.asset.create({
data: {
name: 'videoB.mp4',
type: AssetType.file,
projectId: project.id,
parentId: rootFolder.id,
creatorId: user.id,
status: 'uploaded',
},
})
// Insert embedding chunks:
// We will insert 2 chunks for videoAssetA and 1 chunk for videoAssetB.
// Vector size is 1536. We use unit vectors to ensure distinct cosine distances:
// Chunk A1: startTime = 0.0, endTime = 10.0, embedding = [1, 0, 0...] (cosine similarity = 1.0, distance = 0.0)
// Chunk B1: startTime = 5.0, endTime = 15.0, embedding = [1, 1, 0...] (cosine similarity = 0.707, distance = 0.293)
// Chunk A2: startTime = 10.0, endTime = 20.0, embedding = [0, 1, 0...] (cosine similarity = 0.0, distance = 1.0)
const arrA1 = Array(1536).fill(0)
arrA1[0] = 1.0
const vectorA1 = JSON.stringify(arrA1)
const arrB1 = Array(1536).fill(0)
arrB1[0] = 1.0
arrB1[1] = 1.0
const vectorB1 = JSON.stringify(arrB1)
const arrA2 = Array(1536).fill(0)
arrA2[1] = 1.0
const vectorA2 = JSON.stringify(arrA2)
await prisma.$executeRaw`
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, created_at, updated_at)
VALUES (
'chunk-a1',
${videoAssetA.id},
${vectorA1}::vector,
0.0,
10.0,
NOW(),
NOW()
)
`
await prisma.$executeRaw`
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, created_at, updated_at)
VALUES (
'chunk-a2',
${videoAssetA.id},
${vectorA2}::vector,
10.0,
20.0,
NOW(),
NOW()
)
`
await prisma.$executeRaw`
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, created_at, updated_at)
VALUES (
'chunk-b1',
${videoAssetB.id},
${vectorB1}::vector,
5.0,
15.0,
NOW(),
NOW()
)
`
// Mock the embedding generation workflow task.
// Our query vector points along the first dimension [1, 0, 0...]
const queryVector = Array(1536).fill(0)
queryVector[0] = 1.0
const mockExecuteWait = vi
.spyOn(workflowService, 'executeWait')
.mockImplementation(async (task) => {
return {
...task,
status: 'completed',
output: {
embedding: queryVector,
},
} as unknown as typeof task
})
// Search using semantic mode
const result = await searchService.search(rootFolder.id, {
recursively: true,
assetType: 'file',
operator: 'AND',
conditions: [],
query: 'find some cute cat video segments',
isSemantic: true,
})
// We expect 3 distinct results because videoAssetA matches twice and videoAssetB matches once:
// Sorting should be based on vector distance:
// Distance from query (0.2) to:
// - Chunk A1 (0.1): |0.2 - 0.1| = 0.1 -> closest (1st)
// - Chunk B1 (0.5): |0.2 - 0.5| = 0.3 -> medium (2nd)
// - Chunk A2 (0.9): |0.2 - 0.9| = 0.7 -> farthest (3rd)
expect(result.data).toHaveLength(3)
// 1st: Chunk A1
expect(result.data[0].id).toBe(videoAssetA.id)
expect(result.data[0].startTime).toBe(0)
expect(result.data[0].endTime).toBe(10)
// 2nd: Chunk B1
expect(result.data[1].id).toBe(videoAssetB.id)
expect(result.data[1].startTime).toBe(5)
expect(result.data[1].endTime).toBe(15)
// 3rd: Chunk A2
expect(result.data[2].id).toBe(videoAssetA.id)
expect(result.data[2].startTime).toBe(10)
expect(result.data[2].endTime).toBe(20)
mockExecuteWait.mockRestore()
})
})
})
describe('SearchService — natural sort by name', () => {
setupTestDbHooks()
let searchService: SearchService
beforeEach(() => {
searchService = new SearchService()
})
const setupSearchNaturalSortAssets = async (names: string[]) => {
const user = await prisma.user.create({
data: {
name: 'search-natural-sort-user',
email: `search-natural-sort-${Date.now()}@example.com`,
type: 'human',
},
})
const team = await prisma.team.create({ data: { name: 'search-natural-sort-team' } })
const project = await prisma.project.create({
data: { name: 'search-natural-sort-proj', teamId: team.id },
})
const root = await prisma.asset.create({
data: {
name: 'root',
type: AssetType.folder,
projectId: project.id,
creatorId: user.id,
status: 'uploaded',
},
})
for (const name of names) {
await prisma.asset.create({
data: {
name,
type: AssetType.file,
projectId: project.id,
parentId: root.id,
creatorId: user.id,
status: 'uploaded',
sizeByte: 0,
},
})
}
return { root }
}
it('returns results in natural name order (asc) via raw-SQL sort path', async () => {
const { root } = await setupSearchNaturalSortAssets(['clip10', 'clip2', 'clip20', 'clip1'])
const result = await searchService.search(root.id, {
recursively: false,
assetType: 'file',
operator: 'AND',
conditions: [],
isSemantic: false,
sort: { field: 'name', order: 'asc' },
})
expect(result.data.map((a) => a.name)).toEqual(['clip1', 'clip2', 'clip10', 'clip20'])
})
it('returns results in natural name order (desc) via raw-SQL sort path', async () => {
const { root } = await setupSearchNaturalSortAssets(['clip10', 'clip2', 'clip20', 'clip1'])
const result = await searchService.search(root.id, {
recursively: false,
assetType: 'file',
operator: 'AND',
conditions: [],
isSemantic: false,
sort: { field: 'name', order: 'desc' },
})
expect(result.data.map((a) => a.name)).toEqual(['clip20', 'clip10', 'clip2', 'clip1'])
})
it('sorts mixed alpha-numeric names naturally via search', async () => {
const { root } = await setupSearchNaturalSortAssets([
'scene 100',
'scene 9',
'scene 10',
'scene 2',
])
const result = await searchService.search(root.id, {
recursively: false,
assetType: 'file',
operator: 'AND',
conditions: [],
isSemantic: false,
sort: { field: 'name', order: 'asc' },
})
expect(result.data.map((a) => a.name)).toEqual(['scene 2', 'scene 9', 'scene 10', 'scene 100'])
})
})
+394
View File
@@ -0,0 +1,394 @@
import { prisma } from '@shumai/db'
import { Prisma, AssetType, WorkflowTaskType } from '@shumai/db'
import { AssetService, assetService } from '@shumai/core/src/asset/asset'
import { AssetInfo } from '@shumai/dtos'
import { SearchRequest } from '@shumai/dtos'
import { PaginatedData, decodeCursor, encodeCursor, PageInfo } from '@shumai/core/src/pagination'
import { generateSearchNgrams } from '@/utils/ngram'
import { workflowService } from '@/workflow/workflow'
import { HTTPException } from 'hono/http-exception'
import { SqlQueryBuilder } from './sql-query-builder'
export class SearchService {
constructor(
private readonly prismaClient: typeof prisma = prisma,
private readonly assetSvc: AssetService = assetService,
) {}
async search(folderId: string, req: SearchRequest): Promise<PaginatedData<AssetInfo[]>> {
let targetFolderIds: string[] = []
if (req.recursively === false) {
targetFolderIds = [folderId]
} else {
targetFolderIds = await this.assetSvc.getDescendantFolderIds(folderId)
}
const targetTypes =
req.assetType === 'folder' ? [AssetType.folder] : [AssetType.file, AssetType.version_stack]
// ----------------------------------------------------------------------
// AI Semantic search
// ----------------------------------------------------------------------
if (req.query && req.isSemantic) {
// 1. Check if embedding agent exists and is enabled
const team = await this.prismaClient.asset.findUnique({
where: { id: folderId },
select: { project: { select: { teamId: true } } },
})
const teamId = team?.project?.teamId
if (!teamId) throw new Error('Team ID not found for folder')
const embeddingAgent = await this.prismaClient.agent.findFirst({
where: { teamId, type: 'embedding', enabled: true },
})
if (!embeddingAgent) {
throw new HTTPException(422, {
message: 'Embedding agent not configured or disabled for this team.',
})
}
// 2. Generate query embedding via workflow
const task = await this.prismaClient.workflowTask.create({
data: {
type: WorkflowTaskType.query_embedding_for_search,
teamId,
assetId: folderId,
payload: {
projectId: '',
queryEmbeddingForSearch: { text: req.query },
} as PrismaJson.WorkflowTaskPayload,
status: 'pending',
},
})
const completedTask = await workflowService.executeWait(task)
const output = completedTask.output as Record<string, unknown> | null
const queryVector = output?.embedding as number[] | undefined
if (!queryVector) {
throw new Error('Failed to generate query embedding')
}
// 3. Construct raw SQL using SqlQueryBuilder
const vectorJson = JSON.stringify(queryVector)
const builder = new SqlQueryBuilder()
.select(
Prisma.sql`a.id as "assetId", ae.start_time as "startTime", ae.end_time as "endTime", (ae.embedding <=> ${vectorJson}::vector) as "distance"`,
)
.from(Prisma.sql`assets a JOIN asset_embeddings ae ON a.id = ae.asset_id`)
.addWhere(Prisma.sql`a.is_deleted = false`)
if (targetFolderIds.length > 0) {
builder.addWhere(Prisma.sql`a.parent_id = ANY(${targetFolderIds})`)
}
if (req.showSymlink) {
builder.addWhere(Prisma.sql`
(a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]))))
`)
} else {
builder.addWhere(Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`)
}
if (req.conditions && req.conditions.length > 0) {
builder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
}
const nameCond = req.conditions?.find((c) => c.field === 'name' && c.operator === 'contains')
if (nameCond) {
const valStr = String(nameCond.value)
const ngrams = generateSearchNgrams(valStr)
if (ngrams.length > 0) {
builder.addWhere(Prisma.sql`a.name_ngram @> ${ngrams}::text[]`)
builder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
} else {
builder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
}
}
builder.orderBy(Prisma.sql`distance ASC`)
// 4. Paginate in SQL using limit/offset
let limit = req.first || 20
if (limit <= 0 || limit > 200) {
limit = 20
}
let offset = 0
if (req.after) {
offset = decodeCursor(req.after)
}
builder.limit(limit + 1).offset(offset)
// 5. Execute raw SQL query
const query = builder.build()
const semanticMatches = await this.prismaClient.$queryRaw<
{
assetId: string
startTime: number | null
endTime: number | null
distance: number
}[]
>(query)
const hasNextPage = semanticMatches.length > limit
const finalMatches = hasNextPage ? semanticMatches.slice(0, limit) : semanticMatches
// 6. Map back to full rich metadata and return time-based duplicate segments
const uniqueIds = Array.from(new Set(finalMatches.map((m) => m.assetId)))
const fetchedInfos = await this.assetSvc.listAssetsByIds(uniqueIds)
const assetInfosMap = new Map<string, AssetInfo>()
for (const info of fetchedInfos) {
assetInfosMap.set(info.id, info)
}
const data: AssetInfo[] = []
for (const match of finalMatches) {
const baseInfo = assetInfosMap.get(match.assetId)
if (baseInfo) {
data.push({
...baseInfo,
startTime: match.startTime,
endTime: match.endTime,
})
}
}
const pageInfo: PageInfo = {}
if (req.includeCount) {
const countBuilder = new SqlQueryBuilder()
.select(Prisma.sql`COUNT(*)`)
.from(Prisma.sql`assets a JOIN asset_embeddings ae ON a.id = ae.asset_id`)
.addWhere(Prisma.sql`a.is_deleted = false`)
if (targetFolderIds.length > 0) {
countBuilder.addWhere(Prisma.sql`a.parent_id = ANY(${targetFolderIds})`)
}
if (req.showSymlink) {
countBuilder.addWhere(Prisma.sql`
(a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]))))
`)
} else {
countBuilder.addWhere(Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`)
}
if (req.conditions && req.conditions.length > 0) {
countBuilder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
}
if (nameCond) {
const valStr = String(nameCond.value)
const ngrams = generateSearchNgrams(valStr)
if (ngrams.length > 0) {
countBuilder.addWhere(Prisma.sql`a.name_ngram @> ${ngrams}::text[]`)
countBuilder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
} else {
countBuilder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
}
}
const countRes = await this.prismaClient.$queryRaw<{ count: bigint }[]>(
countBuilder.build(),
)
pageInfo.total = Number(countRes[0]?.count || 0)
}
if (hasNextPage) {
pageInfo.cursor = encodeCursor(offset + limit)
}
return { data, pageInfo }
}
// ----------------------------------------------------------------------
// Non-semantic search (using SqlQueryBuilder)
// ----------------------------------------------------------------------
const builder = new SqlQueryBuilder()
.select(Prisma.sql`a.id as "assetId"`)
.from(Prisma.sql`assets a`)
.addWhere(Prisma.sql`a.is_deleted = false`)
if (targetFolderIds.length > 0) {
builder.addWhere(Prisma.sql`a.parent_id = ANY(${targetFolderIds})`)
}
if (req.showSymlink) {
builder.addWhere(Prisma.sql`
(a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]))))
`)
} else {
builder.addWhere(Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`)
}
if (req.conditions && req.conditions.length > 0) {
builder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
}
// name contains n-grams / Switching Search Optimization
let countOverride: number | undefined
let useNgram = false
let valStr = ''
let ngrams: string[] = []
const nameCond = req.conditions?.find((c) => c.field === 'name' && c.operator === 'contains')
if (nameCond) {
valStr = String(nameCond.value)
ngrams = generateSearchNgrams(valStr)
if (ngrams.length > 0) {
const PROBE_LIMIT = 10001
// Build SQL probe query to limit and fetch selective IDs
const probeBuilder = new SqlQueryBuilder()
.select(Prisma.sql`a.id`)
.from(Prisma.sql`assets a`)
.addWhere(Prisma.sql`a.is_deleted = false`)
if (targetFolderIds.length > 0) {
probeBuilder.addWhere(Prisma.sql`a.parent_id = ANY(${targetFolderIds})`)
}
if (req.showSymlink) {
probeBuilder.addWhere(Prisma.sql`
(a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]))))
`)
} else {
probeBuilder.addWhere(Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`)
}
if (req.conditions && req.conditions.length > 0) {
probeBuilder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
}
probeBuilder.addWhere(Prisma.sql`a.name_ngram @> ${ngrams}::text[]`)
probeBuilder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
probeBuilder.limit(PROBE_LIMIT)
const probeMatches = await this.prismaClient.$queryRaw<{ id: string }[]>(
probeBuilder.build(),
)
const probeCount = probeMatches.length
if (probeCount < PROBE_LIMIT) {
useNgram = true
countOverride = probeCount
} else {
countOverride = PROBE_LIMIT
}
}
}
if (nameCond) {
if (useNgram && ngrams.length > 0) {
builder.addWhere(Prisma.sql`a.name_ngram @> ${ngrams}::text[]`)
builder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
} else {
builder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
}
}
// Sorting
let orderSql = Prisma.sql`a.sort_index ASC`
if (req.sort) {
const direction = req.sort.order === 'desc' ? Prisma.raw('DESC') : Prisma.raw('ASC')
if (req.sort.field === 'custom') {
orderSql = Prisma.sql`a.sort_index ASC`
} else if (req.sort.field === 'name') {
orderSql = Prisma.sql`a.name ${direction}`
} else if (req.sort.field === 'created_at' || req.sort.field === 'createdAt') {
orderSql = Prisma.sql`a.created_at ${direction}`
} else if (req.sort.field === 'size_byte' || req.sort.field === 'sizeByte') {
orderSql = Prisma.sql`a.size_byte ${direction}`
} else {
orderSql = Prisma.sql`a.id DESC`
}
}
builder.orderBy(orderSql)
// Paginate in SQL using limit/offset
let limit = req.first || 20
if (limit <= 0 || limit > 200) {
limit = 20
}
let offset = 0
if (req.after) {
offset = decodeCursor(req.after)
}
builder.limit(limit + 1).offset(offset)
// Execute raw SQL query
const query = builder.build()
const matches = await this.prismaClient.$queryRaw<{ assetId: string }[]>(query)
const hasNextPage = matches.length > limit
const finalMatches = hasNextPage ? matches.slice(0, limit) : matches
// Map back to full rich metadata
const uniqueIds = Array.from(new Set(finalMatches.map((m) => m.assetId)))
const fetchedInfos = await this.assetSvc.listAssetsByIds(uniqueIds)
const assetInfosMap = new Map<string, AssetInfo>()
for (const info of fetchedInfos) {
assetInfosMap.set(info.id, info)
}
const data: AssetInfo[] = []
for (const match of finalMatches) {
const baseInfo = assetInfosMap.get(match.assetId)
if (baseInfo) {
data.push(baseInfo)
}
}
const pageInfo: PageInfo = {}
if (req.includeCount) {
if (countOverride !== undefined) {
pageInfo.total = countOverride
} else {
const countBuilder = new SqlQueryBuilder()
.select(Prisma.sql`COUNT(*)`)
.from(Prisma.sql`assets a`)
.addWhere(Prisma.sql`a.is_deleted = false`)
if (targetFolderIds.length > 0) {
countBuilder.addWhere(Prisma.sql`a.parent_id = ANY(${targetFolderIds})`)
}
if (req.showSymlink) {
countBuilder.addWhere(Prisma.sql`
(a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]))))
`)
} else {
countBuilder.addWhere(Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`)
}
if (req.conditions && req.conditions.length > 0) {
countBuilder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
}
if (nameCond) {
countBuilder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
}
const countRes = await this.prismaClient.$queryRaw<{ count: bigint }[]>(
countBuilder.build(),
)
pageInfo.total = Number(countRes[0]?.count || 0)
}
}
if (hasNextPage) {
pageInfo.cursor = encodeCursor(offset + limit)
}
return { data, pageInfo }
}
}
export const searchService = new SearchService()
@@ -0,0 +1,38 @@
import { describe, expect, it } from 'vitest'
import { SqlQueryBuilder } from './sql-query-builder'
import { Prisma } from '@shumai/db'
describe('SqlQueryBuilder', () => {
it('correctly constructs a basic SQL query', () => {
const builder = new SqlQueryBuilder()
.select(Prisma.sql`a.id, a.name`)
.from(Prisma.sql`assets a`)
.addWhere(Prisma.sql`a.is_deleted = false`)
const query = builder.build()
expect(query.text).toContain('SELECT a.id, a.name FROM assets a WHERE a.is_deleted = false')
})
it('correctly constructs query with where clauses, order, limit, and offset', () => {
const vectorJson = '[0.1, 0.2, 0.3]'
const builder = new SqlQueryBuilder()
.select(Prisma.sql`a.id, ae.start_time as "startTime"`)
.from(Prisma.sql`assets a JOIN asset_embeddings ae ON a.id = ae.asset_id`)
.addWhere(Prisma.sql`a.is_deleted = false`)
.addWhere(Prisma.sql`a.project_id = ${'project-123'}`)
.orderBy(Prisma.sql`ae.embedding <=> ${vectorJson}::vector ASC`)
.limit(10)
.offset(20)
const query = builder.build()
expect(query.text).toContain(
'SELECT a.id, ae.start_time as "startTime" FROM assets a JOIN asset_embeddings ae ON a.id = ae.asset_id WHERE a.is_deleted = false AND a.project_id = $1 ORDER BY ae.embedding <=> $2::vector ASC LIMIT $3 OFFSET $4',
)
expect(query.values).toEqual(['project-123', vectorJson, 10, 20])
})
it('throws an error if FROM clause is missing', () => {
const builder = new SqlQueryBuilder().select(Prisma.sql`id`)
expect(() => builder.build()).toThrow('FROM clause is required')
})
})
@@ -0,0 +1,371 @@
import { Prisma } from '@shumai/db'
import { SearchCondition } from '@shumai/dtos'
export class SqlQueryBuilder {
private selectSql: Prisma.Sql = Prisma.sql`*`
private fromSql: Prisma.Sql | null = null
private wheres: Prisma.Sql[] = []
private orderSql: Prisma.Sql | null = null
private limitCount: number | null = null
private offsetCount: number | null = null
select(fields: Prisma.Sql): this {
this.selectSql = fields
return this
}
from(relation: Prisma.Sql): this {
this.fromSql = relation
return this
}
addWhere(condition: Prisma.Sql): this {
this.wheres.push(condition)
return this
}
orderBy(order: Prisma.Sql): this {
this.orderSql = order
return this
}
limit(n: number): this {
this.limitCount = n
return this
}
offset(n: number): this {
this.offsetCount = n
return this
}
addSearchConditions(
operator: 'AND' | 'OR',
conditions: SearchCondition[],
options?: { skipNameContains?: boolean },
): this {
if (!conditions || conditions.length === 0) return this
const condSqls: Prisma.Sql[] = []
for (const cond of conditions) {
if (options?.skipNameContains && cond.field === 'name' && cond.operator === 'contains') {
continue
}
const sqlCond = this.buildSqlCondition(cond.field, cond.operator, cond.value)
if (sqlCond) {
condSqls.push(sqlCond)
}
}
if (condSqls.length > 0) {
const separator = operator === 'OR' ? ' OR ' : ' AND '
this.addWhere(Prisma.sql`(${Prisma.join(condSqls, separator)})`)
}
return this
}
build(): Prisma.Sql {
if (!this.fromSql) {
throw new Error('FROM clause is required in SqlQueryBuilder')
}
const queryParts: Prisma.Sql[] = [
Prisma.sql`SELECT`,
this.selectSql,
Prisma.sql`FROM`,
this.fromSql,
]
if (this.wheres.length > 0) {
queryParts.push(Prisma.sql`WHERE`)
queryParts.push(Prisma.join(this.wheres, ' AND '))
}
if (this.orderSql) {
queryParts.push(Prisma.sql`ORDER BY`)
queryParts.push(this.orderSql)
}
if (this.limitCount !== null) {
queryParts.push(Prisma.sql`LIMIT ${this.limitCount}`)
}
if (this.offsetCount !== null) {
queryParts.push(Prisma.sql`OFFSET ${this.offsetCount}`)
}
return Prisma.join(queryParts, ' ')
}
private isDate(value: unknown): boolean {
if (value instanceof Date) return true
if (typeof value !== 'string') return false
const valStr = value.toLowerCase()
const relativeKeywords = [
'today',
'yesterday',
'tomorrow',
'one week ago',
'one week from now',
'one month ago',
'one month from now',
]
if (relativeKeywords.includes(valStr) || valStr.match(/\d+\s+days?\s+(ago|from\s+now)/)) {
return true
}
const d = new Date(value)
return !isNaN(d.getTime()) && value.includes('-')
}
private toDate(value: unknown): Date {
return this.toDateBound(value, 'start')
}
private toDateBound(value: unknown, bound: 'start' | 'end'): Date {
const d = this.parseRelativeDate(value)
if (d instanceof Date) return d
if (d && 'gte' in d && 'lte' in d) {
return bound === 'start' ? d.gte! : d.lte!
}
return new Date(value as string)
}
private parseDateRange(value: unknown): { start: Date; end: Date } {
const d = this.parseRelativeDate(value)
if (d && 'gte' in d && 'lte' in d) {
return { start: d.gte!, end: d.lte! }
}
const date = d instanceof Date ? d : new Date(value as string)
const start = new Date(date)
start.setHours(0, 0, 0, 0)
const end = new Date(date)
end.setHours(23, 59, 59, 999)
return { start, end }
}
private parseRelativeDate(value: unknown): { gte?: Date; lte?: Date } | Date | null {
if (value instanceof Date) return value
const valStr = String(value).toLowerCase()
const now = new Date()
const startOf = (d: Date) => {
const res = new Date(d)
res.setHours(0, 0, 0, 0)
return res
}
const endOf = (d: Date) => {
const res = new Date(d)
res.setHours(23, 59, 59, 999)
return res
}
if (valStr === 'today') {
return { gte: startOf(now), lte: endOf(now) }
}
if (valStr === 'yesterday') {
const d = new Date(now)
d.setDate(d.getDate() - 1)
return { gte: startOf(d), lte: endOf(d) }
}
if (valStr === 'tomorrow') {
const d = new Date(now)
d.setDate(d.getDate() + 1)
return { gte: startOf(d), lte: endOf(d) }
}
if (valStr === 'one week ago') {
const d = new Date(now)
d.setDate(d.getDate() - 7)
return d
}
if (valStr === 'one week from now') {
const d = new Date(now)
d.setDate(d.getDate() + 7)
return d
}
if (valStr === 'one month ago') {
const d = new Date(now)
d.setMonth(d.getMonth() - 1)
return d
}
if (valStr === 'one month from now') {
const d = new Date(now)
d.setMonth(d.getMonth() + 1)
return d
}
const daysAgoMatch = valStr.match(/(\d+)\s+days?\s+ago/)
if (daysAgoMatch) {
const d = new Date(now)
d.setDate(d.getDate() - parseInt(daysAgoMatch[1]))
return d
}
const daysFromNowMatch = valStr.match(/(\d+)\s+days?\s+from\s+now/)
if (daysFromNowMatch) {
const d = new Date(now)
d.setDate(d.getDate() + parseInt(daysFromNowMatch[1]))
return d
}
const parsed = new Date(value as string)
return isNaN(parsed.getTime()) ? null : parsed
}
private buildEavValueMatch(value: unknown): Prisma.Sql {
if (typeof value === 'string') {
const valStr = String(value)
if (this.isDate(valStr)) {
const d = this.parseRelativeDate(valStr)
if (d instanceof Date) {
return Prisma.sql`date_value = ${d}`
} else if (d && 'gte' in d) {
return Prisma.sql`date_value >= ${d.gte} AND date_value <= ${d.lte}`
}
}
return Prisma.sql`string_value = ${valStr}`
}
if (typeof value === 'number') {
return Prisma.sql`number_value = ${Number(value)}`
}
if (typeof value === 'boolean') {
return Prisma.sql`boolean_value = ${Boolean(value)}`
}
if (value instanceof Date) {
return Prisma.sql`date_value = ${value}`
}
if (Array.isArray(value) || (typeof value === 'object' && value !== null)) {
return Prisma.sql`json_value = ${JSON.stringify(value)}::jsonb`
}
return Prisma.sql`string_value = ${String(value)}`
}
private buildSqlCondition(field: string, operator: string, value: unknown): Prisma.Sql | null {
const colName =
field === 'sizeByte' || field === 'size_byte'
? 'size_byte'
: field === 'createdAt' || field === 'created_at'
? 'created_at'
: field === 'updatedAt' || field === 'updated_at'
? 'updated_at'
: field
const dbCol = Prisma.raw(`a."${colName}"`)
if (field === 'name') {
const valStr = String(value)
switch (operator) {
case 'eq':
return Prisma.sql`${dbCol} = ${valStr}`
case 'neq':
return Prisma.sql`${dbCol} != ${valStr}`
case 'contains':
return Prisma.sql`${dbCol} ILIKE ${'%' + valStr + '%'}`
case 'notContains':
return Prisma.sql`${dbCol} NOT ILIKE ${'%' + valStr + '%'}`
case 'isEmpty':
return Prisma.sql`${dbCol} = ''`
case 'isNotEmpty':
return Prisma.sql`${dbCol} != ''`
default:
throw new Error(`Unsupported operator for name field: ${operator}`)
}
}
if (field === 'sizeByte' || field === 'size_byte') {
const valNum = Number(value)
switch (operator) {
case 'eq':
return Prisma.sql`${dbCol} = ${valNum}`
case 'neq':
return Prisma.sql`${dbCol} != ${valNum}`
case 'gt':
return Prisma.sql`${dbCol} > ${valNum}`
case 'gte':
return Prisma.sql`${dbCol} >= ${valNum}`
case 'lt':
return Prisma.sql`${dbCol} < ${valNum}`
case 'lte':
return Prisma.sql`${dbCol} <= ${valNum}`
default:
throw new Error(`Unsupported operator for sizeByte field: ${operator}`)
}
}
if (
field === 'createdAt' ||
field === 'updatedAt' ||
field === 'created_at' ||
field === 'updated_at'
) {
const valDate = this.toDate(value)
switch (operator) {
case 'eq':
return Prisma.sql`${dbCol} = ${valDate}`
case 'neq':
return Prisma.sql`${dbCol} != ${valDate}`
case 'gt':
return Prisma.sql`${dbCol} > ${this.toDateBound(value, 'end')}`
case 'gte':
return Prisma.sql`${dbCol} >= ${this.toDateBound(value, 'start')}`
case 'lt':
return Prisma.sql`${dbCol} < ${this.toDateBound(value, 'start')}`
case 'lte':
return Prisma.sql`${dbCol} <= ${this.toDateBound(value, 'end')}`
case 'isWithin': {
const range = this.parseDateRange(value)
return Prisma.sql`${dbCol} >= ${range.start} AND ${dbCol} <= ${range.end}`
}
default:
throw new Error(`Unsupported operator for date field: ${operator}`)
}
}
// Custom EAV metadata field query on asset_metadata_values
switch (operator) {
case 'isEmpty':
return Prisma.sql`a.id NOT IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field})`
case 'isNotEmpty':
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field})`
case 'eq': {
const matchSql = this.buildEavValueMatch(value)
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND ${matchSql})`
}
case 'neq': {
const matchSql = this.buildEavValueMatch(value)
return Prisma.sql`a.id NOT IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field}) OR a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND NOT (${matchSql}))`
}
case 'gt':
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND (number_value > ${Number(value)} OR date_value > ${this.toDateBound(value, 'end')}))`
case 'gte':
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND (number_value >= ${Number(value)} OR date_value >= ${this.toDateBound(value, 'start')}))`
case 'lt':
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND (number_value < ${Number(value)} OR date_value < ${this.toDateBound(value, 'start')}))`
case 'lte':
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND (number_value <= ${Number(value)} OR date_value <= ${this.toDateBound(value, 'end')}))`
case 'contains':
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND string_value ILIKE ${'%' + String(value) + '%'})`
case 'notContains':
return Prisma.sql`a.id NOT IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND string_value ILIKE ${'%' + String(value) + '%'})`
case 'in': {
const valArr = Array.isArray(value) ? value : [value]
const valNumArr = valArr.map((v) => Number(v)).filter((v) => !isNaN(v))
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND (string_value = ANY(${valArr}) OR number_value = ANY(${valNumArr}::double precision[])))`
}
case 'notIn': {
const valArr = Array.isArray(value) ? value : [value]
const valNumArr = valArr.map((v) => Number(v)).filter((v) => !isNaN(v))
return Prisma.sql`a.id NOT IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND (string_value = ANY(${valArr}) OR number_value = ANY(${valNumArr}::double precision[])))`
}
case 'hasAny':
case 'hasAll':
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND json_value @> ${JSON.stringify(value)}::jsonb)`
case 'hasNone':
return Prisma.sql`a.id NOT IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND json_value @> ${JSON.stringify(value)}::jsonb)`
case 'isWithin': {
const range = this.parseDateRange(value)
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND date_value >= ${range.start} AND date_value <= ${range.end})`
}
default:
throw new Error(`Unsupported operator for metadata field: ${operator}`)
}
}
}
+271
View File
@@ -0,0 +1,271 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import { shareService } from './share'
import { assetService } from '@shumai/core/src/asset/asset'
import { projectService } from '@shumai/core/src/project/project'
import { AssetType } from '@shumai/db'
describe('ShareService', () => {
setupTestDbHooks()
let teamId: string
let projectId: string
let userId: string
beforeEach(async () => {
const user = await prisma.user.create({
data: { name: 'Test User', email: `test-${Date.now()}@example.com` },
})
userId = user.id
const team = await prisma.team.create({ data: { name: 'Test Team' } })
teamId = team.id
await prisma.teamMember.create({
data: { teamId, userId, role: 'owner' },
})
const project = await projectService.createProject(
{ id: userId },
{
name: 'Test Project',
teamId,
},
)
projectId = project.id
})
it('creates a share link and its root folder', async () => {
const shareLink = await shareService.createShareLink(projectId, {
name: 'Public Share',
})
expect(shareLink.name).toBe('Public Share')
expect(shareLink.rootFolderId).toBeDefined()
const asset = await prisma.asset.findUnique({
where: { id: shareLink.rootFolderId },
})
expect(asset?.type).toBe(AssetType.share)
expect(asset?.projectId).toBe(projectId)
})
it('adds multiple assets to share and handles duplicates', async () => {
// Create real assets
const file1 = await prisma.asset.create({
data: {
name: 'file1.txt',
type: AssetType.file,
status: 'processed',
projectId,
},
})
const file2 = await prisma.asset.create({
data: {
name: 'file2.txt',
type: AssetType.file,
status: 'processed',
projectId,
},
})
const shareLink = await shareService.createShareLink(projectId, {
name: 'Batch Share',
})
// Add first asset
const count1 = await shareService.addAssetToShare(shareLink.id, {
assetIds: [file1.id],
})
expect(count1).toBe(1)
// Add both assets (one is duplicate)
const count2 = await shareService.addAssetToShare(shareLink.id, {
assetIds: [file1.id, file2.id],
})
expect(count2).toBe(1) // Only file2 added
// Add both again (all duplicates)
const count3 = await shareService.addAssetToShare(shareLink.id, {
assetIds: [file1.id, file2.id],
})
expect(count3).toBe(0)
// List children of the share root folder
const children = await assetService.listChildren({
assetId: shareLink.rootFolderId,
assetType: 'file',
})
expect(children.data).toHaveLength(2)
})
it('verifies public access correctly', async () => {
const file = await prisma.asset.create({
data: {
name: 'data.png',
type: AssetType.file,
status: 'processed',
projectId,
},
})
const shareLink = await shareService.createShareLink(projectId, {
name: 'Protected Share',
password: 'secret-password',
})
await shareService.addAssetToShare(shareLink.id, {
assetIds: [file.id],
})
const symlink = await prisma.asset.findFirst({
where: { targetId: file.id, parentId: shareLink.rootFolderId },
})
expect(symlink).toBeDefined()
// Test password check
await expect(shareService.verifyPublicAccess(symlink!.id, 'wrong')).rejects.toThrow(
'Invalid password',
)
await expect(
shareService.verifyPublicAccess(symlink!.id, 'secret-password'),
).resolves.toBeDefined()
// Test expiration
await prisma.shareLink.update({
where: { id: shareLink.id },
data: { expireAt: new Date(Date.now() - 1000) },
})
await expect(shareService.verifyPublicAccess(symlink!.id, 'secret-password')).rejects.toThrow(
'expired',
)
})
it('traces deep ancestors for public access', async () => {
const shareLink = await shareService.createShareLink(projectId, {
name: 'Deep Share',
})
const subfolder = await prisma.asset.create({
data: {
name: 'subfolder',
type: AssetType.folder,
status: 'processed',
projectId,
parentId: shareLink.rootFolderId,
},
})
const deepFile = await prisma.asset.create({
data: {
name: 'deep.txt',
type: AssetType.file,
status: 'processed',
projectId,
parentId: subfolder.id,
},
})
await expect(shareService.verifyPublicAccess(deepFile.id)).resolves.toBeDefined()
})
it('verifies public access via symlink to a folder', async () => {
// 1. Create a real folder with a file
const realFolder = await prisma.asset.create({
data: {
name: 'Real Folder',
type: AssetType.folder,
status: 'processed',
projectId,
},
})
const realFile = await prisma.asset.create({
data: {
name: 'Real File',
type: AssetType.file,
status: 'processed',
projectId,
parentId: realFolder.id,
},
})
// 2. Share the folder via symlink
const shareLink = await shareService.createShareLink(projectId, { name: 'Folder Share' })
await shareService.addAssetToShare(shareLink.id, { assetIds: [realFolder.id] })
// 3. Verify access to the file inside the real folder (which is reached via the symlinked folder)
await expect(shareService.verifyPublicAccess(realFile.id)).resolves.toBeDefined()
})
it('fails public access for non-shared assets', async () => {
const privateFile = await prisma.asset.create({
data: {
name: 'private.txt',
type: AssetType.file,
status: 'processed',
projectId,
},
})
await expect(shareService.verifyPublicAccess(privateFile.id)).rejects.toThrow(
'Asset is not shared',
)
})
it('updates a share link including fieldVisibility', async () => {
const shareLink = await shareService.createShareLink(projectId, { name: 'Old Name' })
const updated = await shareService.updateShareLink(shareLink.id, {
name: 'New Name',
password: 'new-password',
fieldVisibility: { field1: true, field2: false },
})
expect(updated.name).toBe('New Name')
expect(updated.hasPassword).toBe(true)
expect(updated.fieldVisibility).toEqual({ field1: true, field2: false })
const rootAsset = await prisma.asset.findUnique({ where: { id: shareLink.rootFolderId } })
expect(rootAsset?.name).toBe('New Name')
})
it('deletes a share link', async () => {
const shareLink = await shareService.createShareLink(projectId, { name: 'To Delete' })
await shareService.deleteShareLink(shareLink.id)
const link = await prisma.shareLink.findUnique({ where: { id: shareLink.id } })
expect(link).toBeNull()
const asset = await prisma.asset.findUnique({ where: { id: shareLink.rootFolderId } })
expect(asset).toBeNull()
})
it('lists share links for a project', async () => {
await shareService.createShareLink(projectId, { name: 'Share 1' })
await shareService.createShareLink(projectId, { name: 'Share 2' })
const list = await shareService.listProjectShareLinks({ projectId })
expect(list.data).toHaveLength(2)
})
it('gets a single share link', async () => {
const shareLink = await shareService.createShareLink(projectId, { name: 'Target' })
const fetched = await shareService.getShareLink(shareLink.id)
expect(fetched.name).toBe('Target')
})
it('removes an asset from share', async () => {
const file = await prisma.asset.create({
data: { name: 'f', type: AssetType.file, status: 'processed', projectId },
})
const shareLink = await shareService.createShareLink(projectId, { name: 'S' })
await shareService.addAssetToShare(shareLink.id, { assetIds: [file.id] })
const symlink = await prisma.asset.findFirst({ where: { targetId: file.id } })
expect(symlink).toBeDefined()
await shareService.removeAssetFromShare(shareLink.id, symlink!.id)
const symlinkAfter = await prisma.asset.findUnique({ where: { id: symlink!.id } })
expect(symlinkAfter).toBeNull()
})
})
+302
View File
@@ -0,0 +1,302 @@
import { prisma } from '@shumai/db'
import { AssetType, Prisma } from '@shumai/db'
import {
ShareLinkInfo,
CreateShareLinkRequest,
UpdateShareLinkRequest,
ListShareLinksRequest,
AddAssetToShareRequest,
} from '@shumai/dtos'
import { PaginatedData, paginateQuery } from '@shumai/core/src/pagination'
export class ShareService {
async createShareLink(projectId: string, req: CreateShareLinkRequest): Promise<ShareLinkInfo> {
let project = await prisma.project.findUnique({
where: { id: projectId },
include: { shareRoot: true },
})
if (!project) throw new Error('Project not found')
// Lazy create share root if missing (for existing projects)
if (!project.shareRootId) {
const shareRootFolder = await prisma.asset.create({
data: {
name: 'share_root',
type: AssetType.share_root,
status: 'processed',
projectId: projectId,
},
})
project = await prisma.project.update({
where: { id: projectId },
data: { shareRootId: shareRootFolder.id },
include: { shareRoot: true },
})
}
return await prisma.$transaction(async (tx) => {
const shareFolder = await tx.asset.create({
data: {
name: req.name,
type: AssetType.share,
status: 'processed',
projectId: projectId,
parentId: project.shareRootId,
},
})
const shareLink = await tx.shareLink.create({
data: {
name: req.name,
expireAt: req.expireAt ? new Date(req.expireAt) : null,
password: req.password,
isDisabled: req.isDisabled ?? false,
defaultSortOrder: req.defaultSortOrder,
projectId: projectId,
rootFolderId: shareFolder.id,
},
})
return this.toShareLinkInfo(shareLink)
})
}
async updateShareLink(shareLinkId: string, req: UpdateShareLinkRequest): Promise<ShareLinkInfo> {
const shareLink = await prisma.shareLink.findUnique({
where: { id: shareLinkId },
})
if (!shareLink) throw new Error('Share link not found')
const updated = await prisma.shareLink.update({
where: { id: shareLinkId },
data: {
name: req.name,
expireAt:
req.expireAt !== undefined ? (req.expireAt ? new Date(req.expireAt) : null) : undefined,
password: req.password,
isDisabled: req.isDisabled,
defaultSortOrder: req.defaultSortOrder,
fieldVisibility: (req.fieldVisibility as PrismaJson.ShareLinkFieldVisibility) ?? undefined,
},
})
if (req.name) {
await prisma.asset.update({
where: { id: shareLink.rootFolderId },
data: { name: req.name },
})
}
return this.toShareLinkInfo(updated)
}
async deleteShareLink(shareLinkId: string): Promise<void> {
const shareLink = await prisma.shareLink.findUnique({
where: { id: shareLinkId },
})
if (!shareLink) throw new Error('Share link not found')
await prisma.$transaction(async (tx) => {
await tx.shareLink.delete({ where: { id: shareLinkId } })
// Delete the root folder asset, which should cascade to symlinks if set up correctly
// But Asset relation in prisma might not cascade delete children unless configured.
// Actually, targetId has onDelete: Cascade, but parentId doesn't necessarily.
// Let's manually delete the asset tree or ensure it's handled.
await tx.asset.delete({ where: { id: shareLink.rootFolderId } })
})
}
async listProjectShareLinks(req: ListShareLinksRequest): Promise<PaginatedData<ShareLinkInfo[]>> {
const where: Prisma.ShareLinkWhereInput = {
projectId: req.projectId,
}
return paginateQuery(
async (skip, take) => {
const links = await prisma.shareLink.findMany({
where,
skip,
take,
orderBy: { createdAt: 'desc' },
})
return links.map((l) => this.toShareLinkInfo(l))
},
() => prisma.shareLink.count({ where }),
req,
)
}
async getShareLink(shareLinkId: string): Promise<ShareLinkInfo> {
const shareLink = await prisma.shareLink.findUnique({
where: { id: shareLinkId },
})
if (!shareLink) throw new Error('Share link not found')
return this.toShareLinkInfo(shareLink)
}
async addAssetToShare(shareLinkId: string, req: AddAssetToShareRequest): Promise<number> {
const shareLink = await prisma.shareLink.findUnique({
where: { id: shareLinkId },
})
if (!shareLink) throw new Error('Share link not found')
const assetIds = req.assetIds
const existingSymlinks = await prisma.asset.findMany({
where: {
parentId: shareLink.rootFolderId,
targetId: { in: assetIds },
type: AssetType.symlink,
},
select: { targetId: true },
})
const existingTargetIds = new Set(existingSymlinks.map((s) => s.targetId))
const idsToAdd = assetIds.filter((id) => !existingTargetIds.has(id))
if (idsToAdd.length === 0) return 0
const targetAssets = await prisma.asset.findMany({
where: { id: { in: idsToAdd } },
})
const targetAssetMap = new Map(targetAssets.map((a) => [a.id, a]))
await prisma.$transaction(async (tx) => {
for (const assetId of idsToAdd) {
const targetAsset = targetAssetMap.get(assetId)
if (!targetAsset) continue
await tx.asset.create({
data: {
name: targetAsset.name,
type: AssetType.symlink,
status: 'processed',
projectId: shareLink.projectId,
parentId: shareLink.rootFolderId,
targetId: assetId,
},
})
}
await tx.asset.update({
where: { id: shareLink.rootFolderId },
data: { fileCount: { increment: idsToAdd.length } },
})
})
return idsToAdd.length
}
async removeAssetFromShare(shareLinkId: string, assetId: string): Promise<void> {
// Here assetId is the id of the symlink asset
const symlink = await prisma.asset.findUnique({
where: { id: assetId },
})
if (!symlink || symlink.type !== AssetType.symlink) {
throw new Error('Symlink not found')
}
const shareLink = await prisma.shareLink.findUnique({
where: { id: shareLinkId },
})
if (!shareLink || symlink.parentId !== shareLink.rootFolderId) {
throw new Error('Asset does not belong to this share link')
}
await prisma.$transaction(async (tx) => {
await tx.asset.delete({ where: { id: assetId } })
await tx.asset.update({
where: { id: shareLink.rootFolderId },
data: { fileCount: { decrement: 1 } },
})
})
}
async verifyPublicAccess(
assetId: string,
providedPassword?: string,
): Promise<Prisma.ShareLinkGetPayload<true>> {
// 1. Trace ancestors of the current asset in the real tree
// 2. Find if any ancestor (including itself) is the target of a symlink that belongs to a share
// 3. Or if the asset itself is a descendant of a 'share' type folder (direct share link root or subfolder within)
const rows = await prisma.$queryRaw<{ shareRootId: string }[]>`
WITH RECURSIVE
-- Trace ancestors in the real asset tree
real_ancestors AS (
SELECT id, parent_id, type::text FROM assets WHERE id = ${assetId}
UNION ALL
SELECT a.id, a.parent_id, a.type::text FROM assets a
INNER JOIN real_ancestors ra ON ra.parent_id = a.id
),
-- Find all symlinks pointing to any of these real ancestors
found_symlinks AS (
SELECT s.id, s.parent_id, s.type::text FROM assets s
INNER JOIN real_ancestors ra ON s.target_id = ra.id
WHERE s.type = 'symlink'
),
-- Combine: start with either real ancestors that are 'share' type, or symlinks that lead to 'share' type
search_starts AS (
SELECT id, parent_id, type FROM real_ancestors WHERE type = 'share'
UNION
SELECT id, parent_id, type FROM found_symlinks
),
-- Trace UP from these search starts to find the ultimate 'share' root
share_trace AS (
SELECT id, parent_id, type FROM search_starts
UNION ALL
SELECT a.id, a.parent_id, a.type::text FROM assets a
INNER JOIN share_trace st ON st.parent_id = a.id
)
SELECT id as "shareRootId" FROM share_trace WHERE type = 'share' LIMIT 1;
`
if (rows.length === 0) {
throw new Error('Asset is not shared')
}
const shareRootId = rows[0].shareRootId
const shareLink = await prisma.shareLink.findUnique({
where: { rootFolderId: shareRootId },
})
if (!shareLink) {
throw new Error('Share link not found for this asset')
}
if (shareLink.isDisabled) {
throw new Error('Share link is disabled')
}
if (shareLink.expireAt && shareLink.expireAt < new Date()) {
throw new Error('Share link has expired')
}
if (shareLink.password && shareLink.password !== providedPassword) {
throw new Error('Invalid password for share link')
}
return shareLink
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private toShareLinkInfo(l: any): ShareLinkInfo {
const isExpired = l.expireAt ? new Date(l.expireAt) < new Date() : false
return {
id: l.id,
name: l.name,
expireAt: l.expireAt?.toISOString(),
isDisabled: l.isDisabled,
hasPassword: !!l.password,
defaultSortOrder: l.defaultSortOrder,
fieldVisibility: l.fieldVisibility as Record<string, boolean> | undefined,
rootFolderId: l.rootFolderId,
projectId: l.projectId,
isExpired,
createdAt: l.createdAt.toISOString(),
updatedAt: l.updatedAt.toISOString(),
}
}
}
export const shareService = new ShareService()
+226
View File
@@ -0,0 +1,226 @@
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import { s3Service } from '@shumai/core/src/s3/s3'
import { skillService } from '@shumai/core/src/skill/skill'
import AdmZip from 'adm-zip'
import { describe, expect, it, vi } from 'vitest'
describe('SkillService', () => {
setupTestDbHooks()
it('should list skills', async () => {
const team = await prisma.team.create({ data: { name: 'Test Team' } })
await prisma.skill.create({
data: {
name: 'Skill 1',
description: 'Desc 1',
assetId: 'asset1',
hash: 'hash1',
teamId: team.id,
},
})
const skills = await skillService.listSkills(team.id)
expect(skills).toHaveLength(1)
expect(skills[0].name).toBe('Skill 1')
})
it('should upsert skill from asset', async () => {
const team = await prisma.team.create({ data: { name: 'Test Team' } })
// Create a dummy zip buffer
const zip = new AdmZip()
zip.addFile(
'SKILL.md',
Buffer.from('---\nname: "Test Skill"\ndescription: "This is a test skill."\n---'),
)
const zipBuffer = zip.toBuffer()
const asset = await prisma.asset.create({
data: {
name: 'test.zip',
storageKey: { create: { key: 'test.zip' } },
type: 'file',
status: 'uploaded',
},
})
const getObjectSpy = vi.spyOn(s3Service, 'getObject').mockResolvedValue({
buffer: zipBuffer,
contentType: 'application/zip',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const putObjectSpy = vi.spyOn(s3Service, 'putObject').mockResolvedValue(undefined as any)
const skill = await skillService.upsertSkill(team.id, {
assetId: asset.id,
})
expect(skill.name).toBe('Test Skill')
expect(skill.description).toBe('This is a test skill.')
expect(getObjectSpy).toHaveBeenCalled()
expect(putObjectSpy).toHaveBeenCalled()
const dbSkill = await prisma.skill.findUnique({
where: { id: skill.id },
})
expect(dbSkill).toBeDefined()
expect(dbSkill?.name).toBe('Test Skill')
getObjectSpy.mockRestore()
putObjectSpy.mockRestore()
})
it('should upsert skill from github url with path', async () => {
const team = await prisma.team.create({ data: { name: 'Test Team' } })
// Create a dummy github zip buffer (nested structure)
const zip = new AdmZip()
const rootDir = 'repo-main'
zip.addFile(`${rootDir}/`, Buffer.from(''))
zip.addFile(`${rootDir}/skills/`, Buffer.from(''))
zip.addFile(
`${rootDir}/skills/pptx-generator/SKILL.md`,
Buffer.from('---\nname: "PPTX Generator"\ndescription: "Generate powerpoint files."\n---'),
)
zip.addFile(`${rootDir}/skills/pptx-generator/index.ts`, Buffer.from('console.log("hello")'))
// Add some noise
zip.addFile(`${rootDir}/README.md`, Buffer.from('root readme'))
const zipBuffer = zip.toBuffer()
const fetchSpy = vi.spyOn(global, 'fetch').mockResolvedValue({
ok: true,
arrayBuffer: async () => zipBuffer.buffer,
} as Response)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const putObjectSpy = vi.spyOn(s3Service, 'putObject').mockResolvedValue(undefined as any)
const skill = await skillService.upsertSkill(team.id, {
githubUrl: 'https://github.com/owner/repo/tree/main/skills/pptx-generator',
})
expect(skill.name).toBe('PPTX Generator')
expect(skill.description).toBe('Generate powerpoint files.')
expect(fetchSpy).toHaveBeenCalledWith(
'https://codeload.github.com/owner/repo/zip/refs/heads/main',
)
// Verify repacking
expect(putObjectSpy).toHaveBeenCalled()
const repackedBuffer = putObjectSpy.mock.calls[0][2] as Buffer
const repackedZip = new AdmZip(repackedBuffer)
const entries = repackedZip.getEntries().map((e) => e.entryName)
expect(entries).toContain('SKILL.md')
expect(entries).toContain('index.ts')
fetchSpy.mockRestore()
putObjectSpy.mockRestore()
})
it('should upsert skill from github url using "blob" marker', async () => {
const team = await prisma.team.create({ data: { name: 'Test Team' } })
const zip = new AdmZip()
const rootDir = 'repo-main'
zip.addFile(
`${rootDir}/SKILL.md`,
Buffer.from('---\nname: "Blob Skill"\ndescription: "From blob URL."\n---'),
)
const zipBuffer = zip.toBuffer()
const fetchSpy = vi.spyOn(global, 'fetch').mockResolvedValue({
ok: true,
arrayBuffer: async () => zipBuffer.buffer,
} as Response)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const putObjectSpy = vi.spyOn(s3Service, 'putObject').mockResolvedValue(undefined as any)
const skill = await skillService.upsertSkill(team.id, {
githubUrl: 'https://github.com/owner/repo/blob/main/SKILL.md',
})
expect(skill.name).toBe('Blob Skill')
expect(fetchSpy).toHaveBeenCalledWith(
'https://codeload.github.com/owner/repo/zip/refs/heads/main',
)
fetchSpy.mockRestore()
putObjectSpy.mockRestore()
})
it('should upsert skill from github url using direct path (no tree/blob)', async () => {
const team = await prisma.team.create({ data: { name: 'Test Team' } })
const zip = new AdmZip()
const rootDir = 'repo-main'
zip.addFile(
`${rootDir}/my-path/SKILL.md`,
Buffer.from('---\nname: "Direct Skill"\ndescription: "From direct path."\n---'),
)
const zipBuffer = zip.toBuffer()
const fetchSpy = vi.spyOn(global, 'fetch').mockResolvedValue({
ok: true,
arrayBuffer: async () => zipBuffer.buffer,
} as Response)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const putObjectSpy = vi.spyOn(s3Service, 'putObject').mockResolvedValue(undefined as any)
const skill = await skillService.upsertSkill(team.id, {
githubUrl: 'https://github.com/owner/repo/my-path',
})
expect(skill.name).toBe('Direct Skill')
expect(fetchSpy).toHaveBeenCalledWith(
'https://codeload.github.com/owner/repo/zip/refs/heads/main',
)
fetchSpy.mockRestore()
putObjectSpy.mockRestore()
})
it('should delete skill', async () => {
const team = await prisma.team.create({ data: { name: 'Test Team' } })
const skill = await prisma.skill.create({
data: {
name: 'Delete Me',
assetId: 'asset1',
hash: 'hash1',
teamId: team.id,
},
})
await skillService.deleteSkill(skill.id)
const dbSkill = await prisma.skill.findUnique({
where: { id: skill.id },
})
expect(dbSkill).toBeNull()
})
it('should update skill config', async () => {
const team = await prisma.team.create({ data: { name: 'Test Team' } })
const skill = await prisma.skill.create({
data: {
name: 'Config Skill',
assetId: 'asset1',
hash: 'hash1',
teamId: team.id,
},
})
const newConfig = {
environmentVariables: [{ name: 'MY_VAR', default: 'my_val' }],
}
const updatedSkill = await skillService.updateSkillConfig(skill.id, newConfig)
expect(updatedSkill.config).toEqual(newConfig)
const dbSkill = await prisma.skill.findUnique({
where: { id: skill.id },
})
expect(dbSkill?.config).toEqual(newConfig)
})
})
+285
View File
@@ -0,0 +1,285 @@
import { prisma } from '@shumai/db'
import { SkillInfo, UpsertSkillRequest } from '@shumai/dtos'
import { s3Service } from '@shumai/core/src/s3/s3'
import AdmZip from 'adm-zip'
import * as crypto from 'crypto'
import { ulid } from 'ulid'
import { parseFrontmatter } from '@/utils/frontmatter'
interface SkillFrontmatter extends Record<string, unknown> {
name?: string
description?: string
}
export class SkillService {
constructor(private readonly prismaClient: typeof prisma = prisma) {}
async upsertSkill(teamId: string, req: UpsertSkillRequest): Promise<SkillInfo> {
let zipBuffer: Buffer
let requestedPath: string | undefined
if (req.githubUrl) {
const { downloadUrl, path } = this.parseGithubUrl(req.githubUrl)
requestedPath = path
zipBuffer = await this.downloadGithubZip(downloadUrl)
} else if (req.assetId) {
const asset = await this.prismaClient.asset.findUnique({
where: { id: req.assetId },
include: { storageKey: true },
})
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')
}
const { name, description, repackedZip } = await this.processSkillZip(zipBuffer, requestedPath)
// Check for existing skill if override is not requested
const existingSkill = await this.prismaClient.skill.findUnique({
where: {
// eslint-disable-next-line @typescript-eslint/naming-convention
teamId_name: {
teamId,
name,
},
},
})
if (existingSkill && !req.override) {
const err = new Error(`Skill with name "${name}" already exists.`)
err.name = 'ConflictError'
throw err
}
const hash = crypto.createHash('sha256').update(repackedZip).digest('hex')
// Upload repacked zip to S3
const assetKey = `skills/${ulid()}.zip`
await s3Service.putObject(
process.env.S3_BUCKET || 'shumai',
assetKey,
repackedZip,
repackedZip.length,
'application/zip',
)
// Create a new asset record for the repacked zip
const skillAsset = await this.prismaClient.asset.create({
data: {
name: `${name}.zip`,
storageKey: { create: { key: assetKey } },
type: 'file',
mediaType: 'application/zip',
sizeByte: repackedZip.length,
status: 'uploaded',
},
})
const skill = await this.prismaClient.skill.upsert({
where: {
// eslint-disable-next-line @typescript-eslint/naming-convention
teamId_name: {
teamId,
name,
},
},
update: {
description,
assetId: skillAsset.id,
hash,
},
create: {
name,
description,
assetId: skillAsset.id,
hash,
teamId,
},
})
return this.toSkillInfo(skill)
}
async deleteSkill(id: string): Promise<void> {
const skill = await this.prismaClient.skill.findUnique({
where: { id },
})
if (!skill) return
await this.prismaClient.skill.delete({
where: { id },
})
// Optionally delete the asset as well, though it might be shared or kept for history.
// For now, let's keep it simple and just delete the DB record.
}
async updateSkillConfig(id: string, config: PrismaJson.SkillConfig): Promise<SkillInfo> {
const skill = await this.prismaClient.skill.update({
where: { id },
data: { config },
})
return this.toSkillInfo(skill)
}
async listSkills(teamId: string): Promise<SkillInfo[]> {
const skills = await this.prismaClient.skill.findMany({
where: { teamId },
orderBy: { id: 'desc' },
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return skills.map((s: any) => this.toSkillInfo(s))
}
private parseGithubUrl(url: string): { downloadUrl: string; path?: string } {
// Standard GitHub URL patterns:
// 1. https://github.com/owner/repo/tree/branch/path
// 2. https://github.com/owner/repo/blob/branch/path
// 3. https://github.com/owner/repo/path (direct path, main branch)
const parsed = new URL(url)
const parts = parsed.pathname.split('/').filter(Boolean)
if (parts.length < 2) {
throw new Error('Invalid GitHub URL: missing owner or repo')
}
const owner = parts[0]
const repo = parts[1]
let ref = 'main'
let path: string | undefined
if (parts.length > 2) {
if (parts[2] === 'tree' || parts[2] === 'blob') {
if (parts.length < 4) {
throw new Error('Invalid GitHub URL: missing ref or path')
}
ref = parts[3]
path = parts.slice(4).join('/')
} else {
// Fallback: assume everything after repo is the path on 'main'
path = parts.slice(2).join('/')
}
}
const downloadUrl = `https://codeload.github.com/${owner}/${repo}/zip/refs/heads/${ref}`
return { downloadUrl, path }
}
private async downloadGithubZip(url: string): Promise<Buffer> {
const res = await fetch(url)
if (!res.ok) {
// Try 'master' if 'main' fails and it was a default guess
if (url.endsWith('/refs/heads/main')) {
const fallbackUrl = url.replace('/refs/heads/main', '/refs/heads/master')
const fallbackRes = await fetch(fallbackUrl)
if (fallbackRes.ok) {
return Buffer.from(await fallbackRes.arrayBuffer())
}
}
throw new Error(`Failed to download GitHub ZIP from ${url}`)
}
return Buffer.from(await res.arrayBuffer())
}
private async processSkillZip(
buffer: Buffer,
requestedPath?: string,
): Promise<{
name: string
description: string
repackedZip: Buffer
}> {
const zip = new AdmZip(buffer)
const entries = zip.getEntries()
if (entries.length === 0) {
throw new Error('The provided ZIP file is empty')
}
// Extract search path from entries
const firstEntryName = entries[0].entryName
const firstPart = firstEntryName.split('/')[0]
const isGithubStructure = entries.every((e) => e.entryName.startsWith(`${firstPart}/`))
let effectiveRequestedPath = requestedPath || ''
if (effectiveRequestedPath.toLowerCase().endsWith('skill.md')) {
effectiveRequestedPath = effectiveRequestedPath.substring(
0,
effectiveRequestedPath.toLowerCase().lastIndexOf('skill.md'),
)
}
let searchPath = ''
if (isGithubStructure) {
searchPath = effectiveRequestedPath
? `${firstPart}/${effectiveRequestedPath.replace(/\/$/, '')}/`
: `${firstPart}/`
} else {
searchPath = effectiveRequestedPath ? `${effectiveRequestedPath.replace(/\/$/, '')}/` : ''
}
// Find SKILL.md in the searchPath (case-insensitive)
const skillMdEntry = entries.find((e) => {
const entryLower = e.entryName.toLowerCase()
const searchLower = searchPath.toLowerCase()
return entryLower.startsWith(searchLower) && entryLower.endsWith('skill.md')
})
if (!skillMdEntry) {
throw new Error(`SKILL.md not found in ${requestedPath || 'root'}`)
}
const content = skillMdEntry.getData().toString('utf8')
const { name, description } = this.parseSkillMd(content)
// Repack: ensure the found SKILL.md's directory becomes the root
const newZip = new AdmZip()
const prefix = skillMdEntry.entryName.substring(
0,
skillMdEntry.entryName.toLowerCase().lastIndexOf('skill.md'),
)
for (const entry of entries) {
if (entry.isDirectory) continue
if (entry.entryName.startsWith(prefix)) {
const relPath = entry.entryName.substring(prefix.length)
newZip.addFile(relPath, entry.getData())
}
}
return {
name,
description,
repackedZip: newZip.toBuffer(),
}
}
private parseSkillMd(content: string): { name: string; description: string } {
const { frontmatter } = parseFrontmatter<SkillFrontmatter>(content)
const name = frontmatter.name || 'Unnamed Skill'
const description = frontmatter.description || ''
return { name, description }
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private toSkillInfo(s: any): SkillInfo {
return {
id: s.id,
name: s.name,
description: s.description,
config: s.config as PrismaJson.SkillConfig,
assetId: s.assetId,
hash: s.hash,
createdAt: s.createdAt.toISOString(),
updatedAt: s.updatedAt.toISOString(),
}
}
}
export const skillService = new SkillService()
+233
View File
@@ -0,0 +1,233 @@
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import { teamService } from '@shumai/core/src/team/team'
import { describe, expect, it } from 'vitest'
describe('TeamService', () => {
setupTestDbHooks()
it('should ensure default team', async () => {
const team = await teamService.ensureDefaultTeam()
expect(team).toBeDefined()
expect(team.name).toBe('Default Team')
})
it('should create team', async () => {
const user = await prisma.user.create({
data: { name: 'Test User', email: 'test-user@example.com', password: 'pw' },
})
const team = await teamService.createTeam(user, {
name: 'Test Team',
})
expect(team.id).toBeDefined()
expect(team.name).toBe('Test Team')
expect(team.rootFolder).toBeDefined()
// Test that the team member is created
const members = await prisma.teamMember.findMany({
where: { teamId: team.id },
})
expect(members).toHaveLength(1)
expect(members[0].userId).toBe(user.id)
expect(members[0].role).toBe('owner')
})
it('should get user teams', async () => {
const user = await prisma.user.create({
data: { name: 'Test User', email: 'test-user-2@example.com', password: 'pw' },
})
const team = await teamService.createTeam(user, {
name: 'Test Team',
})
const teams = await teamService.getUserTeams({
userId: user.id,
pagination: { first: 10 },
})
expect(teams.data).toHaveLength(1)
expect(teams.data[0].id).toBe(team.id)
})
it('should join team', async () => {
const owner = await prisma.user.create({
data: { name: 'Owner', email: 'owner@example.com', password: 'pw' },
})
const user = await prisma.user.create({
data: { name: 'Joiner', email: 'joiner@example.com', password: 'pw' },
})
const team = await teamService.createTeam(owner, {
name: 'Test Team',
})
await teamService.joinTeam({
teamId: team.id,
userId: user.id,
})
const members = await prisma.teamMember.findMany({
where: { teamId: team.id },
})
expect(members).toHaveLength(2)
})
it('should get me', async () => {
const user = await prisma.user.create({
data: { name: 'Test User', email: `test-${Date.now()}@example.com`, password: 'pw' },
})
const team = await teamService.createTeam(user, {
name: 'Test Team',
})
const me = await teamService.getMe({
teamId: team.id,
user,
})
expect(me.id).toBe(user.id)
expect(me.name).toBe('Test User')
expect(me.role).toBe('owner')
})
it('should get team members', async () => {
const user1 = await prisma.user.create({
data: { name: 'Test User 1', email: `test1-${Date.now()}@example.com`, password: 'pw' },
})
const user2 = await prisma.user.create({
data: { name: 'Test User 2', email: `test2-${Date.now()}@example.com`, password: 'pw' },
})
const team = await teamService.createTeam(user1, {
name: 'Test Team',
})
await teamService.joinTeam({
teamId: team.id,
userId: user2.id,
})
const members = await teamService.getTeamMembers({
teamId: team.id,
})
expect(members).toHaveLength(2)
})
it('should filter bots in team members', async () => {
const user = await prisma.user.create({
data: { name: 'Human', email: `human-${Date.now()}@example.com`, password: 'pw' },
})
const team = await teamService.createTeam(user, {
name: 'Test Team',
})
const bot = await prisma.user.create({
data: {
name: 'Bot',
email: `bot-${Date.now()}@example.com`,
password: 'pw',
type: 'agent',
agent: {
create: {
teamId: team.id,
type: 'chat',
enabled: true,
config: {
provider: 'google',
model: 'gemini',
},
},
},
},
})
await teamService.joinTeam({
teamId: team.id,
userId: bot.id,
})
// Should hide bots by default
const members = await teamService.getTeamMembers({
teamId: team.id,
})
expect(members).toHaveLength(1)
expect(members[0].id).toBe(user.id)
// Should include bots if requested
const allMembers = await teamService.getTeamMembers({
teamId: team.id,
includeAgents: true,
})
expect(allMembers).toHaveLength(2)
})
it('should get and update settings', async () => {
const user = await prisma.user.create({
data: { name: 'Test User', email: `test-${Date.now()}@example.com`, password: 'pw' },
})
const team = await teamService.createTeam(user, {
name: 'Test Team',
})
const settings = await teamService.getSettings(team.id)
expect(settings).toEqual({ semanticSearchEnabled: false })
await teamService.updateSettings(team.id, 'theme', 'dark')
const newSettings = await teamService.getSettings(team.id)
expect(newSettings).toEqual({ theme: 'dark', semanticSearchEnabled: false })
})
it('should create sandbox when team is created', async () => {
const user = await prisma.user.create({
data: { name: 'Test User', email: `test-sandbox-${Date.now()}@example.com`, password: 'pw' },
})
const team = await teamService.createTeam(user, {
name: 'Sandbox Team',
})
const sandbox = await prisma.sandbox.findUnique({
where: { teamId: team.id },
})
expect(sandbox).toBeDefined()
expect(sandbox?.allowedDomains).toContain('github.com')
})
it('should get and update sandbox settings', async () => {
const user = await prisma.user.create({
data: { name: 'Test User', email: `test-settings-${Date.now()}@example.com`, password: 'pw' },
})
const team = await teamService.createTeam(user, {
name: 'Settings Team',
})
// Should have default settings
const settings = await teamService.getSandboxSettings(team.id)
expect(settings.allowedDomains).toContain('github.com')
// Should update settings
const updated = await teamService.updateSandboxSettings(team.id, {
allowedDomains: ['example.com'],
})
expect(updated.allowedDomains).toEqual(['example.com'])
// Should persist to DB
const persisted = await teamService.getSandboxSettings(team.id)
expect(persisted.allowedDomains).toEqual(['example.com'])
})
it('should return empty allowedDomains if sandbox is missing for old team', async () => {
const team = await prisma.team.create({
data: { name: 'Old Team' },
})
const settings = await teamService.getSandboxSettings(team.id)
expect(settings.allowedDomains).toEqual([])
})
})
+274
View File
@@ -0,0 +1,274 @@
import { prisma } from '@shumai/db'
import { Prisma } from '@shumai/db'
import { PaginatedData, paginateQuery } from '@shumai/core/src/pagination'
import { ProviderService, providerService } from '@shumai/core/src/provider/provider'
import { notificationService } from '@shumai/core/src/notification/notification'
import {
ServiceCreateTeamRequest,
ServiceGetUserTeamsRequest,
ServiceJoinTeamRequest,
ServiceGetMeRequest,
ServiceGetTeamMembersRequest,
TeamInfo,
GetMeResponse,
UserInfo,
SandboxSettings,
} from '@shumai/dtos'
export class TeamService {
async ensureDefaultTeam() {
let team = await prisma.team.findFirst({
where: { name: 'Default Team' },
})
if (!team) {
team = await prisma.team.create({
data: {
name: 'Default Team',
settings: {
enablePublicSignup: true,
transcode: { videoStrategy: 'best_match' },
},
sandbox: { create: {} },
},
})
await providerService.initBuiltinProviders(team.id)
}
return team
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async createTeam(user: any, req: ServiceCreateTeamRequest): Promise<TeamInfo> {
return await prisma.$transaction(async (tx) => {
const team = await tx.team.create({
data: {
name: req.name,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
settings: {} as any,
sandbox: { create: {} },
},
})
const rootFolder = await tx.asset.create({
data: {
name: 'root',
type: 'root',
status: 'processed',
},
})
const updatedTeam = await tx.team.update({
where: { id: team.id },
data: { rootFolderId: rootFolder.id },
include: { rootFolder: true },
})
await tx.teamMember.create({
data: {
teamId: team.id,
userId: user.id,
role: 'owner',
scope: 'team',
},
})
// We use 'any' here because ProviderService expects the full PrismaClient,
// but the TransactionClient is compatible with the methods we use.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await new ProviderService(tx as any).initBuiltinProviders(team.id)
return this.toTeamInfo(updatedTeam)
})
}
async getUserTeams(req: ServiceGetUserTeamsRequest): Promise<PaginatedData<TeamInfo[]>> {
const where: Prisma.TeamWhereInput = {
members: {
some: {
userId: req.userId,
},
},
}
return await paginateQuery(
async (skip, take) => {
const teams = await prisma.team.findMany({
where,
skip,
take,
orderBy: { id: 'desc' },
include: { rootFolder: true },
})
return teams.map(this.toTeamInfo)
},
null,
req.pagination,
)
}
async joinTeam(req: ServiceJoinTeamRequest): Promise<void> {
const existing = await prisma.teamMember.findUnique({
where: {
teamIdUserId: {
teamId: req.teamId,
userId: req.userId,
},
},
})
if (!existing) {
await prisma.teamMember.create({
data: {
teamId: req.teamId,
userId: req.userId,
role: 'reviewer',
scope: 'team',
},
})
}
}
async getMe(req: ServiceGetMeRequest): Promise<GetMeResponse> {
const member = await prisma.teamMember.findUnique({
where: {
teamIdUserId: {
teamId: req.teamId,
userId: req.user.id,
},
},
})
if (!member) throw new Error('user is not a team member')
const unreadNotificationCount = await notificationService.getUnreadCount(
req.teamId,
req.user.id,
)
return {
id: req.user.id,
name: req.user.name,
email: undefined,
role: member.role,
unreadNotificationCount,
}
}
async getTeamMembers(req: ServiceGetTeamMembersRequest): Promise<UserInfo[]> {
const members = await prisma.teamMember.findMany({
where: {
teamId: req.teamId,
...(req.includeAgents
? {
user: {
OR: [
{ type: 'human' },
{
type: 'agent',
agent: {
type: 'chat',
enabled: true,
},
},
],
},
}
: { user: { type: { not: 'agent' } } }),
},
include: { user: true },
})
return members.map((m) => ({
id: m.user.id,
name: m.user.name,
email: undefined,
role: m.role,
type: m.user.type || undefined,
}))
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async getSettings(teamId: string): Promise<any> {
const team = await prisma.team.findUnique({
where: { id: teamId },
})
if (!team) throw new Error('team not found')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const settings = (team.settings || {}) as any
const embeddingAgent = await prisma.agent.findFirst({
where: { teamId, type: 'embedding', enabled: true },
})
settings.semanticSearchEnabled = !!embeddingAgent
return settings
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async updateSettings(teamId: string, key: string, value: any): Promise<any> {
const team = await prisma.team.findUnique({ where: { id: teamId } })
if (!team) throw new Error('team not found')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const settings = (team.settings || {}) as any
settings[key] = value
const updated = await prisma.team.update({
where: { id: teamId },
data: { settings },
})
return updated.settings || {}
}
async getSandboxSettings(teamId: string): Promise<SandboxSettings> {
const sandbox = await prisma.sandbox.findUnique({
where: { teamId },
})
return {
allowedDomains: sandbox?.allowedDomains || [],
}
}
async updateSandboxSettings(teamId: string, settings: SandboxSettings): Promise<SandboxSettings> {
const sandbox = await prisma.sandbox.upsert({
where: { teamId },
create: {
teamId,
allowedDomains: settings.allowedDomains,
},
update: {
allowedDomains: settings.allowedDomains,
},
})
return {
allowedDomains: sandbox.allowedDomains,
}
}
async getSignupInfo() {
const count = await prisma.user.count()
const defaultTeam = await this.ensureDefaultTeam()
const settings = defaultTeam.settings as {
enablePublicSignup?: boolean
} | null
return {
userCount: count,
enablePublicSignup: settings?.enablePublicSignup ?? false,
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private toTeamInfo(team: any): TeamInfo {
return {
id: team.id,
name: team.name,
rootFolder: team.rootFolder?.id || team.rootFolderId || undefined,
updatedAt: team.updatedAt,
}
}
}
export const teamService = new TeamService()
+330
View File
@@ -0,0 +1,330 @@
import { describe, expect, it, vi, beforeEach } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import { uploadService } from './upload'
import { s3Service } from '@shumai/core/src/s3/s3'
import { AssetStatus, AssetType, WorkflowTaskType } from '@shumai/db'
vi.mock('@shumai/core/src/s3/s3', () => ({
s3Service: {
presign: vi.fn().mockResolvedValue('http://presigned-url.com'),
getObjectSize: vi.fn().mockResolvedValue(100),
},
}))
describe('UploadService', () => {
setupTestDbHooks()
let userId: string
let teamId: string
let projectId: string
let parentId: string
beforeEach(async () => {
const user = await prisma.user.create({
data: { name: 'test', email: 'test-upload@example.com' },
})
userId = user.id
const team = await prisma.team.create({ data: { name: 'team' } })
teamId = team.id
const project = await prisma.project.create({
data: { name: 'project', teamId },
})
projectId = project.id
const parent = await prisma.asset.create({
data: {
name: 'parent',
type: AssetType.folder,
projectId,
status: AssetStatus.uploaded,
},
})
parentId = parent.id
})
it('should create an upload task', async () => {
const req = {
parentId: parentId,
files: [
{
name: 'file1.txt',
id: '1',
size: 100,
type: 'file',
mediaType: 'video/mp4',
children: [],
},
{
name: 'folder1',
id: '2',
type: 'folder',
size: 0,
children: [
{
name: 'file2.txt',
id: '3',
size: 200,
type: 'file',
mediaType: 'image/png',
children: [],
},
],
},
{ name: '.hidden', id: '4', size: 100, type: 'file', children: [] },
],
}
const resp = await uploadService.createUploadTask(userId, req)
expect(resp.taskId).toBeDefined()
expect(resp.presignedUrls).toHaveLength(2)
const task = await prisma.task.findUnique({ where: { id: resp.taskId } })
expect(task?.name).toBe('2 Items')
expect(task?.total).toBe(2)
const file1 = await prisma.asset.findFirst({ where: { name: 'file1.txt' } })
expect(file1?.mediaType).toBe('video/mp4')
const file2 = await prisma.asset.findFirst({ where: { name: 'file2.txt' } })
expect(file2?.mediaType).toBe('image/png')
const hidden = await prisma.asset.findFirst({ where: { name: '.hidden' } })
expect(hidden).toBeNull()
})
it('should confirm file upload and create transcode tasks for video', async () => {
const task = await prisma.task.create({
data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' },
})
const asset = await prisma.asset.create({
data: {
name: 'video.mp4',
type: AssetType.file,
project: { connect: { id: projectId } },
parent: { connect: { id: parentId } },
status: AssetStatus.uploading,
storageKey: {
connectOrCreate: {
where: { key: 'test-key' },
create: { key: 'test-key' },
},
},
mediaType: 'video/mp4',
},
})
await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id })
const updatedAsset = await prisma.asset.findUnique({ where: { id: asset.id } })
// For video/image, status remains 'uploaded' while transcoding is pending
expect(updatedAsset?.status).toBe(AssetStatus.uploaded)
const workflowTask = await prisma.workflowTask.findFirst({
where: { assetId: asset.id, type: WorkflowTaskType.transcode },
})
expect(workflowTask).toBeDefined()
expect(workflowTask?.payload).toEqual({
projectId: projectId,
transcode: {
videoStrategy: 'best_match',
sprite: true,
poster: true,
},
})
})
it('should confirm file upload and create transcode tasks for image', async () => {
const task = await prisma.task.create({
data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' },
})
const asset = await prisma.asset.create({
data: {
name: 'image.png',
type: AssetType.file,
project: { connect: { id: projectId } },
parent: { connect: { id: parentId } },
status: AssetStatus.uploading,
storageKey: {
connectOrCreate: {
where: { key: 'test-key' },
create: { key: 'test-key' },
},
},
mediaType: 'image/png',
},
})
await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id })
const workflowTask = await prisma.workflowTask.findFirst({
where: { assetId: asset.id, type: WorkflowTaskType.transcode },
})
expect(workflowTask).toBeDefined()
expect(workflowTask?.payload).toEqual({
projectId: projectId,
transcode: {
thumbnail: true,
},
})
})
it('should confirm file upload for non-media files', async () => {
const task = await prisma.task.create({
data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' },
})
const asset = await prisma.asset.create({
data: {
name: 'file.txt',
type: AssetType.file,
project: { connect: { id: projectId } },
parent: { connect: { id: parentId } },
status: AssetStatus.uploading,
storageKey: {
connectOrCreate: {
where: { key: 'test-key' },
create: { key: 'test-key' },
},
},
mediaType: 'text/plain',
},
})
await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id })
const updatedAsset = await prisma.asset.findUnique({ where: { id: asset.id } })
expect(updatedAsset?.status).toBe(AssetStatus.processed)
const workflowTask = await prisma.workflowTask.findFirst({
where: { assetId: asset.id, type: WorkflowTaskType.transcode },
})
expect(workflowTask).toBeNull()
})
it('should create a version stack when parentId is a file', async () => {
// Create an existing file
const fileA = await prisma.asset.create({
data: {
name: 'fileA.txt',
type: AssetType.file,
projectId,
parentId,
status: AssetStatus.processed,
sizeByte: 1000,
},
})
const req = {
parentId: fileA.id,
files: [
{
name: 'fileA_v2.txt',
id: 'v2',
size: 2000,
type: 'file' as const,
mediaType: 'text/plain',
children: [],
},
],
}
const resp = await uploadService.createUploadTask(userId, req)
expect(resp.taskId).toBeDefined()
// Should have created a version stack
const stack = await prisma.asset.findFirst({
where: { type: AssetType.version_stack, parentId },
})
expect(stack).toBeDefined()
expect(stack?.fileCount).toBe(1) // Only fileA is "uploaded", the new one is still "uploading"
expect(stack?.sizeByte).toBe(1000)
// The new asset should be inside the stack
const newAsset = await prisma.asset.findFirst({
where: { taskId: resp.taskId, parentId: stack!.id },
})
expect(newAsset).toBeDefined()
expect(newAsset?.status).toBe(AssetStatus.uploading)
})
it('should correctly update counts when confirming a version in a stack', async () => {
// Create a stack with one existing file
const stack = await prisma.asset.create({
data: {
name: '',
type: AssetType.version_stack,
projectId,
parentId,
status: AssetStatus.uploaded,
fileCount: 1,
sizeByte: 1000,
},
})
await prisma.asset.create({
data: {
name: 'v1.txt',
type: AssetType.file,
projectId,
parentId: stack.id,
status: AssetStatus.processed,
sizeByte: 1000,
},
})
// Create an uploading asset in that stack
const task = await prisma.task.create({
data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' },
})
const fileV2 = await prisma.asset.create({
data: {
name: 'v2.txt',
type: AssetType.file,
project: { connect: { id: projectId } },
parent: { connect: { id: stack.id } },
status: AssetStatus.uploading,
storageKey: {
connectOrCreate: {
where: { key: 'v2-key' },
create: { key: 'v2-key' },
},
},
sizeByte: 2000,
},
})
vi.spyOn(s3Service, 'getObjectSize').mockResolvedValue(2000)
// Manually set parent folder size to match initial stack size for realistic aggregation
await prisma.asset.update({
where: { id: parentId },
data: { sizeByte: 1000 },
})
await uploadService.confirmFileUpload(userId, task.id, { fileId: fileV2.id })
const updatedStack = await prisma.asset.findUnique({ where: { id: stack.id } })
expect(updatedStack?.fileCount).toBe(2)
expect(updatedStack?.sizeByte).toBe(3000)
// Verify parent folder size (initially 1000 from stack)
const parentFolder = await prisma.asset.findUnique({ where: { id: parentId } })
expect(parentFolder?.sizeByte).toBe(3000)
})
it('should list upload tasks', async () => {
const task = await prisma.task.create({
data: {
creatorId: userId,
total: 3,
uploaded: 1,
type: 'upload',
name: 'test-upload-task',
},
})
const result = await uploadService.listUploadTasks(userId, { first: 10 })
expect(result.data).toHaveLength(1)
expect(result.data[0].id).toBe(task.id)
expect(result.data[0].name).toBe('test-upload-task')
})
})
+370
View File
@@ -0,0 +1,370 @@
import { prisma } from '@shumai/db'
import { ulid } from 'ulid'
import { generateKeyBetween } from 'jittered-fractional-indexing'
import { s3Service } from '@shumai/core/src/s3/s3'
import { assetService } from '@shumai/core/src/asset/asset'
import {
ConfirmFileUploadRequest,
CreateUploadTaskRequest,
CreateUploadTaskResponse,
FileNode,
PresignedUrl,
TaskInfo,
} from '@shumai/dtos'
import {
AssetStatus,
AssetType,
Prisma,
TaskStatus,
WorkflowTaskStatus,
WorkflowTaskType,
} from '@shumai/db'
import { PaginationParams, paginateQuery, PaginatedData } from '@shumai/core/src/pagination'
import { VideoTranscoder, ImageTranscoder } from '@/transcode/transcoder'
export class UploadService {
constructor(private readonly prismaClient: typeof prisma = prisma) {}
async createUploadTask(
userId: string,
req: CreateUploadTaskRequest,
): Promise<CreateUploadTaskResponse> {
const visibleFiles = req.files.filter((f) => !f.name.startsWith('.'))
let taskName = ''
if (visibleFiles.length === 1) {
taskName = visibleFiles[0].name
} else {
taskName = `${visibleFiles.length} Items`
}
let total = 0
const countTotalFiles = (nodes: FileNode[]) => {
for (const node of nodes) {
if (node.name.startsWith('.')) continue
if (node.type === 'file') {
total++
} else {
countTotalFiles(node.children)
}
}
}
countTotalFiles(req.files)
const task = await this.prismaClient.task.create({
data: {
creatorId: userId,
type: 'upload',
name: taskName,
total,
status: TaskStatus.pending,
},
})
const parentAsset = await this.prismaClient.asset.findUnique({
where: { id: req.parentId },
include: { project: true },
})
if (!parentAsset) throw new Error('Parent asset not found')
if (!parentAsset.projectId) throw new Error('Parent asset has no project')
const presignedUrls: PresignedUrl[] = []
const isParentFile = parentAsset.type === AssetType.file
const targetParentId = isParentFile ? parentAsset.parentId! : parentAsset.id
const createdAssetIds = await this.createAssetsRecursively(
userId,
task.id,
parentAsset.projectId,
targetParentId,
req.files,
presignedUrls,
)
if (isParentFile && createdAssetIds.length > 0) {
for (const assetId of createdAssetIds) {
await assetService.reparentAssets({
assetIds: [assetId],
newParentId: parentAsset.id,
creatorId: userId,
})
}
}
return {
taskId: task.id,
presignedUrls: presignedUrls,
}
}
private async createAssetsRecursively(
userId: string,
taskId: string,
projectId: string,
parentId: string,
files: FileNode[],
presignedUrls: PresignedUrl[],
): Promise<string[]> {
const firstFile = await this.prismaClient.asset.findFirst({
where: { parentId },
orderBy: { sortIndex: 'asc' },
})
let currentSortIndex = firstFile?.sortIndex || undefined
const createdIds: string[] = []
for (const file of files) {
if (file.name.startsWith('.')) continue
const newSortIndex = generateKeyBetween(null, currentSortIndex || null)
currentSortIndex = newSortIndex
const assetType = file.type === 'folder' ? AssetType.folder : AssetType.file
let key: string | null = null
if (assetType === AssetType.file) {
key = `file/${ulid()}/raw`
}
const newAsset = await this.prismaClient.asset.create({
data: {
name: file.name,
type: assetType,
storageKey: key ? { create: { key } } : undefined,
sortIndex: newSortIndex,
mediaType: file.mediaType,
status: AssetStatus.uploading,
sizeByte: file.size,
creator: userId ? { connect: { id: userId } } : undefined,
parent: parentId ? { connect: { id: parentId } } : undefined,
project: { connect: { id: projectId } },
task: { connect: { id: taskId } },
},
})
createdIds.push(newAsset.id)
if (file.children && file.children.length > 0) {
await this.createAssetsRecursively(
userId,
taskId,
projectId,
newAsset.id,
file.children,
presignedUrls,
)
} else if (assetType === AssetType.file && key) {
const url = await s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'PUT')
presignedUrls.push({
id: file.id,
fileId: newAsset.id,
url,
})
}
}
return createdIds
}
async confirmFileUpload(
userId: string,
taskId: string,
req: ConfirmFileUploadRequest,
): Promise<void> {
const asset = await this.prismaClient.asset.findUnique({
where: { id: req.fileId },
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')
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 } })
const t = await this.prismaClient.task.findUnique({ where: { id: taskId } })
if (t) {
const updatedTask = await this.prismaClient.task.update({
where: { id: taskId },
data: { uploaded: { increment: 1 } },
})
if (updatedTask.uploaded === updatedTask.total) {
await this.prismaClient.task.update({
where: { id: taskId },
data: { status: TaskStatus.completed },
})
}
}
return
}
const size = await s3Service.getObjectSize(process.env.S3_BUCKET || 'shumai', key)
const project = asset.project
await this.prismaClient.$transaction(async (tx) => {
// Update asset
const updatedAsset = await tx.asset.update({
where: { id: asset.id },
data: {
status: AssetStatus.uploaded,
sizeByte: size,
},
})
// Update parent and ancestors
if (asset.parentId) {
await tx.asset.update({
where: { id: asset.parentId },
data: { fileCount: { increment: 1 } },
})
// The transaction context is compatible with the asset service's requirements
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await assetService.updateAncestorsSize(tx as any, asset.parentId, updatedAsset.sizeByte)
}
// Update task
const updatedTask = await tx.task.update({
where: { id: taskId },
data: { uploaded: { increment: 1 } },
})
if (updatedTask.uploaded === (updatedTask.total || 0)) {
await tx.task.update({
where: { id: taskId },
data: { status: TaskStatus.completed },
})
}
const team = project.team
if (!team) return
if (!asset.projectId) throw new Error('Asset project ID is missing')
await this.triggerPostUploadWorkflows(tx, asset.id, team.id, asset.projectId)
})
}
async triggerPostUploadWorkflows(
tx: Prisma.TransactionClient,
assetId: string,
teamId: string,
projectId: string,
): Promise<void> {
const asset = await tx.asset.findUnique({
where: { id: assetId },
})
if (!asset) throw new Error('Asset not found')
const team = await tx.team.findUnique({
where: { id: teamId },
})
if (!team) throw new Error('Team not found')
// Ai Tasks
const autofillAgent = await tx.agent.findFirst({
where: {
type: 'autofill',
enabled: true,
user: { teamMembers: { some: { teamId: team.id } } },
},
})
if (autofillAgent) {
await tx.workflowTask.create({
data: {
assetId: asset.id,
type: WorkflowTaskType.ai_metadata_autofill,
status: WorkflowTaskStatus.pending,
teamId: team.id,
projectId,
payload: {
projectId,
agent: { agentId: autofillAgent.id },
},
},
})
}
// Ai Embedding if enabled via agent
const embeddingAgent = await tx.agent.findFirst({
where: {
type: 'embedding',
enabled: true,
user: { teamMembers: { some: { teamId: team.id } } },
},
})
if (embeddingAgent) {
if (asset.mediaType?.startsWith('video/') || asset.mediaType?.startsWith('image/')) {
await tx.workflowTask.create({
data: {
assetId: asset.id,
type: WorkflowTaskType.ai_embedding,
status: WorkflowTaskStatus.pending,
teamId: team.id,
projectId,
payload: {
projectId,
agent: { agentId: embeddingAgent.id },
},
},
})
}
}
const isVideo = asset.mediaType?.startsWith('video/')
const isImage = asset.mediaType?.startsWith('image/')
if (!isVideo && !isImage) {
await tx.asset.update({
where: { id: asset.id },
data: { status: AssetStatus.processed },
})
} else {
const settings = team.settings as PrismaJson.Settings | null
if (isVideo) {
const strategy = settings?.transcode?.videoStrategy || 'best_match'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await new VideoTranscoder(tx as any, asset.id, team.id, projectId)
.setStrategy(strategy)
.withSprite()
.withPoster()
.submit()
} else if (isImage) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await new ImageTranscoder(tx as any, asset.id, team.id, projectId).withThumbnail().submit()
}
}
}
async listUploadTasks(
userId: string,
params: PaginationParams,
): Promise<PaginatedData<TaskInfo[]>> {
const where: Prisma.TaskWhereInput = {
creatorId: userId,
type: 'upload',
}
const { data: tasks, pageInfo } = await paginateQuery(
async (skip, take) => {
return this.prismaClient.task.findMany({
where,
orderBy: { id: 'desc' },
skip,
take,
})
},
async () => this.prismaClient.task.count({ where }),
params,
)
const infos: TaskInfo[] = tasks.map((t) => ({
id: t.id,
name: t.name || '',
total: t.total || 0,
uploaded: t.uploaded,
createdAt: t.createdAt.toISOString(),
}))
return { data: infos, pageInfo }
}
}
export const uploadService = new UploadService()
@@ -0,0 +1,66 @@
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import { userMetadataService } from './user-metadata'
import { describe, expect, it } from 'vitest'
describe('UserMetadataService', () => {
setupTestDbHooks()
it('should upsert and get metadata', async () => {
const user = await prisma.user.create({
data: { name: 'Test User', email: `test-${Date.now()}@example.com`, password: 'pw' },
})
const team = await prisma.team.create({
data: { name: 'Test Team' },
})
const key = 'project:1:sort'
const value = { field: 'name', order: 'asc' }
await userMetadataService.upsertMetadata(user.id, team.id, key, value)
const metadata = await userMetadataService.getMetadata(user.id, team.id, key)
expect(metadata).toEqual({
key,
value,
})
// Update
const newValue = { field: 'updatedAt', order: 'desc' }
await userMetadataService.upsertMetadata(user.id, team.id, key, newValue)
const updatedMetadata = await userMetadataService.getMetadata(user.id, team.id, key)
expect(updatedMetadata?.value).toEqual(newValue)
})
it('should list all metadata for a user in a team', async () => {
const user = await prisma.user.create({
data: { name: 'Test User 2', email: `test2-${Date.now()}@example.com`, password: 'pw' },
})
const team = await prisma.team.create({
data: { name: 'Test Team 2' },
})
await userMetadataService.upsertMetadata(user.id, team.id, 'key1', 'value1')
await userMetadataService.upsertMetadata(user.id, team.id, 'key2', 'value2')
const list = await userMetadataService.listMetadata(user.id, team.id)
expect(list).toHaveLength(2)
expect(list).toEqual([
{ key: 'key1', value: 'value1' },
{ key: 'key2', value: 'value2' },
])
})
it('should return null if metadata not found', async () => {
const user = await prisma.user.create({
data: { name: 'Test User 3', email: `test3-${Date.now()}@example.com`, password: 'pw' },
})
const team = await prisma.team.create({
data: { name: 'Test Team 3' },
})
const metadata = await userMetadataService.getMetadata(user.id, team.id, 'nonexistent')
expect(metadata).toBeNull()
})
})
@@ -0,0 +1,63 @@
import { prisma } from '@shumai/db'
import { UserMetadataItem } from '@shumai/dtos'
export class UserMetadataService {
async upsertMetadata(userId: string, teamId: string, key: string, value: unknown) {
return await prisma.userMetadata.upsert({
where: {
userIdTeamIdKey: {
userId,
teamId,
key,
},
},
update: {
value,
},
create: {
userId,
teamId,
key,
value,
},
})
}
async listMetadata(userId: string, teamId: string): Promise<UserMetadataItem[]> {
const items = await prisma.userMetadata.findMany({
where: {
userId,
teamId,
},
orderBy: {
key: 'asc',
},
})
return items.map((item) => ({
key: item.key,
value: item.value,
}))
}
async getMetadata(userId: string, teamId: string, key: string): Promise<UserMetadataItem | null> {
const item = await prisma.userMetadata.findUnique({
where: {
userIdTeamIdKey: {
userId,
teamId,
key,
},
},
})
if (!item) return null
return {
key: item.key,
value: item.value,
}
}
}
export const userMetadataService = new UserMetadataService()
@@ -0,0 +1,208 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import { VersionStackService } from './versionStack'
import { AssetType } from '@shumai/db'
describe('VersionStackService', () => {
setupTestDbHooks()
let service: VersionStackService
beforeEach(() => {
service = new VersionStackService()
})
describe('createVersionStack', () => {
it('creates a version stack and reparents files', async () => {
// Setup: Create team, project, user, and parent folder
const team = await prisma.team.create({ data: { name: 'Test Team' } })
const proj = await prisma.project.create({
data: { name: 'Test Project', teamId: team.id },
})
const user = await prisma.user.create({
data: { name: 'Test User', email: `test-${Date.now()}@example.com` },
})
const root = await prisma.asset.create({
data: {
name: 'root',
type: AssetType.folder,
status: 'uploaded',
projectId: proj.id,
creatorId: user.id,
},
})
const parent = await prisma.asset.create({
data: {
name: 'Parent Folder',
type: AssetType.folder,
projectId: proj.id,
parentId: root.id,
creatorId: user.id,
status: 'uploaded',
fileCount: 2,
},
})
// Setup: Create files
const file1 = await prisma.asset.create({
data: {
name: 'file1.txt',
type: AssetType.file,
parentId: parent.id,
projectId: proj.id,
creatorId: user.id,
status: 'uploaded',
sizeByte: 100,
},
})
const file2 = await prisma.asset.create({
data: {
name: 'file2.txt',
type: AssetType.file,
parentId: parent.id,
projectId: proj.id,
creatorId: user.id,
status: 'uploaded',
sizeByte: 200,
},
})
// Execute
const stack = await service.createVersionStack({
fileIds: [file1.id, file2.id],
projectId: proj.id,
creatorId: user.id,
})
// Verify Stack
expect(stack).toBeDefined()
expect(stack.name).toBe('')
expect(stack.type).toBe(AssetType.version_stack)
expect(stack.fileCount).toBe(2)
expect(stack.sizeByte).toBe(300)
expect(stack.parentId).toBe(parent.id)
// Verify Parent file count
const updatedParent = await prisma.asset.findUnique({ where: { id: parent.id } })
expect(updatedParent?.fileCount).toBe(1)
// Verify Files
const updatedFile1 = await prisma.asset.findUnique({ where: { id: file1.id } })
expect(updatedFile1?.parentId).toBe(stack.id)
expect(updatedFile1?.sortIndex).toBeDefined()
const updatedFile2 = await prisma.asset.findUnique({ where: { id: file2.id } })
expect(updatedFile2?.parentId).toBe(stack.id)
expect(updatedFile2?.sortIndex).toBeDefined()
expect(updatedFile2!.sortIndex! > updatedFile1!.sortIndex!).toBe(true)
})
})
describe('changeStackFileVersion', () => {
it('changes the order of files in a version stack', async () => {
// Setup
const team = await prisma.team.create({ data: { name: 'Test Team' } })
const proj = await prisma.project.create({
data: { name: 'Test Project', teamId: team.id },
})
const user = await prisma.user.create({
data: { name: 'Test User', email: `test-${Date.now()}@example.com` },
})
const root = await prisma.asset.create({
data: {
name: 'root',
type: AssetType.folder,
status: 'uploaded',
projectId: proj.id,
creatorId: user.id,
},
})
const parent = await prisma.asset.create({
data: {
name: 'Parent',
type: AssetType.folder,
projectId: proj.id,
parentId: root.id,
creatorId: user.id,
status: 'uploaded',
fileCount: 3,
},
})
const file1 = await prisma.asset.create({
data: {
name: 'f1',
type: AssetType.file,
parentId: parent.id,
projectId: proj.id,
creatorId: user.id,
status: 'uploaded',
},
})
const file2 = await prisma.asset.create({
data: {
name: 'f2',
type: AssetType.file,
parentId: parent.id,
projectId: proj.id,
creatorId: user.id,
status: 'uploaded',
},
})
const file3 = await prisma.asset.create({
data: {
name: 'f3',
type: AssetType.file,
parentId: parent.id,
projectId: proj.id,
creatorId: user.id,
status: 'uploaded',
},
})
const stack = await service.createVersionStack({
fileIds: [file1.id, file2.id, file3.id],
projectId: proj.id,
creatorId: user.id,
})
// Move file2 to be before file1
await service.changeStackFileVersion({
stackId: stack.id,
fileId: file2.id,
beforeId: file1.id,
})
let children = await prisma.asset.findMany({
where: { parentId: stack.id },
orderBy: { sortIndex: 'asc' },
})
expect(children).toHaveLength(3)
expect(children.map((c) => c.id).includes(file1.id)).toBe(true)
expect(children.map((c) => c.id).includes(file2.id)).toBe(true)
expect(children.map((c) => c.id).includes(file3.id)).toBe(true)
// Move file1 to the end (-1)
await service.changeStackFileVersion({
stackId: stack.id,
fileId: file1.id,
beforeId: '-1',
})
children = await prisma.asset.findMany({
where: { parentId: stack.id },
orderBy: { sortIndex: 'asc' },
})
expect(children).toHaveLength(3)
expect(children.map((c) => c.id).includes(file1.id)).toBe(true)
expect(children.map((c) => c.id).includes(file2.id)).toBe(true)
expect(children.map((c) => c.id).includes(file3.id)).toBe(true)
})
})
})
@@ -0,0 +1,169 @@
import { generateKeyBetween } from 'jittered-fractional-indexing'
import { prisma } from '@shumai/db'
import { type Asset, AssetType } from '@shumai/db'
import { ChangeStackFileVersionParams, CreateVersionStackParams } from '@shumai/dtos'
function generateSortIndex(previous?: string | null): string {
if (!previous) return generateKeyBetween(null, null)
return generateKeyBetween(previous, null)
}
export class VersionStackService {
constructor(private readonly prismaClient: typeof prisma = prisma) {}
async createVersionStack(params: CreateVersionStackParams): Promise<Asset> {
const { fileIds, projectId, creatorId } = params
if (!fileIds || fileIds.length === 0) {
throw new Error('no file ids provided')
}
return await this.prismaClient.$transaction(async (tx) => {
const files = await tx.asset.findMany({
where: { id: { in: fileIds } },
include: { parent: true },
})
if (files.length !== fileIds.length) {
throw new Error('some files not found')
}
let parentId: string | undefined = undefined
let totalSize = 0
for (const f of files) {
if (f.type !== AssetType.file) {
throw new Error(`asset ${f.id} is not a file`)
}
if (!f.parentId) {
throw new Error(`file ${f.id} does not have a parent`)
}
if (parentId === undefined) {
parentId = f.parentId
} else if (f.parentId !== parentId) {
throw new Error('files do not have the same parent')
}
totalSize += f.sizeByte
}
if (!parentId) {
throw new Error('files do not have a parent')
}
const parent = await tx.asset.findUnique({
where: { id: parentId },
})
if (!parent) {
throw new Error('parent not found')
}
const stack = await tx.asset.create({
data: {
type: AssetType.version_stack,
fileCount: files.length,
sizeByte: totalSize,
status: 'uploaded', // all existing files are already uploaded in the legacy go logic
projectId: projectId,
creatorId: creatorId,
parentId: parentId,
},
})
let currentSortIndex: string | null = null
for (const fileId of fileIds) {
currentSortIndex = generateSortIndex(currentSortIndex)
await tx.asset.update({
where: { id: fileId },
data: {
parentId: stack.id,
sortIndex: currentSortIndex,
},
})
}
await tx.asset.update({
where: { id: parentId },
data: {
fileCount: {
decrement: files.length - 1,
},
},
})
return stack
})
}
async changeStackFileVersion(params: ChangeStackFileVersionParams): Promise<void> {
const { stackId, fileId, beforeId } = params
await this.prismaClient.$transaction(async (tx) => {
const stack = await tx.asset.findUnique({
where: { id: stackId },
})
if (!stack) {
throw new Error('stack not found')
}
if (stack.type !== AssetType.version_stack) {
throw new Error('asset is not a version stack')
}
const fileToMove = await tx.asset.findUnique({
where: { id: fileId },
})
if (!fileToMove) {
throw new Error('file not found')
}
if (fileToMove.parentId !== stackId) {
throw new Error('file is not in the stack')
}
let newSortIndex: string
if (beforeId === '-1') {
const lastFile = await tx.asset.findFirst({
where: { parentId: stackId },
orderBy: { sortIndex: 'desc' },
})
newSortIndex = generateKeyBetween(lastFile?.sortIndex || null, null)
} else {
const beforeFile = await tx.asset.findUnique({
where: { id: beforeId },
})
if (!beforeFile) {
throw new Error('before_id file not found')
}
if (beforeFile.parentId !== stackId) {
throw new Error('before_id file is not in the stack')
}
const prevFile = await tx.asset.findFirst({
where: {
parentId: stackId,
sortIndex: {
lt: beforeFile.sortIndex!,
},
},
orderBy: { sortIndex: 'desc' },
})
let prevSortIndex = prevFile?.sortIndex || null
if (prevSortIndex && prevSortIndex >= beforeFile.sortIndex!) {
prevSortIndex = null
}
newSortIndex = generateKeyBetween(prevSortIndex, beforeFile.sortIndex!)
}
await tx.asset.update({
where: { id: fileId },
data: {
sortIndex: newSortIndex,
},
})
})
}
}
export const versionStackService = new VersionStackService()