Skip to content
Open
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
31 changes: 31 additions & 0 deletions src/lib/match-leaders.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { MAX_CHAT } from '$lib/chat';

/** One RCON broadcast. Unknown next-map data is shown as — rather than guessed. */
export const DEFAULT_LEADERS_MESSAGE =
'LEADERS\n{kills_name} — {kills} kills\n{cash_name} — ${cash} cash\n{streak_name} — {streak_count} kill streak\n\nNEXT: {next_map}\nWeather: {next_weather}';
export const LEADERS_MESSAGE_VARS = [
'kills_name', 'kills', 'cash_name', 'cash', 'streak', 'streak_name', 'streak_count', 'next_map', 'next_weather'
] as const;
export interface LeadersMessageData {
killsName: string; kills: number; cashName: string; cash: number;
streakName?: string; streakCount?: number; nextMap?: string; nextWeather?: string;
}
export function renderLeadersMessage(template: string | undefined, data: LeadersMessageData): string {
const safe = (name: string) => name.replace(/[\r\n\t]+/g, ' ').slice(0, 80);
const streakName = data.streakCount && data.streakName ? safe(data.streakName) : '';
const count = streakName ? data.streakCount! : 0;
const source = template || DEFAULT_LEADERS_MESSAGE;
const streakSeparator = source.includes('\n') ? '\n' : ' | ';
const values: Record<string, string> = {
kills_name: safe(data.killsName), kills: String(data.kills),
cash_name: safe(data.cashName), cash: data.cash.toLocaleString('en-US'),
streak: count ? `${streakSeparator}${streakName} — ${count} kill streak` : '',
streak_name: streakName || '—', streak_count: count ? String(count) : '—',
next_map: data.nextMap ? safe(data.nextMap) : '—',
next_weather: data.nextWeather ? safe(data.nextWeather) : '—'
};
const result = source
.replace(/\{([a-z_]+)\}/gi, (match, key: string) => values[key.toLowerCase()] ?? match)
.slice(0, MAX_CHAT);
return (/[\uD800-\uDBFF]$/.test(result) ? result.slice(0, -1) : result).trim();
}
32 changes: 32 additions & 0 deletions src/lib/server/match-leaders.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { describe, expect, test } from 'bun:test';
import { nextLeaderMap, renderLeadersMessage } from './match-leaders';
import type { Rotation } from '$lib/types';
import { validateConfig } from './trigger-rules';

