@animastor/orchestration 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,185 @@
1
+ // ======================================================
2
+ // gen/stage — helpers shared by command creation and stage transitions
3
+ // (1.3.0: video, ADR §6.3, §6.5, §13 п.11)
4
+ // ======================================================
5
+ // Everything here runs on the caller's transaction client (command tx or
6
+ // acceptance tx) and never UPDATEs gen_commands (acceptance holds those rows
7
+ // FOR SHARE).
8
+
9
+ 'use strict';
10
+
11
+ const { GenError, LAYER_OF_KIND, LIVE } = require('./util');
12
+
13
+ /** part kind → its merge kind (a part kind with input.merge_parts ends in this local job) */
14
+ const MERGE_OF_PART = Object.freeze({ video_group: 'video_merge', audio_chunk: 'audio_merge' });
15
+ /** kinds a waiting video command joins in its scene (images + audio, §6.5, §13 п.11 п.3) */
16
+ const VIDEO_WAIT_KINDS = Object.freeze(['iu_image', 'audio_chunk', 'audio_merge']);
17
+ const SKIP_REASON_RE = /^skipped_[a-z_]{1,48}$/;
18
+
19
+ /** input.merge_parts → [{unit_key, part_hash}] (non-empty, string fields) or null. */
20
+ function mergePartsOf(input) {
21
+ const v = input && input.merge_parts;
22
+ if (!Array.isArray(v) || v.length === 0) return null;
23
+ const out = [];
24
+ for (const p of v) {
25
+ if (!p || typeof p.unit_key !== 'string' || !p.unit_key || typeof p.part_hash !== 'string' || !p.part_hash) return null;
26
+ out.push({ unit_key: p.unit_key, part_hash: p.part_hash });
27
+ }
28
+ return out;
29
+ }
30
+
31
+ /**
32
+ * planUnits result → {units, waits, skipped}. A plain array (every layer before
33
+ * 1.3.0, audio / image now) is {units: array}. Video may return the object form:
34
+ * units — first-stage units (video_group)
35
+ * waits — [{chapter_id, scene_id}] scenes waiting for live images / audio: the
36
+ * command joins those live jobs; the video stage follows their acceptance
37
+ * skipped — [{chapter_id, scene_id, reason: 'skipped_*'}]
38
+ */
39
+ function normalisePlan(planned, layer) {
40
+ if (Array.isArray(planned)) return { units: planned, waits: [], skipped: [] };
41
+ if (!planned || typeof planned !== 'object' || !Array.isArray(planned.units)) {
42
+ throw new GenError('bad_plan', 500, `planUnits(${layer}) must return an array or {units, waits?, skipped?}`);
43
+ }
44
+ const scene = (x) => x && typeof x.chapter_id === 'string' && x.chapter_id && typeof x.scene_id === 'string' && x.scene_id;
45
+ const waits = Array.isArray(planned.waits) ? planned.waits : [];
46
+ const skipped = Array.isArray(planned.skipped) ? planned.skipped : [];
47
+ if (!waits.every(scene)) throw new GenError('bad_plan', 500, `planUnits(${layer}): waits[] entries need chapter_id, scene_id`);
48
+ if (!skipped.every((s) => scene(s) && typeof s.reason === 'string' && SKIP_REASON_RE.test(s.reason))) {
49
+ throw new GenError('bad_plan', 500, `planUnits(${layer}): skipped[] entries need chapter_id, scene_id, reason skipped_*`);
50
+ }
51
+ return {
52
+ units: planned.units,
53
+ waits: waits.map((w) => ({ chapter_id: w.chapter_id, scene_id: w.scene_id })),
54
+ skipped: skipped.map((s) => ({ chapter_id: s.chapter_id, scene_id: s.scene_id, reason: s.reason })),
55
+ };
56
+ }
57
+
58
+ /**
59
+ * Units whose part is already accepted for the current content: the scene asset
60
+ * of the same build records gen_parts[unit_key].part_hash = input.part_hash
61
+ * (row pending / ready — a 'stale' row proves nothing). 1.1.0 rule, shared.
62
+ * @returns {Promise<Set<object>>} subset of `units` (by identity)
63
+ */
64
+ async function readyParts(client, bookId, units) {
65
+ const parted = units.filter((u) => u.input && typeof u.input.part_hash === 'string' && u.input.part_hash);
66
+ if (!parted.length) return new Set();
67
+ const r = await client.query(
68
+ `SELECT t.ord FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[])
69
+ WITH ORDINALITY AS t(chapter_id, scene_id, asset_type, build_id, unit_key, part_hash, ord)
70
+ WHERE EXISTS (SELECT 1 FROM scene_assets a
71
+ WHERE a.book_id = $1 AND a.chapter_id = t.chapter_id AND a.scene_id = t.scene_id
72
+ AND a.asset_type = t.asset_type AND a.build_id = t.build_id
73
+ AND a.status IN ('pending', 'ready')
74
+ AND jsonb_typeof(a.metadata->'gen_parts') = 'object'
75
+ AND a.metadata->'gen_parts'->t.unit_key->>'part_hash' = t.part_hash)`,
76
+ [bookId, parted.map((u) => u.chapter_id), parted.map((u) => u.scene_id), parted.map((u) => LAYER_OF_KIND[u.kind]),
77
+ parted.map((u) => u.build_id), parted.map((u) => u.unit_key), parted.map((u) => u.input.part_hash)]);
78
+ return new Set(r.rows.map((row) => parted[Number(row.ord) - 1]));
79
+ }
80
+
81
+ /**
82
+ * For every listed part: the latest DONE job of that unit_key with that part_hash
83
+ * (same build). Returned in `parts` order; `missing` = parts without such a job.
84
+ */
85
+ async function donePartsFor(client, { bookId, chapterId, sceneId, buildId, kind }, parts) {
86
+ const r = await client.query(
87
+ `SELECT DISTINCT ON (j.unit_key) j.unit_key, j.job_id, j.result_path, j.result_sha256,
88
+ j.input->'part_meta' AS meta, j.input->>'part_hash' AS part_hash
89
+ FROM gen_jobs j
90
+ JOIN unnest($6::text[], $7::text[]) AS t(uk, ph) ON j.unit_key = t.uk AND j.input->>'part_hash' = t.ph
91
+ WHERE j.book_id = $1 AND j.chapter_id = $2 AND j.scene_id = $3 AND j.kind = $4 AND j.build_id = $5
92
+ AND j.status = 'done'
93
+ ORDER BY j.unit_key, j.finished_at DESC`,
94
+ [bookId, chapterId, sceneId, kind, buildId, parts.map((p) => p.unit_key), parts.map((p) => p.part_hash)]);
95
+ const by = new Map(r.rows.map((x) => [x.unit_key, x]));
96
+ const done = [];
97
+ const missing = [];
98
+ for (const p of parts) {
99
+ const x = by.get(p.unit_key);
100
+ if (!x) { missing.push(p); continue; }
101
+ done.push({ unit_key: x.unit_key, job_id: x.job_id, path: x.result_path, sha256: x.result_sha256, part_hash: x.part_hash, meta: x.meta || null });
102
+ }
103
+ return { done, missing };
104
+ }
105
+
106
+ /** Is any job of these unit_keys of the scene live (queued / running)? */
107
+ async function anyLive(client, { bookId, chapterId, sceneId, kind }, unitKeys) {
108
+ const r = await client.query(
109
+ `SELECT 1 FROM gen_jobs WHERE book_id = $1 AND chapter_id = $2 AND scene_id = $3 AND kind = $4
110
+ AND unit_key = ANY($5::text[]) AND status = ANY($6::text[]) LIMIT 1`,
111
+ [bookId, chapterId, sceneId, kind, unitKeys, LIVE]);
112
+ return r.rowCount > 0;
113
+ }
114
+
115
+ /**
116
+ * The merge unit of a scene whose parts (input.merge_parts of its part units) are
117
+ * all done: {kind: merge, unit_key: 'scene', input: {scene_hash, parts}} or null.
118
+ */
119
+ async function mergeUnitFor(client, bookId, partUnit) {
120
+ const parts = mergePartsOf(partUnit.input);
121
+ const mergeKind = MERGE_OF_PART[partUnit.kind];
122
+ if (!parts || !mergeKind) return null;
123
+ const where = { bookId, chapterId: partUnit.chapter_id, sceneId: partUnit.scene_id, buildId: partUnit.build_id, kind: partUnit.kind };
124
+ if (await anyLive(client, where, parts.map((p) => p.unit_key))) return null;
125
+ const { done, missing } = await donePartsFor(client, where, parts);
126
+ if (missing.length) return null;
127
+ const sceneHash = partUnit.scene_hash ?? partUnit.input.scene_hash ?? null;
128
+ return {
129
+ chapter_id: partUnit.chapter_id, scene_id: partUnit.scene_id, kind: mergeKind, unit_key: 'scene',
130
+ build_id: partUnit.build_id, scene_hash: sceneHash,
131
+ input: { scene_hash: sceneHash, parts: done, merge_parts: parts },
132
+ };
133
+ }
134
+
135
+ /** Link commands to every live job of `kinds` in the given scenes (a waiting command joins them). */
136
+ async function linkSceneLive(client, commandIds, bookId, scenes, kinds = VIDEO_WAIT_KINDS) {
137
+ if (!commandIds.length || !scenes.length) return 0;
138
+ const r = await client.query(
139
+ `INSERT INTO gen_command_jobs (command_id, job_id)
140
+ SELECT c, j.job_id
141
+ FROM gen_jobs j
142
+ JOIN unnest($2::text[], $3::text[]) AS s(ch, sc) ON j.chapter_id = s.ch AND j.scene_id = s.sc
143
+ CROSS JOIN unnest($4::uuid[]) AS c
144
+ WHERE j.book_id = $1 AND j.kind = ANY($5::text[]) AND j.status IN ('queued','running')
145
+ ON CONFLICT DO NOTHING`,
146
+ [bookId, scenes.map((s) => s.chapter_id), scenes.map((s) => s.scene_id), commandIds, kinds]);
147
+ return r.rowCount;
148
+ }
149
+
150
+ /** Record skip reasons for commands (insert-only, idempotent). */
151
+ async function recordSkips(client, commandIds, skipped) {
152
+ if (!commandIds.length || !skipped.length) return 0;
153
+ const rows = [];
154
+ for (const c of commandIds) for (const s of skipped) rows.push([c, s.chapter_id, s.scene_id, s.reason]);
155
+ const r = await client.query(
156
+ `INSERT INTO gen_command_skips (command_id, chapter_id, scene_id, reason)
157
+ SELECT * FROM unnest($1::uuid[], $2::text[], $3::text[], $4::text[])
158
+ ON CONFLICT DO NOTHING`,
159
+ [rows.map((x) => x[0]), rows.map((x) => x[1]), rows.map((x) => x[2]), rows.map((x) => x[3])]);
160
+ return r.rowCount;
161
+ }
162
+
163
+ /** skipped[] → {skipped_x: [scene_id…]} for the command summary. */
164
+ function skipSummary(skipped) {
165
+ const out = {};
166
+ for (const s of skipped) {
167
+ if (!out[s.reason]) out[s.reason] = [];
168
+ if (!out[s.reason].includes(s.scene_id)) out[s.reason].push(s.scene_id);
169
+ }
170
+ return out;
171
+ }
172
+
173
+ module.exports = {
174
+ MERGE_OF_PART,
175
+ VIDEO_WAIT_KINDS,
176
+ mergePartsOf,
177
+ normalisePlan,
178
+ readyParts,
179
+ donePartsFor,
180
+ anyLive,
181
+ mergeUnitFor,
182
+ linkSceneLive,
183
+ recordSkips,
184
+ skipSummary,
185
+ };
@@ -14,10 +14,13 @@
14
14
  const fs = require('fs');
