mirror of
https://github.com/whyour/qinglong.git
synced 2026-12-01 09:45:36 +08:00
perf(cron): share global concurrency budget and streamline execution
Share durable permits across manual, scheduled and recovered runs, prioritize short ready tasks with aging, and record global queue occupancy. Reduce launch, log polling, dashboard and SQLite overhead while preserving transactional receipts, cancellation, recovery and script hook compatibility. Keep ordinary CRUD in ORM and bound SQL on measured execution hot paths. Fix supervisor descendant tracking, asynchronous log draining, concurrent log directory creation, Linux fallback launches and snapshot clock rollback. Include regression coverage, SQL audits and evolution/review documentation. Validation: five review rounds; local full suite 1478 passed, 28 platform skips; dev suites 415 passed, no failures/skips; backend types and formatting passed.
This commit is contained in:
1 parent
cddabbaf0e
commit
2f01f756d7
74 files changed
+6891
-837
No files matched your search
@@ -1,8 +1,14 @@
|
||||
import { QueryTypes, Sequelize } from 'sequelize';
|
||||
import { Op, Sequelize, col, fn } from 'sequelize';
|
||||
import {
|
||||
executionAssociation,
|
||||
executionModel,
|
||||
} from '../../data/executionModels';
|
||||
|
||||
type Occupant = { id?: string; name: string };
|
||||
type WaitingSample = { db: Sequelize; context?: string };
|
||||
const LIVE_SAMPLE_INTERVAL_MS = 250;
|
||||
export type Admission = {
|
||||
queue: 'manual' | 'scheduled';
|
||||
queue: 'manual' | 'scheduled' | 'global';
|
||||
limit: number;
|
||||
occupied: number;
|
||||
holders: Occupant[];
|
||||
@@ -11,9 +17,10 @@ export type Admission = {
|
||||
// Each object belongs to exactly one execution pool in its owning process.
|
||||
export class QueueOccupants {
|
||||
private active = new Set<Occupant>();
|
||||
private waiting = new Map<string, Sequelize>();
|
||||
private waiting = new Map<string, WaitingSample>();
|
||||
private writing = false;
|
||||
private changed = false;
|
||||
private timer?: NodeJS.Timeout;
|
||||
|
||||
constructor(
|
||||
private queue: Admission['queue'],
|
||||
@@ -22,45 +29,74 @@ export class QueueOccupants {
|
||||
) {}
|
||||
|
||||
watch(id: string, db: Sequelize) {
|
||||
this.waiting.set(id, db);
|
||||
this.waiting.set(id, { db });
|
||||
this.refresh();
|
||||
}
|
||||
|
||||
forget(id?: string) {
|
||||
if (id) this.waiting.delete(id);
|
||||
if (!this.waiting.size) {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = undefined;
|
||||
this.changed = false;
|
||||
}
|
||||
}
|
||||
|
||||
refresh() {
|
||||
if (!this.waiting.size) return;
|
||||
this.changed = true;
|
||||
if (this.writing) return;
|
||||
if (this.writing || this.timer) return;
|
||||
// Bound diagnostic write frequency across asynchronous admissions/handoffs.
|
||||
// Execution and its durable admission/dequeue records never wait for this timer.
|
||||
this.timer = setTimeout(() => {
|
||||
this.timer = undefined;
|
||||
void this.flush();
|
||||
}, LIVE_SAMPLE_INTERVAL_MS);
|
||||
this.timer.unref();
|
||||
}
|
||||
|
||||
private async flush() {
|
||||
this.writing = true;
|
||||
// Coalesce synchronous PQueue handoffs and keep SQLite writes in observation order.
|
||||
void Promise.resolve().then(async () => {
|
||||
try {
|
||||
while (this.changed) {
|
||||
this.changed = false;
|
||||
const context = JSON.stringify(this.snapshot(this.limit()));
|
||||
const groups = new Map<Sequelize, string[]>();
|
||||
for (const [id, db] of this.waiting) {
|
||||
const ids = groups.get(db);
|
||||
if (ids) ids.push(id);
|
||||
else groups.set(db, [id]);
|
||||
}
|
||||
for (const [db, ids] of groups) {
|
||||
await db
|
||||
.query(
|
||||
`UPDATE CronTriggers SET queue_live_context=$context
|
||||
WHERE state='queued' AND dequeued_at IS NULL AND id IN (SELECT value FROM json_each($ids))`,
|
||||
{ bind: { context, ids: JSON.stringify(ids) } },
|
||||
)
|
||||
.catch(this.warn);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
this.writing = false;
|
||||
this.changed = false;
|
||||
try {
|
||||
const context = JSON.stringify(this.snapshot(this.limit()));
|
||||
const groups = new Map<Sequelize, Map<string, WaitingSample>>();
|
||||
for (const [id, sample] of this.waiting) {
|
||||
if (sample.context === context) continue;
|
||||
let group = groups.get(sample.db);
|
||||
if (!group) groups.set(sample.db, (group = new Map()));
|
||||
group.set(id, sample);
|
||||
}
|
||||
});
|
||||
for (const [db, samples] of groups) {
|
||||
try {
|
||||
await executionModel(db, 'CronTriggers').update(
|
||||
{ queue_live_context: context },
|
||||
{
|
||||
where: {
|
||||
state: 'queued',
|
||||
dequeued_at: null,
|
||||
[Op.or]: [
|
||||
{ queue_live_context: null },
|
||||
{ queue_live_context: { [Op.ne]: context } },
|
||||
],
|
||||
id: { [Op.in]: [...samples.keys()] },
|
||||
},
|
||||
hooks: false,
|
||||
validate: false,
|
||||
},
|
||||
);
|
||||
for (const [id, sample] of samples) {
|
||||
// A removed/re-admitted ID belongs to a different observation.
|
||||
if (this.waiting.get(id) === sample) sample.context = context;
|
||||
}
|
||||
} catch (error) {
|
||||
this.warn(error as Error);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
this.writing = false;
|
||||
if (this.changed) this.refresh();
|
||||
}
|
||||
}
|
||||
|
||||
admission(limit: number): Admission | undefined {
|
||||
@@ -104,24 +140,145 @@ export function recordQueueAdmission(
|
||||
id: string,
|
||||
admission: Admission,
|
||||
) {
|
||||
return db.query(
|
||||
'UPDATE CronTriggers SET queue_context=$context WHERE id=$id AND queued_at <= $at AND queue_context IS NULL',
|
||||
{ bind: { id, at: Date.now(), context: JSON.stringify(admission) } },
|
||||
return executionModel(db, 'CronTriggers').update(
|
||||
{ queue_context: JSON.stringify(admission) },
|
||||
{
|
||||
where: { id, queued_at: { [Op.lte]: Date.now() }, queue_context: null },
|
||||
silent: true,
|
||||
hooks: false,
|
||||
validate: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export function oldestQueued(db: Sequelize) {
|
||||
return db.query<{
|
||||
id: string;
|
||||
name: string;
|
||||
source: string;
|
||||
queued_at: number;
|
||||
queue_context: string | null;
|
||||
queue_live_context: string | null;
|
||||
}>(
|
||||
`SELECT t.id, COALESCE(NULLIF(c.name,''), c.command, '#' || t.cron_id) AS name, t.source,t.queued_at,t.queue_context,t.queue_live_context
|
||||
FROM CronTriggers t LEFT JOIN Crontabs c ON c.id=t.cron_id
|
||||
WHERE t.state='queued' AND t.dequeued_at IS NULL AND t.queued_at IS NOT NULL ORDER BY t.queued_at,t.id LIMIT 25`,
|
||||
{ type: QueryTypes.SELECT },
|
||||
);
|
||||
return executionModel(db, 'CronTriggers').findAll({
|
||||
attributes: [
|
||||
'id',
|
||||
[
|
||||
fn(
|
||||
'COALESCE',
|
||||
fn('NULLIF', col('task.name'), ''),
|
||||
col('task.command'),
|
||||
fn('printf', '#%s', col('CronTriggers.cron_id')),
|
||||
),
|
||||
'name',
|
||||
],
|
||||
'source',
|
||||
'queued_at',
|
||||
'queue_context',
|
||||
'queue_live_context',
|
||||
],
|
||||
where: {
|
||||
state: 'queued',
|
||||
dequeued_at: null,
|
||||
queued_at: { [Op.not]: null },
|
||||
},
|
||||
include: [
|
||||
{
|
||||
association: executionAssociation(db, 'triggerTask'),
|
||||
attributes: [],
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
order: [
|
||||
['queued_at', 'ASC'],
|
||||
['id', 'ASC'],
|
||||
],
|
||||
limit: 25,
|
||||
raw: true,
|
||||
}) as unknown as Promise<
|
||||
Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
source: string;
|
||||
queued_at: number;
|
||||
queue_context: string | null;
|
||||
queue_live_context: string | null;
|
||||
}>
|
||||
>;
|
||||
}
|
||||
|
||||
// The shared budget supplies its existing occupancy snapshot, including foreign
|
||||
// workers. Diagnostics never open a transaction on the admission critical path.
|
||||
export class GlobalQueueDiagnostics {
|
||||
private pending = new Map<string, string>();
|
||||
private sampled = new Map<string, string>();
|
||||
private timer?: NodeJS.Timeout;
|
||||
private writing = false;
|
||||
|
||||
constructor(private db: Sequelize) {}
|
||||
|
||||
observe(ids: string[], admission?: Admission) {
|
||||
const context = admission && JSON.stringify(admission);
|
||||
this.pending = new Map(
|
||||
ids.map((id) => [id, context ?? this.pending.get(id) ?? '']),
|
||||
);
|
||||
for (const id of this.sampled.keys())
|
||||
if (!this.pending.has(id)) this.sampled.delete(id);
|
||||
if (!ids.length) {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = undefined;
|
||||
} else this.schedule();
|
||||
}
|
||||
|
||||
private schedule() {
|
||||
if (
|
||||
this.timer ||
|
||||
this.writing ||
|
||||
![...this.pending].some(
|
||||
([id, value]) => value && this.sampled.get(id) !== value,
|
||||
)
|
||||
)
|
||||
return;
|
||||
this.timer = setTimeout(() => {
|
||||
this.timer = undefined;
|
||||
void this.flush();
|
||||
}, LIVE_SAMPLE_INTERVAL_MS);
|
||||
this.timer.unref();
|
||||
}
|
||||
|
||||
private async flush() {
|
||||
this.writing = true;
|
||||
const groups = new Map<string, string[]>();
|
||||
for (const [id, context] of this.pending) {
|
||||
if (!context || this.sampled.get(id) === context) continue;
|
||||
const group = groups.get(context) ?? [];
|
||||
group.push(id);
|
||||
groups.set(context, group);
|
||||
}
|
||||
try {
|
||||
for (const [context, ids] of groups) {
|
||||
await executionModel(this.db, 'CronTriggers').update(
|
||||
{
|
||||
queue_context: fn('COALESCE', col('queue_context'), context),
|
||||
queue_live_context: context,
|
||||
},
|
||||
{
|
||||
where: {
|
||||
id: { [Op.in]: ids },
|
||||
state: 'queued',
|
||||
dequeued_at: null,
|
||||
[Op.or]: [
|
||||
{ queue_live_context: null },
|
||||
{ queue_live_context: { [Op.ne]: context } },
|
||||
],
|
||||
},
|
||||
hooks: false,
|
||||
validate: false,
|
||||
},
|
||||
);
|
||||
for (const id of ids)
|
||||
if (this.pending.get(id) === context) this.sampled.set(id, context);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[queue] Could not save global occupancy:', error);
|
||||
// A later observation retries a failed sample, without a timer that can
|
||||
// outlive the budget/database after the last waiter has left.
|
||||
return;
|
||||
} finally {
|
||||
this.writing = false;
|
||||
}
|
||||
this.schedule();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user