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
+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)