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
24 changes: 22 additions & 2 deletions .github/workflows/sync-data.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,17 @@ jobs:
with:
node-version: 22

- name: Test the sync script
run: node --test scripts/sync-data.test.mjs
- name: Test the sync scripts
run: node --test scripts/sync-data.test.mjs scripts/notify-discord.test.mjs

- name: Dry run
if: github.event_name == 'pull_request'
run: node scripts/sync-data.mjs --dry-run

- name: Keep the current fusion data to compare against
if: github.event_name != 'pull_request'
run: cp fusion-data.json "$RUNNER_TEMP/fusion-before.json"

- name: Build and check data
id: sync
if: github.event_name != 'pull_request'
Expand All @@ -48,6 +52,22 @@ jobs:
STATUS: ${{ steps.sync.outputs.status }}
run: bash scripts/publish-sync.sh "$STATUS" "$RUNNER_TEMP/sync-report.md"

- name: Ping Discord about new shard recipes
if: steps.sync.outputs.status == 'publish' || steps.sync.outputs.status == 'review'
# A Discord outage shouldn't mark the sync as failed.
continue-on-error: true
env:
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_WEBHOOK_URL }}
DISCORD_PING_ID: ${{ secrets.DISCORD_PING_ID }}
SITE_URL: https://lyn-flipper.vercel.app
STATUS: ${{ steps.sync.outputs.status }}
run: |
if [ -z "$DISCORD_WEBHOOK_URL" ]; then
echo 'No DISCORD_WEBHOOK_URL secret, skipping.'
exit 0
fi
node scripts/notify-discord.mjs "$RUNNER_TEMP/fusion-before.json" fusion-data.json --status "$STATUS"

- name: Report failure
if: failure() && github.event_name != 'pull_request'
env:
Expand Down
63 changes: 63 additions & 0 deletions .github/workflows/watch-fusion-data.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
name: Watch fusion data

# SkyShards-Parser isn't ours, so its pushes can't trigger us. Instead this checks
# every 15 minutes whether its fusion-data.json differs from ours, and runs the full
# sync only when it does. Most runs take a few seconds and do nothing.

on:
schedule:
- cron: '*/15 * * * *'
workflow_dispatch:

permissions:
actions: write
contents: read

concurrency:
group: watch-fusion-data

jobs:
check:
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Compare upstream fusion-data.json with ours
id: compare
env:
GH_TOKEN: ${{ github.token }}
run: |
# The sync saves the upstream file byte for byte, so equal blob SHAs mean equal data.
upstream=$(gh api repos/Campionnn/SkyShards-Parser/contents/dist/fusion-data.json --jq .sha)
ours=$(gh api "repos/$GITHUB_REPOSITORY/contents/fusion-data.json?ref=main" --jq .sha)
echo "upstream $upstream, ours $ours"
echo "upstream=$upstream" >> "$GITHUB_OUTPUT"
[ "$upstream" != "$ours" ] && echo changed=true >> "$GITHUB_OUTPUT" || true

# Trigger once per upstream version. Without this, a change held for review
# (or a failing sync) would start a new sync every 15 minutes; the 6-hour
# schedule in sync-data.yml still retries those.
- name: Check whether this version was already handed to the sync
if: steps.compare.outputs.changed == 'true'
id: seen
uses: actions/cache/restore@v4
with:
path: .fusion-seen
key: fusion-seen-${{ steps.compare.outputs.upstream }}
lookup-only: true

- name: Run the sync
if: steps.compare.outputs.changed == 'true' && steps.seen.outputs.cache-hit != 'true'
env:
GH_TOKEN: ${{ github.token }}
run: gh workflow run sync-data.yml --repo "$GITHUB_REPOSITORY" --ref main

- name: Remember this version
if: steps.compare.outputs.changed == 'true' && steps.seen.outputs.cache-hit != 'true'
run: echo "${{ steps.compare.outputs.upstream }}" > .fusion-seen

