feat(notifications): dispatch Gitea webhooks through the notification service
A guild can reroute a notification type to its own channel from SQLite, with the environment values as fallback, without editing the configuration or restarting the bot.
This commit is contained in:
4 files changed
+184
-10
No files matched your search
@@ -0,0 +1,31 @@
|
||||
import { GITEA_EVENT_TYPES } from '../../config/constants.js';
|
||||
import { issueEmbed, pullRequestEmbed, pushEmbed, releaseEmbed, refEmbed } from '../gitea/gitea-embeds.js';
|
||||
|
||||
/**
|
||||
* Maps a raw Gitea webhook to `{ type, embed }`, or returns null when the event
|
||||
* should not be published (M9-T03).
|
||||
*/
|
||||
export function buildGiteaNotification(event, payload) {
|
||||
const type = GITEA_EVENT_TYPES[event];
|
||||
if (!type) return null;
|
||||
|
||||
switch (event) {
|
||||
case 'issues':
|
||||
return { type, embed: issueEmbed(payload.issue ?? payload) };
|
||||
case 'pull_request':
|
||||
return { type, embed: pullRequestEmbed(payload.pull_request ?? payload) };
|
||||
case 'push':
|
||||
if (!payload.commits?.length) return null;
|
||||
return { type, embed: pushEmbed(payload) };
|
||||
case 'create':
|
||||
case 'delete':
|
||||
return {
|
||||
type,
|
||||
embed: refEmbed(payload, payload.ref_type && event === 'delete' ? 'deleted' : 'created'),
|
||||
};
|
||||
case 'release':
|
||||
return { type, embed: releaseEmbed(payload.release ?? payload) };
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,31 @@
|
||||
import { env } from '../../config/env.js';
|
||||
import { createLogger } from '../../core/logger.js';
|
||||
import { getNotificationChannel } from '../../database/repositories/notification-repository.js';
|
||||
import { errorEmbed } from '../../ui/embeds.js';
|
||||
|
||||
const log = createLogger('notifications');
|
||||
|
||||
/** Fallback routing from the environment when the guild has no override (M9-T01). */
|
||||
const defaultChannels = {
|
||||
issues: env.channels.notifIssues,
|
||||
pull_request: env.channels.notifPullRequests,
|
||||
push: env.channels.notifCommits,
|
||||
release: env.channels.notifReleases,
|
||||
errors: env.channels.notifErrors,
|
||||
announcements: env.channels.announcements,
|
||||
community: env.channels.logs,
|
||||
};
|
||||
|
||||
// TODO(M9-T01): resolve channels from notification_channels in SQLite first.
|
||||
export function resolveChannelId(type) {
|
||||
/** SQLite override first, then the environment default (M9-T01). */
|
||||
export function resolveChannelId(type, guildId = env.discord.guildId) {
|
||||
try {
|
||||
if (guildId) {
|
||||
const override = getNotificationChannel(guildId, type);
|
||||
if (override?.channel_id) return override.channel_id;
|
||||
}
|
||||
} catch {
|
||||
// The database is unavailable (tests, early startup): use the environment.
|
||||
}
|
||||
return defaultChannels[type] ?? null;
|
||||
}
|
||||
|
||||
@@ -21,13 +34,26 @@ export async function notify(client, type, payload) {
|
||||
const channelId = resolveChannelId(type);
|
||||
if (!channelId) {
|
||||
log.debug(`No channel configured for notification type ${type}`);
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
const channel = await client.channels.fetch(channelId).catch(() => null);
|
||||
if (!channel?.isSendable()) {
|
||||
log.warn(`Notification channel unavailable for ${type}`, { channelId });
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
await channel.send(payload);
|
||||
return channel.send(payload);
|
||||
}
|
||||
|
||||
/** Reports an unexpected failure in the technical channel (M9-T07). */
|
||||
export async function notifyError(client, error, context = 'application') {
|
||||
log.error(`Notification error (${context})`, error);
|
||||
return notify(client, 'errors', {
|
||||
embeds: [
|
||||
errorEmbed(`Une erreur est survenue dans **${context}**.`).addFields({
|
||||
name: 'Détail',
|
||||
value: `\`${String(error?.message ?? error).slice(0, 500)}\``,
|
||||
}),
|
||||
],
|
||||
});
|
||||
}
|
||||
@@ -2,6 +2,9 @@ import { createHmac, timingSafeEqual } from 'node:crypto';
|
||||
import { env } from '../config/env.js';
|
||||
import { createLogger } from '../core/logger.js';
|
||||
import { getDatabase } from '../database/index.js';
|
||||
import { logEvent } from '../database/repositories/event-log-repository.js';
|
||||
import { buildGiteaNotification } from '../services/notifications/gitea-notifications.js';
|
||||
import { notify } from '../services/notifications/notification-service.js';
|
||||
|
||||
const log = createLogger('webhooks');
|
||||
|
||||
@@ -20,8 +23,8 @@ function markDelivered(deliveryId, event) {
|
||||
return result.changes > 0;
|
||||
}
|
||||
|
||||
/** Validates and dispatches a Gitea webhook. Returns the HTTP status code. */
|
||||
export async function handleGiteaWebhook(_client, headers, rawBody) {
|
||||
/** Validates, deduplicates and publishes a Gitea webhook. Returns the HTTP status code. */
|
||||
export async function handleGiteaWebhook(client, headers, rawBody) {
|
||||
if (!isValidSignature(rawBody, headers['x-gitea-signature'])) {
|
||||
log.warn('Rejected webhook with invalid signature');
|
||||
return 401;
|
||||
@@ -32,9 +35,35 @@ export async function handleGiteaWebhook(_client, headers, rawBody) {
|
||||
if (!event || !deliveryId) return 400;
|
||||
if (!markDelivered(deliveryId, event)) return 200;
|
||||
|
||||
const payload = JSON.parse(rawBody.toString('utf8'));
|
||||
log.info(`Received Gitea event ${event}`, { deliveryId, repository: payload.repository?.full_name });
|
||||
let payload;
|
||||
try {
|
||||
payload = JSON.parse(rawBody.toString('utf8'));
|
||||
} catch {
|
||||
log.warn('Rejected webhook with invalid JSON body', { deliveryId, event });
|
||||
return 400;
|
||||
}
|
||||
|
||||
log.info(`Received Gitea event ${event}`, {
|
||||
deliveryId,
|
||||
repository: payload.repository?.full_name,
|
||||
});
|
||||
|
||||
const notification = buildGiteaNotification(event, payload);
|
||||
if (!notification) {
|
||||
log.debug(`No notification mapping for Gitea event ${event}`);
|
||||
return 202;
|
||||
}
|
||||
|
||||
logEvent({
|
||||
guildId: env.discord.guildId || null,
|
||||
type: `gitea.${event}`,
|
||||
payload: { deliveryId, type: notification.type },
|
||||
});
|
||||
|
||||
await notify(client, notification.type, {
|
||||
embeds: [notification.embed],
|
||||
content: payload.repository?.full_name ? `**${payload.repository.full_name}**` : undefined,
|
||||
}).catch((error) => log.error('Could not publish the Gitea notification', error));
|
||||
|
||||
// TODO(M9-T03..T07): filter events and publish embeds through notification-service.
|
||||
return 202;
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { describe, it } from 'node:test';
|
||||
import { buildGiteaNotification } from '../src/services/notifications/gitea-notifications.js';
|
||||
import { releaseEmbed, truncate } from '../src/services/gitea/gitea-embeds.js';
|
||||
|
||||
const issue = {
|
||||
number: 12,
|
||||
title: 'Le lecteur ne démarre pas',
|
||||
body: 'Depuis la mise à jour.',
|
||||
state: 'open',
|
||||
comments: 3,
|
||||
user: { login: 'alice' },
|
||||
html_url: 'https://gitea.example/FWS/FWS-Arch/issues/12',
|
||||
labels: [{ name: 'bug' }],
|
||||
};
|
||||
|
||||
describe('buildGiteaNotification', () => {
|
||||
it('maps an issue event to the issues channel', () => {
|
||||
const notification = buildGiteaNotification('issues', { issue });
|
||||
assert.equal(notification.type, 'issues');
|
||||
assert.equal(notification.embed.data.title, '#12 Le lecteur ne démarre pas');
|
||||
assert.equal(notification.embed.data.url, issue.html_url);
|
||||
});
|
||||
|
||||
it('maps a pull request to its own type', () => {
|
||||
const notification = buildGiteaNotification('pull_request', {
|
||||
pull_request: {
|
||||
number: 4,
|
||||
title: 'Corrige le démarrage',
|
||||
state: 'open',
|
||||
user: { login: 'bob' },
|
||||
head: { ref: 'fix/boot' },
|
||||
base: { ref: 'main' },
|
||||
},
|
||||
});
|
||||
assert.equal(notification.type, 'pull_request');
|
||||
assert.match(notification.embed.data.fields[2].value, /fix\/boot → main/);
|
||||
});
|
||||
|
||||
it('reports a release with its tag', () => {
|
||||
const notification = buildGiteaNotification('release', {
|
||||
release: { tag_name: 'v1.2.0', name: 'Version 1.2.0', body: 'Nouveautés' },
|
||||
});
|
||||
assert.equal(notification.type, 'release');
|
||||
assert.equal(notification.embed.data.title, 'Version 1.2.0');
|
||||
});
|
||||
|
||||
it('ignores a push without commits', () => {
|
||||
assert.equal(buildGiteaNotification('push', { commits: [], ref: 'refs/heads/main' }), null);
|
||||
});
|
||||
|
||||
it('summarises the commits of a push', () => {
|
||||
const notification = buildGiteaNotification('push', {
|
||||
ref: 'refs/heads/main',
|
||||
sender: { login: 'carol' },
|
||||
commits: [{ id: 'abcdef1234567', message: 'fix: boot\n\nDétails' }],
|
||||
});
|
||||
assert.equal(notification.type, 'push');
|
||||
assert.equal(notification.embed.data.title, 'Push sur main');
|
||||
assert.match(notification.embed.data.description, /`abcdef1` fix: boot/);
|
||||
});
|
||||
|
||||
it('ignores events without a notification type', () => {
|
||||
assert.equal(buildGiteaNotification('repository', { repository: {} }), null);
|
||||
});
|
||||
});
|
||||
|
||||
describe('releaseEmbed', () => {
|
||||
it('keeps the notes by default and can drop them', () => {
|
||||
const release = {
|
||||
tag_name: 'v2.0.0',
|
||||
name: 'v2.0.0',
|
||||
body: 'Changements',
|
||||
published_at: '2026-01-01T10:00:00Z',
|
||||
};
|
||||
assert.equal(releaseEmbed(release).data.description, 'Changements');
|
||||
assert.equal(releaseEmbed(release, { withNotes: false }).data.description, undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe('truncate', () => {
|
||||
it('keeps short text and cuts long text', () => {
|
||||
assert.equal(truncate('court'), 'court');
|
||||
assert.equal(truncate('', 10), '');
|
||||
assert.equal(truncate('ab'.repeat(20), 10).length, 10);
|
||||
assert.match(truncate('ab'.repeat(20), 10), /…$/);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user