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:
whyour committed 2026-11-25 00:54:41 +08:00
1 parent cddabbaf0e
commit 2f01f756d7
74 files changed
+6891 -837

No files matched your search

+3 -39
View File
@@ -1,5 +1,6 @@
import { defineCrontabModel } from './executionModelDefinitions';
import { sequelize } from '.';
import { DataTypes, Model, ModelDefined } from 'sequelize';
import { Model } from 'sequelize';
export class Crontab {
name?: string;
@@ -72,41 +73,4 @@ export enum CrontabStatus {
}
export interface CronInstance extends Model<Crontab, Crontab>, Crontab {}
export const CrontabModel = sequelize.define<CronInstance>('Crontab', {
name: {
unique: 'compositeIndex',
type: DataTypes.STRING,
},
command: {
unique: 'compositeIndex',
type: DataTypes.STRING,
},
schedule: {
unique: 'compositeIndex',
type: DataTypes.STRING,
},
timestamp: DataTypes.STRING,
saved: DataTypes.BOOLEAN,
status: DataTypes.NUMBER,
isSystem: DataTypes.NUMBER,
pid: DataTypes.NUMBER,
isDisabled: DataTypes.NUMBER,
isPinned: DataTypes.NUMBER,
log_path: DataTypes.STRING,
queued_token: DataTypes.STRING,
labels: DataTypes.JSON,
last_instance_id: DataTypes.INTEGER,
last_running_time: DataTypes.NUMBER,
last_execution_time: DataTypes.NUMBER,
sub_id: { type: DataTypes.NUMBER, allowNull: true },
extra_schedules: DataTypes.JSON,
task_before: DataTypes.STRING,
task_after: DataTypes.STRING,
log_name: DataTypes.STRING,
allow_multiple_instances: DataTypes.NUMBER,
skip_if_pending: DataTypes.BOOLEAN,
max_queue_wait: DataTypes.INTEGER,
catchup_seconds: DataTypes.INTEGER,
recovery_from: DataTypes.BIGINT,
work_dir: DataTypes.STRING,
});
export const CrontabModel = defineCrontabModel(sequelize);
+3 -51
View File
@@ -1,4 +1,5 @@
import { DataTypes, Model } from 'sequelize';
import { defineCrontabStatModel } from './executionModelDefinitions';
import { Model } from 'sequelize';
import { sequelize } from '.';
export class CrontabStat {
@@ -30,53 +31,4 @@ export interface CrontabStatInstance
extends Model<CrontabStat, CrontabStat>,
CrontabStat {}
export const CrontabStatModel = sequelize.define<CrontabStatInstance>(
'CrontabStat',
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
ref_id: {
type: DataTypes.NUMBER,
allowNull: false,
},
date: {
type: DataTypes.STRING,
allowNull: false,
},
run_count: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
success_count: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
fail_count: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
untimed_count: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0,
},
total_time: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
fixed_max_time: { type: DataTypes.NUMBER, allowNull: true },
max_time: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
},
{
indexes: [
{ unique: true, fields: ['ref_id', 'date'] },
{ fields: ['date'] },
],
},
);
export const CrontabStatModel = defineCrontabStatModel(sequelize);
+160
View File
@@ -0,0 +1,160 @@
import { DataTypes, Sequelize } from 'sequelize';
import type { CronInstance } from './cron';
import type { RunningInstanceModel } from './runningInstance';
import type { CrontabStatInstance } from './cronStats';
import type { SystemInstance } from './system';
export function defineCrontabModel(database: Sequelize) {
return database.define<CronInstance>('Crontab', {
name: {
unique: 'compositeIndex',
type: DataTypes.STRING,
},
command: {
unique: 'compositeIndex',
type: DataTypes.STRING,
},
schedule: {
unique: 'compositeIndex',
type: DataTypes.STRING,
},
timestamp: DataTypes.STRING,
saved: DataTypes.BOOLEAN,
status: DataTypes.NUMBER,
isSystem: DataTypes.NUMBER,
pid: DataTypes.NUMBER,
isDisabled: DataTypes.NUMBER,
isPinned: DataTypes.NUMBER,
log_path: DataTypes.STRING,
queued_token: DataTypes.STRING,
labels: DataTypes.JSON,
last_instance_id: DataTypes.INTEGER,
last_running_time: DataTypes.NUMBER,
last_execution_time: DataTypes.NUMBER,
sub_id: { type: DataTypes.NUMBER, allowNull: true },
extra_schedules: DataTypes.JSON,
task_before: DataTypes.STRING,
task_after: DataTypes.STRING,
log_name: DataTypes.STRING,
allow_multiple_instances: DataTypes.NUMBER,
skip_if_pending: DataTypes.BOOLEAN,
max_queue_wait: DataTypes.INTEGER,
catchup_seconds: DataTypes.INTEGER,
recovery_from: DataTypes.BIGINT,
work_dir: DataTypes.STRING,
});
}
export function defineRunningInstanceModel(database: Sequelize) {
return database.define<RunningInstanceModel>(
'RunningInstance',
{
cron_id: {
type: DataTypes.NUMBER,
allowNull: false,
},
pid: {
type: DataTypes.NUMBER,
allowNull: true,
},
log_path: {
type: DataTypes.STRING,
allowNull: true,
},
started_at: {
type: DataTypes.NUMBER,
allowNull: false,
},
finished_at: {
type: DataTypes.NUMBER,
allowNull: true,
},
status: {
type: DataTypes.NUMBER,
allowNull: false,
defaultValue: 0,
},
exit_code: {
type: DataTypes.NUMBER,
allowNull: true,
},
},
{
indexes: [
{ fields: ['cron_id', 'pid', 'started_at'] },
{ fields: ['cron_id', 'id'] },
// Settlement looks for live siblings while holding the writer transaction.
// Finished history must not make that lookup scan every past execution.
{
name: 'running_instances_active_cron_id',
fields: ['cron_id', 'id'],
where: { status: 0 },
},
],
},
);
}
export function defineCrontabStatModel(database: Sequelize) {
return database.define<CrontabStatInstance>(
'CrontabStat',
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
ref_id: {
type: DataTypes.NUMBER,
allowNull: false,
},
date: {
type: DataTypes.STRING,
allowNull: false,
},
run_count: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
success_count: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
fail_count: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
untimed_count: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0,
},
total_time: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
fixed_max_time: { type: DataTypes.NUMBER, allowNull: true },
max_time: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
},
{
indexes: [
{ unique: true, fields: ['ref_id', 'date'] },
{ fields: ['date'] },
],
},
);
}
export function defineSystemModel(database: Sequelize) {
return database.define<SystemInstance>('Auth', {
ip: DataTypes.STRING,
type: DataTypes.STRING,
info: {
type: DataTypes.JSON,
allowNull: true,
},
});
}
+390
View File
@@ -0,0 +1,390 @@
import {
defineCrontabModel,
defineRunningInstanceModel,
defineCrontabStatModel,
defineSystemModel,
} from './executionModelDefinitions';
import {
DataTypes,
Model,
ModelStatic,
Sequelize,
ModelAttributes,
} from 'sequelize';
import type { Literal, Fn, Col } from 'sequelize/types/utils';
import type { CronInstance } from './cron';
import type { RunningInstanceModel } from './runningInstance';
import type { CrontabStatInstance } from './cronStats';
import type { SystemInstance } from './system';
import type { TriggerSource, TriggerState } from '../cron/types';
// Ledger tables are installed by versioned migrations, not Model.sync().
// Bind each mapping to its caller's connection: workers and test databases must
// never share the application's singleton or silently open another transaction.
interface LedgerRows {
CronPlanCoverage: { id: number; since: number };
CronTriggers: {
id: string;
source: TriggerSource;
state: TriggerState;
reason: string | null;
log_path: string | null;
owner: string | null;
queue_context: string | null;
queue_live_context: string | null;
system_rule: string | null;
process_identity: string | null;
command_identity: string | null;
cron_id: number;
scheduled_at: number | null;
queued_at: number | null;
started_at: number | null;
finished_at: number | null;
exit_code: number | null;
counted: number;
observed_at: number;
dequeued_at: number | null;
system_dispatch_at: number | null;
command_started_at: number | null;
instance_id: number | null;
script_started_at: number | null;
stop_requested: number | null;
resume_pending: number | null;
stop_exit_at: number | null;
stop_exit_verified: number | null;
exit_pending: number | null;
};
CronConcurrencyLeases: {
trigger_id: string;
token: string;
owner: string;
command_identity: string | null;
};
CronConcurrencyWaiters: {
trigger_id: string;
token: string;
owner: string;
};
CronStopRequests: {
targets: string | null;
root_identity: string | null;
namespace_owner: string | null;
instance_id: number;
cron_id: number;
pid: number | null;
signalled: number;
signalled_at: number | null;
};
CronStopBatches: {
request_id: string;
cron_ids: string;
snapshot: string | null;
status_code: number;
};
CronManualSubmissions: {
trigger_id: string;
token: string;
snapshot: string;
};
CronShellBindings: {
receipt: string;
trigger_id: string | null;
};
CronExitObservations: {
trigger_id: string;
outcome: string;
finished_at: number;
};
CronBoundExitConflicts: {
trigger_id: string;
outcome: string;
finished_at: number;
};
CronUnmatchedBoundExits: {
trigger_id: string;
outcome: string | null;
finished_at: number | null;
};
CronLegacyExitBookings: {
trigger_id: string;
source: TriggerSource;
outcome: string | null;
day: string | null;
cron_id: number;
started_at: number | null;
finished_at: number | null;
stopped: number | null;
stat_id: number | null;
disputed: number | null;
bound: number | null;
};
CronPrunedUnknownRuns: {
trigger_id: string;
source: TriggerSource;
last_possible_day: string;
cron_id: number;
started_at: number;
};
CronHistoryRetention: {
id: number;
cutoff: number;
};
CronPlanSwitches: {
token: string;
seq: number;
staged_at: number | null;
first_at: number | null;
last_at: number | null;
};
CronSystemPlans: {
zone: string;
rules: string;
id: number;
staged: number;
confirmed: number | null;
};
SchemaMigrations: {
id: string;
applied_at: string;
};
}
type Persisted<T> = {
[K in keyof T]-?: undefined extends T[K]
? Exclude<T[K], undefined> | null
: T[K];
} & { id: number; createdAt: Date; updatedAt: Date };
type ExistingRows = {
Crontabs: Persisted<CronInstance['_attributes']>;
RunningInstances: Persisted<RunningInstanceModel['_attributes']>;
CrontabStats: Persisted<CrontabStatInstance['_attributes']>;
Auths: Persisted<SystemInstance['_attributes']>;
};
type Rows = LedgerRows & ExistingRows;
type Creation<T> = { [K in keyof T]?: T[K] | Literal | Fn | Col };
type RowModel<T extends object> = Model<T, Creation<T>> & T;
const definitions: {
[K in keyof LedgerRows]: ModelAttributes<RowModel<LedgerRows[K]>>;
} = {
CronPlanCoverage: {
id: { type: DataTypes.INTEGER, primaryKey: true },
since: DataTypes.BIGINT,
},
CronTriggers: {
id: { type: DataTypes.TEXT, primaryKey: true },
source: DataTypes.TEXT,
state: DataTypes.TEXT,
reason: DataTypes.TEXT,
log_path: DataTypes.TEXT,
owner: DataTypes.TEXT,
queue_context: DataTypes.TEXT,
queue_live_context: DataTypes.TEXT,
system_rule: DataTypes.TEXT,
process_identity: DataTypes.TEXT,
command_identity: DataTypes.TEXT,
cron_id: DataTypes.BIGINT,
scheduled_at: DataTypes.BIGINT,
queued_at: DataTypes.BIGINT,
started_at: DataTypes.BIGINT,
finished_at: DataTypes.BIGINT,
exit_code: DataTypes.BIGINT,
counted: DataTypes.BIGINT,
observed_at: DataTypes.BIGINT,
dequeued_at: DataTypes.BIGINT,
system_dispatch_at: DataTypes.BIGINT,
command_started_at: DataTypes.BIGINT,
instance_id: DataTypes.BIGINT,
script_started_at: DataTypes.BIGINT,
stop_requested: DataTypes.BIGINT,
resume_pending: DataTypes.BIGINT,
stop_exit_at: DataTypes.BIGINT,
stop_exit_verified: DataTypes.BIGINT,
exit_pending: DataTypes.BIGINT,
},
CronConcurrencyLeases: {
trigger_id: { type: DataTypes.TEXT, primaryKey: true },
token: DataTypes.TEXT,
owner: DataTypes.TEXT,
command_identity: DataTypes.TEXT,
},
CronConcurrencyWaiters: {
trigger_id: { type: DataTypes.TEXT, primaryKey: true },
token: DataTypes.TEXT,
owner: DataTypes.TEXT,
},
CronStopRequests: {
targets: DataTypes.TEXT,
root_identity: DataTypes.TEXT,
namespace_owner: DataTypes.TEXT,
instance_id: { type: DataTypes.INTEGER, primaryKey: true },
cron_id: DataTypes.BIGINT,
pid: DataTypes.BIGINT,
signalled: DataTypes.BIGINT,
signalled_at: DataTypes.BIGINT,
},
CronStopBatches: {
request_id: { type: DataTypes.TEXT, primaryKey: true },
cron_ids: DataTypes.TEXT,
snapshot: DataTypes.TEXT,
status_code: DataTypes.BIGINT,
},
CronManualSubmissions: {
trigger_id: { type: DataTypes.TEXT, primaryKey: true },
token: DataTypes.TEXT,
snapshot: DataTypes.TEXT,
},
CronShellBindings: {
receipt: { type: DataTypes.TEXT, primaryKey: true },
trigger_id: DataTypes.TEXT,
},
CronExitObservations: {
trigger_id: { type: DataTypes.TEXT, primaryKey: true },
outcome: { type: DataTypes.TEXT, primaryKey: true },
finished_at: { type: DataTypes.INTEGER, primaryKey: true },
},
CronBoundExitConflicts: {
trigger_id: { type: DataTypes.TEXT, primaryKey: true },
outcome: { type: DataTypes.TEXT, primaryKey: true },
finished_at: { type: DataTypes.INTEGER, primaryKey: true },
},
CronUnmatchedBoundExits: {
trigger_id: { type: DataTypes.TEXT, primaryKey: true },
outcome: DataTypes.TEXT,
finished_at: DataTypes.BIGINT,
},
CronLegacyExitBookings: {
trigger_id: { type: DataTypes.TEXT, primaryKey: true },
source: DataTypes.TEXT,
outcome: DataTypes.TEXT,
day: DataTypes.TEXT,
cron_id: DataTypes.BIGINT,
started_at: DataTypes.BIGINT,
finished_at: DataTypes.BIGINT,
stopped: DataTypes.BIGINT,
stat_id: DataTypes.BIGINT,
disputed: DataTypes.BIGINT,
bound: DataTypes.BIGINT,
},
CronPrunedUnknownRuns: {
trigger_id: { type: DataTypes.TEXT, primaryKey: true },
source: DataTypes.TEXT,
last_possible_day: DataTypes.TEXT,
cron_id: DataTypes.BIGINT,
started_at: DataTypes.BIGINT,
},
CronHistoryRetention: {
id: { type: DataTypes.INTEGER, primaryKey: true },
cutoff: DataTypes.BIGINT,
},
CronPlanSwitches: {
token: DataTypes.TEXT,
seq: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
staged_at: DataTypes.BIGINT,
first_at: DataTypes.BIGINT,
last_at: DataTypes.BIGINT,
},
CronSystemPlans: {
zone: DataTypes.TEXT,
rules: DataTypes.TEXT,
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
staged: DataTypes.BIGINT,
confirmed: DataTypes.BIGINT,
},
SchemaMigrations: {
id: { type: DataTypes.TEXT, primaryKey: true },
applied_at: DataTypes.TEXT,
},
};
const existingNames: Record<keyof ExistingRows, string> = {
Crontabs: 'Crontab',
RunningInstances: 'RunningInstance',
CrontabStats: 'CrontabStat',
Auths: 'Auth',
};
export function executionModel<K extends keyof Rows>(
database: Sequelize,
table: K,
): ModelStatic<RowModel<Rows[K]>> {
const name =
table in existingNames ? existingNames[table as keyof ExistingRows] : table;
if (!database.isDefined(name)) {
if (table === 'Crontabs') defineCrontabModel(database);
else if (table === 'RunningInstances') defineRunningInstanceModel(database);
else if (table === 'CrontabStats') defineCrontabStatModel(database);
else if (table === 'Auths') defineSystemModel(database);
else
database.define(
name,
definitions[table as keyof LedgerRows] as ModelAttributes,
{ tableName: table, timestamps: false, freezeTableName: true },
);
}
return database.model(name) as ModelStatic<RowModel<Rows[K]>>;
}
const relationships = {
leaseTrigger: [
'CronConcurrencyLeases',
'CronTriggers',
'trigger',
'trigger_id',
'id',
],
waiterTrigger: [
'CronConcurrencyWaiters',
'CronTriggers',
'trigger',
'trigger_id',
'id',
],
submissionTrigger: [
'CronManualSubmissions',
'CronTriggers',
'trigger',
'trigger_id',
'id',
],
triggerStop: [
'CronTriggers',
'CronStopRequests',
'stop',
'instance_id',
'instance_id',
],
triggerTask: ['CronTriggers', 'Crontabs', 'task', 'cron_id', 'id'],
instanceTrigger: [
'RunningInstances',
'CronTriggers',
'trigger',
'instance_id',
'id',
],
} as const;
// Associations describe existing joins only; migrations own foreign keys.
export function executionAssociation(
database: Sequelize,
relation: keyof typeof relationships,
) {
const [from, to, as, foreignKey, key] = relationships[relation];
const source: ModelStatic<Model> = executionModel(database, from);
if (!source.associations[as]) {
const target: ModelStatic<Model> = executionModel(database, to);
if (relation === 'instanceTrigger')
source.hasOne(target, {
as,
foreignKey,
sourceKey: key,
constraints: false,
});
else
source.belongsTo(target, {
as,
foreignKey,
targetKey: key,
constraints: false,
});
}
return source.associations[as];
}
+9 -1
View File
@@ -8,7 +8,11 @@ export const sequelize = new Sequelize({
storage: join(config.dbPath, 'database.sqlite'),
logging: false,
retry: {
max: 10,
// Keep a bounded 15-second wait in JS. Constant delays let a burst of
// writers make progress without exponential retries stretching the queue.
max: 301,
backoffBase: 50,
backoffExponent: 1,
match: ['SQLITE_BUSY: database is locked'],
},
pool: {
@@ -29,6 +33,10 @@ sequelize.addHook('beforeQuery', async (_options, query) => {
let ready = initialized.get(connection);
if (!ready) {
ready = new Promise<void>((resolve, reject) => {
// Native busy waits occupy libuv workers. Concurrent BEGINs can exhaust
// that pool and prevent the lock holder's next query or COMMIT from
// running. Let Sequelize's asynchronous SQLITE_BUSY retries wait instead.
connection.configure('busyTimeout', 0);
connection.run('PRAGMA synchronous=EXTRA', (error) =>
error ? reject(error) : resolve(),
);
+3 -41
View File
@@ -1,5 +1,6 @@
import { defineRunningInstanceModel } from './executionModelDefinitions';
import { sequelize } from '.';
import { DataTypes, Model } from 'sequelize';
import { Model } from 'sequelize';
export enum InstanceStatus {
'running' = 0,
@@ -46,43 +47,4 @@ export interface RunningInstanceModel
extends Model<RunningInstanceAttributes, RunningInstanceAttributes>,
RunningInstanceAttributes {}
export const RunningInstanceModel = sequelize.define<RunningInstanceModel>(
'RunningInstance',
{
cron_id: {
type: DataTypes.NUMBER,
allowNull: false,
},
pid: {
type: DataTypes.NUMBER,
allowNull: true,
},
log_path: {
type: DataTypes.STRING,
allowNull: true,
},
started_at: {
type: DataTypes.NUMBER,
allowNull: false,
},
finished_at: {
type: DataTypes.NUMBER,
allowNull: true,
},
status: {
type: DataTypes.NUMBER,
allowNull: false,
defaultValue: InstanceStatus.running,
},
exit_code: {
type: DataTypes.NUMBER,
allowNull: true,
},
},
{
indexes: [
{ fields: ['cron_id', 'pid', 'started_at'] },
{ fields: ['cron_id', 'id'] },
],
},
);
export const RunningInstanceModel = defineRunningInstanceModel(sequelize);
+38 -25
View File
@@ -1,7 +1,8 @@
import { executionModel } from './executionModels';
import dayjs from 'dayjs';
import { installTriggerHistory } from '../cron/schema';
import { repairLegacyDailyStatistics } from '../cron/settlement/legacyDailyStatistics';
import { QueryTypes, Sequelize } from 'sequelize';
import { QueryTypes, Sequelize, literal, DataTypes } from 'sequelize';
export const prunedExitMigrationId = 'preserve-pruned-bound-exits-v1';
@@ -45,15 +46,20 @@ const columns = [
export async function migrateSchema(database: Sequelize): Promise<void> {
await database.transaction(async (transaction) => {
await database.query(
'CREATE TABLE IF NOT EXISTS "SchemaMigrations" ("id" TEXT PRIMARY KEY, "applied_at" TEXT NOT NULL)',
await database.getQueryInterface().createTable(
'SchemaMigrations',
{
id: { type: DataTypes.TEXT, primaryKey: true },
applied_at: { type: DataTypes.TEXT, allowNull: false },
},
{ transaction },
);
await installTriggerHistory(database, transaction);
const applied = await database.query<{ id: string }>(
'SELECT "id" FROM "SchemaMigrations"',
{ type: QueryTypes.SELECT, transaction },
);
const applied = await executionModel(database, 'SchemaMigrations').findAll({
attributes: ['id'],
transaction,
raw: true,
});
const appliedIds = new Set(applied.map(({ id }) => id));
for (const { table, column, type } of columns) {
const id = `add-${table}-${column}`;
@@ -68,18 +74,22 @@ export async function migrateSchema(database: Sequelize): Promise<void> {
throw new Error(`Migration table is missing: ${table}`);
if (!fields.some((field) => field.name === column)) {
// table/column/type come only from the static migration manifest above.
await database.query(
`ALTER TABLE "${table}" ADD COLUMN "${column}" ${type}`,
await database.getQueryInterface().addColumn(
table,
column,
{
type: type.replace(' NOT NULL DEFAULT 0', ''),
...(type.includes('NOT NULL')
? { allowNull: false, defaultValue: 0 }
: {}),
},
{ transaction },
);
}
if (!appliedIds.has(id)) {
await database.query(
'INSERT INTO "SchemaMigrations" ("id", "applied_at") VALUES (:id, :appliedAt)',
{
replacements: { id, appliedAt: new Date().toISOString() },
transaction,
},
await executionModel(database, 'SchemaMigrations').create(
{ id, applied_at: new Date().toISOString() },
{ transaction, silent: true, hooks: false, validate: false },
);
}
}
@@ -107,19 +117,22 @@ export async function migrateSchema(database: Sequelize): Promise<void> {
},
);
}
await database.query(
'INSERT INTO SchemaMigrations(id,applied_at) VALUES ($id,CURRENT_TIMESTAMP)',
{ bind: { id: retentionId }, transaction },
await executionModel(database, 'SchemaMigrations').create(
{ id: retentionId, applied_at: literal('CURRENT_TIMESTAMP') },
{ transaction, silent: true, hooks: false, validate: false },
);
}
if (!appliedIds.has(repairId)) {
await repairLegacyDailyStatistics(database, transaction, prior);
// This reconciliation includes v1 and v2. Record all on fresh installations
// so rolling back and upgrading again cannot replay the superseded repair.
await database.query(
`INSERT OR IGNORE INTO SchemaMigrations(id,applied_at)
VALUES ('repair-legacy-daily-statistics-v1',CURRENT_TIMESTAMP),('repair-legacy-daily-statistics-v2',CURRENT_TIMESTAMP),($id,CURRENT_TIMESTAMP)`,
{ transaction, bind: { id: repairId } },
await executionModel(database, 'SchemaMigrations').bulkCreate(
[
'repair-legacy-daily-statistics-v1',
'repair-legacy-daily-statistics-v2',
repairId,
].map((id) => ({ id, applied_at: literal('CURRENT_TIMESTAMP') })),
{ transaction, ignoreDuplicates: true, hooks: false },
);
}
@@ -133,9 +146,9 @@ export async function migrateSchema(database: Sequelize): Promise<void> {
AND NOT EXISTS (SELECT 1 FROM CronBoundExitConflicts WHERE trigger_id=b.trigger_id)`,
{ transaction },
);
await database.query(
'INSERT INTO SchemaMigrations(id,applied_at) VALUES ($id,CURRENT_TIMESTAMP)',
{ bind: { id: prunedExitMigrationId }, transaction },
await executionModel(database, 'SchemaMigrations').create(
{ id: prunedExitMigrationId, applied_at: literal('CURRENT_TIMESTAMP') },
{ transaction, silent: true, hooks: false, validate: false },
);
}
+3 -9
View File
@@ -1,5 +1,6 @@
import { defineSystemModel } from './executionModelDefinitions';
import { sequelize } from '.';
import { DataTypes, Model, ModelDefined } from 'sequelize';
import { Model } from 'sequelize';
import { NotificationInfo } from './notify';
export class SystemInfo {
@@ -109,11 +110,4 @@ export type SystemModelInfo = SystemConfigInfo &
export interface SystemInstance
extends Model<SystemInfo, SystemInfo>,
SystemInfo {}
export const SystemModel = sequelize.define<SystemInstance>('Auth', {
ip: DataTypes.STRING,
type: DataTypes.STRING,
info: {
type: DataTypes.JSON,
allowNull: true,
},
});
export const SystemModel = defineSystemModel(sequelize);