Активность: сообщения в проектных каналах Slack считаются действием; загрузка в data_collector, миграция 014
Some checks failed
ci / test (push) Failing after 24s
ci / deploy (push) Has been skipped

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-15 20:59:43 +03:00
parent 61001a0e46
commit a88b0c9ebf
12 changed files with 279 additions and 20 deletions

View File

@@ -0,0 +1,118 @@
import type { Pool } from "khb_common";
const SOURCE = "slack_messages";
const HUMAN_SUBTYPES = new Set([undefined, "file_share", "thread_broadcast"]);
interface SlackMessage {
ts?: string;
user?: string;
bot_id?: string;
subtype?: string;
thread_ts?: string;
reply_count?: number;
}
interface SlackPage {
ok?: boolean;
error?: string;
messages?: SlackMessage[];
response_metadata?: { next_cursor?: string };
}
export interface SyncSlackOptions {
botToken: string;
fetchFn?: typeof fetch;
now?: Date;
/** Сколько дней истории загружать для канала, по которому ещё ничего нет. */
backfillDays?: number;
/** Принудительно загрузить историю за столько дней. */
sinceDays?: number;
/** Запас назад от последнего сообщения канала (поздние сообщения, правки). */
overlapMinutes?: number;
sleep?: (ms: number) => Promise<void>;
}
export interface SyncSlackResult { channels: number; fetched: number; inserted: number; errors: { channel: string; error: string }[] }
/** Сообщение человека: без ботов и служебных подтипов (вход в канал, huddle, правки). */
export function isHumanMessage(m: SlackMessage): m is SlackMessage & { ts: string; user: string } {
return !!m.ts && !!m.user && !m.bot_id && HUMAN_SUBTYPES.has(m.subtype) && m.user !== "USLACKBOT";
}
/**
* Инкрементальная загрузка сообщений людей из проектных каналов (project_channel.track_activity) в slack_channel_message.
* Ответы в тредах берутся через conversations.replies. Канал, где бот не состоит, пропускается с записью ошибки (остальные грузятся).
*/
export async function syncSlackMessages(pool: Pool, opts: SyncSlackOptions): Promise<SyncSlackResult> {
const f = opts.fetchFn ?? fetch;
const now = opts.now ?? new Date();
const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
await pool.query("insert into activity_sync_state (source, last_started_at) values ($1, $2) on conflict (source) do update set last_started_at = $2", [SOURCE, now]);
const call = async (method: string, params: Record<string, string>): Promise<SlackPage> => {
for (let attempt = 0; ; attempt++) {
const res = await f(`https://slack.com/api/${method}?${new URLSearchParams(params)}`, { headers: { authorization: `Bearer ${opts.botToken}` } });
if (res.status === 429 && attempt < 5) {
await sleep((Number(res.headers.get("retry-after")) || 5) * 1000);
continue;
}
return (await res.json()) as SlackPage;
}
};
const pageAll = async (method: string, params: Record<string, string>): Promise<SlackMessage[]> => {
const out: SlackMessage[] = [];
let cursor = "";
do {
const page = await call(method, { ...params, limit: "200", ...(cursor ? { cursor } : {}) });
if (!page.ok) throw new Error(page.error ?? "slack error");
out.push(...(page.messages ?? []));
cursor = page.response_metadata?.next_cursor ?? "";
} while (cursor);
return out;
};
const channels = (await pool.query("select channel_id from project_channel where track_activity order by channel_id")).rows.map((r) => String(r.channel_id));
const last = new Map<string, Date>(
(await pool.query("select channel_id, max(posted_at) as m from slack_channel_message group by 1")).rows.map((r) => [String(r.channel_id), new Date(r.m)]),
);
const result: SyncSlackResult = { channels: channels.length, fetched: 0, inserted: 0, errors: [] };
for (const channel of channels) {
try {
const prev = last.get(channel);
const since = opts.sinceDays
? new Date(now.getTime() - opts.sinceDays * 86_400_000)
: prev
? new Date(prev.getTime() - (opts.overlapMinutes ?? 120) * 60_000)
: new Date(now.getTime() - (opts.backfillDays ?? 90) * 86_400_000);
const oldest = String(since.getTime() / 1000);
const top = await pageAll("conversations.history", { channel, oldest });
const all = new Map<string, SlackMessage & { reply: boolean }>();
for (const m of top) if (m.ts) all.set(m.ts, { ...m, reply: false });
for (const m of top) {
if (!m.ts || !m.reply_count) continue;
for (const r of await pageAll("conversations.replies", { channel, ts: m.ts, oldest })) {
if (r.ts && r.ts !== m.ts) all.set(r.ts, { ...r, reply: true });
}
}
const rows = [...all.values()].filter(isHumanMessage);
result.fetched += rows.length;
for (let i = 0; i < rows.length; i += 200) {
const chunk = rows.slice(i, i + 200);
const params: unknown[] = [];
const values = chunk.map((m, j) => {
params.push(channel, m.ts, m.user, new Date(Number(m.ts) * 1000), m.subtype ?? null, m.reply);
return `($${j * 6 + 1}, $${j * 6 + 2}, $${j * 6 + 3}, $${j * 6 + 4}, $${j * 6 + 5}, $${j * 6 + 6})`;
});
const res = await pool.query(
`insert into slack_channel_message (channel_id, message_ts, user_id, posted_at, subtype, is_reply) values ${values.join(", ")} on conflict (channel_id, message_ts) do nothing`,
params,
);
result.inserted += res.rowCount ?? 0;
}
} catch (e) {
result.errors.push({ channel, error: e instanceof Error ? e.message : String(e) });
}
}
const error = result.errors.length ? result.errors.map((e) => `${e.channel}: ${e.error}`).join("; ").slice(0, 1000) : null;
await pool.query("update activity_sync_state set last_success_at = $2, last_error = $3, last_loaded = $4 where source = $1", [SOURCE, new Date(), error, result.inserted]);
return result;
}