first commit
This commit is contained in:
22
libs/api/tracker/infrastructure/README.md
Normal file
22
libs/api/tracker/infrastructure/README.md
Normal file
@@ -0,0 +1,22 @@
|
||||
# api-tracker-infrastructure
|
||||
|
||||
Adaptadores de salida del tracker.
|
||||
|
||||
- **Import**: `@task-stream/api/tracker/infrastructure`
|
||||
- **Capa**: `infrastructure` · **Tags**: `scope:api-tracker`, `type:infrastructure`
|
||||
|
||||
## Contenido
|
||||
|
||||
- `postgres/`: lookups de escritura (`project_keys`, `issue_sequences`, `release_names`) y `ReleaseIssuesRepository` (consulta el event store).
|
||||
- `mongo/`: esquemas del read model, repositorios `Find*` y `UpsertMaterialized*` (upsert idempotente por versión).
|
||||
- `realtime/`: `RedisChangeFeed` (canales de Redis pub/sub por proyecto, ticket y usuario).
|
||||
- `identity/`: `IdentityUserDirectory`, capa anticorrupción hacia el contexto de identidad.
|
||||
|
||||
## Comandos
|
||||
|
||||
```sh
|
||||
npx nx lint api-tracker-infrastructure
|
||||
npx nx test api-tracker-infrastructure # Jest
|
||||
```
|
||||
|
||||
Reglas de dependencia entre capas: [Arquitectura](../../../../docs/02-arquitectura.md#21-capas-hexagonales).
|
||||
3
libs/api/tracker/infrastructure/eslint.config.mjs
Normal file
3
libs/api/tracker/infrastructure/eslint.config.mjs
Normal file
@@ -0,0 +1,3 @@
|
||||
import baseConfig from '../../../../eslint.config.mjs';
|
||||
|
||||
export default [...baseConfig];
|
||||
11
libs/api/tracker/infrastructure/jest.config.cts
Normal file
11
libs/api/tracker/infrastructure/jest.config.cts
Normal file
@@ -0,0 +1,11 @@
|
||||
module.exports = {
|
||||
displayName: 'api-tracker-infrastructure',
|
||||
preset: '../../../../jest.preset.js',
|
||||
testEnvironment: 'node',
|
||||
passWithNoTests: true,
|
||||
transform: {
|
||||
'^.+\\.[tj]s$': ['ts-jest', { tsconfig: '<rootDir>/tsconfig.spec.json' }],
|
||||
},
|
||||
moduleFileExtensions: ['ts', 'js', 'html'],
|
||||
coverageDirectory: '../../../../coverage/libs/api/tracker/infrastructure',
|
||||
};
|
||||
12
libs/api/tracker/infrastructure/project.json
Normal file
12
libs/api/tracker/infrastructure/project.json
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "api-tracker-infrastructure",
|
||||
"$schema": "../../../../node_modules/nx/schemas/project-schema.json",
|
||||
"sourceRoot": "libs/api/tracker/infrastructure/src",
|
||||
"projectType": "library",
|
||||
"tags": [
|
||||
"scope:api-tracker",
|
||||
"type:infrastructure"
|
||||
],
|
||||
"// targets": "to see all targets run: nx show project api-tracker-infrastructure --web",
|
||||
"targets": {}
|
||||
}
|
||||
1
libs/api/tracker/infrastructure/src/index.ts
Normal file
1
libs/api/tracker/infrastructure/src/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from './lib/tracker-infrastructure.module';
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { QueryBus } from '@nestjs/cqrs';
|
||||
import {
|
||||
FindUserQuery,
|
||||
FindUsersByIdsQuery,
|
||||
} from '@task-stream/api/identity/application';
|
||||
import {
|
||||
DirectoryUser,
|
||||
UserDirectory,
|
||||
UserRefs,
|
||||
} from '@task-stream/api/tracker/application';
|
||||
|
||||
/** Anti-corruption layer: the tracker asks the identity context about users. */
|
||||
@Injectable()
|
||||
export class IdentityUserDirectory extends UserDirectory {
|
||||
constructor(private readonly queryBus: QueryBus) {
|
||||
super();
|
||||
}
|
||||
|
||||
async findById(
|
||||
userId: string,
|
||||
accessToken?: string,
|
||||
): Promise<DirectoryUser | null> {
|
||||
const user = await this.queryBus.execute(
|
||||
new FindUserQuery(userId, accessToken),
|
||||
);
|
||||
return user
|
||||
? { id: user.id, name: user.name, isActive: user.isActive }
|
||||
: null;
|
||||
}
|
||||
|
||||
async refs(userIds: (string | null | undefined)[]): Promise<UserRefs> {
|
||||
const wanted = [...new Set(userIds.filter((id): id is string => !!id))];
|
||||
const users = wanted.length
|
||||
? await this.queryBus.execute(new FindUsersByIdsQuery(wanted))
|
||||
: [];
|
||||
const names = new Map(users.map((u) => [u.id, u.name]));
|
||||
const of = (id: string) => ({ id, name: names.get(id) ?? id });
|
||||
return { of, ofNullable: (id) => (id ? of(id) : null) };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectModel } from '@nestjs/mongoose';
|
||||
import {
|
||||
FindActivityRepository,
|
||||
FindCommentsRepository,
|
||||
FindIssuesRepository,
|
||||
FindProjectsRepository,
|
||||
FindReleasesRepository,
|
||||
IssueFilter,
|
||||
Page,
|
||||
} from '@task-stream/api/tracker/application';
|
||||
import {
|
||||
ActivityReadModel,
|
||||
CommentReadModel,
|
||||
CountBy,
|
||||
FINISHED_STATUSES,
|
||||
IssueReadModel,
|
||||
IssueStatus,
|
||||
ProjectReadModel,
|
||||
ProjectRole,
|
||||
ProjectStatsReadModel,
|
||||
ReleaseProgressReadModel,
|
||||
ReleaseReadModel,
|
||||
UserRefReadModel,
|
||||
} from '@task-stream/api/tracker/domain';
|
||||
import { FilterQuery, Model } from 'mongoose';
|
||||
import {
|
||||
ActivityDoc,
|
||||
CommentDoc,
|
||||
IssueDoc,
|
||||
ProjectDoc,
|
||||
ReadModels,
|
||||
ReleaseDoc,
|
||||
fromDoc,
|
||||
issueFromDoc,
|
||||
} from './read-model.schemas';
|
||||
|
||||
/* Query-side adapters (MongoDB). */
|
||||
|
||||
const escapeRegex = (text: string) =>
|
||||
text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
|
||||
function toProject(doc: ProjectDoc): ProjectReadModel {
|
||||
const { memberIds: _ignored, ...rest } = doc;
|
||||
return fromDoc(rest);
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class MongoFindProjectsRepository extends FindProjectsRepository {
|
||||
constructor(
|
||||
@InjectModel(ReadModels.Project)
|
||||
private readonly projects: Model<ProjectDoc>,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async findById(id: string): Promise<ProjectReadModel | null> {
|
||||
const doc = await this.projects.findById(id).lean<ProjectDoc>();
|
||||
return doc ? toProject(doc) : null;
|
||||
}
|
||||
|
||||
async findByKey(key: string): Promise<ProjectReadModel | null> {
|
||||
const doc = await this.projects.findOne({ key }).lean<ProjectDoc>();
|
||||
return doc ? toProject(doc) : null;
|
||||
}
|
||||
|
||||
async findByMember(userId: string): Promise<ProjectReadModel[]> {
|
||||
const docs = await this.projects
|
||||
.find({ memberIds: userId })
|
||||
.sort({ name: 1 })
|
||||
.lean<ProjectDoc[]>();
|
||||
return docs.map(toProject);
|
||||
}
|
||||
|
||||
async findRole(
|
||||
projectId: string,
|
||||
userId: string,
|
||||
): Promise<ProjectRole | null> {
|
||||
const doc = await this.projects
|
||||
.findOne({ _id: projectId, memberIds: userId }, { members: 1 })
|
||||
.lean<Pick<ProjectDoc, 'members'>>();
|
||||
return doc?.members.find((m) => m.user.id === userId)?.role ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class MongoFindIssuesRepository extends FindIssuesRepository {
|
||||
constructor(
|
||||
@InjectModel(ReadModels.Issue) private readonly issues: Model<IssueDoc>,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async findById(id: string): Promise<IssueReadModel | null> {
|
||||
const doc = await this.issues.findById(id).lean<IssueDoc>();
|
||||
return doc ? issueFromDoc(doc) : null;
|
||||
}
|
||||
|
||||
async findByKey(key: string): Promise<IssueReadModel | null> {
|
||||
const doc = await this.issues.findOne({ key }).lean<IssueDoc>();
|
||||
return doc ? issueFromDoc(doc) : null;
|
||||
}
|
||||
|
||||
async findByIds(ids: string[]): Promise<IssueReadModel[]> {
|
||||
if (ids.length === 0) return [];
|
||||
const docs = await this.issues
|
||||
.find({ _id: { $in: ids } })
|
||||
.lean<IssueDoc[]>();
|
||||
return docs.map(issueFromDoc);
|
||||
}
|
||||
|
||||
async search(filter: IssueFilter): Promise<Page<IssueReadModel>> {
|
||||
const query = toMongoFilter(filter);
|
||||
const [docs, total] = await Promise.all([
|
||||
this.issues
|
||||
.find(query)
|
||||
.sort({ updatedAt: -1 })
|
||||
.skip(filter.offset)
|
||||
.limit(filter.limit)
|
||||
.lean<IssueDoc[]>(),
|
||||
this.issues.countDocuments(query),
|
||||
]);
|
||||
return { items: docs.map(issueFromDoc), total };
|
||||
}
|
||||
|
||||
async stats(projectId: string): Promise<ProjectStatsReadModel> {
|
||||
const countBy = (field: string) => [
|
||||
{ $group: { _id: `$${field}`, count: { $sum: 1 } } },
|
||||
{ $sort: { count: -1 as const } },
|
||||
];
|
||||
const [facets] = await this.issues.aggregate<{
|
||||
total: { count: number }[];
|
||||
open: { count: number }[];
|
||||
byStatus: { _id: IssueStatus; count: number }[];
|
||||
byType: { _id: string; count: number }[];
|
||||
byPriority: { _id: string; count: number }[];
|
||||
byArea: { _id: string | null; count: number }[];
|
||||
byAssignee: { _id: UserRefReadModel | null; count: number }[];
|
||||
}>([
|
||||
{ $match: { projectId } },
|
||||
{
|
||||
$facet: {
|
||||
total: [{ $count: 'count' }],
|
||||
open: [
|
||||
{ $match: { status: { $nin: FINISHED_STATUSES } } },
|
||||
{ $count: 'count' },
|
||||
],
|
||||
byStatus: countBy('status'),
|
||||
byType: countBy('type'),
|
||||
byPriority: countBy('priority'),
|
||||
byArea: countBy('area'),
|
||||
byAssignee: [
|
||||
{ $match: { status: { $nin: FINISHED_STATUSES } } },
|
||||
...countBy('assignee'),
|
||||
],
|
||||
},
|
||||
},
|
||||
]);
|
||||
const keyed = <T>(rows: { _id: unknown; count: number }[]): CountBy<T>[] =>
|
||||
rows.map((r) => ({ key: (r._id ?? 'NONE') as T, count: r.count }));
|
||||
|
||||
return {
|
||||
total: facets.total[0]?.count ?? 0,
|
||||
open: facets.open[0]?.count ?? 0,
|
||||
byStatus: keyed(facets.byStatus),
|
||||
byType: keyed(facets.byType),
|
||||
byPriority: keyed(facets.byPriority),
|
||||
byArea: keyed(facets.byArea),
|
||||
byAssignee: facets.byAssignee.map((r) => ({
|
||||
user: r._id?.id ? r._id : null,
|
||||
count: r.count,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
async releaseProgress(releaseId: string): Promise<ReleaseProgressReadModel> {
|
||||
const rows = await this.issues.aggregate<{
|
||||
_id: IssueStatus;
|
||||
count: number;
|
||||
}>([
|
||||
{ $match: { 'release.id': releaseId } },
|
||||
{ $group: { _id: '$status', count: { $sum: 1 } } },
|
||||
]);
|
||||
const total = rows.reduce((sum, r) => sum + r.count, 0);
|
||||
const finished = rows
|
||||
.filter((r) => FINISHED_STATUSES.includes(r._id))
|
||||
.reduce((sum, r) => sum + r.count, 0);
|
||||
return {
|
||||
total,
|
||||
finished,
|
||||
percent: total === 0 ? 0 : Math.round((finished / total) * 100),
|
||||
byStatus: rows.map((r) => ({ key: r._id, count: r.count })),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function toMongoFilter(filter: IssueFilter): FilterQuery<IssueDoc> {
|
||||
const query: FilterQuery<IssueDoc> = { projectId: filter.projectId };
|
||||
if (filter.statuses?.length) query.status = { $in: filter.statuses };
|
||||
if (filter.types?.length) query['type'] = { $in: filter.types };
|
||||
if (filter.areas?.length) query['area'] = { $in: filter.areas };
|
||||
if (filter.priorities?.length) query['priority'] = { $in: filter.priorities };
|
||||
if (filter.labels?.length)
|
||||
query.labels = { $all: filter.labels.map((l) => l.toLowerCase()) };
|
||||
if (filter.releaseId) query['release.id'] = filter.releaseId;
|
||||
if (filter.unassigned) query['assignee'] = null;
|
||||
else if (filter.assigneeId) query['assignee.id'] = filter.assigneeId;
|
||||
if (filter.search?.trim()) {
|
||||
const pattern = new RegExp(escapeRegex(filter.search.trim()), 'i');
|
||||
query.$or = [
|
||||
{ title: pattern },
|
||||
{ key: pattern },
|
||||
{ description: pattern },
|
||||
];
|
||||
}
|
||||
return query;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class MongoFindCommentsRepository extends FindCommentsRepository {
|
||||
constructor(
|
||||
@InjectModel(ReadModels.Comment)
|
||||
private readonly comments: Model<CommentDoc>,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async findById(id: string): Promise<CommentReadModel | null> {
|
||||
const doc = await this.comments.findById(id).lean<CommentDoc>();
|
||||
return doc ? fromDoc(doc) : null;
|
||||
}
|
||||
|
||||
async findByIssue(
|
||||
issueId: string,
|
||||
limit: number,
|
||||
offset: number,
|
||||
): Promise<Page<CommentReadModel>> {
|
||||
const [docs, total] = await Promise.all([
|
||||
this.comments
|
||||
.find({ issueId })
|
||||
.sort({ createdAt: 1 })
|
||||
.skip(offset)
|
||||
.limit(limit)
|
||||
.lean<CommentDoc[]>(),
|
||||
this.comments.countDocuments({ issueId }),
|
||||
]);
|
||||
return { items: docs.map(fromDoc), total };
|
||||
}
|
||||
|
||||
countByIssue(issueId: string): Promise<number> {
|
||||
return this.comments.countDocuments({ issueId });
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class MongoFindReleasesRepository extends FindReleasesRepository {
|
||||
constructor(
|
||||
@InjectModel(ReadModels.Release)
|
||||
private readonly releases: Model<ReleaseDoc>,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async findById(id: string): Promise<ReleaseReadModel | null> {
|
||||
const doc = await this.releases.findById(id).lean<ReleaseDoc>();
|
||||
return doc ? fromDoc(doc) : null;
|
||||
}
|
||||
|
||||
async findByProject(projectId: string): Promise<ReleaseReadModel[]> {
|
||||
const docs = await this.releases
|
||||
.find({ projectId })
|
||||
.sort({ createdAt: -1 })
|
||||
.lean<ReleaseDoc[]>();
|
||||
return docs.map(fromDoc);
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class MongoFindActivityRepository extends FindActivityRepository {
|
||||
constructor(
|
||||
@InjectModel(ReadModels.Activity)
|
||||
private readonly activity: Model<ActivityDoc>,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async find(params: {
|
||||
projectId: string;
|
||||
issueId?: string;
|
||||
limit: number;
|
||||
before?: string;
|
||||
}): Promise<ActivityReadModel[]> {
|
||||
const query: FilterQuery<ActivityDoc> = { projectId: params.projectId };
|
||||
if (params.issueId) query.issueId = params.issueId;
|
||||
if (params.before) query.occurredAt = { $lt: params.before };
|
||||
const docs = await this.activity
|
||||
.find(query)
|
||||
.sort({ occurredAt: -1 })
|
||||
.limit(params.limit)
|
||||
.lean<ActivityDoc[]>();
|
||||
return docs.map(fromDoc);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import {
|
||||
ActivityReadModel,
|
||||
CommentReadModel,
|
||||
IssueLinkReadModel,
|
||||
IssueReadModel,
|
||||
ProjectReadModel,
|
||||
ReleaseReadModel,
|
||||
} from '@task-stream/api/tracker/domain';
|
||||
import { Schema } from 'mongoose';
|
||||
|
||||
/* Read model (MongoDB): denormalised documents shaped for the GraphQL queries. */
|
||||
|
||||
type Doc<T extends { id: string }> = Omit<T, 'id'> & { _id: string };
|
||||
|
||||
export type ProjectDoc = Doc<ProjectReadModel> & { memberIds: string[] };
|
||||
/** Links are split: outward ones come from the issue itself, inward ones from other issues' events. */
|
||||
export type IssueDoc = Doc<Omit<IssueReadModel, 'links'>> & {
|
||||
outwardLinks: IssueLinkReadModel[];
|
||||
inwardLinks: IssueLinkReadModel[];
|
||||
};
|
||||
export type CommentDoc = Doc<CommentReadModel>;
|
||||
export type ReleaseDoc = Doc<ReleaseReadModel>;
|
||||
export type ActivityDoc = Doc<ActivityReadModel>;
|
||||
|
||||
export const ReadModels = {
|
||||
Project: 'ProjectReadModel',
|
||||
Issue: 'IssueReadModel',
|
||||
Comment: 'CommentReadModel',
|
||||
Release: 'ReleaseReadModel',
|
||||
Activity: 'ActivityReadModel',
|
||||
} as const;
|
||||
|
||||
const userRef = { _id: false, id: String, name: String };
|
||||
// `type` must be wrapped: a bare `type` key would declare the whole subdocument a String.
|
||||
const link = {
|
||||
_id: false,
|
||||
type: { type: String },
|
||||
direction: String,
|
||||
issueId: String,
|
||||
issueKey: String,
|
||||
};
|
||||
const loose = { strict: false, versionKey: false, _id: false } as const;
|
||||
|
||||
export const ProjectSchema = new Schema<ProjectDoc>(
|
||||
{
|
||||
_id: String,
|
||||
key: { type: String, unique: true },
|
||||
memberIds: { type: [String], index: true },
|
||||
owner: userRef,
|
||||
members: [{ _id: false, user: userRef, role: String }],
|
||||
version: Number,
|
||||
},
|
||||
{ ...loose, collection: 'projects_view' },
|
||||
);
|
||||
|
||||
export const IssueSchema = new Schema<IssueDoc>(
|
||||
{
|
||||
_id: String,
|
||||
projectId: { type: String, index: true },
|
||||
key: { type: String, unique: true },
|
||||
status: String,
|
||||
reporter: userRef,
|
||||
assignee: userRef,
|
||||
release: { _id: false, id: String, name: String },
|
||||
outwardLinks: [link],
|
||||
inwardLinks: [link],
|
||||
labels: [String],
|
||||
version: Number,
|
||||
},
|
||||
{ ...loose, collection: 'issues_view' },
|
||||
);
|
||||
IssueSchema.index({ projectId: 1, status: 1, updatedAt: -1 });
|
||||
IssueSchema.index({ 'assignee.id': 1 });
|
||||
IssueSchema.index({ 'release.id': 1 });
|
||||
IssueSchema.index({ title: 'text', description: 'text', key: 'text' });
|
||||
|
||||
export const CommentSchema = new Schema<CommentDoc>(
|
||||
{
|
||||
_id: String,
|
||||
issueId: { type: String, index: true },
|
||||
author: userRef,
|
||||
version: Number,
|
||||
},
|
||||
{ ...loose, collection: 'comments_view' },
|
||||
);
|
||||
CommentSchema.index({ issueId: 1, createdAt: 1 });
|
||||
|
||||
export const ReleaseSchema = new Schema<ReleaseDoc>(
|
||||
{ _id: String, projectId: { type: String, index: true }, version: Number },
|
||||
{ ...loose, collection: 'releases_view' },
|
||||
);
|
||||
|
||||
export const ActivitySchema = new Schema<ActivityDoc>(
|
||||
{
|
||||
_id: String,
|
||||
projectId: String,
|
||||
issueId: String,
|
||||
actor: userRef,
|
||||
},
|
||||
{ ...loose, collection: 'activity' },
|
||||
);
|
||||
ActivitySchema.index({ projectId: 1, occurredAt: -1 });
|
||||
ActivitySchema.index({ issueId: 1, occurredAt: -1 });
|
||||
|
||||
export const READ_MODEL_SCHEMAS = [
|
||||
{ name: ReadModels.Project, schema: ProjectSchema },
|
||||
{ name: ReadModels.Issue, schema: IssueSchema },
|
||||
{ name: ReadModels.Comment, schema: CommentSchema },
|
||||
{ name: ReadModels.Release, schema: ReleaseSchema },
|
||||
{ name: ReadModels.Activity, schema: ActivitySchema },
|
||||
];
|
||||
|
||||
export function fromDoc<T extends { _id: string }>(
|
||||
doc: T,
|
||||
): Omit<T, '_id'> & { id: string } {
|
||||
const { _id, ...rest } = doc;
|
||||
return { id: _id, ...rest };
|
||||
}
|
||||
|
||||
export function issueFromDoc(doc: IssueDoc): IssueReadModel {
|
||||
const { _id, outwardLinks, inwardLinks, ...rest } = doc;
|
||||
return {
|
||||
id: _id,
|
||||
...rest,
|
||||
links: [...(outwardLinks ?? []), ...(inwardLinks ?? [])],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Model } from 'mongoose';
|
||||
|
||||
/**
|
||||
* Idempotent upsert: only applies a change carrying a newer aggregate
|
||||
* version (event position). Redelivered events become no-ops.
|
||||
*/
|
||||
export async function upsertIfNewer<T extends { _id: string }>(
|
||||
model: Model<T>,
|
||||
id: string,
|
||||
version: number,
|
||||
set: Record<string, unknown>,
|
||||
setOnInsert: Record<string, unknown> = {},
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const result = await model.updateOne(
|
||||
{ _id: id, version: { $lt: version } } as never,
|
||||
{ $set: { ...set, version }, $setOnInsert: setOnInsert } as never,
|
||||
{ upsert: true },
|
||||
);
|
||||
return result.modifiedCount + result.upsertedCount > 0;
|
||||
} catch (error) {
|
||||
// Duplicate _id on upsert: the stored document is already newer.
|
||||
if ((error as { code?: number }).code === 11000) return false;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectModel } from '@nestjs/mongoose';
|
||||
import {
|
||||
UpsertMaterializedActivityRepository,
|
||||
UpsertMaterializedCommentRepository,
|
||||
UpsertMaterializedIssueRepository,
|
||||
UpsertMaterializedProjectRepository,
|
||||
UpsertMaterializedReleaseRepository,
|
||||
} from '@task-stream/api/tracker/application';
|
||||
import {
|
||||
ActivityReadModel,
|
||||
CommentReadModel,
|
||||
IssueLinkReadModel,
|
||||
IssueReadModel,
|
||||
ProjectReadModel,
|
||||
ReleaseReadModel,
|
||||
} from '@task-stream/api/tracker/domain';
|
||||
import { Model } from 'mongoose';
|
||||
import {
|
||||
ActivityDoc,
|
||||
CommentDoc,
|
||||
IssueDoc,
|
||||
ProjectDoc,
|
||||
ReadModels,
|
||||
ReleaseDoc,
|
||||
} from './read-model.schemas';
|
||||
import { upsertIfNewer } from './upsert-if-newer';
|
||||
|
||||
/* Materialized views written by the event handlers (MongoDB). */
|
||||
|
||||
@Injectable()
|
||||
export class MongoUpsertMaterializedProjectRepository extends UpsertMaterializedProjectRepository {
|
||||
constructor(
|
||||
@InjectModel(ReadModels.Project)
|
||||
private readonly projects: Model<ProjectDoc>,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async upsert({
|
||||
id,
|
||||
version,
|
||||
...fields
|
||||
}: Pick<ProjectReadModel, 'id' | 'version'> & Partial<ProjectReadModel>) {
|
||||
const memberIds = fields.members
|
||||
? { memberIds: fields.members.map((m) => m.user.id) }
|
||||
: {};
|
||||
await upsertIfNewer(this.projects, id, version, {
|
||||
...fields,
|
||||
...memberIds,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class MongoUpsertMaterializedIssueRepository extends UpsertMaterializedIssueRepository {
|
||||
constructor(
|
||||
@InjectModel(ReadModels.Issue) private readonly issues: Model<IssueDoc>,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async upsert({
|
||||
id,
|
||||
version,
|
||||
...fields
|
||||
}: Pick<IssueReadModel, 'id' | 'version'> &
|
||||
Partial<Omit<IssueReadModel, 'links' | 'commentCount'>>) {
|
||||
await upsertIfNewer(this.issues, id, version, fields, {
|
||||
outwardLinks: [],
|
||||
inwardLinks: [],
|
||||
commentCount: 0,
|
||||
});
|
||||
}
|
||||
|
||||
async addLink(issueId: string, link: IssueLinkReadModel) {
|
||||
const field = link.direction === 'OUTWARD' ? 'outwardLinks' : 'inwardLinks';
|
||||
await this.issues.updateOne(
|
||||
{
|
||||
_id: issueId,
|
||||
[field]: {
|
||||
$not: { $elemMatch: { type: link.type, issueId: link.issueId } },
|
||||
},
|
||||
},
|
||||
{ $push: { [field]: link } },
|
||||
);
|
||||
}
|
||||
|
||||
async removeLink(
|
||||
issueId: string,
|
||||
link: Omit<IssueLinkReadModel, 'issueKey'>,
|
||||
) {
|
||||
const field = link.direction === 'OUTWARD' ? 'outwardLinks' : 'inwardLinks';
|
||||
await this.issues.updateOne(
|
||||
{ _id: issueId },
|
||||
{ $pull: { [field]: { type: link.type, issueId: link.issueId } } },
|
||||
);
|
||||
}
|
||||
|
||||
async setCommentCount(issueId: string, commentCount: number) {
|
||||
await this.issues.updateOne({ _id: issueId }, { $set: { commentCount } });
|
||||
}
|
||||
|
||||
async renameRelease(releaseId: string, name: string) {
|
||||
await this.issues.updateMany(
|
||||
{ 'release.id': releaseId },
|
||||
{ $set: { 'release.name': name } },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class MongoUpsertMaterializedCommentRepository extends UpsertMaterializedCommentRepository {
|
||||
constructor(
|
||||
@InjectModel(ReadModels.Comment)
|
||||
private readonly comments: Model<CommentDoc>,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async upsert({
|
||||
id,
|
||||
version,
|
||||
...fields
|
||||
}: Pick<CommentReadModel, 'id' | 'version'> & Partial<CommentReadModel>) {
|
||||
await upsertIfNewer(this.comments, id, version, fields);
|
||||
}
|
||||
|
||||
async remove(id: string) {
|
||||
await this.comments.deleteOne({ _id: id });
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class MongoUpsertMaterializedReleaseRepository extends UpsertMaterializedReleaseRepository {
|
||||
constructor(
|
||||
@InjectModel(ReadModels.Release)
|
||||
private readonly releases: Model<ReleaseDoc>,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async upsert({
|
||||
id,
|
||||
version,
|
||||
...fields
|
||||
}: Pick<ReleaseReadModel, 'id' | 'version'> & Partial<ReleaseReadModel>) {
|
||||
await upsertIfNewer(this.releases, id, version, fields);
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class MongoUpsertMaterializedActivityRepository extends UpsertMaterializedActivityRepository {
|
||||
constructor(
|
||||
@InjectModel(ReadModels.Activity)
|
||||
private readonly activity: Model<ActivityDoc>,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async insert({ id, ...fields }: ActivityReadModel): Promise<boolean> {
|
||||
const result = await this.activity.updateOne(
|
||||
{ _id: id },
|
||||
{ $setOnInsert: fields },
|
||||
{ upsert: true },
|
||||
);
|
||||
return result.upsertedCount > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { Column, Entity, PrimaryColumn } from 'typeorm';
|
||||
|
||||
/*
|
||||
* Write-side lookup tables. The event store holds the truth; these only
|
||||
* enforce uniqueness and sequences that cannot be checked per aggregate.
|
||||
*/
|
||||
|
||||
@Entity('project_keys')
|
||||
export class ProjectKeyEntity {
|
||||
@PrimaryColumn({ length: 10 })
|
||||
key!: string;
|
||||
|
||||
@Column({ name: 'project_id', length: 64 })
|
||||
projectId!: string;
|
||||
}
|
||||
|
||||
@Entity('issue_sequences')
|
||||
export class IssueSequenceEntity {
|
||||
@PrimaryColumn({ name: 'project_id', length: 64 })
|
||||
projectId!: string;
|
||||
|
||||
@Column({ name: 'last_number', type: 'int', default: 0 })
|
||||
lastNumber!: number;
|
||||
}
|
||||
|
||||
@Entity('release_names')
|
||||
export class ReleaseNameEntity {
|
||||
@PrimaryColumn({ name: 'project_id', length: 64 })
|
||||
projectId!: string;
|
||||
|
||||
@PrimaryColumn({ length: 60 })
|
||||
name!: string;
|
||||
|
||||
@Column({ name: 'release_id', length: 64 })
|
||||
releaseId!: string;
|
||||
}
|
||||
|
||||
export const LOOKUP_ENTITIES = [
|
||||
ProjectKeyEntity,
|
||||
IssueSequenceEntity,
|
||||
ReleaseNameEntity,
|
||||
];
|
||||
@@ -0,0 +1,80 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { BusinessRuleError } from '@task-stream/api/shared/domain';
|
||||
import {
|
||||
IssueNumbersRepository,
|
||||
ProjectKeysRepository,
|
||||
ReleaseNamesRepository,
|
||||
} from '@task-stream/api/tracker/application';
|
||||
import { DataSource } from 'typeorm';
|
||||
import { ProjectKeyEntity, ReleaseNameEntity } from './lookup.entities';
|
||||
|
||||
const UNIQUE_VIOLATION = '23505';
|
||||
const isUniqueViolation = (error: unknown) =>
|
||||
(error as { code?: string }).code === UNIQUE_VIOLATION;
|
||||
|
||||
@Injectable()
|
||||
export class PostgresProjectKeysRepository extends ProjectKeysRepository {
|
||||
constructor(private readonly dataSource: DataSource) {
|
||||
super();
|
||||
}
|
||||
|
||||
async reserve(key: string, projectId: string): Promise<void> {
|
||||
try {
|
||||
await this.dataSource
|
||||
.getRepository(ProjectKeyEntity)
|
||||
.insert({ key, projectId });
|
||||
} catch (error) {
|
||||
if (isUniqueViolation(error))
|
||||
throw new BusinessRuleError(`Project key ${key} is already taken`);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class PostgresIssueNumbersRepository extends IssueNumbersRepository {
|
||||
constructor(private readonly dataSource: DataSource) {
|
||||
super();
|
||||
}
|
||||
|
||||
async next(projectId: string): Promise<number> {
|
||||
const rows: { last_number: number }[] = await this.dataSource.query(
|
||||
`INSERT INTO issue_sequences (project_id, last_number) VALUES ($1, 1)
|
||||
ON CONFLICT (project_id) DO UPDATE SET last_number = issue_sequences.last_number + 1
|
||||
RETURNING last_number`,
|
||||
[projectId],
|
||||
);
|
||||
return rows[0].last_number;
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class PostgresReleaseNamesRepository extends ReleaseNamesRepository {
|
||||
constructor(private readonly dataSource: DataSource) {
|
||||
super();
|
||||
}
|
||||
|
||||
async reserve(
|
||||
projectId: string,
|
||||
name: string,
|
||||
releaseId: string,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await this.dataSource
|
||||
.getRepository(ReleaseNameEntity)
|
||||
.insert({ projectId, name, releaseId });
|
||||
} catch (error) {
|
||||
if (isUniqueViolation(error))
|
||||
throw new BusinessRuleError(
|
||||
`Release ${name} already exists in this project`,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async free(projectId: string, name: string): Promise<void> {
|
||||
await this.dataSource
|
||||
.getRepository(ReleaseNameEntity)
|
||||
.delete({ projectId, name });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ReleaseIssuesRepository } from '@task-stream/api/tracker/application';
|
||||
import { IssueReleaseChangedEvent } from '@task-stream/api/tracker/domain';
|
||||
import { DataSource } from 'typeorm';
|
||||
|
||||
/** Reads the event store directly: every issue that was ever moved into the release. */
|
||||
@Injectable()
|
||||
export class PostgresReleaseIssuesRepository extends ReleaseIssuesRepository {
|
||||
constructor(private readonly dataSource: DataSource) {
|
||||
super();
|
||||
}
|
||||
|
||||
async findIssueIds(releaseId: string): Promise<string[]> {
|
||||
const rows: { stream_id: string }[] = await this.dataSource.query(
|
||||
`SELECT DISTINCT stream_id FROM events WHERE type = $1 AND data->>'releaseId' = $2`,
|
||||
[IssueReleaseChangedEvent.name, releaseId],
|
||||
);
|
||||
return rows.map((row) => row.stream_id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { GRAPHQL_PUB_SUB } from '@task-stream/api/shared/infrastructure';
|
||||
import {
|
||||
ChangeFeed,
|
||||
CommentChange,
|
||||
IssueChange,
|
||||
ProjectChange,
|
||||
ReleaseChange,
|
||||
} from '@task-stream/api/tracker/application';
|
||||
import { ActivityReadModel } from '@task-stream/api/tracker/domain';
|
||||
import { RedisPubSub } from 'graphql-redis-subscriptions';
|
||||
|
||||
/** Redis pub/sub channels (one per project / issue / user). Works across instances. */
|
||||
const Channels = {
|
||||
issue: (projectId: string) => `tracker.issue.${projectId}`,
|
||||
comment: (issueId: string) => `tracker.comment.${issueId}`,
|
||||
activity: (projectId: string) => `tracker.activity.${projectId}`,
|
||||
release: (projectId: string) => `tracker.release.${projectId}`,
|
||||
project: (projectId: string) => `tracker.project.${projectId}`,
|
||||
userProjects: (userId: string) => `tracker.user-projects.${userId}`,
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class RedisChangeFeed extends ChangeFeed {
|
||||
constructor(@Inject(GRAPHQL_PUB_SUB) private readonly pubSub: RedisPubSub) {
|
||||
super();
|
||||
}
|
||||
|
||||
publishIssue(change: IssueChange): Promise<void> {
|
||||
return this.pubSub.publish(Channels.issue(change.issue.projectId), change);
|
||||
}
|
||||
|
||||
publishComment(change: CommentChange): Promise<void> {
|
||||
return this.pubSub.publish(Channels.comment(change.issueId), change);
|
||||
}
|
||||
|
||||
publishActivity(activity: ActivityReadModel): Promise<void> {
|
||||
return this.pubSub.publish(Channels.activity(activity.projectId), activity);
|
||||
}
|
||||
|
||||
publishRelease(change: ReleaseChange): Promise<void> {
|
||||
return this.pubSub.publish(
|
||||
Channels.release(change.release.projectId),
|
||||
change,
|
||||
);
|
||||
}
|
||||
|
||||
async publishProject(
|
||||
change: ProjectChange,
|
||||
notifyUserIds: string[] = [],
|
||||
): Promise<void> {
|
||||
await this.pubSub.publish(Channels.project(change.project.id), change);
|
||||
await Promise.all(
|
||||
notifyUserIds.map((userId) =>
|
||||
this.pubSub.publish(Channels.userProjects(userId), change),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
issues(projectId: string): AsyncIterableIterator<IssueChange> {
|
||||
return this.pubSub.asyncIterableIterator(Channels.issue(projectId));
|
||||
}
|
||||
|
||||
comments(issueId: string): AsyncIterableIterator<CommentChange> {
|
||||
return this.pubSub.asyncIterableIterator(Channels.comment(issueId));
|
||||
}
|
||||
|
||||
activity(projectId: string): AsyncIterableIterator<ActivityReadModel> {
|
||||
return this.pubSub.asyncIterableIterator(Channels.activity(projectId));
|
||||
}
|
||||
|
||||
releases(projectId: string): AsyncIterableIterator<ReleaseChange> {
|
||||
return this.pubSub.asyncIterableIterator(Channels.release(projectId));
|
||||
}
|
||||
|
||||
project(projectId: string): AsyncIterableIterator<ProjectChange> {
|
||||
return this.pubSub.asyncIterableIterator(Channels.project(projectId));
|
||||
}
|
||||
|
||||
userProjects(userId: string): AsyncIterableIterator<ProjectChange> {
|
||||
return this.pubSub.asyncIterableIterator(Channels.userProjects(userId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { CqrsModule } from '@nestjs/cqrs';
|
||||
import { MongooseModule } from '@nestjs/mongoose';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import {
|
||||
ChangeFeed,
|
||||
FindActivityRepository,
|
||||
FindCommentsRepository,
|
||||
FindIssuesRepository,
|
||||
FindProjectsRepository,
|
||||
FindReleasesRepository,
|
||||
IssueNumbersRepository,
|
||||
ProjectKeysRepository,
|
||||
ReleaseIssuesRepository,
|
||||
ReleaseNamesRepository,
|
||||
UpsertMaterializedActivityRepository,
|
||||
UpsertMaterializedCommentRepository,
|
||||
UpsertMaterializedIssueRepository,
|
||||
UpsertMaterializedProjectRepository,
|
||||
UpsertMaterializedReleaseRepository,
|
||||
UserDirectory,
|
||||
} from '@task-stream/api/tracker/application';
|
||||
import { IdentityUserDirectory } from './identity/identity-user-directory';
|
||||
import {
|
||||
MongoFindActivityRepository,
|
||||
MongoFindCommentsRepository,
|
||||
MongoFindIssuesRepository,
|
||||
MongoFindProjectsRepository,
|
||||
MongoFindReleasesRepository,
|
||||
} from './mongo/find.repositories';
|
||||
import { READ_MODEL_SCHEMAS } from './mongo/read-model.schemas';
|
||||
import {
|
||||
MongoUpsertMaterializedActivityRepository,
|
||||
MongoUpsertMaterializedCommentRepository,
|
||||
MongoUpsertMaterializedIssueRepository,
|
||||
MongoUpsertMaterializedProjectRepository,
|
||||
MongoUpsertMaterializedReleaseRepository,
|
||||
} from './mongo/upsert-materialized.repositories';
|
||||
import { LOOKUP_ENTITIES } from './postgres/lookup.entities';
|
||||
import {
|
||||
PostgresIssueNumbersRepository,
|
||||
PostgresProjectKeysRepository,
|
||||
PostgresReleaseNamesRepository,
|
||||
} from './postgres/lookup.repositories';
|
||||
import { PostgresReleaseIssuesRepository } from './postgres/release-issues.repository';
|
||||
import { RedisChangeFeed } from './realtime/redis-change-feed';
|
||||
|
||||
const PORTS = [
|
||||
// Write side lookups → PostgreSQL (aggregates themselves live in the event store)
|
||||
{ provide: ProjectKeysRepository, useClass: PostgresProjectKeysRepository },
|
||||
{ provide: IssueNumbersRepository, useClass: PostgresIssueNumbersRepository },
|
||||
{ provide: ReleaseNamesRepository, useClass: PostgresReleaseNamesRepository },
|
||||
{
|
||||
provide: ReleaseIssuesRepository,
|
||||
useClass: PostgresReleaseIssuesRepository,
|
||||
},
|
||||
// Read side → MongoDB
|
||||
{ provide: FindProjectsRepository, useClass: MongoFindProjectsRepository },
|
||||
{ provide: FindIssuesRepository, useClass: MongoFindIssuesRepository },
|
||||
{ provide: FindCommentsRepository, useClass: MongoFindCommentsRepository },
|
||||
{ provide: FindReleasesRepository, useClass: MongoFindReleasesRepository },
|
||||
{ provide: FindActivityRepository, useClass: MongoFindActivityRepository },
|
||||
{
|
||||
provide: UpsertMaterializedProjectRepository,
|
||||
useClass: MongoUpsertMaterializedProjectRepository,
|
||||
},
|
||||
{
|
||||
provide: UpsertMaterializedIssueRepository,
|
||||
useClass: MongoUpsertMaterializedIssueRepository,
|
||||
},
|
||||
{
|
||||
provide: UpsertMaterializedCommentRepository,
|
||||
useClass: MongoUpsertMaterializedCommentRepository,
|
||||
},
|
||||
{
|
||||
provide: UpsertMaterializedReleaseRepository,
|
||||
useClass: MongoUpsertMaterializedReleaseRepository,
|
||||
},
|
||||
{
|
||||
provide: UpsertMaterializedActivityRepository,
|
||||
useClass: MongoUpsertMaterializedActivityRepository,
|
||||
},
|
||||
// Realtime → Redis pub/sub
|
||||
{ provide: ChangeFeed, useClass: RedisChangeFeed },
|
||||
// Identity context (anti-corruption layer)
|
||||
{ provide: UserDirectory, useClass: IdentityUserDirectory },
|
||||
];
|
||||
|
||||
/** Driven adapters of the tracker context. */
|
||||
@Module({
|
||||
imports: [
|
||||
CqrsModule,
|
||||
TypeOrmModule.forFeature(LOOKUP_ENTITIES),
|
||||
MongooseModule.forFeature(READ_MODEL_SCHEMAS),
|
||||
],
|
||||
providers: PORTS,
|
||||
exports: PORTS.map((port) => port.provide),
|
||||
})
|
||||
export class TrackerInfrastructureModule {}
|
||||
23
libs/api/tracker/infrastructure/tsconfig.json
Normal file
23
libs/api/tracker/infrastructure/tsconfig.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"extends": "../../../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"strict": true,
|
||||
"importHelpers": true,
|
||||
"noImplicitOverride": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noPropertyAccessFromIndexSignature": true
|
||||
},
|
||||
"files": [],
|
||||
"include": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.lib.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.spec.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
23
libs/api/tracker/infrastructure/tsconfig.lib.json
Normal file
23
libs/api/tracker/infrastructure/tsconfig.lib.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../../../../dist/out-tsc",
|
||||
"declaration": true,
|
||||
"types": ["node"],
|
||||
"target": "es2021",
|
||||
"experimentalDecorators": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"strictNullChecks": true,
|
||||
"noImplicitAny": true,
|
||||
"strictBindCallApply": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": [
|
||||
"jest.config.ts",
|
||||
"jest.config.cts",
|
||||
"src/**/*.spec.ts",
|
||||
"src/**/*.test.ts"
|
||||
]
|
||||
}
|
||||
16
libs/api/tracker/infrastructure/tsconfig.spec.json
Normal file
16
libs/api/tracker/infrastructure/tsconfig.spec.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../../../../dist/out-tsc",
|
||||
"module": "commonjs",
|
||||
"moduleResolution": "bundler",
|
||||
"types": ["jest", "node"]
|
||||
},
|
||||
"include": [
|
||||
"jest.config.ts",
|
||||
"jest.config.cts",
|
||||
"src/**/*.test.ts",
|
||||
"src/**/*.spec.ts",
|
||||
"src/**/*.d.ts"
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user