mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-04-19 16:19:25 -07:00
Refactor startup, queries, and workflow into focused modules (#36)
* chore(backlog): add mining workflow milestone and tasks
* refactor: split character dictionary runtime modules
* refactor: split shared type entrypoints
* refactor: use bun serve for stats server
* feat: add repo-local subminer workflow plugin
* fix: add stats server node fallback
* refactor: split immersion tracker query modules
* chore: update backlog task records
* refactor: migrate shared type imports
* refactor: compose startup and setup window wiring
* Add backlog tasks and launcher time helper tests
- Track follow-up cleanup work in Backlog.md
- Replace Date.now usage with shared nowMs helper
- Add launcher args/parser and core regression tests
* test: increase launcher test timeout for CI stability
* fix: address CodeRabbit review feedback
* refactor(main): extract remaining inline runtime logic from main
* chore(backlog): update task notes and changelog fragment
* refactor: split main boot phases
* test: stabilize bun coverage reporting
* Switch plausible endpoint and harden coverage lane parsing
- update docs-site tracking to use the Plausible capture endpoint
- tighten coverage lane argument and LCOV parsing checks
- make script entrypoint use CommonJS main guard
* Restrict docs analytics and build coverage input
- limit Plausible init to docs.subminer.moe
- build Yomitan before src coverage lane
* fix(ci): normalize Windows shortcut paths for cross-platform tests
* Fix verification and immersion-tracker grouping
- isolate verifier artifacts and lease handling
- switch weekly/monthly tracker cutoffs to calendar boundaries
- tighten boot lifecycle and zip writer tests
* fix: resolve CI type failures in boot and immersion query tests
* fix: remove strict spread usage in Date mocks
* fix: use explicit super args for MockDate constructors
* Factor out mock date helper in tracker tests
- reuse a shared `withMockDate` helper for date-sensitive query tests
- make monthly rollup assertions key off `videoId` instead of row order
* fix: use variadic array type for MockDate constructor args
TS2367: fixed-length tuple made args.length === 0 unreachable.
* refactor: remove unused createMainBootRuntimes/Handlers aggregate functions
These functions were never called by production code — main.ts imports
the individual composeBoot* re-exports directly.
* refactor: remove boot re-export alias layer
main.ts now imports directly from the runtime/composers and runtime/domains
modules, eliminating the intermediate boot/ indirection.
* refactor: consolidate 3 near-identical setup window factories
Extract shared createSetupWindowHandler with a config parameter.
Public API unchanged.
* refactor: parameterize duplicated getAffected*Ids query helpers
Four structurally identical functions collapsed into two parameterized
helpers while preserving the existing public API.
* refactor: inline identity composers (stats-startup, overlay-window)
composeStatsStartupRuntime was a no-op that returned its input.
composeOverlayWindowHandlers was a 1-line delegation.
Both removed in favor of direct usage.
* chore: remove unused token/queue file path constants from main.ts
* fix: replace any types in boot services with proper signatures
* refactor: deduplicate ensureDir into shared/fs-utils
5 copies of mkdir-p-if-not-exists consolidated into one shared module
with ensureDir (directory path) and ensureDirForFile (file path) variants.
* fix: tighten type safety in boot services
- Add AppLifecycleShape and OverlayModalInputStateShape constraints
so TAppLifecycleApp and TOverlayModalInputState generics are bounded
- Remove unsafe `as { handleModalInputStateChange? }` cast — now
directly callable via the constraint
- Use `satisfies AppLifecycleShape` for structural validation on the
appLifecycleApp object literal
- Document Electron App.on incompatibility with simple signatures
* refactor: inline subtitle-prefetch-runtime-composer
The composer was a pure pass-through that destructured an object and
reassembled it with the same fields. Inlined at the call site.
* chore: consolidate duplicate import paths in main.ts
* test: extract mpv composer test fixture factory to reduce duplication
* test: add behavioral assertions to composer tests
Upgrade 8 composer test files from shape-only typeof checks to behavioral
assertions that invoke returned handlers and verify injected dependencies are
actually called, following the mpv-runtime-composer pattern.
* refactor: normalize import extensions in query modules
* refactor: consolidate toDbMs into query-shared.ts
* refactor: remove Node.js fallback from stats-server, use Bun only
* Fix monthly rollup test expectations
- Preserve multi-arg Date construction in mock helper
- Align rollup assertions with the correct videoId
* fix: address PR 36 CodeRabbit follow-ups
* fix: harden coverage lane cleanup
* fix(stats): fallback to node server when Bun.serve unavailable
* fix(ci): restore coverage lane compatibility
* chore(backlog): close TASK-242
* fix: address latest CodeRabbit review round
* fix: guard disabled immersion retention windows
* fix: migrate discord rpc wrapper
* fix(ci): add changelog fragment for PR 36
* fix: stabilize macOS visible overlay toggle
* fix: pin installed mpv plugin to current binary
* fix: strip inline subtitle markup from sidebar cues
* fix(renderer): restore subtitle sidebar mpv passthrough
* feat(discord): add configurable presence style presets
Replace the hardcoded "Mining and crafting (Anki cards)" meme message
with a preset system. New `discordPresence.presenceStyle` option
supports four presets: "default" (clean bilingual), "meme" (the OG
Minecraft joke), "japanese" (fully JP), and "minimal". The default
preset shows "Sentence Mining" with 日本語学習中 as the small image
tooltip. Existing users can set presenceStyle to "meme" to keep the
old behavior.
* fix: finalize v0.10.0 release prep
* docs: add subtitle sidebar guide and release note
* chore(backlog): mark docs task done
* fix: lazily resolve youtube playback socket path
* chore(release): build v0.10.0 changelog
* Revert "chore(release): build v0.10.0 changelog"
This reverts commit 9741c0f020.
This commit is contained in:
282
src/core/services/immersion-tracker/query-shared.ts
Normal file
282
src/core/services/immersion-tracker/query-shared.ts
Normal file
@@ -0,0 +1,282 @@
|
||||
import type { DatabaseSync } from './sqlite';
|
||||
|
||||
export const ACTIVE_SESSION_METRICS_CTE = `
|
||||
WITH active_session_metrics AS (
|
||||
SELECT
|
||||
t.session_id AS sessionId,
|
||||
MAX(t.total_watched_ms) AS totalWatchedMs,
|
||||
MAX(t.active_watched_ms) AS activeWatchedMs,
|
||||
MAX(t.lines_seen) AS linesSeen,
|
||||
MAX(t.tokens_seen) AS tokensSeen,
|
||||
MAX(t.cards_mined) AS cardsMined,
|
||||
MAX(t.lookup_count) AS lookupCount,
|
||||
MAX(t.lookup_hits) AS lookupHits,
|
||||
MAX(t.yomitan_lookup_count) AS yomitanLookupCount
|
||||
FROM imm_session_telemetry t
|
||||
JOIN imm_sessions s ON s.session_id = t.session_id
|
||||
WHERE s.ended_at_ms IS NULL
|
||||
GROUP BY t.session_id
|
||||
)
|
||||
`;
|
||||
|
||||
export function makePlaceholders(values: number[]): string {
|
||||
return values.map(() => '?').join(',');
|
||||
}
|
||||
|
||||
export function resolvedCoverBlobExpr(mediaAlias: string, blobStoreAlias: string): string {
|
||||
return `COALESCE(${blobStoreAlias}.cover_blob, CASE WHEN ${mediaAlias}.cover_blob_hash IS NULL THEN ${mediaAlias}.cover_blob ELSE NULL END)`;
|
||||
}
|
||||
|
||||
export function cleanupUnusedCoverArtBlobHash(db: DatabaseSync, blobHash: string | null): void {
|
||||
if (!blobHash) {
|
||||
return;
|
||||
}
|
||||
db.prepare(
|
||||
`
|
||||
DELETE FROM imm_cover_art_blobs
|
||||
WHERE blob_hash = ?
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM imm_media_art
|
||||
WHERE cover_blob_hash = ?
|
||||
)
|
||||
`,
|
||||
).run(blobHash, blobHash);
|
||||
}
|
||||
|
||||
export function findSharedCoverBlobHash(
|
||||
db: DatabaseSync,
|
||||
videoId: number,
|
||||
anilistId: number | null,
|
||||
coverUrl: string | null,
|
||||
): string | null {
|
||||
if (anilistId !== null) {
|
||||
const byAnilist = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT cover_blob_hash AS coverBlobHash
|
||||
FROM imm_media_art
|
||||
WHERE video_id != ?
|
||||
AND anilist_id = ?
|
||||
AND cover_blob_hash IS NOT NULL
|
||||
ORDER BY fetched_at_ms DESC, video_id DESC
|
||||
LIMIT 1
|
||||
`,
|
||||
)
|
||||
.get(videoId, anilistId) as { coverBlobHash: string | null } | undefined;
|
||||
if (byAnilist?.coverBlobHash) {
|
||||
return byAnilist.coverBlobHash;
|
||||
}
|
||||
}
|
||||
|
||||
if (coverUrl) {
|
||||
const byUrl = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT cover_blob_hash AS coverBlobHash
|
||||
FROM imm_media_art
|
||||
WHERE video_id != ?
|
||||
AND cover_url = ?
|
||||
AND cover_blob_hash IS NOT NULL
|
||||
ORDER BY fetched_at_ms DESC, video_id DESC
|
||||
LIMIT 1
|
||||
`,
|
||||
)
|
||||
.get(videoId, coverUrl) as { coverBlobHash: string | null } | undefined;
|
||||
return byUrl?.coverBlobHash ?? null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
type LexicalEntity = 'word' | 'kanji';
|
||||
|
||||
function getAffectedIdsForSessions(
|
||||
db: DatabaseSync,
|
||||
entity: LexicalEntity,
|
||||
sessionIds: number[],
|
||||
): number[] {
|
||||
if (sessionIds.length === 0) return [];
|
||||
const table = entity === 'word' ? 'imm_word_line_occurrences' : 'imm_kanji_line_occurrences';
|
||||
const col = `${entity}_id`;
|
||||
return (
|
||||
db
|
||||
.prepare(
|
||||
`SELECT DISTINCT o.${col} AS id
|
||||
FROM ${table} o
|
||||
JOIN imm_subtitle_lines sl ON sl.line_id = o.line_id
|
||||
WHERE sl.session_id IN (${makePlaceholders(sessionIds)})`,
|
||||
)
|
||||
.all(...sessionIds) as Array<{ id: number }>
|
||||
).map((row) => row.id);
|
||||
}
|
||||
|
||||
function getAffectedIdsForVideo(
|
||||
db: DatabaseSync,
|
||||
entity: LexicalEntity,
|
||||
videoId: number,
|
||||
): number[] {
|
||||
const table = entity === 'word' ? 'imm_word_line_occurrences' : 'imm_kanji_line_occurrences';
|
||||
const col = `${entity}_id`;
|
||||
return (
|
||||
db
|
||||
.prepare(
|
||||
`SELECT DISTINCT o.${col} AS id
|
||||
FROM ${table} o
|
||||
JOIN imm_subtitle_lines sl ON sl.line_id = o.line_id
|
||||
WHERE sl.video_id = ?`,
|
||||
)
|
||||
.all(videoId) as Array<{ id: number }>
|
||||
).map((row) => row.id);
|
||||
}
|
||||
|
||||
export function getAffectedWordIdsForSessions(db: DatabaseSync, sessionIds: number[]): number[] {
|
||||
return getAffectedIdsForSessions(db, 'word', sessionIds);
|
||||
}
|
||||
|
||||
export function getAffectedKanjiIdsForSessions(db: DatabaseSync, sessionIds: number[]): number[] {
|
||||
return getAffectedIdsForSessions(db, 'kanji', sessionIds);
|
||||
}
|
||||
|
||||
export function getAffectedWordIdsForVideo(db: DatabaseSync, videoId: number): number[] {
|
||||
return getAffectedIdsForVideo(db, 'word', videoId);
|
||||
}
|
||||
|
||||
export function getAffectedKanjiIdsForVideo(db: DatabaseSync, videoId: number): number[] {
|
||||
return getAffectedIdsForVideo(db, 'kanji', videoId);
|
||||
}
|
||||
|
||||
function refreshWordAggregates(db: DatabaseSync, wordIds: number[]): void {
|
||||
if (wordIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const rows = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT
|
||||
w.id AS wordId,
|
||||
COALESCE(SUM(o.occurrence_count), 0) AS frequency,
|
||||
MIN(COALESCE(sl.CREATED_DATE, sl.LAST_UPDATE_DATE)) AS firstSeen,
|
||||
MAX(COALESCE(sl.LAST_UPDATE_DATE, sl.CREATED_DATE)) AS lastSeen
|
||||
FROM imm_words w
|
||||
LEFT JOIN imm_word_line_occurrences o ON o.word_id = w.id
|
||||
LEFT JOIN imm_subtitle_lines sl ON sl.line_id = o.line_id
|
||||
WHERE w.id IN (${makePlaceholders(wordIds)})
|
||||
GROUP BY w.id
|
||||
`,
|
||||
)
|
||||
.all(...wordIds) as Array<{
|
||||
wordId: number;
|
||||
frequency: number;
|
||||
firstSeen: number | null;
|
||||
lastSeen: number | null;
|
||||
}>;
|
||||
const updateStmt = db.prepare(
|
||||
`
|
||||
UPDATE imm_words
|
||||
SET frequency = ?, first_seen = ?, last_seen = ?
|
||||
WHERE id = ?
|
||||
`,
|
||||
);
|
||||
const deleteStmt = db.prepare('DELETE FROM imm_words WHERE id = ?');
|
||||
|
||||
for (const row of rows) {
|
||||
if (row.frequency <= 0 || row.firstSeen === null || row.lastSeen === null) {
|
||||
deleteStmt.run(row.wordId);
|
||||
continue;
|
||||
}
|
||||
updateStmt.run(
|
||||
row.frequency,
|
||||
Math.floor(row.firstSeen / 1000),
|
||||
Math.floor(row.lastSeen / 1000),
|
||||
row.wordId,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function refreshKanjiAggregates(db: DatabaseSync, kanjiIds: number[]): void {
|
||||
if (kanjiIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const rows = db
|
||||
.prepare(
|
||||
`
|
||||
SELECT
|
||||
k.id AS kanjiId,
|
||||
COALESCE(SUM(o.occurrence_count), 0) AS frequency,
|
||||
MIN(COALESCE(sl.CREATED_DATE, sl.LAST_UPDATE_DATE)) AS firstSeen,
|
||||
MAX(COALESCE(sl.LAST_UPDATE_DATE, sl.CREATED_DATE)) AS lastSeen
|
||||
FROM imm_kanji k
|
||||
LEFT JOIN imm_kanji_line_occurrences o ON o.kanji_id = k.id
|
||||
LEFT JOIN imm_subtitle_lines sl ON sl.line_id = o.line_id
|
||||
WHERE k.id IN (${makePlaceholders(kanjiIds)})
|
||||
GROUP BY k.id
|
||||
`,
|
||||
)
|
||||
.all(...kanjiIds) as Array<{
|
||||
kanjiId: number;
|
||||
frequency: number;
|
||||
firstSeen: number | null;
|
||||
lastSeen: number | null;
|
||||
}>;
|
||||
const updateStmt = db.prepare(
|
||||
`
|
||||
UPDATE imm_kanji
|
||||
SET frequency = ?, first_seen = ?, last_seen = ?
|
||||
WHERE id = ?
|
||||
`,
|
||||
);
|
||||
const deleteStmt = db.prepare('DELETE FROM imm_kanji WHERE id = ?');
|
||||
|
||||
for (const row of rows) {
|
||||
if (row.frequency <= 0 || row.firstSeen === null || row.lastSeen === null) {
|
||||
deleteStmt.run(row.kanjiId);
|
||||
continue;
|
||||
}
|
||||
updateStmt.run(
|
||||
row.frequency,
|
||||
Math.floor(row.firstSeen / 1000),
|
||||
Math.floor(row.lastSeen / 1000),
|
||||
row.kanjiId,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function refreshLexicalAggregates(
|
||||
db: DatabaseSync,
|
||||
wordIds: number[],
|
||||
kanjiIds: number[],
|
||||
): void {
|
||||
refreshWordAggregates(db, [...new Set(wordIds)]);
|
||||
refreshKanjiAggregates(db, [...new Set(kanjiIds)]);
|
||||
}
|
||||
|
||||
export function deleteSessionsByIds(db: DatabaseSync, sessionIds: number[]): void {
|
||||
if (sessionIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const placeholders = makePlaceholders(sessionIds);
|
||||
db.prepare(`DELETE FROM imm_subtitle_lines WHERE session_id IN (${placeholders})`).run(
|
||||
...sessionIds,
|
||||
);
|
||||
db.prepare(`DELETE FROM imm_session_telemetry WHERE session_id IN (${placeholders})`).run(
|
||||
...sessionIds,
|
||||
);
|
||||
db.prepare(`DELETE FROM imm_session_events WHERE session_id IN (${placeholders})`).run(
|
||||
...sessionIds,
|
||||
);
|
||||
db.prepare(`DELETE FROM imm_sessions WHERE session_id IN (${placeholders})`).run(...sessionIds);
|
||||
}
|
||||
|
||||
export function toDbMs(ms: number | bigint): bigint {
|
||||
if (typeof ms === 'bigint') {
|
||||
return ms;
|
||||
}
|
||||
if (!Number.isFinite(ms)) {
|
||||
throw new TypeError(`Invalid database timestamp: ${ms}`);
|
||||
}
|
||||
return BigInt(Math.trunc(ms));
|
||||
}
|
||||
Reference in New Issue
Block a user