const leaders = { killsName: 'Carlo', kills: 41, cashName: 'Carlo', cash: 204000, streakName: 'Alex', streakCount: 17 };
describe('editable leaders message', () => {
test('older rules retain their default message, including the optional streak', () => {
expect(renderLeadersMessage(undefined, leaders)).toBe('LEADERS\nCarlo — 41 kills\nCarlo — $204,000 cash\nAlex — 17 kill streak\n\nNEXT: —\nWeather: —');
expect(renderLeadersMessage(undefined, { ...leaders, streakCount: 0 })).toBe('LEADERS\nCarlo — 41 kills\nCarlo — $204,000 cash\n— — — kill streak\n\nNEXT: —\nWeather: —');
});
test('keeps the separator in existing single-line templates', () => {
expect(renderLeadersMessage('Leaders: {kills_name}{streak}', leaders)).toBe('Leaders: Carlo | Alex — 17 kill streak');
});
test('renders a custom template safely and makes unavailable streaks explicit', () => {
expect(renderLeadersMessage('{kills_name}: {kills} / {cash_name}: {cash} / {streak_name}: {streak_count}', { ...leaders, killsName: '{cash}', streakCount: 0 })).toBe('{cash}: 41 / Carlo: 204,000 / —: —');
});
test('shows next map only when the live ordered rotation has an eligible next entry', () => {
const rotation = { enabled: true, mode: 'ordered', nowIndex: 0, nextIndex: 1, entries: [
{ map: 'Ozeti', experiences: [], lighting: '', zoneAlternator: '', denied: false, status: 'now' },
{ map: 'Bakurani', experiences: [], lighting: 'DayEarlyClear', zoneAlternator: '', denied: false, status: 'next' }
] } satisfies Rotation;
expect(nextLeaderMap(rotation)).toEqual({ nextMap: 'Bakurani', nextWeather: 'Day Early Clear' });
expect(nextLeaderMap({ ...rotation, mode: 'random' })).toEqual({ nextMap: 'Random' });
expect(nextLeaderMap({ ...rotation, nextIndex: -1 })).toEqual({});
expect(renderLeadersMessage('{next_map} / {next_weather}', { ...leaders, ...nextLeaderMap(rotation) })).toBe('Bakurani / Day Early Clear');
});
test('the server preserves a configured template when the option is disabled', () => {
expect(validateConfig('match_broadcast', { leadersAt100: true, leadersMessage: 'Winner {kills_name}' })).toMatchObject({ leadersAt100: true, leadersMessage: 'Winner {kills_name}' });
expect(validateConfig('match_broadcast', { endMessage: 'Done', leadersAt100: false, leadersMessage: 'old' })).toMatchObject({ leadersMessage: 'old' });
});
});
14 changes: 14 additions & 0 deletions src/lib/server/match-leaders.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type { Rotation } from '$lib/types';
import { mapName } from '$lib/format';
import { lightingName } from './weather-cycle';
export { renderLeadersMessage } from '$lib/match-leaders';

