Remove SCUM sqlite user projections

This commit is contained in:
npc0-hue
2026-09-14 13:41:44 +08:00
parent b1f102bafb
commit ecdca8e28b
76 changed files with 2264 additions and 1558 deletions
@@ -14,71 +14,19 @@ export type GameClientActions = {
export type PluginBridgeExecuteEnvelope = { requestId: string; action: string; payload?: Record<string, string> };
export type PluginBridgeExecutionResult = { status?: string; result?: Record<string, string>; error?: { message?: string } };
export type SCUMQueryTemplateKey = "scum.player.profile" | "scum.squads" | "scum.squad-members" | "scum.vehicles" | "scum.flags" | "scum.positions" | "scum.tasks" | "scum.events" | "scum.native-timed-gifts";
export const playerAttributeCatalog = [
{ key: "stamina", label: "体力", column: "stamina", sourceKeys: ["attributes.stamina", "stamina", "体力"] },
{ key: "dexterity", label: "敏捷", column: "dexterity", sourceKeys: ["attributes.dexterity", "dexterity", "敏捷"] },
{ key: "intelligence", label: "智力", column: "intelligence", sourceKeys: ["attributes.intelligence", "intelligence", "智力"] }
] as const;
export type PlayerAttributeDraft = { fieldKey: string; label: string; before: string; after: string };
export function playerAttributeDrafts(player: RecordMap): PlayerAttributeDraft[] {
return playerAttributeCatalog.map((field) => ({ fieldKey: field.key, label: field.label, before: firstText(player, ...field.sourceKeys), after: firstText(player, ...field.sourceKeys) }));
}
export function playerAttributeSqlPreview(drafts: PlayerAttributeDraft[]): string {
const changes = drafts.filter((draft) => draft.after.trim() && draft.after.trim() !== draft.before.trim());
if (!changes.length) return "等待输入要提交的属性变更。";
return buildPlayerAttributeSqlText({ gamePlayerId: ":playerId" }, changes.flatMap((draft) => {
const definition = playerAttributeCatalog.find((candidate) => candidate.key === draft.fieldKey);
const after = Number(draft.after);
return definition && Number.isFinite(after) ? [{ column: definition.column, after }] : [];
}));
}
export function buildPlayerAttributeMutation(player: RecordMap, drafts: PlayerAttributeDraft[]): RecordMap {
const playerId = firstText(player, "steamId", "gamePlayerId", "playerId", "userProfileId", "id");
if (!playerId) throw new Error("用户没有可用的 Steam ID 或游戏用户编号。");
const changes = drafts.filter((draft) => draft.after.trim() && draft.after.trim() !== draft.before.trim()).map((draft) => {
const definition = playerAttributeCatalog.find((candidate) => candidate.key === draft.fieldKey);
const before = draft.before.trim() ? Number(draft.before) : Number.NaN;
const after = Number(draft.after);
if (!definition || !Number.isFinite(after)) throw new Error(`${draft.label}目标值必须是数字。`);
return { fieldKey: draft.fieldKey, label: draft.label, column: definition.column, before: Number.isFinite(before) ? before : null, after };
});
if (!changes.length) throw new Error("至少填写一项与当前值不同的属性。");
const idempotencyKey = safeCommandId(`player-attributes:${playerId}:${changes.map((change) => `${change.fieldKey}:${change.after}`).join(",")}:${Date.now()}`);
return { playerId, reason: "管理员在 SCUM 用户管理中编辑属性", sqlText: buildPlayerAttributeSqlText(player, changes), changes, idempotencyKey };
}
export async function queuePlayerAttributePatch(actions: SCUMWorkspaceActions, player: RecordMap, drafts: PlayerAttributeDraft[]): Promise<unknown> {
if (!actions.dispatch) throw new Error("通用 remote.access.request 能力不可用,无法提交 SQL 执行任务。");
const mutation = buildPlayerAttributeMutation(player, drafts);
const idempotencyKey = textValue(mutation.idempotencyKey);
const result = await actions.dispatch({
requestId: idempotencyKey,
action: "remote.access.request",
payload: {
capability: "remote.run.db.sqlite.execute",
declarationKey: "scum-database",
targetKey: "scum-database",
idempotencyKey,
timeoutSeconds: "60",
maxAttempts: "1",
"input.mode": "execute",
"input.sqlText": textValue(mutation.sqlText),
"input.reason": textValue(mutation.reason)
}
});
if (result?.status && !["queued", "ok"].includes(result.status)) throw new Error(result.error?.message || "SQL 执行任务未进入 Run 队列。");
return result;
}
export type SCUMPlatformActions = {
users: (query?: { limit?: number; changedAfter?: string; online?: boolean; steamId?: string }) => Promise<unknown>;
vehicles: (query?: { limit?: number; changedAfter?: string; exists?: boolean; gameVehicleId?: string }) => Promise<unknown>;
userTrajectories: (query?: { limit?: number; after?: string; steamId?: string; scumUserId?: string }) => Promise<unknown>;
vehicleTrajectories: (query?: { limit?: number; after?: string; gameVehicleId?: string; scumVehicleId?: string }) => Promise<unknown>;
vehicleLocks: (query?: { limit?: number; after?: string; gameVehicleId?: string; scumVehicleId?: string; scumUserId?: string; steamId?: string }) => Promise<unknown>;
};
export type SCUMWorkspaceActions = {
pluginData?: PluginDataActions;
gameClient?: GameClientActions;
scum?: SCUMPlatformActions;
dispatch?: (envelope: PluginBridgeExecuteEnvelope, signal?: AbortSignal) => Promise<PluginBridgeExecutionResult>;
};
@@ -103,17 +51,17 @@ export type SCUMSurfaceData = {
mapRegions: RecordMap[];
mapSettings: RecordMap[];
vehicles: RecordMap[];
vehicleLocks: RecordMap[];
flags: RecordMap[];
trajectories: RecordMap[];
};
export const emptySCUMSurfaceData: SCUMSurfaceData = {
players: [], squads: [], members: [], events: [], eventProduces: [], eventRuns: [], nativeEventRounds: [], tasks: [], activityEvents: [],
tradeGoods: [], tradeEvents: [], gifts: [], giftClaims: [], pendingGifts: [], giftDeliveries: [], timedGiftEvents: [], mapPoints: [], mapRegions: [], mapSettings: [], vehicles: [], flags: [], trajectories: []
tradeGoods: [], tradeEvents: [], gifts: [], giftClaims: [], pendingGifts: [], giftDeliveries: [], timedGiftEvents: [], mapPoints: [], mapRegions: [], mapSettings: [], vehicles: [], vehicleLocks: [], flags: [], trajectories: []
};
export const scumCollections = {
players: "scum_users",
squads: "scum_squads",
members: "scum_squad_members",
events: "scum_activity_definitions",
@@ -132,151 +80,53 @@ export const scumCollections = {
mapPoints: "scum_map_points",
mapRegions: "scum_map_regions",
mapSettings: "scum_map_settings",
vehicles: "scum_vehicles",
flags: "scum_flags",
trajectories: "scum_trajectories"
flags: "scum_flags"
} as const;
type SurfaceKey = keyof SCUMSurfaceData;
type PageKey = "players" | "squads" | "live-map" | "gifts" | "workflows";
type PluginCollectionSurfaceKey = keyof typeof scumCollections;
type SCUMPlatformSurfaceKey = "players" | "vehicles" | "trajectories" | "vehicleLocks";
const pageCollections: Record<PageKey, SurfaceKey[]> = {
players: ["players", "members", "activityEvents", "giftClaims", "pendingGifts", "giftDeliveries", "trajectories", "vehicles"],
const pageCollections: Record<PageKey, PluginCollectionSurfaceKey[]> = {
players: ["members", "activityEvents", "giftClaims", "pendingGifts", "giftDeliveries"],
squads: ["squads", "members", "flags"],
"live-map": ["mapPoints", "mapRegions", "mapSettings", "players", "vehicles", "flags", "trajectories", "tradeGoods"],
gifts: ["gifts", "giftClaims", "pendingGifts", "giftDeliveries", "timedGiftEvents", "players", "tradeGoods"],
"live-map": ["mapPoints", "mapRegions", "mapSettings", "flags", "tradeGoods"],
gifts: ["gifts", "giftClaims", "pendingGifts", "giftDeliveries", "timedGiftEvents", "tradeGoods"],
workflows: ["events", "eventProduces", "eventRuns", "nativeEventRounds", "tasks", "activityEvents", "tradeGoods", "tradeEvents"]
};
const pageQueryTemplates: Record<PageKey, SCUMQueryTemplateKey[]> = {
players: ["scum.player.profile", "scum.positions"],
squads: ["scum.squads", "scum.squad-members", "scum.flags"],
"live-map": ["scum.player.profile", "scum.vehicles", "scum.flags", "scum.positions"],
gifts: ["scum.player.profile", "scum.native-timed-gifts"],
workflows: ["scum.player.profile", "scum.squads", "scum.squad-members", "scum.vehicles", "scum.flags", "scum.positions", "scum.tasks", "scum.events", "scum.native-timed-gifts"]
const pageSCUMTables: Record<PageKey, SCUMPlatformSurfaceKey[]> = {
players: ["players", "vehicles", "trajectories", "vehicleLocks"],
squads: ["players"],
"live-map": ["players", "vehicles", "trajectories", "vehicleLocks"],
gifts: ["players"],
workflows: ["players", "vehicles", "trajectories", "vehicleLocks"]
};
const queryTemplatePollSeconds: Record<SCUMQueryTemplateKey, number> = {
"scum.player.profile": 5,
"scum.positions": 5,
"scum.vehicles": 5,
"scum.flags": 60,
"scum.squads": 1800,
"scum.squad-members": 1800,
"scum.tasks": 1800,
"scum.events": 1800,
"scum.native-timed-gifts": 60
};
const queryTemplateMaxRows: Record<SCUMQueryTemplateKey, number> = {
"scum.player.profile": 500,
"scum.positions": 500,
"scum.vehicles": 500,
"scum.flags": 500,
"scum.squads": 500,
"scum.squad-members": 500,
"scum.tasks": 500,
"scum.events": 500,
"scum.native-timed-gifts": 500
};
const queuedQueryBuckets = new Set<string>();
export async function loadSCUMSurface(actions: SCUMWorkspaceActions, pageKey: string): Promise<SCUMSurfaceData> {
if (!actions.pluginData) throw new Error("通用 pluginData 能力不可用。");
const canonical = canonicalPageKey(pageKey);
void queueSCUMDatabaseRefresh(actions, canonical).catch(() => undefined);
const data: SCUMSurfaceData = { ...emptySCUMSurfaceData };
const keys = pageCollections[canonical];
const records = await Promise.all(keys.map(async (key) => [key, await actions.pluginData!.list(scumCollections[key])] as const));
for (const [key, response] of records) data[key] = collectionRecords(response);
await mergeSCUMSnapshots(actions, data, keys).catch(() => undefined);
if (keys.length) {
const pluginData = requirePluginData(actions);
const records = await Promise.all(keys.map(async (key) => [key, await pluginData.list(scumCollections[key])] as const));
for (const [key, response] of records) data[key] = collectionRecords(response);
}
await loadPlatformSCUMTables(actions, data, pageSCUMTables[canonical]);
return data;
}
export async function queueSCUMDatabaseRefresh(actions: SCUMWorkspaceActions, pageKey: string, now = Date.now()): Promise<PluginBridgeExecutionResult[]> {
if (!actions.dispatch) return [];
const canonical = canonicalPageKey(pageKey);
const templates = [...new Set(pageQueryTemplates[canonical])];
const requests = templates.flatMap((templateKey) => {
const bucketKey = scumQueryBucketKey(templateKey, now);
if (queuedQueryBuckets.has(bucketKey)) return [];
queuedQueryBuckets.add(bucketKey);
return [actions.dispatch!({ requestId: scumQueryRequestId(canonical, templateKey, now), action: "remote.access.request", payload: scumQueryPayload(templateKey, now) })];
});
const settled = await Promise.allSettled(requests);
return settled.flatMap((item) => item.status === "fulfilled" ? [item.value] : []);
}
function scumQueryPayload(templateKey: SCUMQueryTemplateKey, now: number): Record<string, string> {
const maxRows = String(queryTemplateMaxRows[templateKey]);
const payload: Record<string, string> = {
capability: "remote.run.db.sqlite.query",
declarationKey: "scum-database",
targetKey: "scum-database",
idempotencyKey: scumQueryIdempotencyKey(templateKey, now),
timeoutSeconds: "15",
maxAttempts: "1",
"input.templateKey": templateKey,
"input.limit": maxRows,
"input.maxRows": maxRows
};
if (templateKey === "scum.player.profile" || templateKey === "scum.positions" || templateKey === "scum.vehicles") payload["input.activeWithinSeconds"] = "600";
return payload;
}
function scumQueryRequestId(pageKey: PageKey, templateKey: SCUMQueryTemplateKey, now: number): string { return `scum-query:${pageKey}:${templateKey}:${queryBucket(templateKey, now)}`; }
function scumQueryIdempotencyKey(templateKey: SCUMQueryTemplateKey, now: number): string { return `scum-query:${templateKey}:${queryBucket(templateKey, now)}`; }
function scumQueryBucketKey(templateKey: SCUMQueryTemplateKey, now: number): string { return `${templateKey}:${queryBucket(templateKey, now)}`; }
function queryBucket(templateKey: SCUMQueryTemplateKey, now: number): number { return Math.floor(now / (queryTemplatePollSeconds[templateKey] * 1000)); }
async function mergeSCUMSnapshots(actions: SCUMWorkspaceActions, data: SCUMSurfaceData, keys: SurfaceKey[]): Promise<void> {
if (!actions.gameClient) return;
async function loadPlatformSCUMTables(actions: SCUMWorkspaceActions, data: SCUMSurfaceData, keys: SCUMPlatformSurfaceKey[]): Promise<void> {
if (!keys.length) return;
if (!actions.scum) throw new Error("平台 SCUM 数据能力不可用。");
const reads: Array<Promise<void>> = [];
if (keys.includes("players") && data.players.length === 0) reads.push(actions.gameClient.snapshots({ profileKey: "plugin-owned", type: "players", streamKey: "current", limit: 1 }).then((response) => { data.players = mergePlayerSnapshots(data.players, response); }));
if (keys.includes("vehicles") && data.vehicles.length === 0) reads.push(actions.gameClient.snapshots({ profileKey: "plugin-owned", type: "vehicles", streamKey: "current", limit: 1 }).then((response) => { data.vehicles = mergeVehicleSnapshots(data.vehicles, response); }));
if (keys.includes("players")) reads.push(actions.scum.users({ limit: 500 }).then((response) => { data.players = collectionRecords(response); }));
if (keys.includes("vehicles")) reads.push(actions.scum.vehicles({ limit: 500 }).then((response) => { data.vehicles = collectionRecords(response); }));
if (keys.includes("vehicleLocks")) reads.push(actions.scum.vehicleLocks({ limit: 500 }).then((response) => { data.vehicleLocks = collectionRecords(response); }));
if (keys.includes("trajectories")) reads.push(Promise.all([actions.scum.userTrajectories({ limit: 500 }), actions.scum.vehicleTrajectories({ limit: 500 })]).then(([players, vehicles]) => { data.trajectories = [...collectionRecords(players), ...collectionRecords(vehicles)]; }));
await Promise.all(reads);
}
export function mergePlayerSnapshots(players: RecordMap[], playersResponse: unknown): RecordMap[] {
const playerSnapshot = latestSnapshotPayload(playersResponse);
const merged = players.map((player) => ({ ...player }));
const snapshotPlayers = Array.isArray(playerSnapshot?.players) ? playerSnapshot.players.filter(isRecord) : [];
if (snapshotPlayers.length) {
const byIdentity = playerIndex(merged);
for (const snapshotPlayer of snapshotPlayers) {
const match = findPlayer(byIdentity, snapshotPlayer);
const value = { ...(match ? merged[match.index] : {}), ...snapshotPlayer, online: onlineValue(snapshotPlayer), onlineObservedAt: textValue(playerSnapshot?.observedAt) };
if (match) merged[match.index] = value;
else {
const created = { ...value, gamePlayerId: firstText(snapshotPlayer, "gamePlayerId", "playerId", "steamId", "id") };
merged.push(created);
addPlayerToIndex(byIdentity, created, merged.length - 1);
}
}
}
return merged;
}
export function mergeVehicleSnapshots(vehicles: RecordMap[], vehiclesResponse: unknown): RecordMap[] {
const vehicleSnapshot = latestSnapshotPayload(vehiclesResponse);
const merged = vehicles.map((vehicle) => ({ ...vehicle }));
const snapshotVehicles = Array.isArray(vehicleSnapshot?.vehicles) ? vehicleSnapshot.vehicles.filter(isRecord) : [];
if (!snapshotVehicles.length) return merged;
const byIdentity = vehicleIndex(merged);
for (const snapshotVehicle of snapshotVehicles) {
const match = findVehicle(byIdentity, snapshotVehicle);
const value = { ...(match ? merged[match.index] : {}), ...snapshotVehicle, vehicleObservedAt: textValue(vehicleSnapshot?.observedAt) };
if (match) merged[match.index] = value;
else {
const created = { ...value, vehicleId: firstText(snapshotVehicle, "vehicleId", "entityId", "id") };
merged.push(created);
addVehicleToIndex(byIdentity, created, merged.length - 1);
}
}
return merged;
}
export async function saveGiftDefinition(actions: SCUMWorkspaceActions, gift: RecordMap): Promise<unknown> {
const key = requiredKey(gift, "code", "礼包编号");
return requirePluginData(actions).transact(scumCollections.gifts, [{ operation: "put", key, value: gift }]);
@@ -409,29 +259,6 @@ function collectionRecords(response: unknown): RecordMap[] {
});
}
function latestSnapshotPayload(response: unknown): RecordMap | undefined {
if (!isRecord(response) || !Array.isArray(response.items)) return undefined;
const snapshots = response.items.filter(isRecord).sort((left, right) => snapshotOrder(right) - snapshotOrder(left));
const latest = snapshots[0];
if (!latest) return undefined;
return isRecord(latest.payload) ? { ...latest.payload, observedAt: textValue(latest.observedAt) || textValue(latest.payload.observedAt) } : undefined;
}
function snapshotOrder(snapshot: RecordMap): number { const observed = Date.parse(textValue(snapshot.observedAt)); return Number.isNaN(observed) ? Number(snapshot.sequence) || 0 : observed; }
function playerIndex(players: RecordMap[]): Map<string, number> { const result = new Map<string, number>(); players.forEach((player, index) => addPlayerToIndex(result, player, index)); return result; }
function addPlayerToIndex(index: Map<string, number>, player: RecordMap, playerIndex: number): void { playerIdentities(player).forEach((identity) => index.set(identity, playerIndex)); }
function findPlayer(index: Map<string, number>, player: RecordMap): { index: number } | undefined { for (const identity of playerIdentities(player)) { const found = index.get(identity); if (found !== undefined) return { index: found }; } return undefined; }
function vehicleIndex(vehicles: RecordMap[]): Map<string, number> { const result = new Map<string, number>(); vehicles.forEach((vehicle, index) => addVehicleToIndex(result, vehicle, index)); return result; }
function addVehicleToIndex(index: Map<string, number>, vehicle: RecordMap, vehicleIndex: number): void { vehicleIdentities(vehicle).forEach((identity) => index.set(identity, vehicleIndex)); }
function findVehicle(index: Map<string, number>, vehicle: RecordMap): { index: number } | undefined { for (const identity of vehicleIdentities(vehicle)) { const found = index.get(identity); if (found !== undefined) return { index: found }; } return undefined; }
function vehicleIdentities(vehicle: RecordMap): string[] { return ["vehicleId", "entityId", "id"].map((key) => textValue(vehicle[key])).filter(Boolean).map((value) => `vehicle:${value}`); }
function playerIdentities(player: RecordMap): string[] {
const identities = new Set<string>();
for (const key of ["gamePlayerId", "playerId", "steamId", "id"]) { const value = textValue(player[key]); if (value) identities.add(`player:${value}`); }
for (const key of ["userProfileId", "profileId"]) { const value = textValue(player[key]); if (value) identities.add(`profile:${value}`); }
return [...identities];
}
function onlineValue(player: RecordMap): boolean { const status = firstText(player, "status", "state").toLowerCase(); return booleanValue(player.online) || ["online", "active", "connected"].includes(status); }
function booleanValue(value: unknown): boolean { return value === true || value === 1 || value === "1" || String(value).toLowerCase() === "true"; }
function requirePluginData(actions: SCUMWorkspaceActions): PluginDataActions {
@@ -439,23 +266,6 @@ function requirePluginData(actions: SCUMWorkspaceActions): PluginDataActions {
return actions.pluginData;
}
function buildPlayerAttributeSqlText(player: RecordMap, changes: Array<{ column: string; after: number }>): string {
const playerId = firstText(player, "gamePlayerId", "playerId", "id");
const profileId = firstText(player, "userProfileId", "profileId");
const steamId = firstText(player, "steamId", "providerId");
const where = playerId && playerId !== ":playerId"
? `id = ${sqlLiteral(playerId)}`
: profileId
? `id = (SELECT prisoner_id FROM user_profile WHERE CAST(id AS TEXT) = ${sqlLiteral(profileId)} LIMIT 1)`
: steamId
? `id = (SELECT profile.prisoner_id FROM user_profile profile WHERE profile.user_id = ${sqlLiteral(steamId)} LIMIT 1)`
: "id = :playerId";
return changes.map((change) => `UPDATE prisoner SET ${change.column} = ${sqlNumber(change.after)} WHERE ${where};`).join("\n");
}
function sqlLiteral(value: string): string { return value === ":playerId" ? value : `'${value.replace(/'/g, "''")}'`; }
function sqlNumber(value: number): string { return Number.isInteger(value) ? String(value) : String(value); }
function requiredKey(value: RecordMap, key: string, label: string): string {
const result = textValue(value[key]);
if (!result) throw new Error(`${label}不能为空。`);