- name: Save
if: steps.compare.outputs.changed == 'true' && steps.seen.outputs.cache-hit != 'true'
uses: actions/cache/save@v4
with:
path: .fusion-seen
key: fusion-seen-${{ steps.compare.outputs.upstream }}
125 changes: 125 additions & 0 deletions scripts/notify-discord.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
#!/usr/bin/env node
// Pings a Discord webhook when a sync adds shard fusion recipes or new shards.
// Run by .github/workflows/sync-data.yml after publish-sync.sh.
//
// node scripts/notify-discord.mjs <old fusion-data.json> <new fusion-data.json> [--status publish|review] [--dry-run]
//
// The webhook URL comes from $DISCORD_WEBHOOK_URL, and an optional @mention from
// $DISCORD_PING_ID (a user ID, or role:<role ID>). With --dry-run (or no URL) it
// prints the message instead of sending it. Sends nothing when no recipes were added.

import fs from 'node:fs';
import { pathToFileURL } from 'node:url';
import { uniqueFusions } from './sync-data.mjs';

const MAX_OUTPUTS = 15; // outputs listed before "and N more"
const MAX_PAIRS_SHOWN = 3; // example input pairs per output
const MAX_DESCRIPTION = 4000; // Discord caps embed descriptions at 4096

/** New shards and added recipes grouped by output shard, newest data's names. */
export function diffFusions(before, after) {
const old = before ? uniqueFusions(before) : new Set();
const byOutput = new Map();
for (const key of uniqueFusions(after)) {
if (old.has(key)) continue;
const [output, qty, a, b] = key.split('|');
const group = byOutput.get(output) || { output, qty: new Set(), pairs: [] };
group.qty.add(qty);
group.pairs.push([a, b]);
byOutput.set(output, group);
}
const newShards = Object.keys(after.shards).filter(code => !before?.shards?.[code]);
const added = [...byOutput.values()].sort((x, y) => y.pairs.length - x.pairs.length);
return { newShards, added, total: added.reduce((n, g) => n + g.pairs.length, 0) };
}

export function buildMessage(diff, shards, { status = 'publish', siteUrl, reviewUrl } = {}) {
const name = code => shards[code]?.name || code;
const lines = [];
if (diff.newShards.length) lines.push(`**New shards:** ${diff.newShards.map(name).join(', ')}`, '');
for (const g of diff.added.slice(0, MAX_OUTPUTS)) {
const qty = [...g.qty].join('/');
const examples = g.pairs.slice(0, MAX_PAIRS_SHOWN).map(([a, b]) => `${name(a)} + ${name(b)}`).join(', ');
const more = g.pairs.length > MAX_PAIRS_SHOWN ? `, +${g.pairs.length - MAX_PAIRS_SHOWN} more` : '';
lines.push(`**${name(g.output)}** x${qty}: ${examples}${more}`);
}
if (diff.added.length > MAX_OUTPUTS) lines.push(`…and ${diff.added.length - MAX_OUTPUTS} more shards with new recipes`);

let description = lines.join('\n');
if (description.length > MAX_DESCRIPTION) description = `${description.slice(0, MAX_DESCRIPTION - 1)}…`;

const review = status === 'review';
const title = `${diff.total.toLocaleString('en')} new shard recipe${diff.total === 1 ? '' : 's'}`
+ (review ? ' (held for review)' : '');
return {
username: 'lyns-flipper',
embeds: [{
title,
url: review ? reviewUrl : siteUrl,
description,
color: review ? 0xf1c40f : 0x2ecc71,
footer: { text: review ? 'Not live yet: the sync flagged this change for review.' : 'Live on the site now.' },
timestamp: new Date().toISOString(),
}],
};
}

async function main() {
const args = process.argv.slice(2);
const flag = name => (args.includes(name) ? args[args.indexOf(name) + 1] : undefined);
const dryRun = args.includes('--dry-run');
const [beforeFile, afterFile] = args.filter((a, i) => !a.startsWith('--') && !args[i - 1]?.startsWith('--status'));
if (!beforeFile || !afterFile) throw new Error('usage: notify-discord.mjs <old fusion-data.json> <new fusion-data.json> [--status publish|review] [--dry-run]');

const read = file => {
try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return undefined; }
};
const before = read(beforeFile), after = read(afterFile);
if (!after) throw new Error(`can't read ${afterFile}`);