/** The live ordered next entry is a prediction; random selection is not known yet. */
export function nextLeaderMap(rotation: Rotation | undefined): { nextMap?: string; nextWeather?: string } {
if (!rotation?.enabled) return {};
if (rotation.mode === 'random') return { nextMap: 'Random' };
if (rotation.mode !== 'ordered' || rotation.nextIndex < 0) return {};
const next = rotation.entries[rotation.nextIndex];
if (!next || next.denied || !next.map) return {};
return { nextMap: mapName(next.map), nextWeather: next.lighting ? lightingName(next.lighting) : undefined };
}
1 change: 1 addition & 0 deletions src/lib/server/observe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -704,6 +704,7 @@ export async function observeServer(env: Env, m: ServerMemory, kinds: ObserveKin
{
server,
status: m.status,
getRotation: () => ACTIONS.rotation.run(client, {}) as Promise<import('$lib/types').Rotation>,
players: m.players,
playersObserved: players !== null,
playersIntervalMs: m.playersIntervalMs,
Expand Down
6 changes: 4 additions & 2 deletions src/lib/server/trigger-rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,8 @@ export interface SeedRewardConfig {
* builds send no score cap, so the winner is whoever led when the scores reset.
*/
export interface MatchBroadcastConfig {
leadersAt100?: boolean;
leadersMessage?: string;
/** sent for the match that ended; '' for none */
endMessage: string;
/** sent for the match now starting; '' for none */
Expand Down Expand Up @@ -423,12 +425,12 @@ export function validateConfig(kind: TriggerKind, raw: unknown): TriggerConfig {
case 'match_broadcast': {
const endMessage = str(c.endMessage, MAX_CHAT);
const startMessage = str(c.startMessage, MAX_CHAT);
if (!endMessage && !startMessage)
if (!endMessage && !startMessage && c.leadersAt100 !== true)
throw new ApiError(
400,
'Add a message for the match ending, the next one starting, or both.'
);
return { endMessage, startMessage, minPlayers: int(c.minPlayers, 1, 0, 1000) };
return { endMessage, startMessage, minPlayers: int(c.minPlayers, 1, 0, 1000), ...(c.leadersAt100 === true ? { leadersAt100: true } : {}), ...(str(c.leadersMessage, MAX_CHAT) ? { leadersMessage: str(c.leadersMessage, MAX_CHAT) } : {}) };
}
case 'name_filter':
return validateNameFilter(c);
Expand Down
6 changes: 6 additions & 0 deletions src/lib/server/triggers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1002,3 +1002,9 @@ describe('matchReplay', () => {
expect(ends[2].end.leaders).toEqual(['A', 'B']);
});
});

test('match leaders are opt-in and can be the only match broadcast', () => {
const leaders = validateConfig('match_broadcast', { endMessage: '', startMessage: '', leadersAt100: true, leadersMessage: '{kills_name}: {kills}' });
expect(leaders).toMatchObject({ leadersAt100: true, leadersMessage: '{kills_name}: {kills}' });
expect(validateConfig('match_broadcast', { endMessage: 'Done', startMessage: '' })).not.toHaveProperty('leadersAt100');
});
51 changes: 49 additions & 2 deletions src/lib/server/triggers.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { nextLeaderMap, renderLeadersMessage } from './match-leaders';
import { feedRecord, type FeedKill } from './match-players';
// Automation: per-server triggers the worker evaluates on every observation, all
// built on what the worker already sees (joins, player counts, empty stretches) plus the Steam cache:
// welcome whisper a message to players as they join (or once they have picked a faction)
Expand Down Expand Up @@ -54,6 +56,7 @@ import { writeAudit } from './audit';
import { emit } from './events';
import {
kills,
matches,
outbox,
playerSessions,
samples,
Expand Down Expand Up @@ -624,6 +627,7 @@ async function dropQueued(env: Env, triggerId: string, why: string): Promise<voi
// delivers them). Evaluation itself makes no game request.

export interface TickContext {
getRotation?: () => Promise<import('$lib/types').Rotation>;
server: ServerRow;
status: Status;
players: Player[];
Expand Down Expand Up @@ -898,7 +902,7 @@ export async function evaluateTriggers(
await evalSeedReward(env, ctx, row, row.config as SeedRewardConfig, out, read);
break;
case 'match_broadcast':
evalMatchBroadcast(ctx, row, row.config as MatchBroadcastConfig, out);
await evalMatchBroadcast(env, ctx, row, row.config as MatchBroadcastConfig, out);
break;
case 'name_filter':
await evalNameFilter(ctx, row, row.config as NameFilterConfig, out, read);
Expand Down Expand Up @@ -2037,12 +2041,55 @@ export function forgetRuleMemory(): void {
forgetBounties();
}

function evalMatchBroadcast(
/** Once per recorded match, while the scoreboard still shows the finished round. */
async function announceLeadersAt100(env: Env, ctx: TickContext, row: TriggerRow, cfg: MatchBroadcastConfig, out: Evaluation) {
if (!cfg.leadersAt100 || ctx.matchEnd || ctx.status.playerCount < cfg.minPlayers ||
!ctx.status.scores.some((side) => side.score >= 100)) return;
const [match] = await env.db.select({ id: matches.id, map: matches.map }).from(matches)
.where(and(eq(matches.serverId, ctx.server.id), isNull(matches.endedAt))).limit(1);
if (!match || match.map !== ctx.status.map) return;
const state = (row.state ?? {}) as Record<string, unknown>;
if (state.leadersMatchId === match.id) return;
const players = ctx.players.filter((p) => p.name && p.steamId);
if (!players.length) return;
const byKills = [...players].sort((a, b) => b.kills - a.kills || a.name.localeCompare(b.name))[0];
const byCash = [...players].sort((a, b) => b.cash - a.cash || a.name.localeCompare(b.name))[0];
const events = await env.db.select({ killerSteamId: kills.killerSteamId, victimSteamId: kills.victimSteamId,
headshot: kills.headshot, suicide: kills.suicide, teamKill: kills.teamKill,
cause: kills.cause, distanceM: kills.distanceM }).from(kills)
.where(and(eq(kills.serverId, ctx.server.id), eq(kills.matchRow, match.id)))
.orderBy(asc(kills.eventTime), asc(kills.ts));
const streaks = feedRecord(events as FeedKill[]);
const streak = players.map((p) => ({ player: p, count: streaks.get(p.steamId)?.killStreak ?? 0 }))
.sort((a, b) => b.count - a.count || a.player.name.localeCompare(b.player.name))[0];
let next: { nextMap?: string; nextWeather?: string } = {};
try { next = nextLeaderMap(await ctx.getRotation?.()); }
catch { /* A missing rotation must not suppress the leaders. */ }
const message = renderLeadersMessage(cfg.leadersMessage, {
...next,
killsName: byKills.name, kills: byKills.kills, cashName: byCash.name, cash: byCash.cash,
streakName: streak?.player.name, streakCount: streak?.count
});
if (!message) return;
out.intents.push({ trigger: row, action: 'broadcast', params: { message }, target: message,
okMessage: 'Match leaders broadcast sent.', detail: { stage: 'leaders', matchId: match.id },
steamId: null, dedupeKey: key(row, 'leaders', match.id) });
row.state = { ...state, leadersMatchId: match.id };
out.updates.push({ id: row.id, state: row.state, lastFiredAt: ctx.ts, lastResult: 'Sending match leaders at 100 points' });
}

async function evalMatchBroadcast(
env: Env,
ctx: TickContext,
row: TriggerRow,
cfg: MatchBroadcastConfig,
out: Evaluation
) {
try {
await announceLeadersAt100(env, ctx, row, cfg, out);
} catch (err) {
console.warn('[warcon] match leaders:', forLog(err));
}
const step = matchBroadcastStep(
matchHeld.get(row.id) ?? null,
ctx.matchEnd,
Expand Down
8 changes: 8 additions & 0 deletions src/routes/(app)/server/[id]/automation/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -536,6 +536,8 @@
leadMinutes: number;
leadMessage: string;
repeatMinutes: number;
leadersAt100: boolean;
leadersMessage: string;
endMessage: string;
startMessage: string;
warnAt: number;
Expand Down Expand Up @@ -802,6 +804,8 @@
'Scheduled restart in about {minutes} minutes, at the end of the round then in progress.'
),
repeatMinutes: n('repeatMinutes', 0),
leadersAt100: b('leadersAt100', false),
leadersMessage: s('leadersMessage', ''),
endMessage: s('endMessage', 'Match over: {faction} wins on {previous} · {scores}'),
startMessage: s('startMessage', 'New match on {map}. Good luck!'),
warnAt: n('warnAt', 2),
Expand Down Expand Up @@ -1008,6 +1012,8 @@
};
case 'match_broadcast':
return {
leadersAt100: f.leadersAt100,
leadersMessage: f.leadersMessage,
endMessage: f.endMessage,
startMessage: f.startMessage,
minPlayers: Number(f.minPlayers)
Expand Down Expand Up @@ -2295,6 +2301,8 @@
{restartNote} See Game restart on the Settings tab.
</p>
{:else if f.kind === 'match_broadcast'}
<label class="flex items-center gap-2"><input type="checkbox" bind:checked={f.leadersAt100} /> Show match leaders when a faction reaches 100 points</label>
{#if f.leadersAt100}<label class="field-label" for="leaders-message">Leaders message</label><textarea id="leaders-message" class="input min-h-28 font-mono" bind:value={f.leadersMessage} maxlength={MAX_CHAT} placeholder="Leave blank for the default message"></textarea><p class="note">Optional placeholders: {'{kills_name}'}, {'{kills}'}, {'{cash_name}'}, {'{cash}'}, {'{streak}'}, {'{streak_name}'}, {'{streak_count}'}, {'{next_map}'}, {'{next_weather}'}. Sent once per match while scores are visible.</p>{/if}
<fieldset class="space-y-2">
<legend class="field-label">When a match ends</legend>
<input
Expand Down