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
1 change: 1 addition & 0 deletions Backend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ CONTRACT_ID_GIST_REGISTRY=
# IPFS (Pinata) — leave blank to use mock CIDs in dev
PINATA_API_KEY=
PINATA_SECRET_KEY=
IPFS_GATEWAY=https://gateway.pinata.cloud/ipfs

# Optional: backend signing keypair for submitting txs to Soroban
STELLAR_SECRET_KEY=
Expand Down
1 change: 1 addition & 0 deletions Backend/src/config/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,6 @@ export default () => ({
ipfs: {
pinataApiKey: process.env.PINATA_API_KEY ?? '',
pinataSecretKey: process.env.PINATA_SECRET_KEY ?? '',
gateway: process.env.IPFS_GATEWAY ?? 'https://gateway.pinata.cloud/ipfs',
},
});
1 change: 1 addition & 0 deletions Backend/src/config/env.validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export const envValidationSchema = Joi.object({
// IPFS (Pinata) — optional; empty means mock CIDs in dev
PINATA_API_KEY: Joi.string().allow('').default(''),
PINATA_SECRET_KEY: Joi.string().allow('').default(''),
IPFS_GATEWAY: Joi.string().uri().default('https://gateway.pinata.cloud/ipfs'),

// CORS
CORS_ORIGINS: Joi.string().allow('').default(''),
Expand Down
21 changes: 11 additions & 10 deletions Backend/src/gists/gists.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,14 @@ jest.mock('../soroban/soroban.service', () => ({
describe('GistsService', () => {
let service: GistsService;
let gistRepository: jest.Mocked<GistRepository>;
let ipfsService: jest.Mocked<IpfsService>;
let transactionMock: jest.Mock;

const buildGist = (overrides: Partial<Gist> = {}): Gist => ({
id: '00000000-0000-0000-0000-000000000001',
content: 'hello',
location_cell: 's1t7d8c',
content_hash: 'mock_cid',
content_hash: 'Qmrealcid',
stellar_gist_id: 'gist-1',
tx_hash: 'mock_tx',
author_address: null,
Expand Down Expand Up @@ -75,6 +76,7 @@ describe('GistsService', () => {

service = module.get(GistsService);
gistRepository = module.get(GistRepository) as jest.Mocked<GistRepository>;
ipfsService = module.get(IpfsService) as jest.Mocked<IpfsService>;

jest.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);
jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);
Expand All @@ -88,21 +90,21 @@ describe('GistsService', () => {
// create
// ──────────────────────────────────────────────────────────────────────────
describe('create', () => {
it('sanitizes content, encodes the cell, pins IPFS, posts Soroban, and inserts in a transaction', async () => {
it('sanitizes, encodes, pins IPFS, posts Soroban, and inserts in a transaction', async () => {
const created = buildGist();
gistRepository.create.mockResolvedValue(created);

const result = await service.create(buildDto());

expect(transactionMock).toHaveBeenCalledTimes(1);
expect(gistRepository.create).toHaveBeenCalledTimes(1);
const writeArgs = gistRepository.create.mock.calls[0];
expect(writeArgs[0]).toMatchObject({
const [writeArg, managerArg] = gistRepository.create.mock.calls[0];
expect(writeArg).toMatchObject({
content: 'hello',
lat: 9.0579,
lon: 7.4951,
location_cell: 's1t7d8c',
content_hash: 'mock_cid',
content_hash: 'Qmrealcid',
stellar_gist_id: 'gist-1',
tx_hash: 'mock_tx',
});
Expand Down Expand Up @@ -150,22 +152,21 @@ describe('GistsService', () => {
const result = await service.create(buildDto());

expect(gistRepository.findByStellarGistId).toHaveBeenCalledWith('gist-1');
expect(result).toBe(existing);
});

it('throws when the INSERT fails with a non-23505 error', async () => {
const driverError: Error & { code?: string } = new Error('connection lost');
driverError.code = '08006';

gistRepository.create.mockRejectedValue(driverError);
await expect(service.create(buildDto())).rejects.toBe(err);
});

await expect(service.create(buildDto())).rejects.toBe(driverError);
expect(gistRepository.findByStellarGistId).not.toHaveBeenCalled();
});
});

it('rethrows if the idempotent recovery lookup returns null', async () => {
const driverError: Error & { code?: string } = new Error('duplicate key value');
driverError.code = PG_UNIQUE_VIOLATION;
// ── findOne ───────────────────────────────────────────────────────────────

gistRepository.create.mockRejectedValue(driverError);
gistRepository.findByStellarGistId.mockResolvedValue(null);
Expand Down
2 changes: 2 additions & 0 deletions Backend/src/gists/gists.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ export interface CountNearbyResult {
@Injectable()
export class GistsService {
private readonly logger = new Logger(GistsService.name);
private readonly contentCache = new Map<string, CacheEntry>();
private static readonly CACHE_TTL_MS = 5 * 60 * 1000;

constructor(
@InjectDataSource() private readonly dataSource: DataSource,
Expand Down
9 changes: 7 additions & 2 deletions Backend/src/ipfs/ipfs.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ async function withRetry<T>(
} catch (err) {
lastError = err as Error;
logger?.warn(`${label} attempt ${attempt}/${maxAttempts} failed: ${lastError.message}`);
if (attempt < maxAttempts) await sleep(200 * attempt);
if (attempt < maxAttempts) await sleep(500);
}
}
throw lastError;
Expand All @@ -33,13 +33,18 @@ export class IpfsService {
private readonly logger = new Logger(IpfsService.name);
private readonly devMode: boolean;
private readonly maxRetries: number;
private readonly gateway: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private pinata: any;

constructor(private readonly config: ConfigService) {
const apiKey = this.config.get<string>('PINATA_API_KEY');
const secretKey = this.config.get<string>('PINATA_SECRET_KEY');
this.maxRetries = this.config.get<number>('IPFS_RETRY_ATTEMPTS', 3);
this.gateway = this.config.get<string>(
'ipfs.gateway',
'https://gateway.pinata.cloud/ipfs',
);
this.devMode = !apiKey || !secretKey;

if (this.devMode) {
Expand Down Expand Up @@ -74,7 +79,7 @@ export class IpfsService {

return withRetry(
async () => {
const url = `https://gateway.pinata.cloud/ipfs/${cid}`;
const url = `${this.gateway}/${cid}`;
const res = await fetch(url);
if (!res.ok) throw new Error(`IPFS fetch failed: ${res.status}`);
return res.json() as Promise<Record<string, unknown>>;
Expand Down
Loading