15
15
  const path = require('path');
16
16
  const { withTx, notifyProgress } = require('./util');
17
+ const { msBetween } = require('./log');
17
18
 
18
19
  const BATCH = 200;
19
20
 
20
- function createSweeper({ pool, accept, outputDir = null, offlineAfterMs = 60_000, incomingMaxAgeMs = 60 * 60_000, logger = console }) {
21
+ const NOOP_LOG = Object.freeze({ event() {} });
22
+
23
+ function createSweeper({ pool, accept, outputDir = null, offlineAfterMs = 60_000, incomingMaxAgeMs = 60 * 60_000, logger = null, genLog = NOOP_LOG }) {
21
24
  const offlineAfterS = Math.max(1, Math.round(offlineAfterMs / 1000));
22
25
 
23
26
  async function failMany(rows, cls, reason) {
@@ -59,9 +62,15 @@ function createSweeper({ pool, accept, outputDir = null, offlineAfterMs = 60_000
59
62
  `UPDATE gen_commands SET status = $2, finished_at = now(), error = $3 WHERE command_id = $1`,
60
63
  [id, status, err]);
61
64
  await notifyProgress(client, c.book_id, id);
62
- return true;
65
+ return { book_id: c.book_id, status, k, run_ms: msBetween(c.created_at) };
63
66
  });
64
- if (done) n += 1;
67
+ if (done) {
68
+ n += 1;
69
+ genLog.event('command-finished', {
70
+ book_id: done.book_id, command_id: id, status: done.status,
71
+ done: done.k.done, failed: done.k.failed, cancelled: done.k.cancelled, run_ms: done.run_ms,
72
+ });
73
+ }
65
74
  }
66
75
  return n;
67
76
  }
@@ -121,7 +130,7 @@ function createSweeper({ pool, accept, outputDir = null, offlineAfterMs = 60_000
121
130
  if (!busy) {
122
131
  busy = true;
123
132
  try { await sweepOnce(); } catch (err) {
124
- logger.error && logger.error(`[gen-v2] sweeper: ${err && err.message}`);
133
+ logger && logger.error && logger.error(`[gen-v2] sweeper: ${err && err.message}`);
125
134
  } finally { busy = false; }
126
135
  }
127
136
  if (!stopped) { timer = setTimeout(tick, intervalMs); if (timer.unref) timer.unref(); }