Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/analytics/analytics.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
Controller,
ForbiddenException,
Get,
Header,
Param,
ParseUUIDPipe,
Query,
Expand Down Expand Up @@ -46,9 +47,11 @@ export class AnalyticsController {
}

@Get('platform')
// Shared caches (CDN) hold one copy for 60s, so every visitor sees the same figure (#788).
@Header('Cache-Control', 'public, s-maxage=60, stale-while-revalidate=30')
@ApiOperation({
summary: 'Platform-wide homepage summary',
description: `Cached in-process for ANALYTICS_PLATFORM_SUMMARY_TTL_MS (default 60s). Invalidated when a bounty is created or paid, or a repository is first synced. Heatmap/day cap is ${HEATMAP_MAX_DAYS}. Multi-instance deployments may serve up to one TTL of stale data per process.`,
description: `Served with a 60s shared-cache lifetime so all visitors see the same figure. Heatmap/day cap is ${HEATMAP_MAX_DAYS}.`,
})
platformSummary() {
return this.analyticsService.platformSummary();
Expand Down
29 changes: 7 additions & 22 deletions src/analytics/analytics.service.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { OnEvent } from '@nestjs/event-emitter';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import {
Bounty,
Payment,
Repository as RepositoryEntity,
} from '../common/entities';
import { BountyStatus } from '../common/enums';
import { AssetType, PaymentStatus } from '../common/enums';
import { AppConfig } from '../config/configuration';
import {
Expand All @@ -16,8 +15,6 @@ import {
queryPayoutHeatmap,
queryTopClients,
} from '../common/stats/contributor-stats.sql';
import { ANALYTICS_PLATFORM_INVALIDATE_EVENT } from './analytics.events';
import { TtlCache } from './ttl-cache';

export interface ContributorAnalytics {
lifetimeEarnings: number;
Expand Down Expand Up @@ -46,21 +43,13 @@ export interface PlatformSummary {

@Injectable()
export class AnalyticsService {
private readonly platformCache: TtlCache<PlatformSummary>;

constructor(
@InjectRepository(Bounty) private readonly bountyRepo: Repository<Bounty>,
@InjectRepository(Payment)
private readonly paymentRepo: Repository<Payment>,
@InjectRepository(RepositoryEntity)
private readonly repositoryRepo: Repository<RepositoryEntity>,
configService: ConfigService<AppConfig, true>,
) {
const ttlMs = configService.get('analytics', {
infer: true,
}).platformSummaryTtlMs;
this.platformCache = new TtlCache<PlatformSummary>(ttlMs);
}
) {}

async forContributor(
userId: string,
Expand All @@ -86,17 +75,13 @@ export class AnalyticsService {
}

/**
* Platform-wide stats for the homepage. Cached in-process with a TTL
* (ANALYTICS_PLATFORM_SUMMARY_TTL_MS, default 60s) and busted on bounty
* create/pay and new repository insert. Concurrent misses share one query.
* Platform-wide stats for the homepage. Not cached here: an in-process cache
* gives each replica different figures and invalidation reaches only one of
* them (#788). The controller sets a shared-cache header instead, so one copy
* is held at the CDN.
*/
async platformSummary(): Promise<PlatformSummary> {
return this.platformCache.getOrLoad(() => this.loadPlatformSummary());
}

@OnEvent(ANALYTICS_PLATFORM_INVALIDATE_EVENT)
invalidatePlatformSummary(): void {
this.platformCache.invalidate();
return this.loadPlatformSummary();
}

private async loadPlatformSummary(): Promise<PlatformSummary> {
Expand Down
13 changes: 5 additions & 8 deletions src/common/encryption.transformer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,6 @@ import { Logger } from '@nestjs/common';
import { ValueTransformer } from 'typeorm';
import { createCipheriv, createDecipheriv, randomBytes } from 'crypto';

/** Used only outside production when ENCRYPTION_KEY is unset. */
const DEV_FALLBACK_KEY =
'64a2f98b7e3c1d5e6f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4e5f6a7b8c9d0e';

const logger = new Logger('EncryptionTransformer');

let cachedKey: Buffer | null = null;
Expand All @@ -16,11 +12,12 @@ let cachedKey: Buffer | null = null;
*/
function encryptionKey(): Buffer {
if (cachedKey) return cachedKey;
const configured = process.env.ENCRYPTION_KEY;
if (!configured && process.env.NODE_ENV === 'production') {
throw new Error('ENCRYPTION_KEY must be set in production');
// There is no default key. A key committed to the repository is public, so an unset key must fail
// closed in every environment, not only in production (#782).
const hex = process.env.ENCRYPTION_KEY;
if (!hex) {
throw new Error('ENCRYPTION_KEY must be set; there is no default encryption key');
}
const hex = configured || DEV_FALLBACK_KEY;
if (!/^[0-9a-fA-F]{64}$/.test(hex)) {
throw new Error('ENCRYPTION_KEY must be 64 hex characters (32 bytes)');
}
Expand Down
31 changes: 31 additions & 0 deletions src/escrow/escrow.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,37 @@ export class EscrowService {
}
}

/**
* Adds a sponsor deposit to a maintenance pool's existing escrow (#781). It calls the pool contract's
* `deposit` on the escrow row the pool already points at, so repeated deposits share one escrow and
* no new row is created. The call runs under the row lock, like the other escrow operations.
*/
async depositToPool(
escrowId: string,
input: { amount: string; asset: AssetType; funderAddress: string },
): Promise<Escrow> {
this.assertValidAmount(input.amount);
return this.withLockedEscrow(escrowId, async (escrow, manager) => {
await this.invokeOnLockedEscrow(
escrow,
'poolDeposit',
() =>
this.soroban.invoke(
'deposit',
[
input.funderAddress,
this.onChainKeyFor(escrow),
this.toStroops(input.amount),
this.resolveTokenAddress(input.asset),
],
this.contractOpts(escrow),
),
manager,
);
return escrow;
});
}

/** Releases the full escrowed amount to a single recipient (standard bounty payout). */
async release(
escrowId: string,
Expand Down
13 changes: 7 additions & 6 deletions src/maintenance-pool/maintenance-pool.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,25 +125,26 @@ export class MaintenancePoolService {
{ escrowId: escrow.id },
);
if (updateResult.affected === 0) {
// Another request won the race — top up the winner's escrow instead.
// Another request won the race — deposit into the winner's escrow instead of creating a second one (#781).
const existingPool = await this.findOne(id);
const topUp = await this.escrowService.fund({
if (!existingPool.escrowId) {
throw new Error(`Pool ${id} lost the escrow race but has no escrowId`);
}
const topUp = await this.escrowService.depositToPool(existingPool.escrowId, {
amount,
asset: pool.asset,
funderAddress,
maintenancePoolId: pool.id,
});
await this.recordDepositor(topUp, callerUserId);
await this.creditPoolBalance(id, amount);
return this.findOne(id);
}
} else {
// Subsequent deposits top up the existing on-chain escrow balance.
const topUp = await this.escrowService.fund({
// Subsequent deposits top up the existing pool escrow. No new escrow row is created (#781).
const topUp = await this.escrowService.depositToPool(pool.escrowId, {
amount,
asset: pool.asset,
funderAddress,
maintenancePoolId: pool.id,
});
await this.recordDepositor(topUp, callerUserId);
}
Expand Down
73 changes: 35 additions & 38 deletions src/users/users.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export class UsersService {

/** Finds or creates a User + GithubAccount from a completed OAuth handshake. */
async upsertFromGithub(input: UpsertFromGithubInput): Promise<User> {
let account = await this.githubAccountRepo.findOne({
const account = await this.githubAccountRepo.findOne({
where: { githubId: input.githubId },
relations: { user: true },
});
Expand Down Expand Up @@ -155,52 +155,49 @@ export class UsersService {
}
}

const user = await this.saveNewUser({
login: input.login,
email,
displayName: input.displayName,
avatarUrl: input.avatarUrl,
});

account = this.githubAccountRepo.create({
githubId: input.githubId,
login: input.login,
avatarUrl: input.avatarUrl,
profileUrl: input.profileUrl,
accessToken: input.accessToken,
refreshToken: input.refreshToken ?? null,
userId: user.id,
});
await this.githubAccountRepo.save(account);
// User and GithubAccount commit together. Separate saves could leave a User with no GithubAccount
// if the second failed, and the next sign-in would then create a duplicate user (#789).
const user = await this.saveNewIdentity(input, email);

return this.findOneRaw(user.id);
}

/**
* Inserts a new User. The database decides username uniqueness (#790): the
* preferred login is tried first, with no lookup. On a unique violation for
* `username`, a short random suffix is added and the insert is retried. This
* takes one query in the common case and is race-safe, because two concurrent
* sign-ins cannot both insert the same name.
* Inserts a new User and its GithubAccount in one transaction. The database decides username
* uniqueness (#790): the preferred login is tried first. On a unique violation for `username`, the
* whole transaction is rolled back and retried with a short random suffix. Rolling back is required,
* because a Postgres transaction cannot continue after a failed statement.
*/
private async saveNewUser(input: {
login: string;
email: string | null;
displayName: string | null;
avatarUrl: string | null;
}): Promise<User> {
private async saveNewIdentity(
input: UpsertFromGithubInput,
email: string | null,
): Promise<User> {
let username = input.login;
for (let attempt = 1; ; attempt++) {
try {
return await this.userRepo.save(
this.userRepo.create({
username,
email: input.email,
displayName: input.displayName,
avatarUrl: input.avatarUrl,
roles: [UserRole.CONTRIBUTOR],
}),
);
return await this.userRepo.manager.transaction(async (manager) => {
const user = await manager.save(
manager.create(User, {
username,
email,
displayName: input.displayName,
avatarUrl: input.avatarUrl,
roles: [UserRole.CONTRIBUTOR],
}),
);
await manager.save(
manager.create(GithubAccount, {
githubId: input.githubId,
login: input.login,
avatarUrl: input.avatarUrl,
profileUrl: input.profileUrl,
accessToken: input.accessToken,
refreshToken: input.refreshToken ?? null,
userId: user.id,
}),
);
return user;
});
} catch (err) {
if (!isUsernameViolation(err) || attempt >= MAX_USERNAME_ATTEMPTS) {
throw err;
Expand Down