feat: v2.0 iteration — test coverage, reliability, observability

M0: Test coverage expansion (151 → 321 tests, 61% → 66% lines)
  - normalizeKnowledge CRLF/LF normalization fix
  - gooseReviewer: 11 tests, 97.35% coverage
  - r2 storage: 22 tests, 100% coverage
  - triage processor: 11 tests, exported buildTriagePrompt/labelName
  - webhook processor: 35 tests, 72.39% coverage
  - conflict resolver: 12 tests
  - review processor: 7 tests

M1: Reliability hardening
  - Smart retry with jitter, maxTotalTimeoutMs, custom retryable predicate
  - MergeGuard: in-memory merge dedup tracker (100% coverage)
  - failureMessages: 7-category failure classifier (100% coverage)

M2: Observability
  - MetricsCollector: Actions-run metrics with snapshot/markdown/reset
  - 11 tests, 100% coverage

New files: 12 test files, 3 source modules
All gates: typecheck ✓ lint ✓ format ✓ 321/321 tests ✓ build ✓
This commit is contained in:
ghbot committed 2026-08-24 17:34:04 +08:00
1 parent db53296d78
commit 78bf8e9e41
87 files changed
+6003 -2587

No files matched your search

+35 -58
View File
@@ -68,9 +68,9 @@ const fastify = Fastify({
level: process.env.LOG_LEVEL || "info",
transport: {
target: "pino-pretty",
options: { colorize: true },
},
},
options: { colorize: true }
}
}
});
// Plugins
@@ -91,15 +91,15 @@ fastify.post<{
required: ["name", "email"],
properties: {
name: { type: "string", minLength: 1 },
email: { type: "string", format: "email" },
},
},
},
email: { type: "string", format: "email" }
}
}
}
},
async (request, reply) => {
const { name, email } = request.body;
return { id: "123", name };
},
}
);
await fastify.listen({ port: 3000, host: "0.0.0.0" });
@@ -203,7 +203,7 @@ export class UserService {
// Create user
const user = await this.userRepository.create({
...userData,
password: hashedPassword,
password: hashedPassword
});
// Remove password from response
@@ -248,19 +248,13 @@ import { CreateUserDTO, UpdateUserDTO, UserEntity } from "../types/user.types";
export class UserRepository {
constructor(private db: Pool) {}
async create(
userData: CreateUserDTO & { password: string },
): Promise<UserEntity> {
async create(userData: CreateUserDTO & { password: string }): Promise<UserEntity> {
const query = `
INSERT INTO users (name, email, password)
VALUES ($1, $2, $3)
RETURNING id, name, email, password, created_at, updated_at
`;
const { rows } = await this.db.query(query, [
userData.name,
userData.email,
userData.password,
]);
const { rows } = await this.db.query(query, [userData.name, userData.email, userData.password]);
return rows[0];
}
@@ -280,9 +274,7 @@ export class UserRepository {
const fields = Object.keys(updates);
const values = Object.values(updates);
const setClause = fields
.map((field, idx) => `${field} = $${idx + 2}`)
.join(", ");
const setClause = fields.map((field, idx) => `${field} = $${idx + 2}`).join(", ");
const query = `
UPDATE users
@@ -330,11 +322,7 @@ declare global {
}
}
export const authenticate = async (
req: Request,
res: Response,
next: NextFunction,
) => {
export const authenticate = async (req: Request, res: Response, next: NextFunction) => {
try {
const token = req.headers.authorization?.replace("Bearer ", "");
@@ -383,14 +371,14 @@ export const validate = (schema: AnyZodObject) => {
await schema.parseAsync({
body: req.body,
query: req.query,
params: req.params,
params: req.params
});
next();
} catch (error) {
if (error instanceof ZodError) {
const errors = error.errors.map((err) => ({
field: err.path.join("."),
message: err.message,
message: err.message
}));
next(new ValidationError("Validation failed", errors));
} else {
@@ -407,8 +395,8 @@ const createUserSchema = z.object({
body: z.object({
name: z.string().min(1),
email: z.string().email(),
password: z.string().min(8),
}),
password: z.string().min(8)
})
});
router.post("/users", validate(createUserSchema), userController.createUser);
@@ -424,29 +412,29 @@ import Redis from "ioredis";
const redis = new Redis({
host: process.env.REDIS_HOST,
port: parseInt(process.env.REDIS_PORT || "6379"),
port: parseInt(process.env.REDIS_PORT || "6379")
});
export const apiLimiter = rateLimit({
store: new RedisStore({
client: redis,
prefix: "rl:",
prefix: "rl:"
}),
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per windowMs
message: "Too many requests from this IP, please try again later",
standardHeaders: true,
legacyHeaders: false,
legacyHeaders: false
});
export const authLimiter = rateLimit({
store: new RedisStore({
client: redis,
prefix: "rl:auth:",
prefix: "rl:auth:"
}),
windowMs: 15 * 60 * 1000,
max: 5, // Stricter limit for auth endpoints
skipSuccessfulRequests: true,
skipSuccessfulRequests: true
});
```
@@ -461,15 +449,11 @@ const logger = pino({
level: process.env.LOG_LEVEL || "info",
transport: {
target: "pino-pretty",
options: { colorize: true },
},
options: { colorize: true }
}
});
export const requestLogger = (
req: Request,
res: Response,
next: NextFunction,
) => {
export const requestLogger = (req: Request, res: Response, next: NextFunction) => {
const start = Date.now();
// Log response when finished
@@ -481,7 +465,7 @@ export const requestLogger = (
status: res.statusCode,
duration: `${duration}ms`,
userAgent: req.headers["user-agent"],
ip: req.ip,
ip: req.ip
});
});
@@ -501,7 +485,7 @@ export class AppError extends Error {
constructor(
public message: string,
public statusCode: number = 500,
public isOperational: boolean = true,
public isOperational: boolean = true
) {
super(message);
Object.setPrototypeOf(this, AppError.prototype);
@@ -512,7 +496,7 @@ export class AppError extends Error {
export class ValidationError extends AppError {
constructor(
message: string,
public errors?: any[],
public errors?: any[]
) {
super(message, 400);
}
@@ -551,17 +535,12 @@ import { Request, Response, NextFunction } from "express";
import { AppError } from "../utils/errors";
import { logger } from "./logger.middleware";
export const errorHandler = (
err: Error,
req: Request,
res: Response,
next: NextFunction,
) => {
export const errorHandler = (err: Error, req: Request, res: Response, next: NextFunction) => {
if (err instanceof AppError) {
return res.status(err.statusCode).json({
status: "error",
message: err.message,
...(err instanceof ValidationError && { errors: err.errors }),
...(err instanceof ValidationError && { errors: err.errors })
});
}
@@ -570,24 +549,21 @@ export const errorHandler = (
error: err.message,
stack: err.stack,
url: req.url,
method: req.method,
method: req.method
});
// Don't leak error details in production
const message =
process.env.NODE_ENV === "production"
? "Internal server error"
: err.message;
const message = process.env.NODE_ENV === "production" ? "Internal server error" : err.message;
res.status(500).json({
status: "error",
message,
message
});
};
// Async error wrapper
export const asyncHandler = (
fn: (req: Request, res: Response, next: NextFunction) => Promise<any>,
fn: (req: Request, res: Response, next: NextFunction) => Promise<any>
) => {
return (req: Request, res: Response, next: NextFunction) => {
Promise.resolve(fn(req, res, next)).catch(next);
@@ -600,6 +576,7 @@ export const asyncHandler = (
Node.js supports both SQL and NoSQL databases. Use connection pooling for all production databases.
Key patterns covered in [references/advanced-patterns.md](references/advanced-patterns.md):
- **PostgreSQL with connection pool** — `pg` Pool configuration and graceful shutdown
- **MongoDB with Mongoose** — connection management and schema definition
- **Transaction pattern** — `BEGIN`/`COMMIT`/`ROLLBACK` with `pg` client
@@ -54,29 +54,17 @@ container.singleton(
password: process.env.DB_PASSWORD,
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
}),
connectionTimeoutMillis: 2000
})
);
container.singleton(
"userRepository",
() => new UserRepository(container.resolve("db")),
);
container.singleton("userRepository", () => new UserRepository(container.resolve("db")));
container.singleton(
"userService",
() => new UserService(container.resolve("userRepository")),
);
container.singleton("userService", () => new UserService(container.resolve("userRepository")));
container.register(
"userController",
() => new UserController(container.resolve("userService")),
);
container.register("userController", () => new UserController(container.resolve("userService")));
container.singleton(
"authService",
() => new AuthService(container.resolve("userRepository")),
);
container.singleton("authService", () => new AuthService(container.resolve("userRepository")));
```
## Database Patterns
@@ -95,7 +83,7 @@ const poolConfig: PoolConfig = {
password: process.env.DB_PASSWORD,
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
connectionTimeoutMillis: 2000
};
export const pool = new Pool(poolConfig);
@@ -128,7 +116,7 @@ const connectDB = async () => {
await mongoose.connect(process.env.MONGODB_URI!, {
maxPoolSize: 10,
serverSelectionTimeoutMS: 5000,
socketTimeoutMS: 45000,
socketTimeoutMS: 45000
});
console.log("MongoDB connected");
@@ -163,11 +151,11 @@ const userSchema = new Schema<IUser>(
{
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
password: { type: String, required: true }
},
{
timestamps: true,
},
timestamps: true
}
);
// Indexes
@@ -194,7 +182,7 @@ export class OrderService {
// Create order
const orderResult = await client.query(
"INSERT INTO orders (user_id, total) VALUES ($1, $2) RETURNING id",
[userId, calculateTotal(items)],
[userId, calculateTotal(items)]
);
const orderId = orderResult.rows[0].id;
@@ -202,14 +190,14 @@ export class OrderService {
for (const item of items) {
await client.query(
"INSERT INTO order_items (order_id, product_id, quantity, price) VALUES ($1, $2, $3, $4)",
[orderId, item.productId, item.quantity, item.price],
[orderId, item.productId, item.quantity, item.price]
);
// Update inventory
await client.query(
"UPDATE products SET stock = stock - $1 WHERE id = $2",
[item.quantity, item.productId],
);
await client.query("UPDATE products SET stock = stock - $1 WHERE id = $2", [
item.quantity,
item.productId
]);
}
await client.query("COMMIT");
@@ -253,11 +241,11 @@ export class AuthService {
const token = this.generateToken({
userId: user.id,
email: user.email,
email: user.email
});
const refreshToken = this.generateRefreshToken({
userId: user.id,
userId: user.id
});
return {
@@ -266,17 +254,16 @@ export class AuthService {
user: {
id: user.id,
name: user.name,
email: user.email,
},
email: user.email
}
};
}
async refreshToken(refreshToken: string) {
try {
const payload = jwt.verify(
refreshToken,
process.env.REFRESH_TOKEN_SECRET!,
) as { userId: string };
const payload = jwt.verify(refreshToken, process.env.REFRESH_TOKEN_SECRET!) as {
userId: string;
};
const user = await this.userRepository.findById(payload.userId);
@@ -286,7 +273,7 @@ export class AuthService {
const token = this.generateToken({
userId: user.id,
email: user.email,
email: user.email
});
return { token };
@@ -297,13 +284,13 @@ export class AuthService {
private generateToken(payload: any): string {
return jwt.sign(payload, process.env.JWT_SECRET!, {
expiresIn: "15m",
expiresIn: "15m"
});
}
private generateRefreshToken(payload: any): string {
return jwt.sign(payload, process.env.REFRESH_TOKEN_SECRET!, {
expiresIn: "7d",
expiresIn: "7d"
});
}
}
@@ -321,7 +308,7 @@ const redis = new Redis({
retryStrategy: (times) => {
const delay = Math.min(times * 50, 2000);
return delay;
},
}
});
export class CacheService {
@@ -353,11 +340,7 @@ export class CacheService {
// Cache decorator
export function Cacheable(ttl: number = 300) {
return function (
target: any,
propertyKey: string,
descriptor: PropertyDescriptor,
) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = async function (...args: any[]) {
@@ -387,16 +370,11 @@ export function Cacheable(ttl: number = 300) {
import { Response } from "express";
export class ApiResponse {
static success<T>(
res: Response,
data: T,
message?: string,
statusCode = 200,
) {
static success<T>(res: Response, data: T, message?: string, statusCode = 200) {
return res.status(statusCode).json({
status: "success",
message,
data,
data
});
}
@@ -404,17 +382,11 @@ export class ApiResponse {
return res.status(statusCode).json({
status: "error",
message,
...(errors && { errors }),
...(errors && { errors })
});
}
static paginated<T>(
res: Response,
data: T[],
page: number,
limit: number,
total: number,
) {
static paginated<T>(res: Response, data: T[], page: number, limit: number, total: number) {
return res.json({
status: "success",
data,
@@ -422,8 +394,8 @@ export class ApiResponse {
page,
limit,
total,
pages: Math.ceil(total / limit),
},
pages: Math.ceil(total / limit)
}
});
}
}