Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions workspaces/x2a/.changeset/large-cloths-bow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@red-hat-developer-hub/backstage-plugin-x2a-backend': patch
'@red-hat-developer-hub/backstage-plugin-x2a-common': patch
'@red-hat-developer-hub/backstage-plugin-x2a-node': patch
'@red-hat-developer-hub/backstage-plugin-x2a': patch
---

Downstream phase jobs are automatically marked as stale when an upstream phase completes successfully.
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
/*
* Copyright Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import type { Knex } from 'knex';

const PHASES = [
'init',
'analyze',
'migrate',
'publish',
'adversarial-analyze',
'adversarial-migrate',
];

const EXTENDED_STATUSES = [
'pending',
'running',
'success',
'error',
'cancelled',
'stale',
];

const ORIGINAL_STATUSES = [
'pending',
'running',
'success',
'error',
'cancelled',
];

function createJobsTable(
table: Knex.CreateTableBuilder,
statuses: string[],
): void {
table.uuid('id').primary();
table.text('log');
table.timestamp('started_at').notNullable();
table.timestamp('finished_at');
table.string('status').notNullable().defaultTo('pending').checkIn(statuses);
table.string('phase').notNullable().defaultTo('init').checkIn(PHASES);
table
.uuid('project_id')
Comment thread
mareklibra marked this conversation as resolved.
.notNullable()
.references('id')
.inTable('projects')
.onDelete('CASCADE')
.index();
table
.uuid('module_id')
.nullable()
.references('id')
.inTable('modules')
.onDelete('CASCADE')
.index();
table.text('error_details');
table.text('telemetry');
table.string('k8s_job_name');
table.string('callback_token');
table.string('commit_id').nullable();
table.index('started_at');
table.index('finished_at');
table.index('status');
table.index('phase');
table.index('k8s_job_name');
}

async function recreateJobsTableSqlite(
knex: Knex,
statuses: string[],
staging: string,
): Promise<void> {
// staging must be unique across all migrations — SQLite index names are
// global and survive table renames, so reusing a prior staging name causes
// an "index already exists" error on the next recreate.
await knex.schema.raw('PRAGMA foreign_keys = OFF');
try {
await knex.schema.createTable(staging, table =>
createJobsTable(table, statuses),
);
await knex.schema.raw(
`INSERT INTO ${staging} (id, log, started_at, finished_at, status, phase, error_details, telemetry, k8s_job_name, callback_token, commit_id, project_id, module_id)` +
` SELECT id, log, started_at, finished_at, status, phase, error_details, telemetry, k8s_job_name, callback_token, commit_id, project_id, module_id FROM jobs`,
);
await knex.schema.dropTable('jobs');
await knex.schema.raw(`ALTER TABLE ${staging} RENAME TO jobs`);
} finally {
await knex.schema.raw('PRAGMA foreign_keys = ON');
}
}

/**
* Expands the jobs.status CHECK constraint to include 'stale',
* needed for cascading invalidation of downstream phase jobs.
*
* @public
*/
export async function up(knex: Knex): Promise<void> {
const client = knex.client.config.client;

if (client === 'better-sqlite3') {
await recreateJobsTableSqlite(
knex,
EXTENDED_STATUSES,
'jobs_status_expanded',
);
} else {
await knex.raw(
`ALTER TABLE jobs DROP CONSTRAINT IF EXISTS jobs_status_check`,
);
await knex.raw(
`ALTER TABLE jobs ADD CONSTRAINT jobs_status_check CHECK (status IN ('pending', 'running', 'success', 'error', 'cancelled', 'stale'))`,
);
}
}

/**
* Reverts the jobs.status CHECK constraint to exclude 'stale'.
*
* @public
*/
export async function down(knex: Knex): Promise<void> {
// Stale rows must be converted before reinstating the constraint;
await knex('jobs').where('status', 'stale').update({ status: 'success' });

const client = knex.client.config.client;

if (client === 'better-sqlite3') {
await recreateJobsTableSqlite(
knex,
ORIGINAL_STATUSES,
'jobs_status_contracted',
);
} else {
await knex.raw(
`ALTER TABLE jobs DROP CONSTRAINT IF EXISTS jobs_status_check`,
);
await knex.raw(
`ALTER TABLE jobs ADD CONSTRAINT jobs_status_check CHECK (status IN ('pending', 'running', 'success', 'error', 'cancelled'))`,
Comment thread
mareklibra marked this conversation as resolved.
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ export interface MockRouterDeps {
listJobsForModule: jest.Mock;
createJob: jest.Mock;
getJobLogs: jest.Mock;
markJobsAsStale: jest.Mock;
};
kubeService: {
createJob: jest.Mock;
Expand Down Expand Up @@ -298,11 +299,12 @@ export function createMockRouterDeps(): MockRouterDeps {
softDeleteModule: jest.fn().mockResolvedValue(1),
restoreModule: jest.fn().mockResolvedValue(1),
updateModule: jest.fn().mockResolvedValue(1),
listJobs: jest.fn(),
listJobs: jest.fn().mockResolvedValue([]),
listJobsForProject: jest.fn(),
listJobsForModule: jest.fn(),
createJob: jest.fn(),
getJobLogs: jest.fn(),
markJobsAsStale: jest.fn().mockResolvedValue(undefined),
},
kubeService: {
createJob: jest.fn().mockResolvedValue({ k8sJobName: 'test-job' }),
Expand Down
3 changes: 3 additions & 0 deletions workspaces/x2a/plugins/x2a-backend/src/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,9 @@ const getX2aDatabaseServiceMock = (): typeof x2aDatabaseServiceRef.T => ({
listJobsForModule: jest
.fn()
.mockRejectedValue(new NotAllowedError('mock error')),
markJobsAsStale: jest
.fn()
.mockRejectedValue(new NotAllowedError('mock error')),
// rules
createRule: jest.fn().mockRejectedValue(new NotAllowedError('mock error')),
updateRule: jest.fn().mockRejectedValue(new NotAllowedError('mock error')),
Expand Down
Loading
Loading