const diff = diffFusions(before, after);
if (!diff.total && !diff.newShards.length) {
console.log('No new shard recipes, nothing to send.');
return;
}

const repo = process.env.GITHUB_REPOSITORY;
const message = buildMessage(diff, after.shards, {
status: flag('--status'),
siteUrl: process.env.SITE_URL || (repo ? `https://github.com/${repo}` : undefined),
reviewUrl: repo ? `https://github.com/${repo}/compare/main...data-sync-review` : undefined,
});

// Optional ping: a user ID (123...) or a role ID written as "role:123...".
const ping = (process.env.DISCORD_PING_ID || '').trim();
if (/^\d{17,20}$/.test(ping)) {
message.content = `<@${ping}>`;
message.allowed_mentions = { users: [ping] };
} else if (/^role:\d{17,20}$/.test(ping)) {
message.content = `<@&${ping.slice(5)}>`;
message.allowed_mentions = { roles: [ping.slice(5)] };
} else if (ping) {
console.warn('DISCORD_PING_ID should be a user ID or role:<role ID>, ignoring it.');
}

const webhook = process.env.DISCORD_WEBHOOK_URL;
if (dryRun || !webhook) {
if (!webhook && !dryRun) console.log('DISCORD_WEBHOOK_URL is not set, printing instead of sending.');
console.log(JSON.stringify(message, null, 2));
return;
}
const resp = await fetch(webhook, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(message),
});
if (!resp.ok) throw new Error(`Discord returned ${resp.status}: ${(await resp.text()).slice(0, 200)}`);
console.log(`Sent: ${message.embeds[0].title}`);
}

if (import.meta.url === pathToFileURL(process.argv[1]).href) {
main().catch(e => {
console.error(e.message);
process.exitCode = 1;
});
}
43 changes: 43 additions & 0 deletions scripts/notify-discord.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { buildMessage, diffFusions } from './notify-discord.mjs';

const shards = {
A: { name: 'Grove' }, B: { name: 'Bezal' }, C: { name: 'Sun Fish' }, D: { name: 'Galaxy Fish' },
};
const before = { shards: { A: shards.A, B: shards.B, C: shards.C }, recipes: { C: { 2: [['A', 'B']] } } };

test('no added recipes means nothing to send', () => {
const swapped = { shards: before.shards, recipes: { C: { 2: [['B', 'A']] } } };
const diff = diffFusions(before, swapped);
assert.equal(diff.total, 0);
assert.deepEqual(diff.newShards, []);
});

test('finds new shards and new recipes grouped by output', () => {
const after = { shards, recipes: { C: { 2: [['A', 'B'], ['A', 'D']] }, D: { 1: [['A', 'C'], ['B', 'C']] } } };
const diff = diffFusions(before, after);
assert.deepEqual(diff.newShards, ['D']);
assert.equal(diff.total, 3);
assert.deepEqual(diff.added.map(g => [g.output, g.pairs.length]), [['D', 2], ['C', 1]]);
});

test('message names shards and marks reviews', () => {
const after = { shards, recipes: { C: { 2: [['A', 'B']] }, D: { 1: [['A', 'C']] } } };
const live = buildMessage(diffFusions(before, after), shards, { status: 'publish' });
assert.match(live.embeds[0].title, /^1 new shard recipe$/);
assert.match(live.embeds[0].description, /New shards:\*\* Galaxy Fish/);
assert.match(live.embeds[0].description, /\*\*Galaxy Fish\*\* x1: Grove \+ Sun Fish/);
const held = buildMessage(diffFusions(before, after), shards, { status: 'review' });
assert.match(held.embeds[0].title, /held for review/);
});

test('long messages stay under the Discord limit', () => {
const many = { shards: { ...shards }, recipes: {} };
for (let i = 0; i < 200; i++) {
many.shards[`X${i}`] = { name: `Shard ${'x'.repeat(200)} ${i}` };
many.recipes[`X${i}`] = { 1: [['A', 'B'], ['A', 'C'], ['B', 'C'], ['A', 'A']] };
}
const msg = buildMessage(diffFusions(before, many), many.shards);
assert.ok(msg.embeds[0].description.length <= 4096);
});
Loading