feat: attachments on tickets and comments
Files are uploaded over REST, stored on disk (a volume in Docker) and recorded on the ticket as events; the bytes are written first, so no attachment ever points at a missing file. Only images, video, audio, PDF and plain text are shown inline, everything with nosniff and a sandbox CSP. The web shows thumbnails, uploads by drag and drop or by pasting a screenshot, and attaches files to new comments. Also adds `nx run api:contracts`, which writes schema.gql and openapi.json without starting the API or any database. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
|
||||
import { BusinessRuleError } from '@task-stream/api/shared/domain';
|
||||
import { AttachmentStorage, attachmentKey } from '../ports/attachment-storage';
|
||||
import { AttachFileCommand } from './attach-file.command';
|
||||
import { CommandResult, ack } from './command-result';
|
||||
import { WriteAccess } from './write-access';
|
||||
|
||||
/**
|
||||
* Stores the bytes first and records them on the ticket after: a file with no
|
||||
* record is cleaned up here, never a record with no file.
|
||||
*/
|
||||
@CommandHandler(AttachFileCommand)
|
||||
export class AttachFileCommandHandler
|
||||
implements ICommandHandler<AttachFileCommand>
|
||||
{
|
||||
constructor(
|
||||
private readonly access: WriteAccess,
|
||||
private readonly storage: AttachmentStorage,
|
||||
) {}
|
||||
|
||||
async execute(command: AttachFileCommand): Promise<CommandResult> {
|
||||
const { issue } = await this.access.issueForContributor(
|
||||
command.issueId,
|
||||
command.actorId,
|
||||
);
|
||||
if (command.commentId) {
|
||||
const comment = await this.access.comment(command.commentId);
|
||||
if (comment.issueId !== issue.id) {
|
||||
throw new BusinessRuleError(
|
||||
`That comment belongs to another ticket, not ${issue.key}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const id = randomUUID();
|
||||
const key = attachmentKey(issue.projectId, issue.id, id);
|
||||
issue.attach(command.actorId, {
|
||||
id,
|
||||
fileName: command.file.fileName,
|
||||
mimeType: command.file.mimeType,
|
||||
size: command.file.content.length,
|
||||
uploadedBy: command.actorId,
|
||||
uploadedAt: new Date().toISOString(),
|
||||
commentId: command.commentId,
|
||||
});
|
||||
|
||||
await this.storage.put(key, command.file.content);
|
||||
try {
|
||||
await issue.commitAndWait();
|
||||
} catch (error) {
|
||||
await this.storage.remove(key);
|
||||
throw error;
|
||||
}
|
||||
return ack(issue);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Command } from '@nestjs/cqrs';
|
||||
import { CommandResult } from './command-result';
|
||||
|
||||
export interface IncomingFile {
|
||||
fileName: string;
|
||||
mimeType: string;
|
||||
content: Buffer;
|
||||
}
|
||||
|
||||
export class AttachFileCommand extends Command<CommandResult> {
|
||||
constructor(
|
||||
public readonly actorId: string,
|
||||
public readonly issueId: string,
|
||||
public readonly file: IncomingFile,
|
||||
/** Places it under one of the ticket's comments. */
|
||||
public readonly commentId: string | null = null,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,8 @@ import { PurgeCommentCommandHandler } from './purge-comment.command-handler';
|
||||
import { DropLinksToIssueCommandHandler } from './drop-links-to-issue.command-handler';
|
||||
import { DetachIssueFromReleaseCommandHandler } from './detach-issue-from-release.command-handler';
|
||||
import { UnassignIssueCommandHandler } from './unassign-issue.command-handler';
|
||||
import { AttachFileCommandHandler } from './attach-file.command-handler';
|
||||
import { DetachFileCommandHandler } from './detach-file.command-handler';
|
||||
|
||||
export const COMMAND_HANDLERS = [
|
||||
CreateProjectCommandHandler,
|
||||
@@ -55,4 +57,6 @@ export const COMMAND_HANDLERS = [
|
||||
DropLinksToIssueCommandHandler,
|
||||
DetachIssueFromReleaseCommandHandler,
|
||||
UnassignIssueCommandHandler,
|
||||
AttachFileCommandHandler,
|
||||
DetachFileCommandHandler,
|
||||
];
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
} from '@task-stream/api/shared/domain';
|
||||
import {
|
||||
Comment,
|
||||
Issue,
|
||||
IssueStatus,
|
||||
Project,
|
||||
IssueType,
|
||||
@@ -20,6 +21,7 @@ import {
|
||||
} from '@task-stream/api/tracker/domain';
|
||||
import {
|
||||
FakeUserDirectory,
|
||||
InMemoryAttachmentStorage,
|
||||
InMemoryEventStore,
|
||||
InMemoryEventStorePublisher,
|
||||
InMemoryIssueNumbers,
|
||||
@@ -32,9 +34,12 @@ import { IssueNumbersRepository } from '../ports/issue-numbers.repository';
|
||||
import { ProjectKeysRepository } from '../ports/project-keys.repository';
|
||||
import { ReleaseNamesRepository } from '../ports/release-names.repository';
|
||||
import { UserDirectory } from '../ports/user-directory';
|
||||
import { AttachmentStorage } from '../ports/attachment-storage';
|
||||
import { AddCommentCommand } from './add-comment.command';
|
||||
import { AddProjectMemberCommand } from './add-project-member.command';
|
||||
import { AssignIssueCommand } from './assign-issue.command';
|
||||
import { AttachFileCommand } from './attach-file.command';
|
||||
import { DetachFileCommand } from './detach-file.command';
|
||||
import { ChangeIssueStatusCommand } from './change-issue-status.command';
|
||||
import { COMMAND_HANDLERS } from './command-handlers';
|
||||
import { CommandResult } from './command-result';
|
||||
@@ -48,6 +53,7 @@ import { WriteAccess } from './write-access';
|
||||
|
||||
async function setup() {
|
||||
const store = new InMemoryEventStore();
|
||||
const files = new InMemoryAttachmentStorage();
|
||||
const users = new FakeUserDirectory()
|
||||
.add('owner')
|
||||
.add('dev')
|
||||
@@ -62,6 +68,7 @@ async function setup() {
|
||||
WriteAccess,
|
||||
AggregateRehydrator,
|
||||
{ provide: EventStore, useValue: store },
|
||||
{ provide: AttachmentStorage, useValue: files },
|
||||
{ provide: UserDirectory, useValue: users },
|
||||
{ provide: ProjectKeysRepository, useClass: InMemoryProjectKeys },
|
||||
{ provide: IssueNumbersRepository, useClass: InMemoryIssueNumbers },
|
||||
@@ -78,7 +85,12 @@ async function setup() {
|
||||
const commandBus = moduleRef.get(CommandBus);
|
||||
const run = (command: object): Promise<CommandResult> =>
|
||||
commandBus.execute(command as never);
|
||||
return { store, run, rehydrator: moduleRef.get(AggregateRehydrator) };
|
||||
return {
|
||||
store,
|
||||
files,
|
||||
run,
|
||||
rehydrator: moduleRef.get(AggregateRehydrator),
|
||||
};
|
||||
}
|
||||
|
||||
async function projectWithTeam(run: (c: object) => Promise<CommandResult>) {
|
||||
@@ -178,6 +190,74 @@ describe('tracker commands (event sourced)', () => {
|
||||
).rejects.toThrow(BusinessRuleError);
|
||||
});
|
||||
|
||||
describe('attachments', () => {
|
||||
const png = {
|
||||
fileName: 'captura.png',
|
||||
mimeType: 'image/png',
|
||||
content: Buffer.from('fake png'),
|
||||
};
|
||||
|
||||
it('stores the file and records it on the ticket', async () => {
|
||||
const { run, files, rehydrator } = await setup();
|
||||
const projectId = await projectWithTeam(run);
|
||||
const issue = await run(
|
||||
new CreateIssueCommand('qa', projectId, IssueType.BUG, 'Crash', {}),
|
||||
);
|
||||
|
||||
await run(new AttachFileCommand('qa', issue.id, png));
|
||||
|
||||
const rebuilt = await rehydrator.rehydrate(issue.id, Issue);
|
||||
expect(rebuilt.attachments).toHaveLength(1);
|
||||
expect(rebuilt.attachments[0]).toMatchObject({
|
||||
fileName: 'captura.png',
|
||||
size: 8,
|
||||
uploadedBy: 'qa',
|
||||
});
|
||||
expect([...files.files.keys()]).toEqual([
|
||||
`${projectId}/${issue.id}/${rebuilt.attachments[0].id}`,
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps no file when the ticket cannot take it', async () => {
|
||||
const { run, files } = await setup();
|
||||
const projectId = await projectWithTeam(run);
|
||||
const issue = await run(
|
||||
new CreateIssueCommand('qa', projectId, IssueType.BUG, 'Crash', {}),
|
||||
);
|
||||
|
||||
await expect(
|
||||
run(new AttachFileCommand('pm', issue.id, png)),
|
||||
).rejects.toThrow(ForbiddenError);
|
||||
await expect(
|
||||
run(
|
||||
new AttachFileCommand('qa', issue.id, {
|
||||
...png,
|
||||
content: Buffer.alloc(0),
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow();
|
||||
expect(files.files.size).toBe(0);
|
||||
});
|
||||
|
||||
it('lets the uploader or an admin remove it, and deletes the bytes', async () => {
|
||||
const { run, files, rehydrator } = await setup();
|
||||
const projectId = await projectWithTeam(run);
|
||||
const issue = await run(
|
||||
new CreateIssueCommand('qa', projectId, IssueType.BUG, 'Crash', {}),
|
||||
);
|
||||
await run(new AttachFileCommand('qa', issue.id, png));
|
||||
const [attachment] = (await rehydrator.rehydrate(issue.id, Issue))
|
||||
.attachments;
|
||||
|
||||
await expect(
|
||||
run(new DetachFileCommand('dev', issue.id, attachment.id)),
|
||||
).rejects.toThrow(ForbiddenError);
|
||||
await run(new DetachFileCommand('owner', issue.id, attachment.id));
|
||||
|
||||
expect(files.files.size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
it('does not let viewers modify tickets', async () => {
|
||||
const { run } = await setup();
|
||||
const projectId = await projectWithTeam(run);
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
|
||||
import { ProjectRole } from '@task-stream/api/tracker/domain';
|
||||
import { AttachmentStorage, attachmentKey } from '../ports/attachment-storage';
|
||||
import { CommandResult, ack } from './command-result';
|
||||
import { DetachFileCommand } from './detach-file.command';
|
||||
import { WriteAccess } from './write-access';
|
||||
|
||||
/** Removes the record first; the bytes go once nothing points at them. */
|
||||
@CommandHandler(DetachFileCommand)
|
||||
export class DetachFileCommandHandler
|
||||
implements ICommandHandler<DetachFileCommand>
|
||||
{
|
||||
constructor(
|
||||
private readonly access: WriteAccess,
|
||||
private readonly storage: AttachmentStorage,
|
||||
) {}
|
||||
|
||||
async execute(command: DetachFileCommand): Promise<CommandResult> {
|
||||
const { issue, project } = await this.access.issueForContributor(
|
||||
command.issueId,
|
||||
command.actorId,
|
||||
);
|
||||
const role = project.roleOf(command.actorId);
|
||||
issue.detach(
|
||||
command.actorId,
|
||||
command.attachmentId,
|
||||
role === ProjectRole.OWNER || role === ProjectRole.ADMIN,
|
||||
);
|
||||
await issue.commitAndWait();
|
||||
await this.storage.remove(
|
||||
attachmentKey(issue.projectId, issue.id, command.attachmentId),
|
||||
);
|
||||
return ack(issue);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Command } from '@nestjs/cqrs';
|
||||
import { CommandResult } from './command-result';
|
||||
|
||||
export class DetachFileCommand extends Command<CommandResult> {
|
||||
constructor(
|
||||
public readonly actorId: string,
|
||||
public readonly issueId: string,
|
||||
public readonly attachmentId: string,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
@@ -26,3 +26,5 @@ export * from './purge-comment.command';
|
||||
export * from './drop-links-to-issue.command';
|
||||
export * from './detach-issue-from-release.command';
|
||||
export * from './unassign-issue.command';
|
||||
export * from './attach-file.command';
|
||||
export * from './detach-file.command';
|
||||
|
||||
@@ -3,6 +3,8 @@ import {
|
||||
CommentDeletedEvent,
|
||||
CommentEditedEvent,
|
||||
IssueAssignedEvent,
|
||||
IssueAttachmentAddedEvent,
|
||||
IssueAttachmentRemovedEvent,
|
||||
IssueCreatedEvent,
|
||||
IssueLinkedEvent,
|
||||
IssueLinkType,
|
||||
@@ -135,6 +137,11 @@ export function describeEvent(
|
||||
: `${actor} sacó ${issueKey} de su release`;
|
||||
}
|
||||
|
||||
if (event instanceof IssueAttachmentAddedEvent)
|
||||
return `${actor} adjuntó ${event.attachment.fileName} a ${issueKey}`;
|
||||
if (event instanceof IssueAttachmentRemovedEvent)
|
||||
return `${actor} quitó el adjunto ${event.fileName} de ${issueKey}`;
|
||||
|
||||
if (event instanceof CommentAddedEvent)
|
||||
return `${actor} comentó en ${issueKey}`;
|
||||
if (event instanceof CommentEditedEvent)
|
||||
|
||||
@@ -5,6 +5,8 @@ import {
|
||||
CommentDeletedEvent,
|
||||
CommentEditedEvent,
|
||||
IssueAssignedEvent,
|
||||
IssueAttachmentAddedEvent,
|
||||
IssueAttachmentRemovedEvent,
|
||||
IssueCreatedEvent,
|
||||
IssueLinkedEvent,
|
||||
IssueReleaseChangedEvent,
|
||||
@@ -51,6 +53,8 @@ import { versionOf } from './read-model-notifier';
|
||||
IssueLinkedEvent,
|
||||
IssueUnlinkedEvent,
|
||||
IssueReleaseChangedEvent,
|
||||
IssueAttachmentAddedEvent,
|
||||
IssueAttachmentRemovedEvent,
|
||||
CommentAddedEvent,
|
||||
CommentEditedEvent,
|
||||
CommentDeletedEvent,
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
|
||||
import { IssueDeletedEvent } from '@task-stream/api/tracker/domain';
|
||||
import {
|
||||
AttachmentStorage,
|
||||
issueAttachmentsPrefix,
|
||||
} from '../ports/attachment-storage';
|
||||
|
||||
/** A deleted ticket takes its files with it. */
|
||||
@EventsHandler(IssueDeletedEvent)
|
||||
export class AttachmentCleanupEventHandler
|
||||
implements IEventHandler<IssueDeletedEvent>
|
||||
{
|
||||
constructor(private readonly storage: AttachmentStorage) {}
|
||||
|
||||
async handle(event: IssueDeletedEvent) {
|
||||
await this.storage.removePrefix(
|
||||
issueAttachmentsPrefix(event.projectId, event.aggregateId),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,9 @@ import { ProjectSettingsChangedEventHandler } from './project-settings-changed.e
|
||||
import { ProjectDeletedEventHandler } from './project-deleted.event-handler';
|
||||
import { IssueDeletedEventHandler } from './issue-deleted.event-handler';
|
||||
import { ReleaseDeletedEventHandler } from './release-deleted.event-handler';
|
||||
import { IssueAttachmentAddedEventHandler } from './issue-attachment-added.event-handler';
|
||||
import { IssueAttachmentRemovedEventHandler } from './issue-attachment-removed.event-handler';
|
||||
import { AttachmentCleanupEventHandler } from './attachment-cleanup.event-handler';
|
||||
|
||||
/** Read-model projections (MongoDB) + realtime, fed by the EventsBridge. */
|
||||
export const EVENT_HANDLERS = [
|
||||
@@ -52,6 +55,9 @@ export const EVENT_HANDLERS = [
|
||||
ReleaseCreatedEventHandler,
|
||||
ReleaseShippedEventHandler,
|
||||
ReleaseUpdatedEventHandler,
|
||||
IssueAttachmentAddedEventHandler,
|
||||
IssueAttachmentRemovedEventHandler,
|
||||
AttachmentCleanupEventHandler,
|
||||
];
|
||||
|
||||
export { ReadModelNotifier };
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
|
||||
import { IssueAttachmentAddedEvent } from '@task-stream/api/tracker/domain';
|
||||
import { UpsertMaterializedIssueRepository } from '../ports/upsert-materialized-issue.repository';
|
||||
import { UserDirectory } from '../ports/user-directory';
|
||||
import { ReadModelNotifier, versionOf } from './read-model-notifier';
|
||||
|
||||
@EventsHandler(IssueAttachmentAddedEvent)
|
||||
export class IssueAttachmentAddedEventHandler
|
||||
implements IEventHandler<IssueAttachmentAddedEvent>
|
||||
{
|
||||
constructor(
|
||||
private readonly upsertMaterializedIssueRepository: UpsertMaterializedIssueRepository,
|
||||
private readonly users: UserDirectory,
|
||||
private readonly notifier: ReadModelNotifier,
|
||||
) {}
|
||||
|
||||
async handle(event: IssueAttachmentAddedEvent) {
|
||||
const { attachment } = event;
|
||||
const users = await this.users.refs([attachment.uploadedBy]);
|
||||
await this.upsertMaterializedIssueRepository.upsert({
|
||||
id: event.aggregateId,
|
||||
updatedAt: event.occurredAt,
|
||||
version: versionOf(event),
|
||||
});
|
||||
await this.upsertMaterializedIssueRepository.addAttachment(
|
||||
event.aggregateId,
|
||||
{ ...attachment, uploadedBy: users.of(attachment.uploadedBy) },
|
||||
);
|
||||
await this.notifier.issue(event.aggregateId, event);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
|
||||
import { IssueAttachmentRemovedEvent } from '@task-stream/api/tracker/domain';
|
||||
import { UpsertMaterializedIssueRepository } from '../ports/upsert-materialized-issue.repository';
|
||||
import { ReadModelNotifier, versionOf } from './read-model-notifier';
|
||||
|
||||
@EventsHandler(IssueAttachmentRemovedEvent)
|
||||
export class IssueAttachmentRemovedEventHandler
|
||||
implements IEventHandler<IssueAttachmentRemovedEvent>
|
||||
{
|
||||
constructor(
|
||||
private readonly upsertMaterializedIssueRepository: UpsertMaterializedIssueRepository,
|
||||
private readonly notifier: ReadModelNotifier,
|
||||
) {}
|
||||
|
||||
async handle(event: IssueAttachmentRemovedEvent) {
|
||||
await this.upsertMaterializedIssueRepository.upsert({
|
||||
id: event.aggregateId,
|
||||
updatedAt: event.occurredAt,
|
||||
version: versionOf(event),
|
||||
});
|
||||
await this.upsertMaterializedIssueRepository.removeAttachment(
|
||||
event.aggregateId,
|
||||
event.attachmentId,
|
||||
);
|
||||
await this.notifier.issue(event.aggregateId, event);
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,11 @@ import {
|
||||
IssueReadModel,
|
||||
} from '@task-stream/api/tracker/domain';
|
||||
import { AssignIssueCommand } from './commands/assign-issue.command';
|
||||
import {
|
||||
AttachFileCommand,
|
||||
IncomingFile,
|
||||
} from './commands/attach-file.command';
|
||||
import { DetachFileCommand } from './commands/detach-file.command';
|
||||
import { ChangeIssueStatusCommand } from './commands/change-issue-status.command';
|
||||
import { CommandResult } from './commands/command-result';
|
||||
import { CreateIssueCommand } from './commands/create-issue.command';
|
||||
@@ -16,6 +21,10 @@ import { UnlinkIssuesCommand } from './commands/unlink-issues.command';
|
||||
import { UpdateIssueCommand } from './commands/update-issue.command';
|
||||
import { IssueFilter, Page } from './ports/find-issues.repository';
|
||||
import { GetActivityQuery } from './queries/get-activity.query';
|
||||
import {
|
||||
AttachmentDownload,
|
||||
GetAttachmentQuery,
|
||||
} from './queries/get-attachment.query';
|
||||
import { GetIssueQuery } from './queries/get-issue.query';
|
||||
import { GetIssuesByIdsQuery } from './queries/get-issues-by-ids.query';
|
||||
import { SearchIssuesQuery } from './queries/search-issues.query';
|
||||
@@ -126,6 +135,39 @@ export class IssuesService {
|
||||
);
|
||||
}
|
||||
|
||||
/** Attaches a file to the ticket, or to one of its comments. */
|
||||
attach(
|
||||
actorId: string,
|
||||
issueId: string,
|
||||
file: IncomingFile,
|
||||
commentId: string | null = null,
|
||||
): Promise<CommandResult> {
|
||||
return this.commandBus.execute(
|
||||
new AttachFileCommand(actorId, issueId, file, commentId),
|
||||
);
|
||||
}
|
||||
|
||||
detach(
|
||||
actorId: string,
|
||||
issueId: string,
|
||||
attachmentId: string,
|
||||
): Promise<CommandResult> {
|
||||
return this.commandBus.execute(
|
||||
new DetachFileCommand(actorId, issueId, attachmentId),
|
||||
);
|
||||
}
|
||||
|
||||
/** A ticket's file, with its bytes, for whoever can read the ticket. */
|
||||
download(
|
||||
viewerId: string | null,
|
||||
issueId: string,
|
||||
attachmentId: string,
|
||||
): Promise<AttachmentDownload> {
|
||||
return this.queryBus.execute(
|
||||
new GetAttachmentQuery(viewerId, issueId, attachmentId),
|
||||
);
|
||||
}
|
||||
|
||||
findOne(viewerId: string | null, idOrKey: string): Promise<IssueReadModel> {
|
||||
return this.queryBus.execute(new GetIssueQuery(viewerId, idOrKey));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { Readable } from 'node:stream';
|
||||
|
||||
/** Where the bytes of attached files live (the tickets only record them). */
|
||||
export abstract class AttachmentStorage {
|
||||
abstract put(key: string, content: Buffer): Promise<void>;
|
||||
/** Fails with NotFoundError when there is nothing at `key`. */
|
||||
abstract read(key: string): Promise<Readable>;
|
||||
/** Idempotent: removing what is not there is fine. */
|
||||
abstract remove(key: string): Promise<void>;
|
||||
/** Everything under `prefix` (a ticket's files, when it is deleted). */
|
||||
abstract removePrefix(prefix: string): Promise<void>;
|
||||
}
|
||||
|
||||
/** One folder per project and ticket, so a ticket's files go together. */
|
||||
export const attachmentKey = (
|
||||
projectId: string,
|
||||
issueId: string,
|
||||
attachmentId: string,
|
||||
): string => `${projectId}/${issueId}/${attachmentId}`;
|
||||
|
||||
export const issueAttachmentsPrefix = (
|
||||
projectId: string,
|
||||
issueId: string,
|
||||
): string => `${projectId}/${issueId}/`;
|
||||
@@ -17,3 +17,4 @@ export * from './release-issues.repository';
|
||||
export * from './upsert-materialized-timeline.repository';
|
||||
export * from './find-timeline.repository';
|
||||
export * from './tracker-streams.repository';
|
||||
export * from './attachment-storage';
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
AttachmentReadModel,
|
||||
IssueLinkReadModel,
|
||||
IssueReadModel,
|
||||
StatusCategory,
|
||||
@@ -8,7 +9,7 @@ export abstract class UpsertMaterializedIssueRepository {
|
||||
/** Applied only if `version` is newer than the stored one (idempotent). */
|
||||
abstract upsert(
|
||||
issue: Pick<IssueReadModel, 'id' | 'version'> &
|
||||
Partial<Omit<IssueReadModel, 'links' | 'commentCount'>>,
|
||||
Partial<Omit<IssueReadModel, 'links' | 'commentCount' | 'attachments'>>,
|
||||
): Promise<void>;
|
||||
/** Adds a relation to an issue (idempotent). */
|
||||
abstract addLink(issueId: string, link: IssueLinkReadModel): Promise<void>;
|
||||
@@ -16,6 +17,15 @@ export abstract class UpsertMaterializedIssueRepository {
|
||||
issueId: string,
|
||||
link: Omit<IssueLinkReadModel, 'issueKey'>,
|
||||
): Promise<void>;
|
||||
/** Adds a file to an issue (idempotent). */
|
||||
abstract addAttachment(
|
||||
issueId: string,
|
||||
attachment: AttachmentReadModel,
|
||||
): Promise<void>;
|
||||
abstract removeAttachment(
|
||||
issueId: string,
|
||||
attachmentId: string,
|
||||
): Promise<void>;
|
||||
abstract setCommentCount(
|
||||
issueId: string,
|
||||
commentCount: number,
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { IQueryHandler, QueryHandler } from '@nestjs/cqrs';
|
||||
import { NotFoundError } from '@task-stream/api/shared/domain';
|
||||
import { AttachmentStorage, attachmentKey } from '../ports/attachment-storage';
|
||||
import { FindIssuesRepository } from '../ports/find-issues.repository';
|
||||
import { AttachmentDownload, GetAttachmentQuery } from './get-attachment.query';
|
||||
import { ReadAccess } from './read-access';
|
||||
|
||||
@QueryHandler(GetAttachmentQuery)
|
||||
export class GetAttachmentQueryHandler
|
||||
implements IQueryHandler<GetAttachmentQuery, AttachmentDownload>
|
||||
{
|
||||
constructor(
|
||||
private readonly findIssues: FindIssuesRepository,
|
||||
private readonly storage: AttachmentStorage,
|
||||
private readonly access: ReadAccess,
|
||||
) {}
|
||||
|
||||
async execute(query: GetAttachmentQuery): Promise<AttachmentDownload> {
|
||||
const issue = this.access.assertFound(
|
||||
await this.findIssues.findById(query.issueId),
|
||||
'Attachment',
|
||||
query.attachmentId,
|
||||
);
|
||||
await this.access.assertCanView(issue.projectId, query.viewerId, {
|
||||
entity: 'Attachment',
|
||||
ref: query.attachmentId,
|
||||
});
|
||||
const attachment = (issue.attachments ?? []).find(
|
||||
(a) => a.id === query.attachmentId,
|
||||
);
|
||||
if (!attachment) throw new NotFoundError('Attachment', query.attachmentId);
|
||||
return {
|
||||
attachment,
|
||||
content: await this.storage.read(
|
||||
attachmentKey(issue.projectId, issue.id, attachment.id),
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Query } from '@nestjs/cqrs';
|
||||
import { AttachmentReadModel } from '@task-stream/api/tracker/domain';
|
||||
import type { Readable } from 'node:stream';
|
||||
|
||||
export interface AttachmentDownload {
|
||||
attachment: AttachmentReadModel;
|
||||
content: Readable;
|
||||
}
|
||||
|
||||
/** A ticket's file, for whoever can read the ticket. */
|
||||
export class GetAttachmentQuery extends Query<AttachmentDownload> {
|
||||
constructor(
|
||||
/** Null: anonymous (public projects only). */
|
||||
public readonly viewerId: string | null,
|
||||
public readonly issueId: string,
|
||||
public readonly attachmentId: string,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
@@ -16,3 +16,4 @@ export * from './get-upcoming-releases.query';
|
||||
export * from './search-issues.query';
|
||||
export * from './search-my-issues.query';
|
||||
export * from './get-public-projects.query';
|
||||
export * from './get-attachment.query';
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { GetAttachmentQueryHandler } from './get-attachment.query-handler';
|
||||
import { GetPublicProjectsQueryHandler } from './get-public-projects.query-handler';
|
||||
import { CanViewProjectQueryHandler } from './can-view-project.query-handler';
|
||||
import { GetActivityQueryHandler } from './get-activity.query-handler';
|
||||
@@ -36,4 +37,5 @@ export const QUERY_HANDLERS = [
|
||||
GetUpcomingReleasesQueryHandler,
|
||||
SearchIssuesQueryHandler,
|
||||
SearchMyIssuesQueryHandler,
|
||||
GetAttachmentQueryHandler,
|
||||
];
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
import { lastValueFrom, of, toArray } from 'rxjs';
|
||||
import {
|
||||
FakeUserDirectory,
|
||||
InMemoryAttachmentStorage,
|
||||
InMemoryEventStore,
|
||||
InMemoryEventStorePublisher,
|
||||
InMemoryIssueNumbers,
|
||||
@@ -51,12 +52,14 @@ import { ReleaseIssuesRepository } from '../ports/release-issues.repository';
|
||||
import { ReleaseNamesRepository } from '../ports/release-names.repository';
|
||||
import { TrackerStreamsRepository } from '../ports/tracker-streams.repository';
|
||||
import { UserDirectory } from '../ports/user-directory';
|
||||
import { AttachmentStorage } from '../ports/attachment-storage';
|
||||
import { ProjectDeletionSaga } from './project-deletion.saga';
|
||||
import { ReleaseArchivedSaga } from './release-archived.saga';
|
||||
import { UserDeactivatedSaga } from './user-deactivated.saga';
|
||||
|
||||
async function setup() {
|
||||
const store = new InMemoryEventStore();
|
||||
const files = new InMemoryAttachmentStorage();
|
||||
const users = new FakeUserDirectory().add('owner').add('dev').add('qa');
|
||||
// Read model double for the user saga: open tickets are tracked by the test.
|
||||
const openAssigned = new Map<string, string[]>();
|
||||
@@ -71,6 +74,7 @@ async function setup() {
|
||||
WriteAccess,
|
||||
AggregateRehydrator,
|
||||
{ provide: EventStore, useValue: store },
|
||||
{ provide: AttachmentStorage, useValue: files },
|
||||
{ provide: UserDirectory, useValue: users },
|
||||
{ provide: ProjectKeysRepository, useClass: InMemoryProjectKeys },
|
||||
{ provide: IssueNumbersRepository, useClass: InMemoryIssueNumbers },
|
||||
|
||||
@@ -7,6 +7,9 @@ import {
|
||||
SerializableEvent,
|
||||
VersionedAggregateRoot,
|
||||
} from '@task-stream/api/shared/domain';
|
||||
import { Readable } from 'node:stream';
|
||||
import { NotFoundError } from '@task-stream/api/shared/domain';
|
||||
import { AttachmentStorage } from '../lib/ports/attachment-storage';
|
||||
import { IssueNumbersRepository } from '../lib/ports/issue-numbers.repository';
|
||||
import { ProjectKeysRepository } from '../lib/ports/project-keys.repository';
|
||||
import { ReleaseIssuesRepository } from '../lib/ports/release-issues.repository';
|
||||
@@ -244,3 +247,28 @@ export class InMemoryTrackerStreams extends TrackerStreamsRepository {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Attachment storage double: files in a map, keyed like on disk. */
|
||||
export class InMemoryAttachmentStorage extends AttachmentStorage {
|
||||
readonly files = new Map<string, Buffer>();
|
||||
|
||||
async put(key: string, content: Buffer) {
|
||||
this.files.set(key, content);
|
||||
}
|
||||
|
||||
async read(key: string) {
|
||||
const content = this.files.get(key);
|
||||
if (!content) throw new NotFoundError('Attachment', key);
|
||||
return Readable.from(content);
|
||||
}
|
||||
|
||||
async remove(key: string) {
|
||||
this.files.delete(key);
|
||||
}
|
||||
|
||||
async removePrefix(prefix: string) {
|
||||
for (const key of [...this.files.keys()]) {
|
||||
if (key.startsWith(prefix)) this.files.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ export * from './lib/project/project';
|
||||
export * from './lib/project/project-role';
|
||||
export * from './lib/issue/issue';
|
||||
export * from './lib/issue/issue.enums';
|
||||
export * from './lib/issue/issue-attachment';
|
||||
export * from './lib/project/project-settings';
|
||||
export * from './lib/comment/comment';
|
||||
export * from './lib/release/release';
|
||||
|
||||
@@ -22,3 +22,5 @@ export * from './release-archived.event';
|
||||
export * from './project-deleted.event';
|
||||
export * from './issue-deleted.event';
|
||||
export * from './release-deleted.event';
|
||||
export * from './issue-attachment-added.event';
|
||||
export * from './issue-attachment-removed.event';
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { AutowiredEvent } from '@task-stream/api/shared/domain';
|
||||
import type { IssueAttachment } from '../issue/issue-attachment';
|
||||
import { TrackerEvent } from './tracker.event';
|
||||
|
||||
/** A file was attached to a ticket (or to one of its comments). */
|
||||
@AutowiredEvent
|
||||
export class IssueAttachmentAddedEvent extends TrackerEvent {
|
||||
constructor(
|
||||
actorId: string,
|
||||
issueId: string,
|
||||
projectId: string,
|
||||
readonly attachment: IssueAttachment,
|
||||
) {
|
||||
super(actorId, issueId, projectId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { AutowiredEvent } from '@task-stream/api/shared/domain';
|
||||
import { TrackerEvent } from './tracker.event';
|
||||
|
||||
/** A file was removed from a ticket. */
|
||||
@AutowiredEvent
|
||||
export class IssueAttachmentRemovedEvent extends TrackerEvent {
|
||||
constructor(
|
||||
actorId: string,
|
||||
issueId: string,
|
||||
projectId: string,
|
||||
readonly attachmentId: string,
|
||||
readonly fileName: string,
|
||||
) {
|
||||
super(actorId, issueId, projectId);
|
||||
}
|
||||
}
|
||||
35
libs/api/tracker/domain/src/lib/issue/issue-attachment.ts
Normal file
35
libs/api/tracker/domain/src/lib/issue/issue-attachment.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { assertThat } from '@task-stream/api/shared/domain';
|
||||
|
||||
/**
|
||||
* A file attached to a ticket — a screenshot, a log, a short video. The bytes
|
||||
* live in the attachment storage; the ticket only records that they exist.
|
||||
* `commentId` places it under one of the ticket's comments.
|
||||
*/
|
||||
export interface IssueAttachment {
|
||||
id: string;
|
||||
fileName: string;
|
||||
mimeType: string;
|
||||
/** Bytes. */
|
||||
size: number;
|
||||
uploadedBy: string;
|
||||
uploadedAt: string;
|
||||
commentId: string | null;
|
||||
}
|
||||
|
||||
/** A ticket keeps at most this many files. */
|
||||
export const MAX_ATTACHMENTS_PER_ISSUE = 50;
|
||||
|
||||
/** Trims the name and keeps only its last path segment. */
|
||||
export function normalizeAttachment(
|
||||
attachment: IssueAttachment,
|
||||
): IssueAttachment {
|
||||
const fileName =
|
||||
attachment.fileName.split(/[\\/]/).pop()?.trim().slice(0, 200) ?? '';
|
||||
assertThat(fileName.length > 0, 'An attachment needs a file name');
|
||||
assertThat(attachment.size > 0, 'An attachment cannot be empty');
|
||||
return {
|
||||
...attachment,
|
||||
fileName,
|
||||
mimeType: attachment.mimeType || 'application/octet-stream',
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
BusinessRuleError,
|
||||
ForbiddenError,
|
||||
ValidationError,
|
||||
} from '@task-stream/api/shared/domain';
|
||||
import { IssueCreatedEvent } from '../events/issue-created.event';
|
||||
@@ -154,4 +155,55 @@ describe('Issue', () => {
|
||||
});
|
||||
expect(rebuilt.getUncommittedEvents()).toHaveLength(0);
|
||||
});
|
||||
|
||||
describe('attachments', () => {
|
||||
const file = (id: string, uploadedBy = 'u-qa') => ({
|
||||
id,
|
||||
fileName: 'C:\\Users\\qa\\captura login.png',
|
||||
mimeType: 'image/png',
|
||||
size: 2048,
|
||||
uploadedBy,
|
||||
uploadedAt: '2026-10-01T10:00:00.000Z',
|
||||
commentId: null,
|
||||
});
|
||||
|
||||
it('records a file with its name cleaned up, once', () => {
|
||||
const issue = newIssue();
|
||||
issue.attach('u-qa', file('a-1'));
|
||||
issue.attach('u-qa', file('a-1'));
|
||||
|
||||
expect(issue.attachments).toHaveLength(1);
|
||||
expect(issue.attachments[0].fileName).toBe('captura login.png');
|
||||
});
|
||||
|
||||
it('lets the uploader or a manager remove it, nobody else', () => {
|
||||
const issue = newIssue();
|
||||
issue.attach('u-qa', file('a-1'));
|
||||
|
||||
expect(() => issue.detach('u-dev', 'a-1', false)).toThrow(ForbiddenError);
|
||||
issue.detach('u-dev', 'a-1', true);
|
||||
|
||||
expect(issue.attachments).toEqual([]);
|
||||
expect(() => issue.detach('u-qa', 'a-1', true)).toThrow(
|
||||
BusinessRuleError,
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects empty files', () => {
|
||||
expect(() =>
|
||||
newIssue().attach('u-qa', { ...file('a-1'), size: 0 }),
|
||||
).toThrow(ValidationError);
|
||||
});
|
||||
|
||||
it('survives a replay', () => {
|
||||
const issue = newIssue();
|
||||
issue.attach('u-qa', file('a-1'));
|
||||
issue.attach('u-qa', file('a-2'));
|
||||
issue.detach('u-qa', 'a-1', false);
|
||||
|
||||
const { rebuilt } = replay(issue, Issue);
|
||||
|
||||
expect(rebuilt.attachments.map((a) => a.id)).toEqual(['a-2']);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import {
|
||||
BusinessRuleError,
|
||||
ForbiddenError,
|
||||
VersionedAggregateRoot,
|
||||
assertThat,
|
||||
} from '@task-stream/api/shared/domain';
|
||||
import { IssueAssignedEvent } from '../events/issue-assigned.event';
|
||||
import { IssueAttachmentAddedEvent } from '../events/issue-attachment-added.event';
|
||||
import { IssueAttachmentRemovedEvent } from '../events/issue-attachment-removed.event';
|
||||
import { IssueCreatedEvent } from '../events/issue-created.event';
|
||||
import { IssueDeletedEvent } from '../events/issue-deleted.event';
|
||||
import { IssueLinkedEvent } from '../events/issue-linked.event';
|
||||
@@ -12,6 +15,11 @@ import { IssueStatusChangedEvent } from '../events/issue-status-changed.event';
|
||||
import { IssueUnlinkedEvent } from '../events/issue-unlinked.event';
|
||||
import { IssueUpdatedEvent } from '../events/issue-updated.event';
|
||||
import { ProjectWorkflow } from '../project/project-settings';
|
||||
import {
|
||||
IssueAttachment,
|
||||
MAX_ATTACHMENTS_PER_ISSUE,
|
||||
normalizeAttachment,
|
||||
} from './issue-attachment';
|
||||
import { IssueLinkType, IssuePriority } from './issue.enums';
|
||||
|
||||
export interface IssueLink {
|
||||
@@ -82,6 +90,7 @@ export class Issue extends VersionedAggregateRoot implements IssueProps {
|
||||
public storyPoints: number | null = null;
|
||||
public dueDate: string | null = null;
|
||||
public links: IssueLink[] = [];
|
||||
public attachments: IssueAttachment[] = [];
|
||||
public createdAt!: string;
|
||||
public updatedAt!: string;
|
||||
public deleted = false;
|
||||
@@ -216,6 +225,43 @@ export class Issue extends VersionedAggregateRoot implements IssueProps {
|
||||
);
|
||||
}
|
||||
|
||||
/** Records a file stored for this ticket (or one of its comments). */
|
||||
attach(actorId: string, attachment: IssueAttachment): void {
|
||||
const next = normalizeAttachment(attachment);
|
||||
if (this.attachments.some((a) => a.id === next.id)) return;
|
||||
if (this.attachments.length >= MAX_ATTACHMENTS_PER_ISSUE) {
|
||||
throw new BusinessRuleError(
|
||||
`${this.key} already has ${MAX_ATTACHMENTS_PER_ISSUE} attachments; remove one first`,
|
||||
);
|
||||
}
|
||||
this.apply(
|
||||
new IssueAttachmentAddedEvent(actorId, this.id, this.projectId, next),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a file. Whoever uploaded it may, and so may whoever manages the
|
||||
* project (`canManage`).
|
||||
*/
|
||||
detach(actorId: string, attachmentId: string, canManage: boolean): void {
|
||||
const attachment = this.attachments.find((a) => a.id === attachmentId);
|
||||
if (!attachment) throw new BusinessRuleError('Attachment not found');
|
||||
if (attachment.uploadedBy !== actorId && !canManage) {
|
||||
throw new ForbiddenError(
|
||||
'Only whoever uploaded a file, or a project admin, can remove it',
|
||||
);
|
||||
}
|
||||
this.apply(
|
||||
new IssueAttachmentRemovedEvent(
|
||||
actorId,
|
||||
this.id,
|
||||
this.projectId,
|
||||
attachment.id,
|
||||
attachment.fileName,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Deletes the ticket (its project was deleted). Idempotent. */
|
||||
delete(actorId: string): void {
|
||||
if (this.deleted) return;
|
||||
@@ -276,6 +322,18 @@ export class Issue extends VersionedAggregateRoot implements IssueProps {
|
||||
this.updatedAt = event.occurredAt;
|
||||
}
|
||||
|
||||
onIssueAttachmentAddedEvent(event: IssueAttachmentAddedEvent): void {
|
||||
this.attachments = [...this.attachments, { ...event.attachment }];
|
||||
this.updatedAt = event.occurredAt;
|
||||
}
|
||||
|
||||
onIssueAttachmentRemovedEvent(event: IssueAttachmentRemovedEvent): void {
|
||||
this.attachments = this.attachments.filter(
|
||||
(a) => a.id !== event.attachmentId,
|
||||
);
|
||||
this.updatedAt = event.occurredAt;
|
||||
}
|
||||
|
||||
onIssueDeletedEvent(): void {
|
||||
this.deleted = true;
|
||||
}
|
||||
|
||||
@@ -12,6 +12,17 @@ export class IssueLinkReadModel {
|
||||
issueKey!: string;
|
||||
}
|
||||
|
||||
export class AttachmentReadModel {
|
||||
id!: string;
|
||||
fileName!: string;
|
||||
mimeType!: string;
|
||||
size!: number;
|
||||
uploadedBy!: UserRefReadModel;
|
||||
uploadedAt!: string;
|
||||
/** Shown under this comment when set. */
|
||||
commentId!: string | null;
|
||||
}
|
||||
|
||||
export class IssueReadModel {
|
||||
id!: string;
|
||||
projectId!: string;
|
||||
@@ -35,6 +46,7 @@ export class IssueReadModel {
|
||||
storyPoints!: number | null;
|
||||
dueDate!: string | null;
|
||||
links!: IssueLinkReadModel[];
|
||||
attachments!: AttachmentReadModel[];
|
||||
commentCount!: number;
|
||||
createdAt!: string;
|
||||
updatedAt!: string;
|
||||
|
||||
@@ -69,6 +69,18 @@ export const IssueSchema = new Schema<IssueDoc>(
|
||||
release: { _id: false, id: String, name: String },
|
||||
outwardLinks: [link],
|
||||
inwardLinks: [link],
|
||||
attachments: [
|
||||
{
|
||||
_id: false,
|
||||
id: String,
|
||||
fileName: String,
|
||||
mimeType: String,
|
||||
size: Number,
|
||||
uploadedBy: userRef,
|
||||
uploadedAt: String,
|
||||
commentId: String,
|
||||
},
|
||||
],
|
||||
labels: [String],
|
||||
version: Number,
|
||||
},
|
||||
@@ -137,5 +149,7 @@ export function issueFromDoc(doc: IssueDoc): IssueReadModel {
|
||||
id: _id,
|
||||
...rest,
|
||||
links: [...(outwardLinks ?? []), ...(inwardLinks ?? [])],
|
||||
// Tickets projected before attachments existed have none.
|
||||
attachments: rest.attachments ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
} from '@task-stream/api/tracker/application';
|
||||
import {
|
||||
ActivityReadModel,
|
||||
AttachmentReadModel,
|
||||
CommentReadModel,
|
||||
IssueLinkReadModel,
|
||||
IssueReadModel,
|
||||
@@ -99,14 +100,29 @@ export class MongoUpsertMaterializedIssueRepository extends UpsertMaterializedIs
|
||||
version,
|
||||
...fields
|
||||
}: Pick<IssueReadModel, 'id' | 'version'> &
|
||||
Partial<Omit<IssueReadModel, 'links' | 'commentCount'>>) {
|
||||
Partial<Omit<IssueReadModel, 'links' | 'commentCount' | 'attachments'>>) {
|
||||
await upsertIfNewer(this.issues, id, version, fields, {
|
||||
outwardLinks: [],
|
||||
inwardLinks: [],
|
||||
attachments: [],
|
||||
commentCount: 0,
|
||||
});
|
||||
}
|
||||
|
||||
async addAttachment(issueId: string, attachment: AttachmentReadModel) {
|
||||
await this.issues.updateOne(
|
||||
{ _id: issueId, 'attachments.id': { $ne: attachment.id } },
|
||||
{ $push: { attachments: attachment } },
|
||||
);
|
||||
}
|
||||
|
||||
async removeAttachment(issueId: string, attachmentId: string) {
|
||||
await this.issues.updateOne(
|
||||
{ _id: issueId },
|
||||
{ $pull: { attachments: { id: attachmentId } } },
|
||||
);
|
||||
}
|
||||
|
||||
async addLink(issueId: string, link: IssueLinkReadModel) {
|
||||
const field = link.direction === 'OUTWARD' ? 'outwardLinks' : 'inwardLinks';
|
||||
await this.issues.updateOne(
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { createReadStream } from 'node:fs';
|
||||
import { mkdir, rm, stat, writeFile } from 'node:fs/promises';
|
||||
import { dirname, resolve, sep } from 'node:path';
|
||||
import type { Readable } from 'node:stream';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { NotFoundError } from '@task-stream/api/shared/domain';
|
||||
import { AttachmentStorage } from '@task-stream/api/tracker/application';
|
||||
|
||||
/**
|
||||
* Attached files on disk, under ATTACHMENTS_DIR (a volume in Docker). Keys
|
||||
* come from ids this API generated, but are still checked to stay inside the
|
||||
* folder: a key is never trusted to be a path.
|
||||
*/
|
||||
@Injectable()
|
||||
export class FileSystemAttachmentStorage extends AttachmentStorage {
|
||||
private readonly root: string;
|
||||
|
||||
constructor(config: ConfigService) {
|
||||
super();
|
||||
this.root = resolve(
|
||||
config.get<string>('ATTACHMENTS_DIR') || 'data/attachments',
|
||||
);
|
||||
}
|
||||
|
||||
async put(key: string, content: Buffer): Promise<void> {
|
||||
const path = this.pathOf(key);
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
await writeFile(path, content, { flag: 'wx' });
|
||||
}
|
||||
|
||||
async read(key: string): Promise<Readable> {
|
||||
const path = this.pathOf(key);
|
||||
try {
|
||||
await stat(path);
|
||||
} catch {
|
||||
throw new NotFoundError('Attachment', key.split('/').pop() ?? key);
|
||||
}
|
||||
return createReadStream(path);
|
||||
}
|
||||
|
||||
async remove(key: string): Promise<void> {
|
||||
await rm(this.pathOf(key), { force: true });
|
||||
}
|
||||
|
||||
async removePrefix(prefix: string): Promise<void> {
|
||||
await rm(this.pathOf(prefix), { recursive: true, force: true });
|
||||
}
|
||||
|
||||
private pathOf(key: string): string {
|
||||
const path = resolve(this.root, key);
|
||||
if (path !== this.root && !path.startsWith(this.root + sep)) {
|
||||
throw new Error(`Attachment key escapes the storage folder: ${key}`);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { CqrsModule } from '@nestjs/cqrs';
|
||||
import { MongooseModule } from '@nestjs/mongoose';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import {
|
||||
AttachmentStorage,
|
||||
ChangeFeed,
|
||||
FindActivityRepository,
|
||||
FindCommentsRepository,
|
||||
@@ -51,6 +52,7 @@ import {
|
||||
import { PostgresReleaseIssuesRepository } from './postgres/release-issues.repository';
|
||||
import { PostgresTrackerStreamsRepository } from './postgres/tracker-streams.repository';
|
||||
import { RedisChangeFeed } from './realtime/redis-change-feed';
|
||||
import { FileSystemAttachmentStorage } from './storage/file-system-attachment.storage';
|
||||
|
||||
const PORTS = [
|
||||
// Write side lookups → PostgreSQL (aggregates themselves live in the event store)
|
||||
@@ -96,6 +98,8 @@ const PORTS = [
|
||||
provide: UpsertMaterializedTimelineRepository,
|
||||
useClass: MongoUpsertMaterializedTimelineRepository,
|
||||
},
|
||||
// Attached files → disk (ATTACHMENTS_DIR)
|
||||
{ provide: AttachmentStorage, useClass: FileSystemAttachmentStorage },
|
||||
// Realtime → Redis pub/sub
|
||||
{ provide: ChangeFeed, useClass: RedisChangeFeed },
|
||||
// Identity context (anti-corruption layer)
|
||||
|
||||
@@ -183,6 +183,18 @@ export class IssueResolver {
|
||||
);
|
||||
}
|
||||
|
||||
@Mutation(() => CommandResultGql, {
|
||||
description:
|
||||
'Remove a file from a ticket (whoever uploaded it, or an owner/admin). Upload with the REST API.',
|
||||
})
|
||||
removeAttachment(
|
||||
@CurrentUser() me: User,
|
||||
@Args('issueId', { type: () => ID }) issueId: string,
|
||||
@Args('attachmentId', { type: () => ID }) attachmentId: string,
|
||||
) {
|
||||
return this.issuesService.detach(me.id, issueId, attachmentId);
|
||||
}
|
||||
|
||||
@Mutation(() => CommandResultGql, {
|
||||
description: 'Assign (or unassign with null) a project member',
|
||||
})
|
||||
|
||||
@@ -91,6 +91,24 @@ export class IssueLinkGql {
|
||||
@Field() issueKey!: string;
|
||||
}
|
||||
|
||||
@ObjectType('Attachment', {
|
||||
description:
|
||||
'A file on a ticket. Download it from the REST API: GET /api/issues/{issueId}/attachments/{id}',
|
||||
})
|
||||
export class AttachmentGql {
|
||||
@Field(() => ID) id!: string;
|
||||
@Field() fileName!: string;
|
||||
@Field() mimeType!: string;
|
||||
@Field(() => Int, { description: 'Bytes' }) size!: number;
|
||||
@Field(() => UserRefGql) uploadedBy!: UserRefGql;
|
||||
@Field() uploadedAt!: string;
|
||||
@Field(() => ID, {
|
||||
nullable: true,
|
||||
description: 'The comment it was attached to, if any',
|
||||
})
|
||||
commentId!: string | null;
|
||||
}
|
||||
|
||||
@ObjectType('ReleaseRef')
|
||||
export class ReleaseRefGql {
|
||||
@Field(() => ID) id!: string;
|
||||
@@ -123,6 +141,7 @@ export class IssueGql {
|
||||
@Field(() => Int, { nullable: true }) storyPoints!: number | null;
|
||||
@Field(() => String, { nullable: true }) dueDate!: string | null;
|
||||
@Field(() => [IssueLinkGql]) links!: IssueLinkGql[];
|
||||
@Field(() => [AttachmentGql]) attachments!: AttachmentGql[];
|
||||
@Field(() => Int) commentCount!: number;
|
||||
@Field() createdAt!: string;
|
||||
@Field() updatedAt!: string;
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Res,
|
||||
StreamableFile,
|
||||
UploadedFile,
|
||||
UseInterceptors,
|
||||
} from '@nestjs/common';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import {
|
||||
ApiBody,
|
||||
ApiConsumes,
|
||||
ApiCreatedResponse,
|
||||
ApiOkResponse,
|
||||
ApiOperation,
|
||||
ApiParam,
|
||||
ApiProduces,
|
||||
ApiTags,
|
||||
} from '@nestjs/swagger';
|
||||
import { User } from '@task-stream/api/identity/domain';
|
||||
import {
|
||||
ApiOptionalPireonAuth,
|
||||
ApiPireonAuth,
|
||||
CurrentUser,
|
||||
} from '@task-stream/api/identity/presenters';
|
||||
import {
|
||||
ApiCommandErrors,
|
||||
ApiReadErrors,
|
||||
} from '@task-stream/api/shared/presenters';
|
||||
import { ValidationError } from '@task-stream/api/shared/domain';
|
||||
import { IssuesService } from '@task-stream/api/tracker/application';
|
||||
import type { Response } from 'express';
|
||||
import { viewerOf } from '../common/viewer';
|
||||
import { AttachFileDto } from './dto/requests.dto';
|
||||
import { CommandResultDto } from './dto/responses.dto';
|
||||
import { Refs } from './refs';
|
||||
|
||||
const ISSUE = ApiParam({
|
||||
name: 'issue',
|
||||
description: 'Ticket id or key',
|
||||
example: 'WEB-12',
|
||||
});
|
||||
|
||||
/** What multer hands over for one uploaded field. */
|
||||
interface UploadedPart {
|
||||
originalname: string;
|
||||
mimetype: string;
|
||||
buffer: Buffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Types a browser may show in place. Anything else — HTML, SVG, scripts — is
|
||||
* always downloaded: a file someone uploaded must never run in this origin.
|
||||
*/
|
||||
const SHOWN_INLINE =
|
||||
/^(image\/(png|jpe?g|gif|webp|avif)|video\/(mp4|webm)|audio\/(mpeg|ogg|wav)|application\/pdf|text\/plain)$/;
|
||||
|
||||
/** REST adapter for a ticket's files: uploaded here, listed on the ticket. */
|
||||
@ApiTags('Issues')
|
||||
@ApiPireonAuth()
|
||||
@Controller('issues/:issue/attachments')
|
||||
export class AttachmentsController {
|
||||
constructor(
|
||||
private readonly issues: IssuesService,
|
||||
private readonly refs: Refs,
|
||||
) {}
|
||||
|
||||
@Post()
|
||||
@ISSUE
|
||||
@UseInterceptors(FileInterceptor('file'))
|
||||
@ApiConsumes('multipart/form-data')
|
||||
@ApiBody({ type: AttachFileDto })
|
||||
@ApiOperation({
|
||||
summary: 'Attach a file to a ticket (members)',
|
||||
description:
|
||||
'Multipart with the file as `file` and, optionally, `commentId` to place it under a comment. ' +
|
||||
'Up to ATTACHMENTS_MAX_MB megabytes (25 by default) and 50 files per ticket.',
|
||||
})
|
||||
@ApiCreatedResponse({ type: CommandResultDto })
|
||||
@ApiCommandErrors()
|
||||
async attach(
|
||||
@CurrentUser() me: User,
|
||||
@Param('issue') issue: string,
|
||||
@UploadedFile() file: UploadedPart | undefined,
|
||||
@Body() body: AttachFileDto,
|
||||
) {
|
||||
if (!file) throw new ValidationError('Send the file as `file`');
|
||||
return this.issues.attach(
|
||||
me.id,
|
||||
await this.refs.issueId(me.id, issue),
|
||||
{
|
||||
fileName: Buffer.from(file.originalname, 'latin1').toString('utf8'),
|
||||
mimeType: file.mimetype,
|
||||
content: file.buffer,
|
||||
},
|
||||
body.commentId || null,
|
||||
);
|
||||
}
|
||||
|
||||
@Get(':attachmentId')
|
||||
@ApiOptionalPireonAuth()
|
||||
@ISSUE
|
||||
@ApiOperation({ summary: "Download one of a ticket's files" })
|
||||
@ApiProduces('application/octet-stream')
|
||||
@ApiOkResponse({ description: 'The file' })
|
||||
@ApiReadErrors()
|
||||
async download(
|
||||
@CurrentUser() me: User | undefined,
|
||||
@Param('issue') issue: string,
|
||||
@Param('attachmentId') attachmentId: string,
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
): Promise<StreamableFile> {
|
||||
const viewer = viewerOf(me);
|
||||
const { attachment, content } = await this.issues.download(
|
||||
viewer,
|
||||
await this.refs.issueId(viewer, issue),
|
||||
attachmentId,
|
||||
);
|
||||
const inline = SHOWN_INLINE.test(attachment.mimeType);
|
||||
res.set({
|
||||
'Content-Type': inline ? attachment.mimeType : 'application/octet-stream',
|
||||
'Content-Length': String(attachment.size),
|
||||
'Content-Disposition': `${inline ? 'inline' : 'attachment'}; filename="${asciiName(attachment.fileName)}"; filename*=UTF-8''${encodeURIComponent(attachment.fileName)}`,
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'Content-Security-Policy': "default-src 'none'; sandbox",
|
||||
'Cache-Control': 'private, max-age=3600',
|
||||
});
|
||||
return new StreamableFile(content);
|
||||
}
|
||||
|
||||
@Delete(':attachmentId')
|
||||
@ISSUE
|
||||
@ApiOperation({
|
||||
summary: 'Remove a file (whoever uploaded it, or an owner/admin)',
|
||||
})
|
||||
@ApiOkResponse({ type: CommandResultDto })
|
||||
@ApiCommandErrors()
|
||||
async remove(
|
||||
@CurrentUser() me: User,
|
||||
@Param('issue') issue: string,
|
||||
@Param('attachmentId') attachmentId: string,
|
||||
) {
|
||||
return this.issues.detach(
|
||||
me.id,
|
||||
await this.refs.issueId(me.id, issue),
|
||||
attachmentId,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** The name with anything outside printable ASCII replaced, for old clients. */
|
||||
function asciiName(name: string): string {
|
||||
return name.replace(/[^\x20-\x7e]|["\\]/g, '_');
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
IsInt,
|
||||
IsISO8601,
|
||||
IsOptional,
|
||||
IsUUID,
|
||||
IsString,
|
||||
IsUrl,
|
||||
Matches,
|
||||
@@ -576,6 +577,20 @@ export class LinkTypeParamDto {
|
||||
type!: IssueLinkType;
|
||||
}
|
||||
|
||||
/** Multipart body of an upload; the file itself travels as `file`. */
|
||||
export class AttachFileDto {
|
||||
@ApiProperty({ type: 'string', format: 'binary', description: 'The file' })
|
||||
file?: unknown;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
format: 'uuid',
|
||||
description: "One of the ticket's comments, to show the file under it",
|
||||
})
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
commentId?: string;
|
||||
}
|
||||
|
||||
export class CommentBodyDto {
|
||||
@ApiProperty({ example: 'Reproducido en Safari 17.', maxLength: 20000 })
|
||||
@IsString()
|
||||
|
||||
@@ -106,6 +106,22 @@ export class ReleaseRefDto {
|
||||
@ApiProperty({ example: 'v1.4.0' }) name!: string;
|
||||
}
|
||||
|
||||
export class AttachmentDto {
|
||||
@ApiProperty({ format: 'uuid' }) id!: string;
|
||||
@ApiProperty({ example: 'captura-login.png' }) fileName!: string;
|
||||
@ApiProperty({ example: 'image/png' }) mimeType!: string;
|
||||
@ApiProperty({ description: 'Bytes', example: 48213 }) size!: number;
|
||||
@ApiProperty({ type: UserRefDto }) uploadedBy!: UserRefDto;
|
||||
@ApiProperty({ format: 'date-time' }) uploadedAt!: string;
|
||||
@ApiProperty({
|
||||
type: String,
|
||||
nullable: true,
|
||||
format: 'uuid',
|
||||
description: 'The comment it was attached to, if any',
|
||||
})
|
||||
commentId!: string | null;
|
||||
}
|
||||
|
||||
export class IssueDto {
|
||||
@ApiProperty({ format: 'uuid' }) id!: string;
|
||||
@ApiProperty({ format: 'uuid' }) projectId!: string;
|
||||
@@ -141,6 +157,7 @@ export class IssueDto {
|
||||
@ApiProperty({ type: String, nullable: true, format: 'date' })
|
||||
dueDate!: string | null;
|
||||
@ApiProperty({ type: [IssueLinkDto] }) links!: IssueLinkDto[];
|
||||
@ApiProperty({ type: [AttachmentDto] }) attachments!: AttachmentDto[];
|
||||
@ApiProperty() commentCount!: number;
|
||||
@ApiProperty({ format: 'date-time' }) createdAt!: string;
|
||||
@ApiProperty({ format: 'date-time' }) updatedAt!: string;
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { DynamicModule, Module, Type } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { MulterModule } from '@nestjs/platform-express';
|
||||
import './graphql/enums';
|
||||
import { CommentResolver } from './graphql/comment.resolver';
|
||||
import { IssueResolver } from './graphql/issue.resolver';
|
||||
import { ProjectResolver } from './graphql/project.resolver';
|
||||
import { ReleaseResolver } from './graphql/release.resolver';
|
||||
import { SubscriptionResolver } from './graphql/subscription.resolver';
|
||||
import { AttachmentsController } from './http/attachments.controller';
|
||||
import { CommentsController } from './http/comments.controller';
|
||||
import { IssuesController } from './http/issues.controller';
|
||||
import { ExploreController } from './http/explore.controller';
|
||||
@@ -18,9 +21,24 @@ import { ReleasesController } from './http/releases.controller';
|
||||
* application services.
|
||||
*/
|
||||
@Module({
|
||||
imports: [
|
||||
// Uploads stay in memory until the command stores them; the size limit
|
||||
// is enforced here, before a byte reaches the application.
|
||||
MulterModule.registerAsync({
|
||||
inject: [ConfigService],
|
||||
useFactory: (config: ConfigService) => ({
|
||||
limits: {
|
||||
fileSize:
|
||||
(config.get<number>('ATTACHMENTS_MAX_MB') ?? 25) * 1024 * 1024,
|
||||
files: 1,
|
||||
},
|
||||
}),
|
||||
}),
|
||||
],
|
||||
controllers: [
|
||||
ProjectsController,
|
||||
IssuesController,
|
||||
AttachmentsController,
|
||||
CommentsController,
|
||||
ReleasesController,
|
||||
ExploreController,
|
||||
@@ -38,6 +56,9 @@ export class TrackerPresentersModule {
|
||||
static withApplication(
|
||||
applicationModule: Type | DynamicModule,
|
||||
): DynamicModule {
|
||||
return { module: TrackerPresentersModule, imports: [applicationModule] };
|
||||
return {
|
||||
module: TrackerPresentersModule,
|
||||
imports: [applicationModule],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user