From 5d1d62acb84948cd69e2827be78408b6b25f6175 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Wed, 8 Jul 2026 23:41:24 +0200 Subject: [PATCH 01/60] feat(preprocessing): initial mock page for preprocessing --- webapp/src/app/app.routes.ts | 7 + .../app-login/app-login.component.html | 9 + .../app-login/app-login.component.scss | 5 + .../modules/app-login/app-login.component.ts | 6 + .../preprocessing.component.html | 204 +++++++++++++ .../preprocessing.component.scss | 264 +++++++++++++++++ .../preprocessing/preprocessing.component.ts | 252 +++++++++++++++++ .../preprocessing/preprocessing.models.ts | 267 ++++++++++++++++++ .../task-schedule-dialog.component.html | 99 +++++++ .../task-schedule-dialog.component.scss | 138 +++++++++ .../task-schedule-dialog.component.ts | 125 ++++++++ .../authentication.interceptor.ts | 9 +- .../app/shared/services/credential.service.ts | 38 ++- .../shared/ui/app-menu/app-menu.component.ts | 7 + 14 files changed, 1425 insertions(+), 5 deletions(-) create mode 100644 webapp/src/app/modules/preprocessing/preprocessing.component.html create mode 100644 webapp/src/app/modules/preprocessing/preprocessing.component.scss create mode 100644 webapp/src/app/modules/preprocessing/preprocessing.component.ts create mode 100644 webapp/src/app/modules/preprocessing/preprocessing.models.ts create mode 100644 webapp/src/app/modules/preprocessing/task-schedule-dialog/task-schedule-dialog.component.html create mode 100644 webapp/src/app/modules/preprocessing/task-schedule-dialog/task-schedule-dialog.component.scss create mode 100644 webapp/src/app/modules/preprocessing/task-schedule-dialog/task-schedule-dialog.component.ts diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 40f31992..8715eef1 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -223,6 +223,13 @@ export const routes: Routes = [ }, runGuardsAndResolvers: 'always', }, + { + path: 'preprocessing', + loadComponent: () => + import('./modules/preprocessing/preprocessing.component').then( + (mod) => mod.PreprocessingComponent, + ), + }, { path: 'news/:id', diff --git a/webapp/src/app/modules/app-login/app-login.component.html b/webapp/src/app/modules/app-login/app-login.component.html index 0c3c7754..bb096a2e 100644 --- a/webapp/src/app/modules/app-login/app-login.component.html +++ b/webapp/src/app/modules/app-login/app-login.component.html @@ -158,5 +158,14 @@ } + + + diff --git a/webapp/src/app/modules/app-login/app-login.component.scss b/webapp/src/app/modules/app-login/app-login.component.scss index c09190d7..8069936c 100644 --- a/webapp/src/app/modules/app-login/app-login.component.scss +++ b/webapp/src/app/modules/app-login/app-login.component.scss @@ -104,6 +104,11 @@ p { font-weight: 700; } +.skip-login-button { + width: 100%; + margin-top: 20px; +} + .form-actions { display: flex; align-items: center; diff --git a/webapp/src/app/modules/app-login/app-login.component.ts b/webapp/src/app/modules/app-login/app-login.component.ts index fe894887..149934ac 100644 --- a/webapp/src/app/modules/app-login/app-login.component.ts +++ b/webapp/src/app/modules/app-login/app-login.component.ts @@ -203,6 +203,12 @@ export class AppLoginComponent implements OnDestroy { }); } + // TEMP: dev login bypass. Remove once the real login flow works again. + skipAsSuperAdmin() { + this.credentialService.loginAsMockSuperAdmin(); + this.router.navigate(['/preprocessing']); + } + editCredentials() { this.currentStep = 'credentials'; this.accountId = undefined; diff --git a/webapp/src/app/modules/preprocessing/preprocessing.component.html b/webapp/src/app/modules/preprocessing/preprocessing.component.html new file mode 100644 index 00000000..e112c71a --- /dev/null +++ b/webapp/src/app/modules/preprocessing/preprocessing.component.html @@ -0,0 +1,204 @@ +
+ + + + +
+ + +
+ {{ containerStatus().name }} +
+ {{ containerStatus().image }} + {{ + containerStatus().imageDigest + }} + @switch (containerStatus().state) { + @case ('running') { + Läuft{{ + containerStatus().uptime + ? ' · seit ' + containerStatus().uptime + : '' + }} + } + @case ('stopped') { + Gestoppt + } + @case ('restarting') { + Wird neu gestartet … + } + } + @if (containerStatus().updateAvailable) { + + upgrade + Neue Version verfügbar + + } +
+
+
+ +
+ @if (containerStatus().updateAvailable) { + + } + @if (containerStatus().state === 'running') { + + + } @else { + + } +
+
+
+ + + + + + +
+ + +
+ {{ row.name }} + {{ row.description }} + {{ row.targetIndex }} +
+
+ + +
+ {{ formatSchedule(row.schedule) }} + +
+
+ + + @switch (row.status) { + @case ('running') { + + + Läuft + + } + @case ('success') { + + check_circle + Erfolgreich + + } + @case ('failed') { + + error + Fehlgeschlagen + + } + @default { + + schedule + Bereit + + } + } + + + + @if (row.lastRun) { +
+ {{ row.lastRun.startedAt | date: 'dd.MM.yyyy HH:mm' }} + {{ row.lastRun.message }} +
+ } @else { + Noch nicht ausgeführt + } +
+ + +
+ + +
+
diff --git a/webapp/src/app/modules/preprocessing/preprocessing.component.scss b/webapp/src/app/modules/preprocessing/preprocessing.component.scss new file mode 100644 index 00000000..ccfa50d4 --- /dev/null +++ b/webapp/src/app/modules/preprocessing/preprocessing.component.scss @@ -0,0 +1,264 @@ +.preprocessing-page { + display: flex; + flex-direction: column; + gap: 20px; + padding: 24px; +} + +.page-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; +} + +h1, +p { + margin: 0; +} + +.page-header h1 { + font-size: 26px; + font-weight: 700; +} + +.page-header p { + color: #64748b; + margin-top: 6px; +} + +mat-card, +mat-paginator { + background-color: var(--sg-background); +} + +.container-card-content { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + flex-wrap: wrap; +} + +.container-info { + display: flex; + align-items: flex-start; + gap: 12px; +} + +.container-state-dot { + margin-top: 6px; + width: 10px; + height: 10px; + border-radius: 50%; + background: #94a3b8; + flex-shrink: 0; + + &--running { + background: #16a34a; + } + + &--stopped { + background: #dc2626; + } + + &--restarting { + background: #ca8a04; + } +} + +.container-meta { + display: flex; + flex-direction: column; + gap: 2px; + font-size: 12px; + color: #64748b; +} + +.container-digest { + font-family: 'Roboto Mono', ui-monospace, monospace; + color: #8a95b3; +} + +.update-badge { + display: inline-flex; + align-items: center; + gap: 4px; + margin-top: 4px; + width: fit-content; + padding: 2px 8px; + border-radius: 999px; + background: #eef2ff; + color: #2259a8; + font-weight: 600; + + mat-icon { + font-size: 16px; + height: 16px; + width: 16px; + } +} + +.container-actions { + display: flex; + gap: 8px; + flex-wrap: wrap; +} + +:host ::ng-deep .mat-mdc-row { + height: 116px; +} + +:host ::ng-deep .mat-mdc-row .mat-mdc-cell { + padding-top: 12px; + padding-bottom: 12px; + vertical-align: middle; +} + +.task-name-cell { + display: flex; + flex-direction: column; + gap: 2px; + min-width: 220px; +} + +.task-description { + font-size: 12px; + color: #64748b; +} + +.task-index { + width: fit-content; + font-size: 11px; + color: #475569; + background: #f1f5f9; + border-radius: 4px; + padding: 1px 6px; +} + +.task-schedule-cell { + display: flex; + flex-direction: column; + gap: 6px; +} + +.schedule-toggle { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 0; + border: none; + background: none; + cursor: pointer; + font: inherit; +} + +.schedule-toggle__track { + position: relative; + flex: 0 0 auto; + width: 36px; + height: 20px; + border-radius: 999px; + background: #cbd5e1; + transition: background 0.15s ease; +} + +.schedule-toggle__thumb { + position: absolute; + top: 2px; + left: 2px; + width: 16px; + height: 16px; + border-radius: 50%; + background: #ffffff; + box-shadow: 0 1px 2px rgba(16, 26, 61, 0.3); + transition: transform 0.15s ease; +} + +.schedule-toggle--on .schedule-toggle__track { + background: #2259a8; +} + +.schedule-toggle--on .schedule-toggle__thumb { + transform: translateX(16px); +} + +.schedule-toggle__label { + font-size: 12px; + color: #64748b; + white-space: nowrap; +} + +.schedule-toggle:focus-visible { + outline: 2px solid #2259a8; + outline-offset: 2px; + border-radius: 4px; +} + +.task-status { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 13px; + font-weight: 600; + + mat-icon { + font-size: 18px; + height: 18px; + width: 18px; + } + + &--success { + color: #166534; + } + + &--failed { + color: #991b1b; + } + + &--running { + color: #92400e; + } + + &--idle { + color: #64748b; + } +} + +.last-run-cell { + display: flex; + flex-direction: column; + gap: 2px; + font-size: 13px; +} + +.last-run-message { + font-size: 12px; + color: #64748b; +} + +.last-run-empty { + font-size: 13px; + color: #64748b; +} + +.row-actions { + display: flex; + gap: 4px; +} + +@media (max-width: 640px) { + .preprocessing-page { + padding: 16px; + } + + .page-header { + align-items: flex-start; + flex-direction: column; + } + + .container-card-content { + flex-direction: column; + align-items: flex-start; + } +} diff --git a/webapp/src/app/modules/preprocessing/preprocessing.component.ts b/webapp/src/app/modules/preprocessing/preprocessing.component.ts new file mode 100644 index 00000000..f5208963 --- /dev/null +++ b/webapp/src/app/modules/preprocessing/preprocessing.component.ts @@ -0,0 +1,252 @@ +import { CommonModule } from '@angular/common'; +import { + Component, + OnInit, + TemplateRef, + inject, + signal, + viewChild, +} from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; +import { MatCardModule } from '@angular/material/card'; +import { MatDialog, MatDialogModule } from '@angular/material/dialog'; +import { MatIconModule } from '@angular/material/icon'; +import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; +import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { + DataTableComponent, + GenericColumn, +} from '../../shared/ui/data-table/data-table.component'; +import { + MOCK_CONTAINER_STATUS, + MOCK_TASKS, + PreprocessingContainerStatus, + PreprocessingTask, + formatSchedule, +} from './preprocessing.models'; +import { + TaskScheduleDialogComponent, + TaskScheduleDialogData, + TaskScheduleDialogResult, +} from './task-schedule-dialog/task-schedule-dialog.component'; + +@Component({ + selector: 'app-preprocessing', + imports: [ + CommonModule, + MatButtonModule, + MatCardModule, + MatDialogModule, + MatIconModule, + MatProgressSpinnerModule, + MatSnackBarModule, + MatTooltipModule, + DataTableComponent, + ], + templateUrl: './preprocessing.component.html', + styleUrl: './preprocessing.component.scss', + standalone: true, +}) +export class PreprocessingComponent implements OnInit { + private readonly dialog = inject(MatDialog); + private readonly snackBar = inject(MatSnackBar); + + protected readonly containerStatus = signal( + MOCK_CONTAINER_STATUS, + ); + protected readonly containerBusy = signal(false); + + protected readonly tasks = signal(MOCK_TASKS); + protected readonly formatSchedule = formatSchedule; + + protected taskColumns: GenericColumn[] = []; + + private readonly taskNameTmp = + viewChild.required>('taskNameTmp'); + private readonly taskScheduleTmp = + viewChild.required>('taskScheduleTmp'); + private readonly taskStatusTmp = + viewChild.required>('taskStatusTmp'); + private readonly taskLastRunTmp = + viewChild.required>('taskLastRunTmp'); + private readonly taskActionsTmp = + viewChild.required>('taskActionsTmp'); + + ngOnInit(): void { + this.taskColumns = [ + { + id: 'name', + header: 'Task', + type: 'display', + cellTemplate: this.taskNameTmp(), + }, + { + id: 'schedule', + header: 'Zeitplan', + type: 'display', + cellTemplate: this.taskScheduleTmp(), + }, + { + id: 'status', + header: 'Status', + type: 'display', + cellTemplate: this.taskStatusTmp(), + }, + { + id: 'lastRun', + header: 'Letzter Lauf', + type: 'display', + cellTemplate: this.taskLastRunTmp(), + }, + { + id: 'actions', + header: 'Aktionen', + type: 'display', + cellTemplate: this.taskActionsTmp(), + }, + ]; + } + + protected runNow(task: PreprocessingTask): void { + if (task.status === 'running') return; + + this.updateTask(task.id, (current) => ({ ...current, status: 'running' })); + this.snackBar.open(`„${task.name}“ wurde gestartet.`, 'OK', { + duration: 3000, + }); + + setTimeout(() => { + const startedAt = new Date().toISOString(); + const run = { + startedAt, + durationSeconds: Math.round(60 + Math.random() * 600), + status: 'success' as const, + message: 'Manueller Lauf erfolgreich abgeschlossen.', + }; + + this.updateTask(task.id, (current) => ({ + ...current, + status: 'success', + lastRun: run, + history: [run, ...current.history], + })); + + this.snackBar.open(`„${task.name}“ wurde abgeschlossen.`, 'OK', { + duration: 3000, + }); + }, 1400); + } + + protected toggleEnabled(task: PreprocessingTask, enabled: boolean): void { + this.updateTask(task.id, (current) => ({ ...current, enabled })); + } + + protected openScheduleDialog(task: PreprocessingTask): void { + const dialogRef = this.dialog.open< + TaskScheduleDialogComponent, + TaskScheduleDialogData, + TaskScheduleDialogResult | undefined + >(TaskScheduleDialogComponent, { + width: '480px', + maxWidth: 'calc(100vw - 32px)', + data: { task }, + }); + + dialogRef.afterClosed().subscribe((result) => { + if (!result) return; + + this.updateTask(result.taskId, (current) => ({ + ...current, + enabled: result.enabled, + schedule: result.schedule, + })); + this.snackBar.open('Zeitplan wurde gespeichert.', 'OK', { + duration: 3000, + }); + }); + } + + protected startContainer(): void { + this.setContainerState('restarting'); + setTimeout(() => { + this.containerStatus.update((current) => ({ + ...current, + state: 'running', + uptime: '0 Std. 0 Min.', + lastStartedAt: new Date().toISOString(), + })); + this.containerBusy.set(false); + this.snackBar.open('Preprocessing-Container wurde gestartet.', 'OK', { + duration: 3000, + }); + }, 1200); + } + + protected stopContainer(): void { + this.setContainerState('restarting'); + setTimeout(() => { + this.containerStatus.update((current) => ({ + ...current, + state: 'stopped', + uptime: undefined, + })); + this.containerBusy.set(false); + this.snackBar.open('Preprocessing-Container wurde gestoppt.', 'OK', { + duration: 3000, + }); + }, 1200); + } + + protected restartContainer(): void { + this.setContainerState('restarting'); + setTimeout(() => { + this.containerStatus.update((current) => ({ + ...current, + state: 'running', + uptime: '0 Std. 0 Min.', + lastStartedAt: new Date().toISOString(), + })); + this.containerBusy.set(false); + this.snackBar.open('Preprocessing-Container wurde neu gestartet.', 'OK', { + duration: 3000, + }); + }, 1200); + } + + protected updateImage(): void { + this.setContainerState('restarting'); + setTimeout(() => { + this.containerStatus.update((current) => ({ + ...current, + state: 'running', + imageDigest: 'sha256:9f2b1c7ae5d3', + updateAvailable: false, + uptime: '0 Std. 0 Min.', + lastStartedAt: new Date().toISOString(), + })); + this.containerBusy.set(false); + this.snackBar.open( + 'Neues Image aus der Registry geladen und Container neu erstellt.', + 'OK', + { duration: 3000 }, + ); + }, 1200); + } + + private setContainerState( + state: PreprocessingContainerStatus['state'], + ): void { + this.containerBusy.set(true); + this.containerStatus.update((current) => ({ ...current, state })); + } + + private updateTask( + id: string, + updater: (task: PreprocessingTask) => PreprocessingTask, + ): void { + this.tasks.update((current) => + current.map((task) => (task.id === id ? updater(task) : task)), + ); + } +} diff --git a/webapp/src/app/modules/preprocessing/preprocessing.models.ts b/webapp/src/app/modules/preprocessing/preprocessing.models.ts new file mode 100644 index 00000000..e3edc1b4 --- /dev/null +++ b/webapp/src/app/modules/preprocessing/preprocessing.models.ts @@ -0,0 +1,267 @@ +export type PreprocessingRunStatus = 'success' | 'failed'; +export type PreprocessingTaskStatus = + 'idle' | 'running' | PreprocessingRunStatus; +export type ScheduleFrequency = + 'manual' | 'hourly' | 'daily' | 'weekly' | 'cron'; + +export const WEEKDAYS = [ + 'Montag', + 'Dienstag', + 'Mittwoch', + 'Donnerstag', + 'Freitag', + 'Samstag', + 'Sonntag', +] as const; + +export interface PreprocessingRun { + startedAt: string; + durationSeconds: number; + status: PreprocessingRunStatus; + message: string; +} + +export interface TaskSchedule { + frequency: ScheduleFrequency; + time?: string; + weekday?: number; + cronExpression?: string; +} + +export interface PreprocessingTask { + id: string; + name: string; + description: string; + targetIndex: string; + status: PreprocessingTaskStatus; + enabled: boolean; + schedule: TaskSchedule; + lastRun?: PreprocessingRun; + history: PreprocessingRun[]; +} + +export interface PreprocessingContainerStatus { + name: string; + image: string; + imageDigest: string; + updateAvailable: boolean; + state: 'running' | 'stopped' | 'restarting'; + uptime?: string; + lastStartedAt?: string; +} + +export function formatSchedule(schedule: TaskSchedule): string { + switch (schedule.frequency) { + case 'manual': + return 'Nur manuell'; + case 'hourly': + return 'Stündlich'; + case 'daily': + return `Täglich${schedule.time ? ` um ${schedule.time} Uhr` : ''}`; + case 'weekly': + return `Wöchentlich${ + schedule.weekday != null ? ` am ${WEEKDAYS[schedule.weekday]}` : '' + }${schedule.time ? `, ${schedule.time} Uhr` : ''}`; + case 'cron': + return schedule.cronExpression + ? `Cron: ${schedule.cronExpression}` + : 'Cron-Ausdruck fehlt'; + } +} + +export const MOCK_CONTAINER_STATUS: PreprocessingContainerStatus = { + name: 'inse-preprocessing', + image: 'docker.nes.uni-due.de/inse/preprocessing:1.0.0', + imageDigest: 'sha256:e40946432f95', + updateAvailable: true, + state: 'running', + uptime: '5 Std. 12 Min.', + lastStartedAt: '2026-07-08T02:58:00', +}; + +export const MOCK_TASKS: PreprocessingTask[] = [ + { + id: 'persons', + name: 'Personen-Index', + description: + 'Aktualisiert Personendaten aus OpenAlex- und UDE-Quellen für die Personensuche.', + targetIndex: 'openalex-authors', + status: 'success', + enabled: true, + schedule: { frequency: 'daily', time: '03:00' }, + lastRun: { + startedAt: '2026-07-08T03:00:00', + durationSeconds: 842, + status: 'success', + message: '18.432 Personen aktualisiert.', + }, + history: [ + { + startedAt: '2026-07-08T03:00:00', + durationSeconds: 842, + status: 'success', + message: '18.432 Personen aktualisiert.', + }, + { + startedAt: '2026-07-07T03:00:00', + durationSeconds: 811, + status: 'success', + message: '18.401 Personen aktualisiert.', + }, + { + startedAt: '2026-07-06T03:00:00', + durationSeconds: 796, + status: 'failed', + message: 'Zeitüberschreitung bei OpenAlex-Anfrage.', + }, + ], + }, + { + id: 'institutions', + name: 'Institutionen-Index', + description: + 'Baut den Suchindex für Institutionen und deren Kennzahlen neu auf.', + targetIndex: 'openalex-institutions', + status: 'success', + enabled: true, + schedule: { frequency: 'weekly', weekday: 6, time: '02:00' }, + lastRun: { + startedAt: '2026-07-05T02:00:00', + durationSeconds: 356, + status: 'success', + message: '612 Institutionen aktualisiert.', + }, + history: [ + { + startedAt: '2026-07-05T02:00:00', + durationSeconds: 356, + status: 'success', + message: '612 Institutionen aktualisiert.', + }, + { + startedAt: '2026-06-28T02:00:00', + durationSeconds: 349, + status: 'success', + message: '609 Institutionen aktualisiert.', + }, + ], + }, + { + id: 'projects', + name: 'Projekte-Index', + description: + 'Importiert Förderprojekte aus DFG-, Bund- und EU-CORDIS-Quellen.', + targetIndex: 'projects_dfg_all, projects_bund_v1, cordis_eu_*_projects', + status: 'idle', + enabled: true, + schedule: { frequency: 'daily', time: '04:00' }, + lastRun: { + startedAt: '2026-07-08T04:00:00', + durationSeconds: 1204, + status: 'success', + message: '3.218 Projekte importiert, 44 aktualisiert.', + }, + history: [ + { + startedAt: '2026-07-08T04:00:00', + durationSeconds: 1204, + status: 'success', + message: '3.218 Projekte importiert, 44 aktualisiert.', + }, + ], + }, + { + id: 'patents', + name: 'Patente-Index', + description: + 'Verarbeitet EPO- und USPTO-Patentdaten und verknüpft Erfinder:innen mit Personen.', + targetIndex: 'epo_index_1.0, uspto_patents_3.0, org_patents', + status: 'failed', + enabled: true, + schedule: { frequency: 'weekly', weekday: 0, time: '01:30' }, + lastRun: { + startedAt: '2026-07-06T01:30:00', + durationSeconds: 233, + status: 'failed', + message: 'Verbindung zum USPTO-Endpunkt fehlgeschlagen.', + }, + history: [ + { + startedAt: '2026-07-06T01:30:00', + durationSeconds: 233, + status: 'failed', + message: 'Verbindung zum USPTO-Endpunkt fehlgeschlagen.', + }, + { + startedAt: '2026-06-29T01:30:00', + durationSeconds: 1988, + status: 'success', + message: '9.104 Patente verarbeitet.', + }, + ], + }, + { + id: 'works', + name: 'Publikationen-Index', + description: 'Aktualisiert Publikationsdaten und Autor:innen-Zuordnungen.', + targetIndex: 'openalex-works', + status: 'success', + enabled: true, + schedule: { frequency: 'daily', time: '03:30' }, + lastRun: { + startedAt: '2026-07-08T03:30:00', + durationSeconds: 1523, + status: 'success', + message: '52.011 Publikationen aktualisiert.', + }, + history: [ + { + startedAt: '2026-07-08T03:30:00', + durationSeconds: 1523, + status: 'success', + message: '52.011 Publikationen aktualisiert.', + }, + ], + }, + { + id: 'news', + name: 'News-Aufbereitung', + description: + 'Übernimmt Artikel aus dem „aktuell“-Index und fügt Relevanz, Personenzuordnungen und Schlagwörter hinzu.', + targetIndex: 'aktuell_postproc', + status: 'running', + enabled: true, + schedule: { frequency: 'hourly' }, + lastRun: { + startedAt: '2026-07-08T18:00:00', + durationSeconds: 96, + status: 'success', + message: '214 neue Artikel indiziert.', + }, + history: [ + { + startedAt: '2026-07-08T18:00:00', + durationSeconds: 96, + status: 'success', + message: '214 neue Artikel indiziert.', + }, + { + startedAt: '2026-07-08T17:00:00', + durationSeconds: 88, + status: 'success', + message: '187 neue Artikel indiziert.', + }, + ], + }, + { + id: 'topics', + name: 'Themen-Vektoren', + description: + 'Liest Themen aus „openalex-topics“, berechnet Embeddings und schreibt sie in den Vektor-Index „topicvectors“.', + targetIndex: 'topicvectors', + status: 'idle', + enabled: false, + schedule: { frequency: 'manual' }, + history: [], + }, +]; diff --git a/webapp/src/app/modules/preprocessing/task-schedule-dialog/task-schedule-dialog.component.html b/webapp/src/app/modules/preprocessing/task-schedule-dialog/task-schedule-dialog.component.html new file mode 100644 index 00000000..40d2ca2e --- /dev/null +++ b/webapp/src/app/modules/preprocessing/task-schedule-dialog/task-schedule-dialog.component.html @@ -0,0 +1,99 @@ +

{{ data.task.name }}

+ + +

{{ data.task.description }}

+ +
+ + + + Häufigkeit + + @for (option of frequencyOptions; track option.value) { + {{ option.label }} + } + + + + @if ( + form.controls.frequency.value === 'daily' || + form.controls.frequency.value === 'weekly' + ) { + + Uhrzeit + + + } + + @if (form.controls.frequency.value === 'weekly') { + + Wochentag + + @for (day of weekdays; track day; let i = $index) { + {{ day }} + } + + + } + + @if (form.controls.frequency.value === 'cron') { + + Cron-Ausdruck + + @if (form.controls.cronExpression.hasError('required')) { + Cron-Ausdruck ist erforderlich. + } + + } +
+ +
+

Letzte Läufe

+ @if (recentHistory.length === 0) { +

Für diesen Task liegt noch kein Lauf vor.

+ } @else { +
    + @for (run of recentHistory; track run.startedAt) { +
  • + + {{ run.status === 'success' ? 'check_circle' : 'error' }} + +
    + {{ + run.startedAt | date: 'dd.MM.yyyy HH:mm' + }} + {{ run.message }} +
    + {{ run.durationSeconds }} s +
  • + } +
+ } +
+
+ + + + + diff --git a/webapp/src/app/modules/preprocessing/task-schedule-dialog/task-schedule-dialog.component.scss b/webapp/src/app/modules/preprocessing/task-schedule-dialog/task-schedule-dialog.component.scss new file mode 100644 index 00000000..59f20223 --- /dev/null +++ b/webapp/src/app/modules/preprocessing/task-schedule-dialog/task-schedule-dialog.component.scss @@ -0,0 +1,138 @@ +.task-description { + margin: 0 0 16px; + color: #64748b; +} + +.schedule-form { + display: flex; + flex-direction: column; + gap: 12px; + min-width: 360px; +} + +.enabled-toggle { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 0; + border: none; + background: none; + cursor: pointer; + font: inherit; + align-self: flex-start; +} + +.enabled-toggle__track { + position: relative; + flex: 0 0 auto; + width: 36px; + height: 20px; + border-radius: 999px; + background: #cbd5e1; + transition: background 0.15s ease; +} + +.enabled-toggle__thumb { + position: absolute; + top: 2px; + left: 2px; + width: 16px; + height: 16px; + border-radius: 50%; + background: #ffffff; + box-shadow: 0 1px 2px rgba(16, 26, 61, 0.3); + transition: transform 0.15s ease; +} + +.enabled-toggle--on .enabled-toggle__track { + background: #2259a8; +} + +.enabled-toggle--on .enabled-toggle__thumb { + transform: translateX(16px); +} + +.enabled-toggle__label { + font-size: 14px; + color: var(--sg-text, #101a3d); +} + +.enabled-toggle:focus-visible { + outline: 2px solid #2259a8; + outline-offset: 2px; + border-radius: 4px; +} + +.history-section { + margin-top: 24px; + border-top: 1px solid #e2e8f0; + padding-top: 16px; + + h3 { + margin: 0 0 8px; + font-size: 14px; + } +} + +.no-history { + color: #64748b; + font-size: 13px; + margin: 0; +} + +.history-list { + list-style: none; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; + gap: 10px; +} + +.history-item { + display: flex; + align-items: flex-start; + gap: 10px; +} + +.history-icon { + font-size: 20px; + height: 20px; + width: 20px; + margin-top: 2px; + + &--success { + color: #16a34a; + } + + &--failed { + color: #dc2626; + } +} + +.history-item-content { + display: flex; + flex-direction: column; + flex: 1; +} + +.history-date { + font-size: 12px; + color: #64748b; +} + +.history-message { + font-size: 13px; +} + +.history-duration { + font-size: 12px; + color: #64748b; + white-space: nowrap; +} + +@media (max-width: 640px) { + .schedule-form { + min-width: 0; + } +} diff --git a/webapp/src/app/modules/preprocessing/task-schedule-dialog/task-schedule-dialog.component.ts b/webapp/src/app/modules/preprocessing/task-schedule-dialog/task-schedule-dialog.component.ts new file mode 100644 index 00000000..caebde91 --- /dev/null +++ b/webapp/src/app/modules/preprocessing/task-schedule-dialog/task-schedule-dialog.component.ts @@ -0,0 +1,125 @@ +import { CommonModule } from '@angular/common'; +import { Component, inject } from '@angular/core'; +import { + FormControl, + FormGroup, + ReactiveFormsModule, + Validators, +} from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { + MAT_DIALOG_DATA, + MatDialogModule, + MatDialogRef, +} from '@angular/material/dialog'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatIconModule } from '@angular/material/icon'; +import { MatInputModule } from '@angular/material/input'; +import { MatSelectModule } from '@angular/material/select'; +import { + PreprocessingTask, + ScheduleFrequency, + TaskSchedule, + WEEKDAYS, +} from '../preprocessing.models'; + +export interface TaskScheduleDialogData { + task: PreprocessingTask; +} + +export interface TaskScheduleDialogResult { + taskId: string; + enabled: boolean; + schedule: TaskSchedule; +} + +@Component({ + selector: 'app-task-schedule-dialog', + imports: [ + CommonModule, + ReactiveFormsModule, + MatButtonModule, + MatDialogModule, + MatFormFieldModule, + MatIconModule, + MatInputModule, + MatSelectModule, + ], + templateUrl: './task-schedule-dialog.component.html', + styleUrl: './task-schedule-dialog.component.scss', + standalone: true, +}) +export class TaskScheduleDialogComponent { + private readonly dialogRef = + inject< + MatDialogRef< + TaskScheduleDialogComponent, + TaskScheduleDialogResult | undefined + > + >(MatDialogRef); + protected readonly data = inject(MAT_DIALOG_DATA); + + protected readonly weekdays = WEEKDAYS; + + protected readonly frequencyOptions: { + value: ScheduleFrequency; + label: string; + }[] = [ + { value: 'manual', label: 'Nur manuell' }, + { value: 'hourly', label: 'Stündlich' }, + { value: 'daily', label: 'Täglich' }, + { value: 'weekly', label: 'Wöchentlich' }, + { value: 'cron', label: 'Cron-Ausdruck' }, + ]; + + protected readonly form = new FormGroup({ + enabled: new FormControl(this.data.task.enabled, { nonNullable: true }), + frequency: new FormControl( + this.data.task.schedule.frequency, + { nonNullable: true }, + ), + time: new FormControl(this.data.task.schedule.time ?? '03:00', { + nonNullable: true, + }), + weekday: new FormControl(this.data.task.schedule.weekday ?? 0, { + nonNullable: true, + }), + cronExpression: new FormControl( + this.data.task.schedule.cronExpression ?? '', + { nonNullable: true, validators: [] }, + ), + }); + + protected readonly recentHistory = this.data.task.history.slice(0, 5); + + protected submit(): void { + const value = this.form.getRawValue(); + + if (value.frequency === 'cron' && !value.cronExpression.trim()) { + this.form.controls.cronExpression.setErrors({ required: true }); + this.form.controls.cronExpression.markAsTouched(); + return; + } + + const schedule: TaskSchedule = { frequency: value.frequency }; + if (value.frequency === 'daily' || value.frequency === 'weekly') { + schedule.time = value.time; + } + if (value.frequency === 'weekly') { + schedule.weekday = value.weekday; + } + if (value.frequency === 'cron') { + schedule.cronExpression = value.cronExpression.trim(); + } + + this.dialogRef.close({ + taskId: this.data.task.id, + enabled: value.enabled, + schedule, + }); + } + + protected close(): void { + this.dialogRef.close(); + } +} diff --git a/webapp/src/app/shared/interceptors/authentication.interceptor.ts b/webapp/src/app/shared/interceptors/authentication.interceptor.ts index 08113260..f54ddbc8 100644 --- a/webapp/src/app/shared/interceptors/authentication.interceptor.ts +++ b/webapp/src/app/shared/interceptors/authentication.interceptor.ts @@ -54,6 +54,13 @@ const handleAccessTokenError = ( export const authenticationInterceptor: HttpInterceptorFn = (req, next) => { const router = inject(Router); + const credentialService = inject(CredentialService); + + // TEMP: dev login bypass. While active, never touch auth state or redirect + // on 401 so a fake session survives the broken backend. + if (credentialService.mockMode()) { + return next(req); + } const requiredType = req.context.get(REQUIRED_TOKEN_TYPE); @@ -77,8 +84,6 @@ export const authenticationInterceptor: HttpInterceptorFn = (req, next) => { return next(req.clone({ withCredentials: true })); } - const credentialService = inject(CredentialService); - const rawAccessToken = credentialService.getRawAccessToken(); if (rawAccessToken && credentialService.accessTokenIsExpired()) { diff --git a/webapp/src/app/shared/services/credential.service.ts b/webapp/src/app/shared/services/credential.service.ts index 6b81fc90..ca8b6ab2 100644 --- a/webapp/src/app/shared/services/credential.service.ts +++ b/webapp/src/app/shared/services/credential.service.ts @@ -109,6 +109,36 @@ export class CredentialService { public readonly accessToken = signal(undefined); + // TEMP: dev login bypass. Remove together with the "skip" button on the + // login page once the real login flow works again. + public readonly mockMode = signal(false); + private readonly mockProfile: AccountProfile = { + id: 'mock-superadmin', + email: 'superadmin@local.mock', + name: 'Mock Superadmin', + role: 'SUPER_ADMIN', + organization_id: 'mock-org', + organization_name: 'Mock Organization', + deleted: false, + activated: true, + is_current: true, + is_real_account: true, + is_impersonating: false, + }; + + public loginAsMockSuperAdmin(): void { + this.mockMode.set(true); + this.accessToken.set({ + real_account_id: this.mockProfile.id, + effective_account_id: this.mockProfile.id, + effective_organization_id: this.mockProfile.organization_id, + effective_role: 'SUPER_ADMIN', + expires_at: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(), + user_fingerprint_hash: 'mock', + raw_token: 'mock-token', + }); + } + public readonly isActiveAccessToken = computed(() => { const accessToken = this.accessToken(); return ( @@ -120,9 +150,11 @@ export class CredentialService { public readonly accountProfile = toSignal( toObservable(this.accessToken).pipe( switchMap((accessToken) => - accessToken - ? this.authService.getCurrentAccount() - : of(undefined), + this.mockMode() + ? of(this.mockProfile) + : accessToken + ? this.authService.getCurrentAccount() + : of(undefined), ), ), { initialValue: undefined }, diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts index 644c59a3..28a9cc9c 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts @@ -142,6 +142,13 @@ export class AppMenuComponent { disabled: false, superAdminOnly: true, }, + { + label: 'Preprocessing', + icon: 'sync', + route: '/preprocessing', + disabled: false, + superAdminOnly: true, + }, ]; navItemGroups: NavItemGroup[] = [ { -- 2.56.1 From 532c94b00be8bed9d6083db4c72a6f79596eeb1c Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Thu, 9 Jul 2026 21:25:36 +0200 Subject: [PATCH 02/60] feat(preprocessing): add first version of preprocessing, dockerize news job processing --- preprocessing/.dockerignore | 5 + preprocessing/.env.example | 7 + preprocessing/.gitignore | 5 + preprocessing/Dockerfile | 17 +++ preprocessing/app/elastic/client.py | 137 +++++++++++++++++++ preprocessing/app/llm/client.py | 95 ++++++++++++++ preprocessing/app/sync.py | 197 ++++++++++++++++++++++++++++ preprocessing/entrypoint.sh | 25 ++++ preprocessing/requirements.txt | 3 + 9 files changed, 491 insertions(+) create mode 100644 preprocessing/.dockerignore create mode 100644 preprocessing/.env.example create mode 100644 preprocessing/.gitignore create mode 100644 preprocessing/Dockerfile create mode 100644 preprocessing/app/elastic/client.py create mode 100644 preprocessing/app/llm/client.py create mode 100644 preprocessing/app/sync.py create mode 100644 preprocessing/entrypoint.sh create mode 100644 preprocessing/requirements.txt diff --git a/preprocessing/.dockerignore b/preprocessing/.dockerignore new file mode 100644 index 00000000..9b43b1ce --- /dev/null +++ b/preprocessing/.dockerignore @@ -0,0 +1,5 @@ +.env +.env.* +__pycache__/ +*.pyc +.venv/ diff --git a/preprocessing/.env.example b/preprocessing/.env.example new file mode 100644 index 00000000..51667cb8 --- /dev/null +++ b/preprocessing/.env.example @@ -0,0 +1,7 @@ +# Copy this file to `.env` and fill in the real values. +# `.env` is gitignored and is NOT baked into the image. +INSE_ELASTIC_URL=https://inse.nes.uni-due.de/elastic +INSE_ELASTIC_API_KEY=your-elastic-api-key-here +INSE_LLM_BASE_URL=https://project.nes.uni-due.de/llm2/v1/ +INSE_LLM_API_KEY=your-llm-api-key-here +INSE_LLM_MODEL=gemma4-e4b diff --git a/preprocessing/.gitignore b/preprocessing/.gitignore new file mode 100644 index 00000000..ccbef30f --- /dev/null +++ b/preprocessing/.gitignore @@ -0,0 +1,5 @@ +# Local secrets – never commit +.env + +__pycache__/ +*.pyc diff --git a/preprocessing/Dockerfile b/preprocessing/Dockerfile new file mode 100644 index 00000000..c3d7e8ab --- /dev/null +++ b/preprocessing/Dockerfile @@ -0,0 +1,17 @@ +# Preprocessing worker, news enrichment job (v1) +FROM python:3.13-slim + +WORKDIR /app + +# Install dependencies first so this layer is cached when only code changes. +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +# Copy the job code. No secrets here, config is read from env vars at runtime. +COPY app/ ./ + +# Small dispatcher that maps a job name to the right command. +COPY entrypoint.sh /entrypoint.sh +RUN chmod +x /entrypoint.sh + +ENTRYPOINT ["/entrypoint.sh"] diff --git a/preprocessing/app/elastic/client.py b/preprocessing/app/elastic/client.py new file mode 100644 index 00000000..a3c06382 --- /dev/null +++ b/preprocessing/app/elastic/client.py @@ -0,0 +1,137 @@ +import os +import requests +from requests.adapters import HTTPAdapter +from urllib.parse import quote +from dotenv import load_dotenv + +load_dotenv() + +INSE_URL = os.getenv("INSE_ELASTIC_URL", "https://inse.nes.uni-due.de/elastic") +INSE_API_KEY = os.getenv("INSE_ELASTIC_API_KEY") +if not INSE_API_KEY: + raise RuntimeError( + "INSE_ELASTIC_API_KEY is not set. Copy .env.example to .env and fill it in, " + "or pass it as an environment variable." + ) + +ES_HEADERS = { + "Authorization": f"ApiKey {INSE_API_KEY}", + "Content-Type": "application/json", +} + +_session = requests.Session() +_session.headers.update(ES_HEADERS) +_adapter = HTTPAdapter(pool_connections=32, pool_maxsize=32) +_session.mount("https://", _adapter) +_session.mount("http://", _adapter) + +def _send_es_request(method: str, url: str, payload: dict = None) -> dict: + + try: + response = _session.request( + method=method, + url=url, + json=payload, + ) + response.raise_for_status() + return response.json() + except requests.RequestException as error: + print(f"Send Request failed: ({method} {url}): {error}") + raise + +def add_entry(index: str, entry: dict): + + endpoint = f"{INSE_URL}/{index}/_doc" + + document_body = { + "news_id": entry["news_id"], + "relevant": int(entry["relevant"]), + "authors": entry["authors"], + "keywords": entry.get("keywords", []), + } + + response_data = _send_es_request("POST", endpoint, payload=document_body) + + created_id = response_data["_id"] + entry["_id"] = created_id + + return created_id + +def update_entry(index: str, document_id: str, partial_doc: dict): + + encoded_document_id = quote(document_id, safe="") + endpoint = f"{INSE_URL}/{index}/_update/{encoded_document_id}" + + return _send_es_request("POST", endpoint, payload={"doc": partial_doc}) + +def get_entry(index: str, document_id: str) -> dict: + + encoded_document_id = quote(document_id, safe="") + endpoint = f"{INSE_URL}/{index}/_doc/{encoded_document_id}" + + return _send_es_request("GET", endpoint) + +def delete_entry(index: str, document_id: str): + + encoded_document_id = quote(document_id, safe="") + endpoint = f"{INSE_URL}/{index}/_doc/{encoded_document_id}" + + return _send_es_request("DELETE", endpoint) + +def get_all_entries(index: str, fields: list = None) -> list: + + if not fields: + source_fields = True + else: + source_fields = fields + + endpoint = f"{INSE_URL}/{index}/_search" + + page_size = 1000 + results = [] + last_sort_value = None + + while True: + payload = { + "query": {"match_all": {}}, + "size": page_size, + "sort": [{"_doc": "asc"}], + "_source": source_fields, + } + if last_sort_value is not None: + payload["search_after"] = last_sort_value + + response_data = _send_es_request("POST", endpoint, payload=payload) + results_list = response_data["hits"]["hits"] + + if not results_list: + break + + results.extend(results_list) + last_sort_value = results_list[-1]["sort"] + + return results + +def delete_all_entries(index: str): + + endpoint = f"{INSE_URL}/{index}/_delete_by_query" + + payload = { + "query": {"match_all": {}} + } + + return _send_es_request("POST", endpoint, payload=payload) + +def remove_field_all(index: str, field: str): + + endpoint = f"{INSE_URL}/{index}/_update_by_query" + + payload = { + "query": {"exists": {"field": field}}, + "script": { + "source": f"ctx._source.remove('{field}')", + "lang": "painless", + }, + } + + return _send_es_request("POST", endpoint, payload=payload) diff --git a/preprocessing/app/llm/client.py b/preprocessing/app/llm/client.py new file mode 100644 index 00000000..e798d14c --- /dev/null +++ b/preprocessing/app/llm/client.py @@ -0,0 +1,95 @@ +import os +import requests +from openai import OpenAI, APIConnectionError +from dotenv import load_dotenv + +load_dotenv() + +LLM_BASE_URL = os.getenv("INSE_LLM_BASE_URL", "https://project.nes.uni-due.de/llm2/v1/") +LLM_API_KEY = os.getenv("INSE_LLM_API_KEY") +if not LLM_API_KEY: + raise RuntimeError( + "INSE_LLM_API_KEY is not set. Copy .env.example to .env and fill it in, " + "or pass it as an environment variable." + ) +LLM_MODEL = os.getenv("INSE_LLM_MODEL", "gemma4-e4b") + +SYSTEM_PROMPT_RELEVANT = (""" + Du bewertest Nachrichtenartikel aus dem Campus-Aktuell-Bereich der Universität Duisburg-Essen. + Entscheide, ob der Artikel inhaltlich über eine konkrete Person berichtet, also über deren Werdegang, Forschung, Leistung, Auszeichnung oder Tätigkeit. + Falls du dir unsicher bist, ob eine Person im Mittelpunkt steht, dann entscheide dich bitte für die positivere Option (also 1), damit die Namensextraktion auf keinen Fall bei Artikeln mit Personenbezug versäumt wird. + Antworte mit 1, wenn eine konkrete Person im Mittelpunkt steht. + Antworte mit 0, wenn es sich um allgemeine Mitteilungen handelt, die keine einzelne Person in den Mittelpunkt stellen, zum Beispiel Veranstaltungs- und Terminhinweise, Spendenaufrufe, organisatorische Ankündigungen, allgemeine Universitätsinformationen oder Pressemitteilungen ohne Personenbezug. + Die bloße Nennung von Namen (etwa als Autor oder Ansprechpartner) reicht für eine 1 nicht aus; die Person muss inhaltlich Thema des Artikels sein. + Antworte ausschließlich mit einer einzigen Ziffer: 0 oder 1. +""") + +SYSTEM_PROMPT_NAMES = (""" + Aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen: Nenne die Namen aller konkreten Personen, um die es im Artikel inhaltlich geht. + Es können mehrere Personen sein. Bitte achte darauf dass du nur die Namen der Personen nennst, die tatsächlich im Mittelpunkt des Artikels stehen. + Insbesondere am Ende von Artikeln werden oft Personen genannt, die nur als Ansprechpartner oder Organisator und sollen deshalb nicht genannt werden. + Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {\"person\": [\"Vorname Nachname\", \"Vorname Nachname\"]} + Gib keine Erklärungen und kein Markdown aus, nur das JSON. +""") + +SYSTEM_PROMPT_KEYWORDS = (""" + Extrahiere aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen die wichtigsten Schlagwörter (Keywords). + Wähle ausschließlich Begriffe oder Phrasen, die tatsächlich im Text vorkommen. Erfinde keine Begriffe, verallgemeinere nicht und nenne keine Oberbegriffe, die nicht im Text stehen. + Übersetze keine Begriffe – verwende ausschließlich Wörter und Phrasen in der Sprache des Artikels. + Gib jedes Schlagwort in seiner Grundform an: Bei deutschen Begriffen Substantive im Nominativ Singular; bei englischen Begriffen Substantive im Singular. Verwende den Plural nur, wenn der Begriff üblicherweise im Plural gebraucht wird. + Vermeide Redundanz: Wenn zwei mögliche Schlagwörter dieselbe Wortbasis teilen (z.B. „Forschung" und „Forschungsprojekt"), nenne nur den spezifischeren Begriff. + Nenne maximal sechs prägnante Begriffe oder kurze Phrasen. Konzentriere dich auf inhaltlich zentrale Begriffe, nicht auf Personennamen oder Datumsangaben. + Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {\"keywords\": [\"Schlagwort\", \"Schlagwort\"]} + Gib keine Erklärungen und kein Markdown aus, nur das JSON. +""") + +_client = OpenAI( + base_url=LLM_BASE_URL, + api_key=LLM_API_KEY, + timeout=30, +) + +def call(system_prompt, user_prompt, model=LLM_MODEL, temperature=1.0, top_p=0.95): + try: + response = _client.chat.completions.create( + model=model, + messages=[ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": user_prompt}, + ], + temperature=temperature, + top_p=top_p, + extra_body={"top_k": 64}, + ) + except APIConnectionError: + return None + + return response.choices[0].message.content or None + +def is_news_relevant(text: str) -> bool: + result = call(SYSTEM_PROMPT_RELEVANT, text) + if result is None: + return False + return result.strip() == "1" + +def extract_names(text: str) -> list[str]: + result = call(SYSTEM_PROMPT_NAMES, text) + if result is None: + return [] + try: + import json + data = json.loads(result) + return data.get("person", []) + except json.JSONDecodeError: + return [] + +def extract_keywords(text: str) -> list[str]: + result = call(SYSTEM_PROMPT_KEYWORDS, text) + if result is None: + return [] + try: + import json + data = json.loads(result) + return data.get("keywords", []) + except json.JSONDecodeError: + return [] diff --git a/preprocessing/app/sync.py b/preprocessing/app/sync.py new file mode 100644 index 00000000..72f330b4 --- /dev/null +++ b/preprocessing/app/sync.py @@ -0,0 +1,197 @@ +import elastic.client as es_client +import llm.client as llm_client +import json +import argparse +import time +import threading +from concurrent.futures import ThreadPoolExecutor, as_completed + +def print_pretty_json(data): + print(json.dumps(data, indent=2)) + +def sync_single_news(news_id, max_retries=3): + attempt = 0 + while attempt < max_retries: + try: + news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"] + is_news_relevant = llm_client.is_news_relevant(news_text) + authors = llm_client.extract_names(news_text) + keywords = llm_client.extract_keywords(news_text) + new_entry = { + "news_id": news_id, + "relevant": is_news_relevant, + "authors": authors, + "keywords": keywords, + } + es_client.add_entry("aktuell_postproc", new_entry) + return True + except Exception as error: + attempt += 1 + print(f"Warning syncing news_id {news_id} (Attempt {attempt}/{max_retries})") + if attempt < max_retries: + time.sleep(1) + else: + print(f"Error: {news_id} - {error}") + return False + +def update_keywords_single(postproc_entry, max_retries=3): + doc_id = postproc_entry["_id"] + news_id = postproc_entry["_source"]["news_id"] + attempt = 0 + while attempt < max_retries: + try: + news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"] + keywords = llm_client.extract_keywords(news_text) + es_client.update_entry("aktuell_postproc", doc_id, {"keywords": keywords}) + return True + except Exception as error: + attempt += 1 + print(f"Warning updating keywords for news_id {news_id} (Attempt {attempt}/{max_retries})") + if attempt < max_retries: + time.sleep(1) + else: + print(f"Error: {news_id} - {error}") + return False + +def main(): + parser = argparse.ArgumentParser(description="Synchronize news articles from 'aktuell' index to 'aktuell_postproc' index with relevance and author extraction using LLM.") + + parser.add_argument( + "--delete-all", + action="store_true", + help="Delete all entries from index 'aktuell_postproc'.", + ) + + parser.add_argument( + "--sync-delta", + action="store_true", + help="Sync only missing entries from 'aktuell' to 'aktuell_postproc'.", + ) + + parser.add_argument( + "--update-keywords", + action="store_true", + help="Add 'keywords' to existing 'aktuell_postproc' entries that don't have them yet (keeps relevant/authors).", + ) + + parser.add_argument( + "--reset-keywords", + action="store_true", + help="Remove the 'keywords' field from all 'aktuell_postproc' entries (keeps relevant/authors). Run before re-extracting with a new prompt.", + ) + + parser.add_argument( + "--stats", + action="store_true", + help="Print statistics about the entries in 'aktuell_postproc' and 'aktuell'.", + ) + + parser.add_argument( + "--threads", + type=int, + default=4, + help="Number of threads for --sync-delta (Default: 4).", + ) + + parser.add_argument( + "--limit", + type=int, + default=None, + help="Process at most this many entries (used by --update-keywords, e.g. for a smoke test).", + ) + + args = parser.parse_args() + + if args.delete_all: + es_client.delete_all_entries("aktuell_postproc") + + if args.reset_keywords: + result = es_client.remove_field_all("aktuell_postproc", "keywords") + print(f"Removed 'keywords' from {result.get('updated', 0)} entries.") + + if args.sync_delta: + start_time = time.time() + aktuell_ids_raw = es_client.get_all_entries("aktuell", fields=["_id"]) + postproc_ids_raw = es_client.get_all_entries("aktuell_postproc", fields=["news_id"]) + + source_ids = set(entry["_id"] for entry in aktuell_ids_raw) + target_ids = set(entry["_source"]["news_id"] for entry in postproc_ids_raw) + missing_ids = source_ids - target_ids + + print(f"Number of missing IDs: {len(missing_ids)}") + + missing_ids = list(missing_ids) + total = len(missing_ids) + + processed = 0 + succeeded = 0 + progress_lock = threading.Lock() + + with ThreadPoolExecutor(max_workers=args.threads) as executor: + futures = [executor.submit(sync_single_news, news_id) for news_id in missing_ids] + for future in as_completed(futures): + was_successful = future.result() + with progress_lock: + processed += 1 + if was_successful: + succeeded += 1 + print(f"Sync: {processed} / {total}") + + end_time = time.time() + print(f"Sync DONE: {succeeded} entries synced.") + print(f"Time taken: {end_time - start_time} seconds.") + + if args.update_keywords: + start_time = time.time() + postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["news_id", "keywords"]) + + pending = [entry for entry in postproc_entries if not entry["_source"].get("keywords")] + print(f"Number of entries without keywords: {len(pending)}") + + if args.limit is not None: + pending = pending[:args.limit] + + total = len(pending) + print(f"Processing {total} entries.") + + processed = 0 + succeeded = 0 + progress_lock = threading.Lock() + + with ThreadPoolExecutor(max_workers=args.threads) as executor: + futures = [executor.submit(update_keywords_single, entry) for entry in pending] + for future in as_completed(futures): + was_successful = future.result() + with progress_lock: + processed += 1 + if was_successful: + succeeded += 1 + print(f"Update keywords: {processed} / {total}") + + end_time = time.time() + print(f"Update keywords DONE: {succeeded} entries updated.") + print(f"Time taken: {end_time - start_time} seconds.") + + if args.stats: + aktuell_entries = es_client.get_all_entries("aktuell", fields=["_id"]) + print(f"Total entries in 'aktuell': {len(aktuell_entries)}") + + postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["_id", "news_id", "relevant", "authors", "keywords"]) + total_entries = len(postproc_entries) + relevant_count = sum(1 for entry in postproc_entries if entry["_source"]["relevant"] == 1) + irrelevant_count = total_entries - relevant_count + news_with_extracted_names = sum(1 for entry in postproc_entries if entry["_source"]["authors"]) + news_without_extracted_names = total_entries - news_with_extracted_names + news_with_keywords = sum(1 for entry in postproc_entries if entry["_source"].get("keywords")) + news_without_keywords = total_entries - news_with_keywords + + print(f"Total entries in 'aktuell_postproc': {total_entries}") + print(f"Relevant entries: {relevant_count}") + print(f"Irrelevant entries: {irrelevant_count}") + print(f"Entries with extracted names: {news_with_extracted_names}") + print(f"Entries without extracted names: {news_without_extracted_names}") + print(f"Entries with keywords: {news_with_keywords}") + print(f"Entries without keywords: {news_without_keywords}") + +if __name__ == "__main__": + main() diff --git a/preprocessing/entrypoint.sh b/preprocessing/entrypoint.sh new file mode 100644 index 00000000..4cfaa044 --- /dev/null +++ b/preprocessing/entrypoint.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env sh +# Job dispatcher for the preprocessing worker. +# Usage: e.g. docker run news +set -eu + +JOB="${1:-}" + +case "$JOB" in + news) + # Enrich new 'aktuell' articles into 'aktuell_postproc' (relevance, authors, keywords). + exec python sync.py --sync-delta + ;; + news-stats) + # Print counts for the aktuell / aktuell_postproc indices (read-only). + exec python sync.py --stats + ;; + "") + echo "No job given. Available jobs: news, news-stats" >&2 + exit 2 + ;; + *) + echo "Unknown job: $JOB. Available jobs: news, news-stats" >&2 + exit 2 + ;; +esac diff --git a/preprocessing/requirements.txt b/preprocessing/requirements.txt new file mode 100644 index 00000000..d5f8a74c --- /dev/null +++ b/preprocessing/requirements.txt @@ -0,0 +1,3 @@ +requests~=2.32 +openai~=2.41 +python-dotenv~=1.0 -- 2.56.1 From f4542d21b8ac38822dc388d513557e0a2ac6c633 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Thu, 9 Jul 2026 21:50:47 +0200 Subject: [PATCH 03/60] feat(preprocessing): revert login bypass --- .../app-login/app-login.component.html | 9 ----- .../app-login/app-login.component.scss | 5 --- .../modules/app-login/app-login.component.ts | 6 --- .../authentication.interceptor.ts | 9 +---- .../app/shared/services/credential.service.ts | 38 ++----------------- 5 files changed, 5 insertions(+), 62 deletions(-) diff --git a/webapp/src/app/modules/app-login/app-login.component.html b/webapp/src/app/modules/app-login/app-login.component.html index bb096a2e..0c3c7754 100644 --- a/webapp/src/app/modules/app-login/app-login.component.html +++ b/webapp/src/app/modules/app-login/app-login.component.html @@ -158,14 +158,5 @@ } - - - diff --git a/webapp/src/app/modules/app-login/app-login.component.scss b/webapp/src/app/modules/app-login/app-login.component.scss index 8069936c..c09190d7 100644 --- a/webapp/src/app/modules/app-login/app-login.component.scss +++ b/webapp/src/app/modules/app-login/app-login.component.scss @@ -104,11 +104,6 @@ p { font-weight: 700; } -.skip-login-button { - width: 100%; - margin-top: 20px; -} - .form-actions { display: flex; align-items: center; diff --git a/webapp/src/app/modules/app-login/app-login.component.ts b/webapp/src/app/modules/app-login/app-login.component.ts index 149934ac..fe894887 100644 --- a/webapp/src/app/modules/app-login/app-login.component.ts +++ b/webapp/src/app/modules/app-login/app-login.component.ts @@ -203,12 +203,6 @@ export class AppLoginComponent implements OnDestroy { }); } - // TEMP: dev login bypass. Remove once the real login flow works again. - skipAsSuperAdmin() { - this.credentialService.loginAsMockSuperAdmin(); - this.router.navigate(['/preprocessing']); - } - editCredentials() { this.currentStep = 'credentials'; this.accountId = undefined; diff --git a/webapp/src/app/shared/interceptors/authentication.interceptor.ts b/webapp/src/app/shared/interceptors/authentication.interceptor.ts index f54ddbc8..08113260 100644 --- a/webapp/src/app/shared/interceptors/authentication.interceptor.ts +++ b/webapp/src/app/shared/interceptors/authentication.interceptor.ts @@ -54,13 +54,6 @@ const handleAccessTokenError = ( export const authenticationInterceptor: HttpInterceptorFn = (req, next) => { const router = inject(Router); - const credentialService = inject(CredentialService); - - // TEMP: dev login bypass. While active, never touch auth state or redirect - // on 401 so a fake session survives the broken backend. - if (credentialService.mockMode()) { - return next(req); - } const requiredType = req.context.get(REQUIRED_TOKEN_TYPE); @@ -84,6 +77,8 @@ export const authenticationInterceptor: HttpInterceptorFn = (req, next) => { return next(req.clone({ withCredentials: true })); } + const credentialService = inject(CredentialService); + const rawAccessToken = credentialService.getRawAccessToken(); if (rawAccessToken && credentialService.accessTokenIsExpired()) { diff --git a/webapp/src/app/shared/services/credential.service.ts b/webapp/src/app/shared/services/credential.service.ts index ca8b6ab2..6b81fc90 100644 --- a/webapp/src/app/shared/services/credential.service.ts +++ b/webapp/src/app/shared/services/credential.service.ts @@ -109,36 +109,6 @@ export class CredentialService { public readonly accessToken = signal(undefined); - // TEMP: dev login bypass. Remove together with the "skip" button on the - // login page once the real login flow works again. - public readonly mockMode = signal(false); - private readonly mockProfile: AccountProfile = { - id: 'mock-superadmin', - email: 'superadmin@local.mock', - name: 'Mock Superadmin', - role: 'SUPER_ADMIN', - organization_id: 'mock-org', - organization_name: 'Mock Organization', - deleted: false, - activated: true, - is_current: true, - is_real_account: true, - is_impersonating: false, - }; - - public loginAsMockSuperAdmin(): void { - this.mockMode.set(true); - this.accessToken.set({ - real_account_id: this.mockProfile.id, - effective_account_id: this.mockProfile.id, - effective_organization_id: this.mockProfile.organization_id, - effective_role: 'SUPER_ADMIN', - expires_at: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(), - user_fingerprint_hash: 'mock', - raw_token: 'mock-token', - }); - } - public readonly isActiveAccessToken = computed(() => { const accessToken = this.accessToken(); return ( @@ -150,11 +120,9 @@ export class CredentialService { public readonly accountProfile = toSignal( toObservable(this.accessToken).pipe( switchMap((accessToken) => - this.mockMode() - ? of(this.mockProfile) - : accessToken - ? this.authService.getCurrentAccount() - : of(undefined), + accessToken + ? this.authService.getCurrentAccount() + : of(undefined), ), ), { initialValue: undefined }, -- 2.56.1 From 9aeb8171a7ef56148abc071510d13b4ac167d980 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Sun, 12 Jul 2026 18:41:33 +0200 Subject: [PATCH 04/60] rename preprocessing worker folder to background-jobs --- {preprocessing => background-jobs}/.dockerignore | 0 {preprocessing => background-jobs}/.env.example | 0 {preprocessing => background-jobs}/.gitignore | 0 {preprocessing => background-jobs}/Dockerfile | 0 {preprocessing => background-jobs}/app/elastic/client.py | 0 {preprocessing => background-jobs}/app/llm/client.py | 0 {preprocessing => background-jobs}/app/sync.py | 0 {preprocessing => background-jobs}/entrypoint.sh | 0 {preprocessing => background-jobs}/requirements.txt | 0 9 files changed, 0 insertions(+), 0 deletions(-) rename {preprocessing => background-jobs}/.dockerignore (100%) rename {preprocessing => background-jobs}/.env.example (100%) rename {preprocessing => background-jobs}/.gitignore (100%) rename {preprocessing => background-jobs}/Dockerfile (100%) rename {preprocessing => background-jobs}/app/elastic/client.py (100%) rename {preprocessing => background-jobs}/app/llm/client.py (100%) rename {preprocessing => background-jobs}/app/sync.py (100%) rename {preprocessing => background-jobs}/entrypoint.sh (100%) rename {preprocessing => background-jobs}/requirements.txt (100%) diff --git a/preprocessing/.dockerignore b/background-jobs/.dockerignore similarity index 100% rename from preprocessing/.dockerignore rename to background-jobs/.dockerignore diff --git a/preprocessing/.env.example b/background-jobs/.env.example similarity index 100% rename from preprocessing/.env.example rename to background-jobs/.env.example diff --git a/preprocessing/.gitignore b/background-jobs/.gitignore similarity index 100% rename from preprocessing/.gitignore rename to background-jobs/.gitignore diff --git a/preprocessing/Dockerfile b/background-jobs/Dockerfile similarity index 100% rename from preprocessing/Dockerfile rename to background-jobs/Dockerfile diff --git a/preprocessing/app/elastic/client.py b/background-jobs/app/elastic/client.py similarity index 100% rename from preprocessing/app/elastic/client.py rename to background-jobs/app/elastic/client.py diff --git a/preprocessing/app/llm/client.py b/background-jobs/app/llm/client.py similarity index 100% rename from preprocessing/app/llm/client.py rename to background-jobs/app/llm/client.py diff --git a/preprocessing/app/sync.py b/background-jobs/app/sync.py similarity index 100% rename from preprocessing/app/sync.py rename to background-jobs/app/sync.py diff --git a/preprocessing/entrypoint.sh b/background-jobs/entrypoint.sh similarity index 100% rename from preprocessing/entrypoint.sh rename to background-jobs/entrypoint.sh diff --git a/preprocessing/requirements.txt b/background-jobs/requirements.txt similarity index 100% rename from preprocessing/requirements.txt rename to background-jobs/requirements.txt -- 2.56.1 From 19933d69b6fc79981572d5d31abdb44d2e39c7f6 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Sun, 12 Jul 2026 19:30:14 +0200 Subject: [PATCH 05/60] add background job definition and run tables with seeding --- .../src/main/inse/background_jobs/__init__.py | 0 .../src/main/inse/background_jobs/model.py | 81 +++++++++++++++++++ service/src/main/inse/background_jobs/seed.py | 49 +++++++++++ service/src/main/inse/main.py | 2 + 4 files changed, 132 insertions(+) create mode 100644 service/src/main/inse/background_jobs/__init__.py create mode 100644 service/src/main/inse/background_jobs/model.py create mode 100644 service/src/main/inse/background_jobs/seed.py diff --git a/service/src/main/inse/background_jobs/__init__.py b/service/src/main/inse/background_jobs/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/service/src/main/inse/background_jobs/model.py b/service/src/main/inse/background_jobs/model.py new file mode 100644 index 00000000..ffaaa066 --- /dev/null +++ b/service/src/main/inse/background_jobs/model.py @@ -0,0 +1,81 @@ +""" +Database tables for the background job runner. +""" + +from datetime import datetime, timezone +from enum import StrEnum +from typing import Optional + +from sqlmodel import Field, SQLModel + + +class BackgroundJobName(StrEnum): + """Jobs known to the background-jobs image's entrypoint.sh dispatcher.""" + + NEWS = "news" + NEWS_STATS = "news-stats" + + +class JobRunStatus(StrEnum): + RUNNING = "running" + SUCCEEDED = "succeeded" + FAILED = "failed" + STOPPED = "stopped" + + +class JobTriggeredBy(StrEnum): + SCHEDULE = "schedule" + MANUAL = "manual" + + +def utcnow() -> datetime: + return datetime.now(timezone.utc).replace(tzinfo=None) + + +class JobDefinition(SQLModel, table=True): + __tablename__ = "background_job_definition" + + id: Optional[int] = Field(default=None, primary_key=True) + name: str = Field( + index=True, unique=True, description="Human-readable job name shown in the UI." + ) + description: str = Field(default="", description="What this job does.") + target_index: str = Field( + default="", description="Elasticsearch index the job writes to (UI info)." + ) + job: BackgroundJobName = Field( + description="Job argument passed to the background-jobs image's entrypoint." + ) + schedule: Optional[str] = Field( + default=None, + description="Cron expression in UTC (e.g. '0 3 * * *'). Null = manual only.", + ) + enabled: bool = Field( + default=True, description="Disabled definitions are never scheduled." + ) + next_run_at: Optional[datetime] = Field( + default=None, description="Computed by the scheduler from the cron expression." + ) + created_at: datetime = Field(default_factory=utcnow) + + +class JobRun(SQLModel, table=True): + __tablename__ = "background_job_run" + + id: Optional[int] = Field(default=None, primary_key=True) + definition_id: int = Field( + foreign_key="background_job_definition.id", index=True + ) + container_id: Optional[str] = Field(default=None) + status: JobRunStatus = Field(default=JobRunStatus.RUNNING) + triggered_by: JobTriggeredBy = Field( + description="Whether the scheduler or a superadmin started this run." + ) + started_at: datetime = Field(default_factory=utcnow) + finished_at: Optional[datetime] = Field(default=None) + exit_code: Optional[int] = Field(default=None) + logs: Optional[str] = Field( + default=None, + description="Captured stdout/stderr, filled in when the run finishes " + "(the container itself is removed afterwards).", + ) diff --git a/service/src/main/inse/background_jobs/seed.py b/service/src/main/inse/background_jobs/seed.py new file mode 100644 index 00000000..73a5ac1b --- /dev/null +++ b/service/src/main/inse/background_jobs/seed.py @@ -0,0 +1,49 @@ +""" +Seeding of the whitelisted background job definitions. +""" + +import logging + +from sqlmodel import Session, select + +from .model import BackgroundJobName, JobDefinition + +logger = logging.getLogger(__name__) + +PREDEFINED_JOB_DEFINITIONS: list[dict] = [ + { + "name": "News-Aufbereitung", + "description": ( + "Übernimmt neue Artikel aus dem „aktuell“-Index und fügt Relevanz, " + "Personenzuordnungen und Schlagwörter hinzu (Delta-Sync per LLM)." + ), + "target_index": "aktuell_postproc", + "job": BackgroundJobName.NEWS, + "schedule": None, + "enabled": True, + }, + { + "name": "News-Statistik", + "description": ( + "Zählt die Einträge in „aktuell“ und „aktuell_postproc“ (read-only, " + "verändert nichts) — nützlich als Verbindungstest." + ), + "target_index": "aktuell_postproc", + "job": BackgroundJobName.NEWS_STATS, + "schedule": None, + "enabled": True, + }, +] + + +def create_predefined_job_definitions(session: Session) -> None: + """Seed the whitelisted job definitions once (idempotent, keyed by job).""" + for entry in PREDEFINED_JOB_DEFINITIONS: + existing = session.exec( + select(JobDefinition).where(JobDefinition.job == entry["job"]) + ).first() + if existing: + continue + session.add(JobDefinition(**entry)) + logger.info("Seeded background job definition '%s'.", entry["name"]) + session.commit() diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index b8fa3d17..b4d12eec 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -43,6 +43,7 @@ from inse.bookmarks.router import router as bookmarks_router from inse.institutions.router import router as institutions_router from inse.database import create_db_and_tables, get_session from inse.auth.service import create_predefined_accounts +from inse.background_jobs.seed import create_predefined_job_definitions from . import config from .service import router as service_router @@ -69,6 +70,7 @@ async def lifespan(app: FastAPI): create_db_and_tables() with contextmanager(get_session)() as session: create_predefined_accounts(session, "../data/predefined_accounts.json") + create_predefined_job_definitions(session) yield logger.info("Shutting down the application...") -- 2.56.1 From 8bb0cf18ada598ffa1ff600e79f721494d6e9a23 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Sun, 12 Jul 2026 19:44:24 +0200 Subject: [PATCH 06/60] add docker job runner and scheduler --- service/Dockerfile | 4 +- .../src/main/inse/background_jobs/runner.py | 196 ++++++++++++++++++ service/src/main/inse/config.py | 5 + 3 files changed, 204 insertions(+), 1 deletion(-) create mode 100644 service/src/main/inse/background_jobs/runner.py diff --git a/service/Dockerfile b/service/Dockerfile index 3fe46ebb..630fb24e 100644 --- a/service/Dockerfile +++ b/service/Dockerfile @@ -19,7 +19,9 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c "partial-json-parser==0.2.1.1.post7" \ "sqlmodel~=0.0.33" \ "argon2-cffi~=25.1.0" \ - "pypdf==6.14.2" + "pypdf==6.14.2" \ + "docker~=7.1.0" \ + "croniter~=6.0.0" COPY [ "src/main", "/home" ] COPY [ "src/data", "/data" ] diff --git a/service/src/main/inse/background_jobs/runner.py b/service/src/main/inse/background_jobs/runner.py new file mode 100644 index 00000000..e4390cdb --- /dev/null +++ b/service/src/main/inse/background_jobs/runner.py @@ -0,0 +1,196 @@ +""" +Execution side of the background job runner: launches job containers as +siblings via the host's Docker daemon (mounted /var/run/docker.sock) and +runs the periodic schedule/reconcile loop. +""" + +import asyncio +import logging +from datetime import datetime +from typing import Optional + +import docker +from croniter import croniter +from docker.errors import NotFound +from sqlmodel import Session, select + +from inse import config +from inse.database import engine + +from .model import JobDefinition, JobRun, JobRunStatus, JobTriggeredBy, utcnow + +logger = logging.getLogger(__name__) + +settings = config.get_settings() + +_client: Optional[docker.DockerClient] = None + + +def get_docker_client() -> docker.DockerClient: + """Lazily create the Docker client so the service still boots (and all + other endpoints work) when no Docker daemon is reachable.""" + global _client + if _client is None: + _client = docker.from_env() + return _client + + +def docker_reachable() -> tuple[bool, str]: + try: + get_docker_client().ping() + return True, "ok" + except Exception as error: # noqa: BLE001 - reported to the caller + return False, str(error) + + +def compute_next_run(schedule: str) -> datetime: + return croniter(schedule, utcnow()).get_next(datetime) + + +def job_environment() -> dict[str, str]: + """Environment for the job container, mapped from the service settings. + + Passed inline: sibling containers are created by the HOST daemon, so an + env *file* path would resolve on the host, not in this container.""" + environment = { + "INSE_ELASTIC_URL": settings.elasticsearch_inse_url, + "INSE_ELASTIC_API_KEY": settings.elasticsearch_inse_api_key, + "INSE_LLM_BASE_URL": settings.llm_api_url, + "INSE_LLM_API_KEY": settings.llm_api_key, + "INSE_LLM_MODEL": settings.llm_model, + } + return {key: value for key, value in environment.items() if value} + + +def start_run( + session: Session, definition: JobDefinition, triggered_by: JobTriggeredBy +) -> JobRun: + """Create a JobRun row and launch its container. Marks the run failed + immediately if the container can't be started (e.g. image missing).""" + run = JobRun(definition_id=definition.id, triggered_by=triggered_by) + session.add(run) + session.commit() + session.refresh(run) # need run.id for the container name + + try: + container = get_docker_client().containers.run( + image=settings.background_jobs_image, + command=[definition.job.value], + environment=job_environment(), + detach=True, + name=f"background-job-{definition.job.value}-run-{run.id}", + remove=False, # reconciler reads logs + exit code, then removes it + ) + run.container_id = container.id + except Exception as error: # noqa: BLE001 - incl. ImageNotFound/daemon down + run.status = JobRunStatus.FAILED + run.finished_at = utcnow() + run.logs = f"failed to start container: {error}" + + session.add(run) + session.commit() + session.refresh(run) + return run + + +def has_running_run(session: Session, definition_id: int) -> bool: + return ( + session.exec( + select(JobRun).where( + JobRun.definition_id == definition_id, + JobRun.status == JobRunStatus.RUNNING, + ) + ).first() + is not None + ) + + +def schedule_due_jobs(session: Session) -> None: + now = utcnow() + scheduled = session.exec( + select(JobDefinition).where( + JobDefinition.enabled == True, # noqa: E712 - SQLModel expression + JobDefinition.schedule != None, # noqa: E711 + ) + ).all() + + for definition in scheduled: + if definition.next_run_at is None: + definition.next_run_at = compute_next_run(definition.schedule) + session.add(definition) + continue + if definition.next_run_at > now: + continue + + # Simple overlap protection: skip this slot if the previous run of + # the same definition is still going. + if has_running_run(session, definition.id): + logger.info( + "Skipping '%s': previous run still running.", definition.name + ) + else: + run = start_run(session, definition, JobTriggeredBy.SCHEDULE) + logger.info( + "Started scheduled run %s of '%s'.", run.id, definition.name + ) + + definition.next_run_at = compute_next_run(definition.schedule) + session.add(definition) + + session.commit() + + +def reconcile_runs(session: Session) -> None: + """Finalize runs whose container has exited: capture logs + exit code + into the JobRun row, then remove the container (the DB row is the + durable record, not the container).""" + running = session.exec( + select(JobRun).where(JobRun.status == JobRunStatus.RUNNING) + ).all() + for run in running: + if not run.container_id: + continue + try: + container = get_docker_client().containers.get(run.container_id) + except NotFound: + run.status = JobRunStatus.FAILED + run.finished_at = utcnow() + run.logs = (run.logs or "") + "\n[container disappeared before reconciliation]" + session.add(run) + continue + + container.reload() + if container.status in ("exited", "dead"): + exit_code = container.attrs["State"]["ExitCode"] + run.logs = container.logs().decode("utf-8", errors="replace") + run.exit_code = exit_code + run.status = ( + JobRunStatus.SUCCEEDED if exit_code == 0 else JobRunStatus.FAILED + ) + run.finished_at = utcnow() + session.add(run) + container.remove() + logger.info( + "Run %s finished: %s (exit %s).", run.id, run.status, exit_code + ) + session.commit() + + +def tick() -> None: + with Session(engine) as session: + schedule_due_jobs(session) + reconcile_runs(session) + + +async def scheduler_loop() -> None: + logger.info( + "Background job scheduler started (tick every %ss).", + settings.background_jobs_tick_seconds, + ) + while True: + try: + # Docker SDK calls are blocking -- keep them off the event loop. + await asyncio.to_thread(tick) + except Exception: # noqa: BLE001 - a failed tick must not kill the loop + logger.exception("Background job scheduler tick failed.") + await asyncio.sleep(settings.background_jobs_tick_seconds) diff --git a/service/src/main/inse/config.py b/service/src/main/inse/config.py index ba0c1765..b435009e 100644 --- a/service/src/main/inse/config.py +++ b/service/src/main/inse/config.py @@ -43,6 +43,11 @@ class Settings(BaseSettings): llm_api_key: Optional[str] = None llm_model: Optional[str] = None + # Background job runner config (Docker-out-of-Docker) + background_jobs_image: str = "docker.nes.uni-due.de/inse/background-jobs:latest" + background_jobs_scheduler_enabled: bool = True + background_jobs_tick_seconds: int = 5 + # Sentence Transformers config sentence_transformers_model_name: str = "intfloat/multilingual-e5-base" -- 2.56.1 From 5ce97e6854e4affeac37005376c7100574411342 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Sun, 12 Jul 2026 20:02:45 +0200 Subject: [PATCH 07/60] add superadmin background job endpoints and scheduler --- .../src/main/inse/background_jobs/model.py | 34 ++- .../src/main/inse/background_jobs/router.py | 108 +++++++++ .../src/main/inse/background_jobs/service.py | 208 ++++++++++++++++++ service/src/main/inse/main.py | 14 ++ service/src/main/inse/tags.py | 1 + 5 files changed, 364 insertions(+), 1 deletion(-) create mode 100644 service/src/main/inse/background_jobs/router.py create mode 100644 service/src/main/inse/background_jobs/service.py diff --git a/service/src/main/inse/background_jobs/model.py b/service/src/main/inse/background_jobs/model.py index ffaaa066..fae504a0 100644 --- a/service/src/main/inse/background_jobs/model.py +++ b/service/src/main/inse/background_jobs/model.py @@ -1,11 +1,12 @@ """ -Database tables for the background job runner. +Database tables and API schemas for the background job runner. """ from datetime import datetime, timezone from enum import StrEnum from typing import Optional +from pydantic import BaseModel from sqlmodel import Field, SQLModel @@ -79,3 +80,34 @@ class JobRun(SQLModel, table=True): description="Captured stdout/stderr, filled in when the run finishes " "(the container itself is removed afterwards).", ) + + +class JobDefinitionUpdateRequest(BaseModel): + + schedule: Optional[str] = None + enabled: Optional[bool] = None + + +class BackgroundJobTask(BaseModel): + id: int + name: str + description: str + target_index: str + job: BackgroundJobName + image: str + schedule: Optional[str] + enabled: bool + next_run_at: Optional[datetime] + last_run: Optional[JobRun] + status: str + + +class JobRunLogs(BaseModel): + run_id: int + status: JobRunStatus + logs: str + + +class DockerHealth(BaseModel): + reachable: bool + detail: str diff --git a/service/src/main/inse/background_jobs/router.py b/service/src/main/inse/background_jobs/router.py new file mode 100644 index 00000000..046a09f2 --- /dev/null +++ b/service/src/main/inse/background_jobs/router.py @@ -0,0 +1,108 @@ +from fastapi import APIRouter, Depends, Query +from sqlmodel import Session + +from inse.auth import service as auth_service +from inse.auth.model import AccessTokenMetadata +from inse.database import get_session +from inse.tags import Tags + +from . import service +from .model import ( + BackgroundJobTask, + DockerHealth, + JobDefinitionUpdateRequest, + JobRun, + JobRunLogs, +) + +router = APIRouter(prefix="/api/background-jobs", tags=[Tags.BACKGROUND_JOBS]) + + +@router.get( + "/tasks", + operation_id="getBackgroundJobTasks", + response_model=list[BackgroundJobTask], +) +async def get_tasks( + session: Session = Depends(get_session), + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, +) -> list[BackgroundJobTask]: + return service.get_tasks(session, access_token) + + +@router.patch( + "/tasks/{task_id}", + operation_id="updateBackgroundJobTask", + response_model=BackgroundJobTask, +) +async def update_task( + task_id: int, + payload: JobDefinitionUpdateRequest, + session: Session = Depends(get_session), + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, +) -> BackgroundJobTask: + return service.update_task(session, access_token, task_id, payload) + + +@router.post( + "/tasks/{task_id}/run", + operation_id="runBackgroundJobTask", + response_model=JobRun, +) +async def run_task( + task_id: int, + session: Session = Depends(get_session), + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, +) -> JobRun: + return service.trigger_run(session, access_token, task_id) + + +@router.get( + "/tasks/{task_id}/runs", + operation_id="getBackgroundJobTaskRuns", + response_model=list[JobRun], +) +async def get_task_runs( + task_id: int, + limit: int = Query(default=20, ge=1, le=100), + session: Session = Depends(get_session), + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, +) -> list[JobRun]: + return service.get_task_runs(session, access_token, task_id, limit) + + +@router.get( + "/runs/{run_id}/logs", + operation_id="getBackgroundJobRunLogs", + response_model=JobRunLogs, +) +async def get_run_logs( + run_id: int, + session: Session = Depends(get_session), + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, +) -> JobRunLogs: + return service.get_run_logs(session, access_token, run_id) + + +@router.post( + "/runs/{run_id}/stop", + operation_id="stopBackgroundJobRun", + response_model=JobRun, +) +async def stop_run( + run_id: int, + session: Session = Depends(get_session), + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, +) -> JobRun: + return service.stop_run(session, access_token, run_id) + + +@router.get( + "/docker-health", + operation_id="getBackgroundJobsDockerHealth", + response_model=DockerHealth, +) +async def docker_health( + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, +) -> DockerHealth: + return service.docker_health(access_token) diff --git a/service/src/main/inse/background_jobs/service.py b/service/src/main/inse/background_jobs/service.py new file mode 100644 index 00000000..a2b2180b --- /dev/null +++ b/service/src/main/inse/background_jobs/service.py @@ -0,0 +1,208 @@ +""" +Business logic for the background job endpoints. Every function checks the +caller's access token first: background jobs start containers on the host, +so nothing here may ever be reachable for non-superadmins. +""" + +import logging + +from croniter import croniter +from fastapi import HTTPException, status +from sqlmodel import Session, col, select + +from inse import config +from inse.auth.model import AccessTokenMetadata, UserRole + +from . import runner +from .model import ( + BackgroundJobTask, + DockerHealth, + JobDefinition, + JobDefinitionUpdateRequest, + JobRun, + JobRunLogs, + JobRunStatus, + JobTriggeredBy, +) + +logger = logging.getLogger(__name__) + +settings = config.get_settings() + + +def _require_super_admin(access_token: AccessTokenMetadata) -> None: + if access_token.effective_role != UserRole.SUPER_ADMIN: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Only superadmins can manage background jobs.", + ) + + +def _get_definition(session: Session, definition_id: int) -> JobDefinition: + definition = session.get(JobDefinition, definition_id) + if not definition: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Unknown background job task id {definition_id}.", + ) + return definition + + +def _get_run(session: Session, run_id: int) -> JobRun: + run = session.get(JobRun, run_id) + if not run: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Unknown background job run id {run_id}.", + ) + return run + + +def _last_run(session: Session, definition_id: int) -> JobRun | None: + return session.exec( + select(JobRun) + .where(JobRun.definition_id == definition_id) + .order_by(col(JobRun.id).desc()) + ).first() + + +def _to_task(session: Session, definition: JobDefinition) -> BackgroundJobTask: + last_run = _last_run(session, definition.id) + if last_run is None: + derived_status = "idle" + elif last_run.status == JobRunStatus.RUNNING: + derived_status = "running" + else: + derived_status = last_run.status.value + return BackgroundJobTask( + id=definition.id, + name=definition.name, + description=definition.description, + target_index=definition.target_index, + job=definition.job, + image=settings.background_jobs_image, + schedule=definition.schedule, + enabled=definition.enabled, + next_run_at=definition.next_run_at, + last_run=last_run, + status=derived_status, + ) + + +def get_tasks( + session: Session, access_token: AccessTokenMetadata +) -> list[BackgroundJobTask]: + _require_super_admin(access_token) + definitions = session.exec( + select(JobDefinition).order_by(col(JobDefinition.id)) + ).all() + return [_to_task(session, definition) for definition in definitions] + + +def update_task( + session: Session, + access_token: AccessTokenMetadata, + definition_id: int, + payload: JobDefinitionUpdateRequest, +) -> BackgroundJobTask: + _require_super_admin(access_token) + changes = payload.model_dump(exclude_unset=True) + if changes.get("schedule") is not None and not croniter.is_valid( + changes["schedule"] + ): + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail=f"Invalid cron expression: '{changes['schedule']}'.", + ) + + definition = _get_definition(session, definition_id) + for key, value in changes.items(): + setattr(definition, key, value) + if "schedule" in changes or "enabled" in changes: + definition.next_run_at = ( + runner.compute_next_run(definition.schedule) + if definition.enabled and definition.schedule + else None + ) + session.add(definition) + session.commit() + session.refresh(definition) + return _to_task(session, definition) + + +def trigger_run( + session: Session, access_token: AccessTokenMetadata, definition_id: int +) -> JobRun: + _require_super_admin(access_token) + definition = _get_definition(session, definition_id) + if runner.has_running_run(session, definition.id): + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail=f"'{definition.name}' is already running.", + ) + return runner.start_run(session, definition, JobTriggeredBy.MANUAL) + + +def get_task_runs( + session: Session, + access_token: AccessTokenMetadata, + definition_id: int, + limit: int, +) -> list[JobRun]: + _require_super_admin(access_token) + _get_definition(session, definition_id) + return session.exec( + select(JobRun) + .where(JobRun.definition_id == definition_id) + .order_by(col(JobRun.id).desc()) + .limit(limit) + ).all() + + +def get_run_logs( + session: Session, access_token: AccessTokenMetadata, run_id: int +) -> JobRunLogs: + """Live from the container while running; from the database once finished.""" + _require_super_admin(access_token) + run = _get_run(session, run_id) + if run.status == JobRunStatus.RUNNING and run.container_id: + try: + container = runner.get_docker_client().containers.get(run.container_id) + return JobRunLogs( + run_id=run_id, + status=run.status, + logs=container.logs().decode("utf-8", errors="replace"), + ) + except Exception: # noqa: BLE001 + pass # container may have just exited; fall through to stored logs + return JobRunLogs(run_id=run_id, status=run.status, logs=run.logs or "") + + +def stop_run( + session: Session, access_token: AccessTokenMetadata, run_id: int +) -> JobRun: + """Stops the container; the scheduler's next reconcile pass records the + final status, logs, and exit code.""" + _require_super_admin(access_token) + run = _get_run(session, run_id) + if run.status != JobRunStatus.RUNNING or not run.container_id: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail=f"Run {run_id} is not running.", + ) + try: + runner.get_docker_client().containers.get(run.container_id).stop() + except Exception as error: # noqa: BLE001 + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail=f"Failed to stop container: {error}", + ) + # The run stays "running" here on purpose: the next reconcile pass sees + # the exited container, captures its logs + exit code and removes it. + return run + + +def docker_health(access_token: AccessTokenMetadata) -> DockerHealth: + _require_super_admin(access_token) + reachable, detail = runner.docker_reachable() + return DockerHealth(reachable=reachable, detail=detail) diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index b4d12eec..1b0eacea 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -6,6 +6,7 @@ for fastapi that loads the service and the webapp. """ +import asyncio from contextlib import asynccontextmanager, contextmanager import logging @@ -43,6 +44,8 @@ from inse.bookmarks.router import router as bookmarks_router from inse.institutions.router import router as institutions_router from inse.database import create_db_and_tables, get_session from inse.auth.service import create_predefined_accounts +from inse.background_jobs.router import router as background_jobs_router +from inse.background_jobs.runner import scheduler_loop as background_jobs_scheduler_loop from inse.background_jobs.seed import create_predefined_job_definitions from . import config @@ -71,7 +74,17 @@ async def lifespan(app: FastAPI): with contextmanager(get_session)() as session: create_predefined_accounts(session, "../data/predefined_accounts.json") create_predefined_job_definitions(session) + + background_jobs_scheduler_task = None + if settings.background_jobs_scheduler_enabled: + background_jobs_scheduler_task = asyncio.create_task( + background_jobs_scheduler_loop() + ) + yield + + if background_jobs_scheduler_task is not None: + background_jobs_scheduler_task.cancel() logger.info("Shutting down the application...") @@ -110,6 +123,7 @@ app.include_router(works_v2_router) app.include_router(dashboard_router) app.include_router(bookmarks_router) +app.include_router(background_jobs_router) app.add_middleware( ETagCacheMiddleware, diff --git a/service/src/main/inse/tags.py b/service/src/main/inse/tags.py index a5411f63..a7690f85 100644 --- a/service/src/main/inse/tags.py +++ b/service/src/main/inse/tags.py @@ -15,3 +15,4 @@ class Tags(StrEnum): ORGANIZATION = "Organization" UNIVERSITY_RANKINGS = "University Rankings" DASHBOARD = "Dashboard" + BACKGROUND_JOBS = "Background Jobs" -- 2.56.1 From 3684a5acf5478a85e726e88a600830fb324be85f Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Sun, 12 Jul 2026 20:16:17 +0200 Subject: [PATCH 08/60] mount docker socket in serve task for job runner --- service/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service/build.gradle b/service/build.gradle index 066a7af3..488753d7 100644 --- a/service/build.gradle +++ b/service/build.gradle @@ -61,7 +61,7 @@ task exportOpenApiSpec(type: Exec) { task runServeContainer(type: Exec) { dependsOn createImage - commandLine 'docker', 'run', '--rm', '-v', "${projectDir}/src/main:/home", '-v', "${projectDir}/src/data:/data", '-p', '8000:8000', '-e', "DOCKER_DEFAULT_PLATFORM='${targetPlatform}'", '-e', "INSE_AUTH_STANDALONE=true", '-e', 'INSE_OPENALEX_WORKS_API_KEY', '--name', "${imageName}-service-serve", '--detach', "${imagePrefix}-service:${imageVersion}", 'run', '--reload', '--reload-dir', './inse' + commandLine 'docker', 'run', '--rm', '-v', "${projectDir}/src/main:/home", '-v', "${projectDir}/src/data:/data", '-v', '/var/run/docker.sock:/var/run/docker.sock', '-p', '8000:8000', '-e', "DOCKER_DEFAULT_PLATFORM='${targetPlatform}'", '-e', "INSE_AUTH_STANDALONE=true", '-e', 'INSE_OPENALEX_WORKS_API_KEY', '--name', "${imageName}-service-serve", '--detach', "${imagePrefix}-service:${imageVersion}", 'run', '--reload', '--reload-dir', './inse' } task stopServeContainer(type: Exec) { -- 2.56.1 From 07278b3f65862861fde51eedf20e7374b95940af Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Sun, 12 Jul 2026 21:09:57 +0200 Subject: [PATCH 09/60] add generated background jobs api client --- .../src/main/inse/background_jobs/model.py | 2 - .../src/main/inse/background_jobs/runner.py | 31 +- service/src/main/inse/background_jobs/seed.py | 1 - .../src/main/inse/background_jobs/service.py | 11 +- webapp/src/app/api/.openapi-generator/FILES | 9 + webapp/src/app/api/api/api.ts | 3 + .../src/app/api/api/backgroundJobs.service.ts | 875 ++++++++++++++++++ webapp/src/app/api/model/backgroundJobName.ts | 19 + webapp/src/app/api/model/backgroundJobTask.ts | 26 + webapp/src/app/api/model/dockerHealth.ts | 14 + .../api/model/jobDefinitionUpdateRequest.ts | 14 + webapp/src/app/api/model/jobRun.ts | 27 + webapp/src/app/api/model/jobRunLogs.ts | 17 + webapp/src/app/api/model/jobRunStatus.ts | 17 + webapp/src/app/api/model/jobTriggeredBy.ts | 16 + webapp/src/app/api/model/models.ts | 8 + 16 files changed, 1055 insertions(+), 35 deletions(-) create mode 100644 webapp/src/app/api/api/backgroundJobs.service.ts create mode 100644 webapp/src/app/api/model/backgroundJobName.ts create mode 100644 webapp/src/app/api/model/backgroundJobTask.ts create mode 100644 webapp/src/app/api/model/dockerHealth.ts create mode 100644 webapp/src/app/api/model/jobDefinitionUpdateRequest.ts create mode 100644 webapp/src/app/api/model/jobRun.ts create mode 100644 webapp/src/app/api/model/jobRunLogs.ts create mode 100644 webapp/src/app/api/model/jobRunStatus.ts create mode 100644 webapp/src/app/api/model/jobTriggeredBy.ts diff --git a/service/src/main/inse/background_jobs/model.py b/service/src/main/inse/background_jobs/model.py index fae504a0..7d470890 100644 --- a/service/src/main/inse/background_jobs/model.py +++ b/service/src/main/inse/background_jobs/model.py @@ -11,8 +11,6 @@ from sqlmodel import Field, SQLModel class BackgroundJobName(StrEnum): - """Jobs known to the background-jobs image's entrypoint.sh dispatcher.""" - NEWS = "news" NEWS_STATS = "news-stats" diff --git a/service/src/main/inse/background_jobs/runner.py b/service/src/main/inse/background_jobs/runner.py index e4390cdb..d2b568cc 100644 --- a/service/src/main/inse/background_jobs/runner.py +++ b/service/src/main/inse/background_jobs/runner.py @@ -1,7 +1,6 @@ """ -Execution side of the background job runner: launches job containers as -siblings via the host's Docker daemon (mounted /var/run/docker.sock) and -runs the periodic schedule/reconcile loop. +Launches background job containers via the host's Docker daemon and runs the +periodic schedule/reconcile loop. """ import asyncio @@ -27,8 +26,6 @@ _client: Optional[docker.DockerClient] = None def get_docker_client() -> docker.DockerClient: - """Lazily create the Docker client so the service still boots (and all - other endpoints work) when no Docker daemon is reachable.""" global _client if _client is None: _client = docker.from_env() @@ -39,7 +36,7 @@ def docker_reachable() -> tuple[bool, str]: try: get_docker_client().ping() return True, "ok" - except Exception as error: # noqa: BLE001 - reported to the caller + except Exception as error: # noqa: BLE001 return False, str(error) @@ -48,10 +45,6 @@ def compute_next_run(schedule: str) -> datetime: def job_environment() -> dict[str, str]: - """Environment for the job container, mapped from the service settings. - - Passed inline: sibling containers are created by the HOST daemon, so an - env *file* path would resolve on the host, not in this container.""" environment = { "INSE_ELASTIC_URL": settings.elasticsearch_inse_url, "INSE_ELASTIC_API_KEY": settings.elasticsearch_inse_api_key, @@ -65,12 +58,10 @@ def job_environment() -> dict[str, str]: def start_run( session: Session, definition: JobDefinition, triggered_by: JobTriggeredBy ) -> JobRun: - """Create a JobRun row and launch its container. Marks the run failed - immediately if the container can't be started (e.g. image missing).""" run = JobRun(definition_id=definition.id, triggered_by=triggered_by) session.add(run) session.commit() - session.refresh(run) # need run.id for the container name + session.refresh(run) try: container = get_docker_client().containers.run( @@ -79,10 +70,10 @@ def start_run( environment=job_environment(), detach=True, name=f"background-job-{definition.job.value}-run-{run.id}", - remove=False, # reconciler reads logs + exit code, then removes it + remove=False, ) run.container_id = container.id - except Exception as error: # noqa: BLE001 - incl. ImageNotFound/daemon down + except Exception as error: # noqa: BLE001 run.status = JobRunStatus.FAILED run.finished_at = utcnow() run.logs = f"failed to start container: {error}" @@ -109,7 +100,7 @@ def schedule_due_jobs(session: Session) -> None: now = utcnow() scheduled = session.exec( select(JobDefinition).where( - JobDefinition.enabled == True, # noqa: E712 - SQLModel expression + JobDefinition.enabled == True, # noqa: E712 JobDefinition.schedule != None, # noqa: E711 ) ).all() @@ -122,8 +113,6 @@ def schedule_due_jobs(session: Session) -> None: if definition.next_run_at > now: continue - # Simple overlap protection: skip this slot if the previous run of - # the same definition is still going. if has_running_run(session, definition.id): logger.info( "Skipping '%s': previous run still running.", definition.name @@ -141,9 +130,6 @@ def schedule_due_jobs(session: Session) -> None: def reconcile_runs(session: Session) -> None: - """Finalize runs whose container has exited: capture logs + exit code - into the JobRun row, then remove the container (the DB row is the - durable record, not the container).""" running = session.exec( select(JobRun).where(JobRun.status == JobRunStatus.RUNNING) ).all() @@ -189,8 +175,7 @@ async def scheduler_loop() -> None: ) while True: try: - # Docker SDK calls are blocking -- keep them off the event loop. await asyncio.to_thread(tick) - except Exception: # noqa: BLE001 - a failed tick must not kill the loop + except Exception: # noqa: BLE001 logger.exception("Background job scheduler tick failed.") await asyncio.sleep(settings.background_jobs_tick_seconds) diff --git a/service/src/main/inse/background_jobs/seed.py b/service/src/main/inse/background_jobs/seed.py index 73a5ac1b..6a4a42d9 100644 --- a/service/src/main/inse/background_jobs/seed.py +++ b/service/src/main/inse/background_jobs/seed.py @@ -37,7 +37,6 @@ PREDEFINED_JOB_DEFINITIONS: list[dict] = [ def create_predefined_job_definitions(session: Session) -> None: - """Seed the whitelisted job definitions once (idempotent, keyed by job).""" for entry in PREDEFINED_JOB_DEFINITIONS: existing = session.exec( select(JobDefinition).where(JobDefinition.job == entry["job"]) diff --git a/service/src/main/inse/background_jobs/service.py b/service/src/main/inse/background_jobs/service.py index a2b2180b..2b772483 100644 --- a/service/src/main/inse/background_jobs/service.py +++ b/service/src/main/inse/background_jobs/service.py @@ -1,7 +1,5 @@ """ -Business logic for the background job endpoints. Every function checks the -caller's access token first: background jobs start containers on the host, -so nothing here may ever be reachable for non-superadmins. +Business logic for the superadmin-only background job endpoints. """ import logging @@ -162,7 +160,6 @@ def get_task_runs( def get_run_logs( session: Session, access_token: AccessTokenMetadata, run_id: int ) -> JobRunLogs: - """Live from the container while running; from the database once finished.""" _require_super_admin(access_token) run = _get_run(session, run_id) if run.status == JobRunStatus.RUNNING and run.container_id: @@ -174,15 +171,13 @@ def get_run_logs( logs=container.logs().decode("utf-8", errors="replace"), ) except Exception: # noqa: BLE001 - pass # container may have just exited; fall through to stored logs + pass return JobRunLogs(run_id=run_id, status=run.status, logs=run.logs or "") def stop_run( session: Session, access_token: AccessTokenMetadata, run_id: int ) -> JobRun: - """Stops the container; the scheduler's next reconcile pass records the - final status, logs, and exit code.""" _require_super_admin(access_token) run = _get_run(session, run_id) if run.status != JobRunStatus.RUNNING or not run.container_id: @@ -197,8 +192,6 @@ def stop_run( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Failed to stop container: {error}", ) - # The run stays "running" here on purpose: the next reconcile pass sees - # the exited container, captures its logs + exit code and removes it. return run diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index 7e1e7127..cacf423b 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -5,6 +5,7 @@ api.base.service.ts api.module.ts api/api.ts api/auth.service.ts +api/backgroundJobs.service.ts api/bookmarks.service.ts api/companyConnections.service.ts api/dashboard.service.ts @@ -51,6 +52,8 @@ model/autocompleteResponse.ts model/autocompleteResponseMeta.ts model/autocompleteResponseResultsInner.ts model/award.ts +model/backgroundJobName.ts +model/backgroundJobTask.ts model/bodyChangePassword.ts model/bodyGetAccessToken.ts model/bodyLogin.ts @@ -83,6 +86,7 @@ model/dehydratedSource.ts model/dfgProjectDetails.ts model/dfgProjectPage.ts model/dfgProjectSummary.ts +model/dockerHealth.ts model/euCordisProjectResponse.ts model/euOrganizationProjectSummary.ts model/euOrganizationProjectSummaryPage.ts @@ -140,6 +144,11 @@ model/institutionNetworkNode.ts model/institutionPage.ts model/institutionsListResponse.ts model/ipcClassification.ts +model/jobDefinitionUpdateRequest.ts +model/jobRun.ts +model/jobRunLogs.ts +model/jobRunStatus.ts +model/jobTriggeredBy.ts model/keywordEntry.ts model/keywordEntryWithTopic.ts model/keywordPatentMatch.ts diff --git a/webapp/src/app/api/api/api.ts b/webapp/src/app/api/api/api.ts index d7bae3a8..6c0d3bdd 100644 --- a/webapp/src/app/api/api/api.ts +++ b/webapp/src/app/api/api/api.ts @@ -1,5 +1,7 @@ export * from './auth.service'; import { AuthService } from './auth.service'; +export * from './backgroundJobs.service'; +import { BackgroundJobsService } from './backgroundJobs.service'; export * from './bookmarks.service'; import { BookmarksService } from './bookmarks.service'; export * from './companyConnections.service'; @@ -36,6 +38,7 @@ export * from './worksV2.service'; import { WorksV2Service } from './worksV2.service'; export const APIS = [ AuthService, + BackgroundJobsService, BookmarksService, CompanyConnectionsService, DashboardService, diff --git a/webapp/src/app/api/api/backgroundJobs.service.ts b/webapp/src/app/api/api/backgroundJobs.service.ts new file mode 100644 index 00000000..871707eb --- /dev/null +++ b/webapp/src/app/api/api/backgroundJobs.service.ts @@ -0,0 +1,875 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { + HttpClient, + HttpHeaders, + HttpParams, + HttpResponse, + HttpEvent, + HttpParameterCodec, + HttpContext, +} from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { BackgroundJobTask } from '../model/backgroundJobTask'; +// @ts-ignore +import { DockerHealth } from '../model/dockerHealth'; +// @ts-ignore +import { HTTPValidationError } from '../model/hTTPValidationError'; +// @ts-ignore +import { JobDefinitionUpdateRequest } from '../model/jobDefinitionUpdateRequest'; +// @ts-ignore +import { JobRun } from '../model/jobRun'; +// @ts-ignore +import { JobRunLogs } from '../model/jobRunLogs'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; +import { BaseService } from '../api.base.service'; + +@Injectable({ + providedIn: 'root', +}) +export class BackgroundJobsService extends BaseService { + constructor( + protected httpClient: HttpClient, + @Optional() @Inject(BASE_PATH) basePath: string | string[], + @Optional() configuration?: Configuration, + ) { + super(basePath, configuration); + } + + /** + * Get Run Logs + * @endpoint get /api/background-jobs/runs/{run_id}/logs + * @param runId + * @param secureFgpAcc + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getBackgroundJobRunLogs( + runId: number, + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getBackgroundJobRunLogs( + runId: number, + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getBackgroundJobRunLogs( + runId: number, + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getBackgroundJobRunLogs( + runId: number, + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (runId === null || runId === undefined) { + throw new Error( + 'Required parameter runId was null or undefined when calling getBackgroundJobRunLogs.', + ); + } + + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/background-jobs/runs/${this.configuration.encodeParam({ name: 'runId', value: runId, in: 'path', style: 'simple', explode: false, dataType: 'number', dataFormat: undefined })}/logs`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Get Task Runs + * @endpoint get /api/background-jobs/tasks/{task_id}/runs + * @param taskId + * @param limit + * @param secureFgpAcc + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getBackgroundJobTaskRuns( + taskId: number, + limit?: number, + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getBackgroundJobTaskRuns( + taskId: number, + limit?: number, + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>>; + public getBackgroundJobTaskRuns( + taskId: number, + limit?: number, + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>>; + public getBackgroundJobTaskRuns( + taskId: number, + limit?: number, + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (taskId === null || taskId === undefined) { + throw new Error( + 'Required parameter taskId was null or undefined when calling getBackgroundJobTaskRuns.', + ); + } + + let localVarQueryParameters = new HttpParams({ encoder: this.encoder }); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + limit, + 'limit', + ); + + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/background-jobs/tasks/${this.configuration.encodeParam({ name: 'taskId', value: taskId, in: 'path', style: 'simple', explode: false, dataType: 'number', dataFormat: undefined })}/runs`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request>( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Get Tasks + * @endpoint get /api/background-jobs/tasks + * @param secureFgpAcc + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getBackgroundJobTasks( + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getBackgroundJobTasks( + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>>; + public getBackgroundJobTasks( + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>>; + public getBackgroundJobTasks( + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/background-jobs/tasks`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request>( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Docker Health + * @endpoint get /api/background-jobs/docker-health + * @param secureFgpAcc + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getBackgroundJobsDockerHealth( + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getBackgroundJobsDockerHealth( + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getBackgroundJobsDockerHealth( + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getBackgroundJobsDockerHealth( + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/background-jobs/docker-health`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Run Task + * @endpoint post /api/background-jobs/tasks/{task_id}/run + * @param taskId + * @param secureFgpAcc + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public runBackgroundJobTask( + taskId: number, + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public runBackgroundJobTask( + taskId: number, + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public runBackgroundJobTask( + taskId: number, + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public runBackgroundJobTask( + taskId: number, + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (taskId === null || taskId === undefined) { + throw new Error( + 'Required parameter taskId was null or undefined when calling runBackgroundJobTask.', + ); + } + + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/background-jobs/tasks/${this.configuration.encodeParam({ name: 'taskId', value: taskId, in: 'path', style: 'simple', explode: false, dataType: 'number', dataFormat: undefined })}/run`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'post', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Stop Run + * @endpoint post /api/background-jobs/runs/{run_id}/stop + * @param runId + * @param secureFgpAcc + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public stopBackgroundJobRun( + runId: number, + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public stopBackgroundJobRun( + runId: number, + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public stopBackgroundJobRun( + runId: number, + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public stopBackgroundJobRun( + runId: number, + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (runId === null || runId === undefined) { + throw new Error( + 'Required parameter runId was null or undefined when calling stopBackgroundJobRun.', + ); + } + + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/background-jobs/runs/${this.configuration.encodeParam({ name: 'runId', value: runId, in: 'path', style: 'simple', explode: false, dataType: 'number', dataFormat: undefined })}/stop`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'post', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Update Task + * @endpoint patch /api/background-jobs/tasks/{task_id} + * @param taskId + * @param jobDefinitionUpdateRequest + * @param secureFgpAcc + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updateBackgroundJobTask( + taskId: number, + jobDefinitionUpdateRequest: JobDefinitionUpdateRequest, + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public updateBackgroundJobTask( + taskId: number, + jobDefinitionUpdateRequest: JobDefinitionUpdateRequest, + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public updateBackgroundJobTask( + taskId: number, + jobDefinitionUpdateRequest: JobDefinitionUpdateRequest, + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public updateBackgroundJobTask( + taskId: number, + jobDefinitionUpdateRequest: JobDefinitionUpdateRequest, + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (taskId === null || taskId === undefined) { + throw new Error( + 'Required parameter taskId was null or undefined when calling updateBackgroundJobTask.', + ); + } + if ( + jobDefinitionUpdateRequest === null || + jobDefinitionUpdateRequest === undefined + ) { + throw new Error( + 'Required parameter jobDefinitionUpdateRequest was null or undefined when calling updateBackgroundJobTask.', + ); + } + + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + // to determine the Content-Type header + const consumes: string[] = ['application/json']; + const httpContentTypeSelected: string | undefined = + this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Content-Type', + httpContentTypeSelected, + ); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/background-jobs/tasks/${this.configuration.encodeParam({ name: 'taskId', value: taskId, in: 'path', style: 'simple', explode: false, dataType: 'number', dataFormat: undefined })}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'patch', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: jobDefinitionUpdateRequest, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } +} diff --git a/webapp/src/app/api/model/backgroundJobName.ts b/webapp/src/app/api/model/backgroundJobName.ts new file mode 100644 index 00000000..2c65eba1 --- /dev/null +++ b/webapp/src/app/api/model/backgroundJobName.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/** + * Jobs known to the background-jobs image\'s entrypoint.sh dispatcher. + */ +export const BackgroundJobName = { + News: 'news', + NewsStats: 'news-stats', +} as const; +export type BackgroundJobName = + (typeof BackgroundJobName)[keyof typeof BackgroundJobName]; diff --git a/webapp/src/app/api/model/backgroundJobTask.ts b/webapp/src/app/api/model/backgroundJobTask.ts new file mode 100644 index 00000000..0f413e88 --- /dev/null +++ b/webapp/src/app/api/model/backgroundJobTask.ts @@ -0,0 +1,26 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { BackgroundJobName } from './backgroundJobName'; +import { JobRun } from './jobRun'; + +export interface BackgroundJobTask { + id: number; + name: string; + description: string; + target_index: string; + job: BackgroundJobName; + image: string; + schedule: string | null; + enabled: boolean; + next_run_at: string | null; + last_run: JobRun | null; + status: string; +} +export namespace BackgroundJobTask {} diff --git a/webapp/src/app/api/model/dockerHealth.ts b/webapp/src/app/api/model/dockerHealth.ts new file mode 100644 index 00000000..ba28ab8a --- /dev/null +++ b/webapp/src/app/api/model/dockerHealth.ts @@ -0,0 +1,14 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +export interface DockerHealth { + reachable: boolean; + detail: string; +} diff --git a/webapp/src/app/api/model/jobDefinitionUpdateRequest.ts b/webapp/src/app/api/model/jobDefinitionUpdateRequest.ts new file mode 100644 index 00000000..faaec21c --- /dev/null +++ b/webapp/src/app/api/model/jobDefinitionUpdateRequest.ts @@ -0,0 +1,14 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +export interface JobDefinitionUpdateRequest { + schedule?: string | null; + enabled?: boolean | null; +} diff --git a/webapp/src/app/api/model/jobRun.ts b/webapp/src/app/api/model/jobRun.ts new file mode 100644 index 00000000..20346ae6 --- /dev/null +++ b/webapp/src/app/api/model/jobRun.ts @@ -0,0 +1,27 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { JobRunStatus } from './jobRunStatus'; +import { JobTriggeredBy } from './jobTriggeredBy'; + +export interface JobRun { + id?: number | null; + definition_id: number; + container_id?: string | null; + status?: JobRunStatus; + /** + * Whether the scheduler or a superadmin started this run. + */ + triggered_by: JobTriggeredBy; + started_at?: string; + finished_at?: string | null; + exit_code?: number | null; + logs?: string | null; +} +export namespace JobRun {} diff --git a/webapp/src/app/api/model/jobRunLogs.ts b/webapp/src/app/api/model/jobRunLogs.ts new file mode 100644 index 00000000..423a6f1a --- /dev/null +++ b/webapp/src/app/api/model/jobRunLogs.ts @@ -0,0 +1,17 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { JobRunStatus } from './jobRunStatus'; + +export interface JobRunLogs { + run_id: number; + status: JobRunStatus; + logs: string; +} +export namespace JobRunLogs {} diff --git a/webapp/src/app/api/model/jobRunStatus.ts b/webapp/src/app/api/model/jobRunStatus.ts new file mode 100644 index 00000000..d50886b4 --- /dev/null +++ b/webapp/src/app/api/model/jobRunStatus.ts @@ -0,0 +1,17 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +export const JobRunStatus = { + Running: 'running', + Succeeded: 'succeeded', + Failed: 'failed', + Stopped: 'stopped', +} as const; +export type JobRunStatus = (typeof JobRunStatus)[keyof typeof JobRunStatus]; diff --git a/webapp/src/app/api/model/jobTriggeredBy.ts b/webapp/src/app/api/model/jobTriggeredBy.ts new file mode 100644 index 00000000..4ace1836 --- /dev/null +++ b/webapp/src/app/api/model/jobTriggeredBy.ts @@ -0,0 +1,16 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +export const JobTriggeredBy = { + Schedule: 'schedule', + Manual: 'manual', +} as const; +export type JobTriggeredBy = + (typeof JobTriggeredBy)[keyof typeof JobTriggeredBy]; diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index f3122d41..88bb2e6c 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -23,6 +23,8 @@ export * from './autocompleteResponse'; export * from './autocompleteResponseMeta'; export * from './autocompleteResponseResultsInner'; export * from './award'; +export * from './backgroundJobName'; +export * from './backgroundJobTask'; export * from './bodyChangePassword'; export * from './bodyGetAccessToken'; export * from './bodyLogin'; @@ -55,6 +57,7 @@ export * from './dehydratedSource'; export * from './dfgProjectDetails'; export * from './dfgProjectPage'; export * from './dfgProjectSummary'; +export * from './dockerHealth'; export * from './euCordisProjectResponse'; export * from './euOrganizationProjectSummary'; export * from './euOrganizationProjectSummaryPage'; @@ -112,6 +115,11 @@ export * from './institutionNetworkNode'; export * from './institutionPage'; export * from './institutionsListResponse'; export * from './ipcClassification'; +export * from './jobDefinitionUpdateRequest'; +export * from './jobRun'; +export * from './jobRunLogs'; +export * from './jobRunStatus'; +export * from './jobTriggeredBy'; export * from './keywordEntry'; export * from './keywordEntryWithTopic'; export * from './keywordPatentMatch'; -- 2.56.1 From 069566d71d13f07fe8b9f1f866a60e188226b537 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Tue, 14 Jul 2026 01:16:42 +0200 Subject: [PATCH 10/60] feat(jobs): rename 'preprocessing' to 'jobs', wire-up backend to frontend --- webapp/src/app/app.routes.ts | 14 +- .../job-logs-dialog.component.html | 46 +++ .../job-logs-dialog.component.scss | 96 +++++++ .../job-logs-dialog.component.ts | 69 +++++ .../src/app/modules/jobs/jobs.component.html | 136 +++++++++ .../jobs.component.scss} | 125 +++----- webapp/src/app/modules/jobs/jobs.component.ts | 248 ++++++++++++++++ webapp/src/app/modules/jobs/jobs.utils.ts | 48 ++++ .../task-schedule-dialog.component.html | 48 ++++ .../task-schedule-dialog.component.scss | 64 +---- .../task-schedule-dialog.component.ts | 79 ++++++ .../preprocessing.component.html | 204 ------------- .../preprocessing/preprocessing.component.ts | 252 ----------------- .../preprocessing/preprocessing.models.ts | 267 ------------------ .../task-schedule-dialog.component.html | 99 ------- .../task-schedule-dialog.component.ts | 125 -------- .../background-job-tasks.resolver.ts | 9 + .../background-jobs-docker-health.resolver.ts | 9 + .../shared/ui/app-menu/app-menu.component.ts | 4 +- 19 files changed, 833 insertions(+), 1109 deletions(-) create mode 100644 webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html create mode 100644 webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.scss create mode 100644 webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts create mode 100644 webapp/src/app/modules/jobs/jobs.component.html rename webapp/src/app/modules/{preprocessing/preprocessing.component.scss => jobs/jobs.component.scss} (58%) create mode 100644 webapp/src/app/modules/jobs/jobs.component.ts create mode 100644 webapp/src/app/modules/jobs/jobs.utils.ts create mode 100644 webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.html rename webapp/src/app/modules/{preprocessing => jobs}/task-schedule-dialog/task-schedule-dialog.component.scss (60%) create mode 100644 webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.ts delete mode 100644 webapp/src/app/modules/preprocessing/preprocessing.component.html delete mode 100644 webapp/src/app/modules/preprocessing/preprocessing.component.ts delete mode 100644 webapp/src/app/modules/preprocessing/preprocessing.models.ts delete mode 100644 webapp/src/app/modules/preprocessing/task-schedule-dialog/task-schedule-dialog.component.html delete mode 100644 webapp/src/app/modules/preprocessing/task-schedule-dialog/task-schedule-dialog.component.ts create mode 100644 webapp/src/app/resolvers/background-job-tasks.resolver.ts create mode 100644 webapp/src/app/resolvers/background-jobs-docker-health.resolver.ts diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 8715eef1..a421ab0e 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -22,6 +22,8 @@ import { accountResolver } from './resolvers/account.resolver'; import { accountsPageResolver } from './resolvers/accounts-page.resolver'; import { accountsOrganizationResolver } from './resolvers/accounts-organizations.resolver'; import { organizationsOrganizationsResolver } from './resolvers/organizations-organizations.resolver'; +import { backgroundJobTasksResolver } from './resolvers/background-job-tasks.resolver'; +import { backgroundJobsDockerHealthResolver } from './resolvers/background-jobs-docker-health.resolver'; import { KeywordsToPersonsResultsComponent } from './modules/keywords-search/search-results/persons-results/persons-results.component'; import { KeywordsToProjectsResultsComponent } from './modules/keywords-search/search-results/projects-results/projects-results.component'; import { KeywordsToPatentsResultsComponent } from './modules/keywords-search/search-results/patents-results/patents-results.component'; @@ -224,11 +226,15 @@ export const routes: Routes = [ runGuardsAndResolvers: 'always', }, { - path: 'preprocessing', + path: 'jobs', + canActivate: [superAdminGuard], loadComponent: () => - import('./modules/preprocessing/preprocessing.component').then( - (mod) => mod.PreprocessingComponent, - ), + import('./modules/jobs/jobs.component').then((mod) => mod.JobsComponent), + resolve: { + tasks: backgroundJobTasksResolver, + dockerHealth: backgroundJobsDockerHealthResolver, + }, + runGuardsAndResolvers: 'always', }, { diff --git a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html new file mode 100644 index 00000000..01122184 --- /dev/null +++ b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html @@ -0,0 +1,46 @@ +

Logs · {{ data.task.name }}

+ + + @if (runId == null) { +

Für diesen Job liegt noch kein Lauf vor.

+ } @else { +
+
+ Letzter Lauf #{{ runId }} + @if (runStatus()) { + + {{ statusMeta(runStatus()!).icon }} + {{ statusMeta(runStatus()!).label }} + + } +
+ +
+ +
+ @if (loading()) { +
+ + Logs werden geladen … +
+ } @else { +
{{ logs() }}
+ } +
+ } +
+ + + + diff --git a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.scss b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.scss new file mode 100644 index 00000000..bf9a2c60 --- /dev/null +++ b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.scss @@ -0,0 +1,96 @@ +.no-logs { + color: #64748b; + margin: 0; +} + +.logs-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + margin-bottom: 12px; +} + +.run-meta { + display: flex; + align-items: center; + gap: 12px; + font-size: 13px; + color: #64748b; +} + +.task-status { + display: inline-flex; + align-items: center; + gap: 4px; + font-weight: 600; + + mat-icon { + font-size: 18px; + height: 18px; + width: 18px; + } + + &--success { + color: #166534; + } + + &--failed { + color: #991b1b; + } + + &--running { + color: #92400e; + } + + &--stopped { + color: #64748b; + } + + &--idle { + color: #64748b; + } +} + +.logs-panel { + background: #0f172a; + border-radius: 6px; + padding: 12px 14px; + min-width: 520px; + max-width: 80vw; + min-height: 120px; + max-height: 55vh; + overflow: auto; + + pre { + margin: 0; + color: #e2e8f0; + font-family: 'Roboto Mono', ui-monospace, monospace; + font-size: 12px; + white-space: pre-wrap; + word-break: break-word; + } + + .logs-loading { + color: #cbd5e1; + } +} + +.logs-loading { + display: flex; + align-items: center; + gap: 10px; + color: #64748b; + font-size: 13px; +} + +@media (max-width: 640px) { + .logs-header { + flex-direction: column; + align-items: stretch; + } + + .logs-panel { + min-width: 0; + } +} diff --git a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts new file mode 100644 index 00000000..62cf0903 --- /dev/null +++ b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts @@ -0,0 +1,69 @@ +import { CommonModule } from '@angular/common'; +import { Component, OnInit, inject, signal } from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; +import { + MAT_DIALOG_DATA, + MatDialogModule, + MatDialogRef, +} from '@angular/material/dialog'; +import { MatIconModule } from '@angular/material/icon'; +import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; +import { BackgroundJobsService, BackgroundJobTask } from '../../../api'; +import { statusMeta } from '../jobs.utils'; + +export interface JobLogsDialogData { + task: BackgroundJobTask; +} + +@Component({ + selector: 'app-job-logs-dialog', + imports: [ + CommonModule, + MatButtonModule, + MatDialogModule, + MatIconModule, + MatProgressSpinnerModule, + ], + templateUrl: './job-logs-dialog.component.html', + styleUrl: './job-logs-dialog.component.scss', + standalone: true, +}) +export class JobLogsDialogComponent implements OnInit { + private readonly dialogRef = inject(MatDialogRef); + private readonly backgroundJobsService = inject(BackgroundJobsService); + protected readonly data = inject(MAT_DIALOG_DATA); + + protected readonly statusMeta = statusMeta; + protected readonly runId = this.data.task.last_run?.id ?? null; + + protected readonly loading = signal(false); + protected readonly logs = signal(''); + protected readonly runStatus = signal( + this.data.task.last_run?.status ?? null, + ); + + ngOnInit(): void { + this.loadLogs(); + } + + protected loadLogs(): void { + if (this.runId == null) return; + + this.loading.set(true); + this.backgroundJobsService.getBackgroundJobRunLogs(this.runId).subscribe({ + next: (result) => { + this.logs.set(result.logs || 'Keine Logs vorhanden.'); + this.runStatus.set(result.status); + this.loading.set(false); + }, + error: () => { + this.logs.set('Logs konnten nicht geladen werden.'); + this.loading.set(false); + }, + }); + } + + protected close(): void { + this.dialogRef.close(); + } +} diff --git a/webapp/src/app/modules/jobs/jobs.component.html b/webapp/src/app/modules/jobs/jobs.component.html new file mode 100644 index 00000000..c0056af5 --- /dev/null +++ b/webapp/src/app/modules/jobs/jobs.component.html @@ -0,0 +1,136 @@ +
+ + + + +
+ + +
+ Docker-Daemon +
+ {{ dockerHealth()?.reachable ? 'Erreichbar' : 'Nicht erreichbar' }} + @if (dockerHealth()?.detail) { + · {{ dockerHealth()?.detail }} + } +
+
+
+ +
+
+ + + +
+ +
+ +
+
+
+ + +
+ {{ row.name }} + {{ row.description }} + {{ row.target_index }} +
+
+ + +
+ {{ formatScheduleCron(row.schedule) }} + @if (row.next_run_at) { + Nächster Lauf: {{ row.next_run_at | date: 'dd.MM.yyyy HH:mm' }} + } + + {{ row.enabled ? 'Aktiv' : 'Inaktiv' }} + +
+
+ + + + @if (row.status === 'running') { + + } @else { + {{ statusMeta(row.status).icon }} + } + {{ statusMeta(row.status).label }} + + + + + @if (row.last_run) { +
+ {{ row.last_run.started_at | date: 'dd.MM.yyyy HH:mm' }} + @if (row.last_run.exit_code != null) { + Exit-Code {{ row.last_run.exit_code }} + } +
+ } @else { + Noch nicht ausgeführt + } +
+ + +
+ + + +
+
diff --git a/webapp/src/app/modules/preprocessing/preprocessing.component.scss b/webapp/src/app/modules/jobs/jobs.component.scss similarity index 58% rename from webapp/src/app/modules/preprocessing/preprocessing.component.scss rename to webapp/src/app/modules/jobs/jobs.component.scss index ccfa50d4..547f1b1d 100644 --- a/webapp/src/app/modules/preprocessing/preprocessing.component.scss +++ b/webapp/src/app/modules/jobs/jobs.component.scss @@ -1,4 +1,4 @@ -.preprocessing-page { +.jobs-page { display: flex; flex-direction: column; gap: 20px; @@ -32,21 +32,20 @@ mat-paginator { background-color: var(--sg-background); } -.container-card-content { +.docker-health-content { display: flex; align-items: center; justify-content: space-between; gap: 16px; - flex-wrap: wrap; } -.container-info { +.docker-health-info { display: flex; align-items: flex-start; gap: 12px; } -.container-state-dot { +.docker-state-dot { margin-top: 6px; width: 10px; height: 10px; @@ -54,59 +53,28 @@ mat-paginator { background: #94a3b8; flex-shrink: 0; - &--running { + &--ok { background: #16a34a; } - &--stopped { + &--error { background: #dc2626; } - - &--restarting { - background: #ca8a04; - } } -.container-meta { - display: flex; - flex-direction: column; - gap: 2px; +.docker-health-detail { font-size: 12px; color: #64748b; } -.container-digest { - font-family: 'Roboto Mono', ui-monospace, monospace; - color: #8a95b3; -} - -.update-badge { - display: inline-flex; - align-items: center; - gap: 4px; - margin-top: 4px; - width: fit-content; - padding: 2px 8px; - border-radius: 999px; - background: #eef2ff; - color: #2259a8; - font-weight: 600; - - mat-icon { - font-size: 16px; - height: 16px; - width: 16px; - } -} - -.container-actions { +.table-toolbar { display: flex; - gap: 8px; - flex-wrap: wrap; + justify-content: flex-end; + margin-bottom: 12px; } :host ::ng-deep .mat-mdc-row { - height: 116px; + height: 96px; } :host ::ng-deep .mat-mdc-row .mat-mdc-cell { @@ -139,60 +107,27 @@ mat-paginator { .task-schedule-cell { display: flex; flex-direction: column; - gap: 6px; + gap: 4px; } -.schedule-toggle { - display: inline-flex; - align-items: center; - gap: 8px; - padding: 0; - border: none; - background: none; - cursor: pointer; - font: inherit; -} - -.schedule-toggle__track { - position: relative; - flex: 0 0 auto; - width: 36px; - height: 20px; - border-radius: 999px; - background: #cbd5e1; - transition: background 0.15s ease; -} - -.schedule-toggle__thumb { - position: absolute; - top: 2px; - left: 2px; - width: 16px; - height: 16px; - border-radius: 50%; - background: #ffffff; - box-shadow: 0 1px 2px rgba(16, 26, 61, 0.3); - transition: transform 0.15s ease; -} - -.schedule-toggle--on .schedule-toggle__track { - background: #2259a8; -} - -.schedule-toggle--on .schedule-toggle__thumb { - transform: translateX(16px); -} - -.schedule-toggle__label { +.next-run { font-size: 12px; color: #64748b; - white-space: nowrap; } -.schedule-toggle:focus-visible { - outline: 2px solid #2259a8; - outline-offset: 2px; - border-radius: 4px; +.enabled-badge { + width: fit-content; + font-size: 11px; + font-weight: 700; + padding: 1px 8px; + border-radius: 999px; + background: #e2e8f0; + color: #64748b; + + &--on { + background: #dcfce7; + color: #166534; + } } .task-status { @@ -220,6 +155,10 @@ mat-paginator { color: #92400e; } + &--stopped { + color: #64748b; + } + &--idle { color: #64748b; } @@ -248,7 +187,7 @@ mat-paginator { } @media (max-width: 640px) { - .preprocessing-page { + .jobs-page { padding: 16px; } @@ -257,7 +196,7 @@ mat-paginator { flex-direction: column; } - .container-card-content { + .docker-health-content { flex-direction: column; align-items: flex-start; } diff --git a/webapp/src/app/modules/jobs/jobs.component.ts b/webapp/src/app/modules/jobs/jobs.component.ts new file mode 100644 index 00000000..b5085eed --- /dev/null +++ b/webapp/src/app/modules/jobs/jobs.component.ts @@ -0,0 +1,248 @@ +import { CommonModule } from '@angular/common'; +import { + Component, + DestroyRef, + OnInit, + TemplateRef, + inject, + input, + signal, + viewChild, +} from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { MatButtonModule } from '@angular/material/button'; +import { MatCardModule } from '@angular/material/card'; +import { MatDialog, MatDialogModule } from '@angular/material/dialog'; +import { MatIconModule } from '@angular/material/icon'; +import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; +import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { interval, switchMap, takeWhile, take } from 'rxjs'; +import { + BackgroundJobsService, + BackgroundJobTask, + DockerHealth, +} from '../../api'; +import { + DataTableComponent, + GenericColumn, +} from '../../shared/ui/data-table/data-table.component'; +import { formatScheduleCron, statusMeta } from './jobs.utils'; +import { + TaskScheduleDialogComponent, + TaskScheduleDialogData, + TaskScheduleDialogResult, +} from './task-schedule-dialog/task-schedule-dialog.component'; +import { + JobLogsDialogComponent, + JobLogsDialogData, +} from './job-logs-dialog/job-logs-dialog.component'; + +@Component({ + selector: 'app-jobs', + imports: [ + CommonModule, + MatButtonModule, + MatCardModule, + MatDialogModule, + MatIconModule, + MatProgressSpinnerModule, + MatSnackBarModule, + MatTooltipModule, + DataTableComponent, + ], + templateUrl: './jobs.component.html', + styleUrl: './jobs.component.scss', + standalone: true, +}) +export class JobsComponent implements OnInit { + private readonly dialog = inject(MatDialog); + private readonly snackBar = inject(MatSnackBar); + private readonly backgroundJobsService = inject(BackgroundJobsService); + private readonly destroyRef = inject(DestroyRef); + + tasksInput = input.required({ alias: 'tasks' }); + dockerHealthInput = input.required({ alias: 'dockerHealth' }); + + protected readonly tasks = signal([]); + protected readonly dockerHealth = signal(null); + protected readonly dockerHealthLoading = signal(false); + + protected readonly statusMeta = statusMeta; + protected readonly formatScheduleCron = formatScheduleCron; + + protected taskColumns: GenericColumn[] = []; + + private readonly taskNameTmp = + viewChild.required>('taskNameTmp'); + private readonly taskScheduleTmp = + viewChild.required>('taskScheduleTmp'); + private readonly taskStatusTmp = + viewChild.required>('taskStatusTmp'); + private readonly taskLastRunTmp = + viewChild.required>('taskLastRunTmp'); + private readonly taskActionsTmp = + viewChild.required>('taskActionsTmp'); + + ngOnInit(): void { + this.tasks.set(this.tasksInput()); + this.dockerHealth.set(this.dockerHealthInput()); + + this.taskColumns = [ + { + id: 'name', + header: 'Task', + type: 'display', + cellTemplate: this.taskNameTmp(), + }, + { + id: 'schedule', + header: 'Zeitplan', + type: 'display', + cellTemplate: this.taskScheduleTmp(), + }, + { + id: 'status', + header: 'Status', + type: 'display', + cellTemplate: this.taskStatusTmp(), + }, + { + id: 'lastRun', + header: 'Letzter Lauf', + type: 'display', + cellTemplate: this.taskLastRunTmp(), + }, + { + id: 'actions', + header: 'Aktionen', + type: 'display', + cellTemplate: this.taskActionsTmp(), + }, + ]; + + if (this.tasks().some((task) => task.status === 'running')) { + this.pollWhileRunning(); + } + } + + protected refreshTasks(): void { + this.backgroundJobsService.getBackgroundJobTasks().subscribe({ + next: (tasks) => this.tasks.set(tasks), + error: () => this.showError('Tasks konnten nicht aktualisiert werden.'), + }); + } + + protected refreshDockerHealth(): void { + this.dockerHealthLoading.set(true); + this.backgroundJobsService.getBackgroundJobsDockerHealth().subscribe({ + next: (health) => { + this.dockerHealth.set(health); + this.dockerHealthLoading.set(false); + }, + error: () => { + this.dockerHealthLoading.set(false); + this.showError('Docker-Status konnte nicht abgerufen werden.'); + }, + }); + } + + protected runNow(task: BackgroundJobTask): void { + if (task.status === 'running') return; + + this.backgroundJobsService.runBackgroundJobTask(task.id).subscribe({ + next: (run) => { + this.updateTask(task.id, (current) => ({ + ...current, + status: 'running', + last_run: run, + })); + this.snackBar.open(`„${task.name}“ wurde gestartet.`, 'OK', { + duration: 3000, + }); + this.pollWhileRunning(); + }, + error: (error) => + this.showError( + error.status === 409 + ? `„${task.name}“ läuft bereits.` + : `„${task.name}“ konnte nicht gestartet werden.`, + ), + }); + } + + protected openLogsDialog(task: BackgroundJobTask): void { + if (task.last_run?.id == null) return; + + this.dialog.open( + JobLogsDialogComponent, + { + width: '640px', + maxWidth: 'calc(100vw - 32px)', + data: { task }, + }, + ); + } + + protected openScheduleDialog(task: BackgroundJobTask): void { + const dialogRef = this.dialog.open< + TaskScheduleDialogComponent, + TaskScheduleDialogData, + TaskScheduleDialogResult | undefined + >(TaskScheduleDialogComponent, { + width: '520px', + maxWidth: 'calc(100vw - 32px)', + data: { task }, + }); + + dialogRef.afterClosed().subscribe((result) => { + if (!result) return; + + this.backgroundJobsService + .updateBackgroundJobTask(result.taskId, { + enabled: result.enabled, + schedule: result.schedule, + }) + .subscribe({ + next: (updatedTask) => { + this.updateTask(result.taskId, () => updatedTask); + this.snackBar.open('Zeitplan wurde gespeichert.', 'OK', { + duration: 3000, + }); + }, + error: (error) => + this.showError( + error?.error?.detail ?? + 'Zeitplan konnte nicht gespeichert werden.', + ), + }); + }); + } + + private pollWhileRunning(): void { + interval(5000) + .pipe( + switchMap(() => this.backgroundJobsService.getBackgroundJobTasks()), + take(24), + takeWhile( + (tasks) => tasks.some((task) => task.status === 'running'), + true, + ), + takeUntilDestroyed(this.destroyRef), + ) + .subscribe((tasks) => this.tasks.set(tasks)); + } + + private updateTask( + id: number, + updater: (task: BackgroundJobTask) => BackgroundJobTask, + ): void { + this.tasks.update((current) => + current.map((task) => (task.id === id ? updater(task) : task)), + ); + } + + private showError(message: string): void { + this.snackBar.open(message, 'OK', { duration: 5000 }); + } +} diff --git a/webapp/src/app/modules/jobs/jobs.utils.ts b/webapp/src/app/modules/jobs/jobs.utils.ts new file mode 100644 index 00000000..599b95ab --- /dev/null +++ b/webapp/src/app/modules/jobs/jobs.utils.ts @@ -0,0 +1,48 @@ +import { JobRun } from '../../api'; + +export interface StatusMeta { + label: string; + icon: string; + cssClass: string; +} + +const STATUS_META: Record = { + running: { label: 'Läuft', icon: 'sync', cssClass: 'task-status--running' }, + succeeded: { + label: 'Erfolgreich', + icon: 'check_circle', + cssClass: 'task-status--success', + }, + failed: { + label: 'Fehlgeschlagen', + icon: 'error', + cssClass: 'task-status--failed', + }, + stopped: { + label: 'Gestoppt', + icon: 'stop_circle', + cssClass: 'task-status--stopped', + }, + idle: { label: 'Bereit', icon: 'schedule', cssClass: 'task-status--idle' }, +}; + +export function statusMeta(status: string): StatusMeta { + return STATUS_META[status] ?? STATUS_META['idle']; +} + +export function formatScheduleCron(schedule: string | null): string { + return schedule ? `Cron: ${schedule}` : 'Nur manuell'; +} + +export function formatRunDuration(run: JobRun): string | null { + if (!run.started_at || !run.finished_at) return null; + const seconds = Math.max( + 0, + Math.round( + (new Date(run.finished_at).getTime() - + new Date(run.started_at).getTime()) / + 1000, + ), + ); + return `${seconds} s`; +} diff --git a/webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.html b/webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.html new file mode 100644 index 00000000..e77b2b95 --- /dev/null +++ b/webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.html @@ -0,0 +1,48 @@ +

{{ data.task.name }}

+ + +

{{ data.task.description }}

+ +
+ + + + Cron-Ausdruck (UTC) + + Leer lassen für nur manuelle Ausführung. + @if (form.controls.cronExpression.hasError('invalidCron')) { + Ungültiger Cron-Ausdruck, z. B. „0 3 * * *“. + } + + + @if (data.task.next_run_at) { +

+ Nächster geplanter Lauf: + {{ data.task.next_run_at | date: 'dd.MM.yyyy HH:mm' }} Uhr +

+ } +
+
+ + + + + diff --git a/webapp/src/app/modules/preprocessing/task-schedule-dialog/task-schedule-dialog.component.scss b/webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.scss similarity index 60% rename from webapp/src/app/modules/preprocessing/task-schedule-dialog/task-schedule-dialog.component.scss rename to webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.scss index 59f20223..7fa6ba05 100644 --- a/webapp/src/app/modules/preprocessing/task-schedule-dialog/task-schedule-dialog.component.scss +++ b/webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.scss @@ -63,74 +63,12 @@ border-radius: 4px; } -.history-section { - margin-top: 24px; - border-top: 1px solid #e2e8f0; - padding-top: 16px; - - h3 { - margin: 0 0 8px; - font-size: 14px; - } -} - -.no-history { - color: #64748b; - font-size: 13px; +.next-run-hint { margin: 0; -} - -.history-list { - list-style: none; - margin: 0; - padding: 0; - display: flex; - flex-direction: column; - gap: 10px; -} - -.history-item { - display: flex; - align-items: flex-start; - gap: 10px; -} - -.history-icon { - font-size: 20px; - height: 20px; - width: 20px; - margin-top: 2px; - - &--success { - color: #16a34a; - } - - &--failed { - color: #dc2626; - } -} - -.history-item-content { - display: flex; - flex-direction: column; - flex: 1; -} - -.history-date { font-size: 12px; color: #64748b; } -.history-message { - font-size: 13px; -} - -.history-duration { - font-size: 12px; - color: #64748b; - white-space: nowrap; -} - @media (max-width: 640px) { .schedule-form { min-width: 0; diff --git a/webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.ts b/webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.ts new file mode 100644 index 00000000..d8526b3a --- /dev/null +++ b/webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.ts @@ -0,0 +1,79 @@ +import { CommonModule } from '@angular/common'; +import { Component, inject } from '@angular/core'; +import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { + MAT_DIALOG_DATA, + MatDialogModule, + MatDialogRef, +} from '@angular/material/dialog'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatIconModule } from '@angular/material/icon'; +import { MatInputModule } from '@angular/material/input'; +import { BackgroundJobTask } from '../../../api'; + +export interface TaskScheduleDialogData { + task: BackgroundJobTask; +} + +export interface TaskScheduleDialogResult { + taskId: number; + enabled: boolean; + schedule: string | null; +} + +const CRON_PATTERN = /^\S+\s+\S+\s+\S+\s+\S+\s+\S+$/; + +@Component({ + selector: 'app-task-schedule-dialog', + imports: [ + CommonModule, + ReactiveFormsModule, + MatButtonModule, + MatDialogModule, + MatFormFieldModule, + MatIconModule, + MatInputModule, + ], + templateUrl: './task-schedule-dialog.component.html', + styleUrl: './task-schedule-dialog.component.scss', + standalone: true, +}) +export class TaskScheduleDialogComponent { + private readonly dialogRef = + inject< + MatDialogRef< + TaskScheduleDialogComponent, + TaskScheduleDialogResult | undefined + > + >(MatDialogRef); + protected readonly data = inject(MAT_DIALOG_DATA); + + protected readonly form = new FormGroup({ + enabled: new FormControl(this.data.task.enabled, { nonNullable: true }), + cronExpression: new FormControl(this.data.task.schedule ?? '', { + nonNullable: true, + }), + }); + + protected submit(): void { + const value = this.form.getRawValue(); + const cron = value.cronExpression.trim(); + + if (cron && !CRON_PATTERN.test(cron)) { + this.form.controls.cronExpression.setErrors({ invalidCron: true }); + this.form.controls.cronExpression.markAsTouched(); + return; + } + + this.dialogRef.close({ + taskId: this.data.task.id, + enabled: value.enabled, + schedule: cron || null, + }); + } + + protected close(): void { + this.dialogRef.close(); + } +} diff --git a/webapp/src/app/modules/preprocessing/preprocessing.component.html b/webapp/src/app/modules/preprocessing/preprocessing.component.html deleted file mode 100644 index e112c71a..00000000 --- a/webapp/src/app/modules/preprocessing/preprocessing.component.html +++ /dev/null @@ -1,204 +0,0 @@ -
- - - - -
- - -
- {{ containerStatus().name }} -
- {{ containerStatus().image }} - {{ - containerStatus().imageDigest - }} - @switch (containerStatus().state) { - @case ('running') { - Läuft{{ - containerStatus().uptime - ? ' · seit ' + containerStatus().uptime - : '' - }} - } - @case ('stopped') { - Gestoppt - } - @case ('restarting') { - Wird neu gestartet … - } - } - @if (containerStatus().updateAvailable) { - - upgrade - Neue Version verfügbar - - } -
-
-
- -
- @if (containerStatus().updateAvailable) { - - } - @if (containerStatus().state === 'running') { - - - } @else { - - } -
-
-
- - - - - - -
- - -
- {{ row.name }} - {{ row.description }} - {{ row.targetIndex }} -
-
- - -
- {{ formatSchedule(row.schedule) }} - -
-
- - - @switch (row.status) { - @case ('running') { - - - Läuft - - } - @case ('success') { - - check_circle - Erfolgreich - - } - @case ('failed') { - - error - Fehlgeschlagen - - } - @default { - - schedule - Bereit - - } - } - - - - @if (row.lastRun) { -
- {{ row.lastRun.startedAt | date: 'dd.MM.yyyy HH:mm' }} - {{ row.lastRun.message }} -
- } @else { - Noch nicht ausgeführt - } -
- - -
- - -
-
diff --git a/webapp/src/app/modules/preprocessing/preprocessing.component.ts b/webapp/src/app/modules/preprocessing/preprocessing.component.ts deleted file mode 100644 index f5208963..00000000 --- a/webapp/src/app/modules/preprocessing/preprocessing.component.ts +++ /dev/null @@ -1,252 +0,0 @@ -import { CommonModule } from '@angular/common'; -import { - Component, - OnInit, - TemplateRef, - inject, - signal, - viewChild, -} from '@angular/core'; -import { MatButtonModule } from '@angular/material/button'; -import { MatCardModule } from '@angular/material/card'; -import { MatDialog, MatDialogModule } from '@angular/material/dialog'; -import { MatIconModule } from '@angular/material/icon'; -import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; -import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; -import { MatTooltipModule } from '@angular/material/tooltip'; -import { - DataTableComponent, - GenericColumn, -} from '../../shared/ui/data-table/data-table.component'; -import { - MOCK_CONTAINER_STATUS, - MOCK_TASKS, - PreprocessingContainerStatus, - PreprocessingTask, - formatSchedule, -} from './preprocessing.models'; -import { - TaskScheduleDialogComponent, - TaskScheduleDialogData, - TaskScheduleDialogResult, -} from './task-schedule-dialog/task-schedule-dialog.component'; - -@Component({ - selector: 'app-preprocessing', - imports: [ - CommonModule, - MatButtonModule, - MatCardModule, - MatDialogModule, - MatIconModule, - MatProgressSpinnerModule, - MatSnackBarModule, - MatTooltipModule, - DataTableComponent, - ], - templateUrl: './preprocessing.component.html', - styleUrl: './preprocessing.component.scss', - standalone: true, -}) -export class PreprocessingComponent implements OnInit { - private readonly dialog = inject(MatDialog); - private readonly snackBar = inject(MatSnackBar); - - protected readonly containerStatus = signal( - MOCK_CONTAINER_STATUS, - ); - protected readonly containerBusy = signal(false); - - protected readonly tasks = signal(MOCK_TASKS); - protected readonly formatSchedule = formatSchedule; - - protected taskColumns: GenericColumn[] = []; - - private readonly taskNameTmp = - viewChild.required>('taskNameTmp'); - private readonly taskScheduleTmp = - viewChild.required>('taskScheduleTmp'); - private readonly taskStatusTmp = - viewChild.required>('taskStatusTmp'); - private readonly taskLastRunTmp = - viewChild.required>('taskLastRunTmp'); - private readonly taskActionsTmp = - viewChild.required>('taskActionsTmp'); - - ngOnInit(): void { - this.taskColumns = [ - { - id: 'name', - header: 'Task', - type: 'display', - cellTemplate: this.taskNameTmp(), - }, - { - id: 'schedule', - header: 'Zeitplan', - type: 'display', - cellTemplate: this.taskScheduleTmp(), - }, - { - id: 'status', - header: 'Status', - type: 'display', - cellTemplate: this.taskStatusTmp(), - }, - { - id: 'lastRun', - header: 'Letzter Lauf', - type: 'display', - cellTemplate: this.taskLastRunTmp(), - }, - { - id: 'actions', - header: 'Aktionen', - type: 'display', - cellTemplate: this.taskActionsTmp(), - }, - ]; - } - - protected runNow(task: PreprocessingTask): void { - if (task.status === 'running') return; - - this.updateTask(task.id, (current) => ({ ...current, status: 'running' })); - this.snackBar.open(`„${task.name}“ wurde gestartet.`, 'OK', { - duration: 3000, - }); - - setTimeout(() => { - const startedAt = new Date().toISOString(); - const run = { - startedAt, - durationSeconds: Math.round(60 + Math.random() * 600), - status: 'success' as const, - message: 'Manueller Lauf erfolgreich abgeschlossen.', - }; - - this.updateTask(task.id, (current) => ({ - ...current, - status: 'success', - lastRun: run, - history: [run, ...current.history], - })); - - this.snackBar.open(`„${task.name}“ wurde abgeschlossen.`, 'OK', { - duration: 3000, - }); - }, 1400); - } - - protected toggleEnabled(task: PreprocessingTask, enabled: boolean): void { - this.updateTask(task.id, (current) => ({ ...current, enabled })); - } - - protected openScheduleDialog(task: PreprocessingTask): void { - const dialogRef = this.dialog.open< - TaskScheduleDialogComponent, - TaskScheduleDialogData, - TaskScheduleDialogResult | undefined - >(TaskScheduleDialogComponent, { - width: '480px', - maxWidth: 'calc(100vw - 32px)', - data: { task }, - }); - - dialogRef.afterClosed().subscribe((result) => { - if (!result) return; - - this.updateTask(result.taskId, (current) => ({ - ...current, - enabled: result.enabled, - schedule: result.schedule, - })); - this.snackBar.open('Zeitplan wurde gespeichert.', 'OK', { - duration: 3000, - }); - }); - } - - protected startContainer(): void { - this.setContainerState('restarting'); - setTimeout(() => { - this.containerStatus.update((current) => ({ - ...current, - state: 'running', - uptime: '0 Std. 0 Min.', - lastStartedAt: new Date().toISOString(), - })); - this.containerBusy.set(false); - this.snackBar.open('Preprocessing-Container wurde gestartet.', 'OK', { - duration: 3000, - }); - }, 1200); - } - - protected stopContainer(): void { - this.setContainerState('restarting'); - setTimeout(() => { - this.containerStatus.update((current) => ({ - ...current, - state: 'stopped', - uptime: undefined, - })); - this.containerBusy.set(false); - this.snackBar.open('Preprocessing-Container wurde gestoppt.', 'OK', { - duration: 3000, - }); - }, 1200); - } - - protected restartContainer(): void { - this.setContainerState('restarting'); - setTimeout(() => { - this.containerStatus.update((current) => ({ - ...current, - state: 'running', - uptime: '0 Std. 0 Min.', - lastStartedAt: new Date().toISOString(), - })); - this.containerBusy.set(false); - this.snackBar.open('Preprocessing-Container wurde neu gestartet.', 'OK', { - duration: 3000, - }); - }, 1200); - } - - protected updateImage(): void { - this.setContainerState('restarting'); - setTimeout(() => { - this.containerStatus.update((current) => ({ - ...current, - state: 'running', - imageDigest: 'sha256:9f2b1c7ae5d3', - updateAvailable: false, - uptime: '0 Std. 0 Min.', - lastStartedAt: new Date().toISOString(), - })); - this.containerBusy.set(false); - this.snackBar.open( - 'Neues Image aus der Registry geladen und Container neu erstellt.', - 'OK', - { duration: 3000 }, - ); - }, 1200); - } - - private setContainerState( - state: PreprocessingContainerStatus['state'], - ): void { - this.containerBusy.set(true); - this.containerStatus.update((current) => ({ ...current, state })); - } - - private updateTask( - id: string, - updater: (task: PreprocessingTask) => PreprocessingTask, - ): void { - this.tasks.update((current) => - current.map((task) => (task.id === id ? updater(task) : task)), - ); - } -} diff --git a/webapp/src/app/modules/preprocessing/preprocessing.models.ts b/webapp/src/app/modules/preprocessing/preprocessing.models.ts deleted file mode 100644 index e3edc1b4..00000000 --- a/webapp/src/app/modules/preprocessing/preprocessing.models.ts +++ /dev/null @@ -1,267 +0,0 @@ -export type PreprocessingRunStatus = 'success' | 'failed'; -export type PreprocessingTaskStatus = - 'idle' | 'running' | PreprocessingRunStatus; -export type ScheduleFrequency = - 'manual' | 'hourly' | 'daily' | 'weekly' | 'cron'; - -export const WEEKDAYS = [ - 'Montag', - 'Dienstag', - 'Mittwoch', - 'Donnerstag', - 'Freitag', - 'Samstag', - 'Sonntag', -] as const; - -export interface PreprocessingRun { - startedAt: string; - durationSeconds: number; - status: PreprocessingRunStatus; - message: string; -} - -export interface TaskSchedule { - frequency: ScheduleFrequency; - time?: string; - weekday?: number; - cronExpression?: string; -} - -export interface PreprocessingTask { - id: string; - name: string; - description: string; - targetIndex: string; - status: PreprocessingTaskStatus; - enabled: boolean; - schedule: TaskSchedule; - lastRun?: PreprocessingRun; - history: PreprocessingRun[]; -} - -export interface PreprocessingContainerStatus { - name: string; - image: string; - imageDigest: string; - updateAvailable: boolean; - state: 'running' | 'stopped' | 'restarting'; - uptime?: string; - lastStartedAt?: string; -} - -export function formatSchedule(schedule: TaskSchedule): string { - switch (schedule.frequency) { - case 'manual': - return 'Nur manuell'; - case 'hourly': - return 'Stündlich'; - case 'daily': - return `Täglich${schedule.time ? ` um ${schedule.time} Uhr` : ''}`; - case 'weekly': - return `Wöchentlich${ - schedule.weekday != null ? ` am ${WEEKDAYS[schedule.weekday]}` : '' - }${schedule.time ? `, ${schedule.time} Uhr` : ''}`; - case 'cron': - return schedule.cronExpression - ? `Cron: ${schedule.cronExpression}` - : 'Cron-Ausdruck fehlt'; - } -} - -export const MOCK_CONTAINER_STATUS: PreprocessingContainerStatus = { - name: 'inse-preprocessing', - image: 'docker.nes.uni-due.de/inse/preprocessing:1.0.0', - imageDigest: 'sha256:e40946432f95', - updateAvailable: true, - state: 'running', - uptime: '5 Std. 12 Min.', - lastStartedAt: '2026-07-08T02:58:00', -}; - -export const MOCK_TASKS: PreprocessingTask[] = [ - { - id: 'persons', - name: 'Personen-Index', - description: - 'Aktualisiert Personendaten aus OpenAlex- und UDE-Quellen für die Personensuche.', - targetIndex: 'openalex-authors', - status: 'success', - enabled: true, - schedule: { frequency: 'daily', time: '03:00' }, - lastRun: { - startedAt: '2026-07-08T03:00:00', - durationSeconds: 842, - status: 'success', - message: '18.432 Personen aktualisiert.', - }, - history: [ - { - startedAt: '2026-07-08T03:00:00', - durationSeconds: 842, - status: 'success', - message: '18.432 Personen aktualisiert.', - }, - { - startedAt: '2026-07-07T03:00:00', - durationSeconds: 811, - status: 'success', - message: '18.401 Personen aktualisiert.', - }, - { - startedAt: '2026-07-06T03:00:00', - durationSeconds: 796, - status: 'failed', - message: 'Zeitüberschreitung bei OpenAlex-Anfrage.', - }, - ], - }, - { - id: 'institutions', - name: 'Institutionen-Index', - description: - 'Baut den Suchindex für Institutionen und deren Kennzahlen neu auf.', - targetIndex: 'openalex-institutions', - status: 'success', - enabled: true, - schedule: { frequency: 'weekly', weekday: 6, time: '02:00' }, - lastRun: { - startedAt: '2026-07-05T02:00:00', - durationSeconds: 356, - status: 'success', - message: '612 Institutionen aktualisiert.', - }, - history: [ - { - startedAt: '2026-07-05T02:00:00', - durationSeconds: 356, - status: 'success', - message: '612 Institutionen aktualisiert.', - }, - { - startedAt: '2026-06-28T02:00:00', - durationSeconds: 349, - status: 'success', - message: '609 Institutionen aktualisiert.', - }, - ], - }, - { - id: 'projects', - name: 'Projekte-Index', - description: - 'Importiert Förderprojekte aus DFG-, Bund- und EU-CORDIS-Quellen.', - targetIndex: 'projects_dfg_all, projects_bund_v1, cordis_eu_*_projects', - status: 'idle', - enabled: true, - schedule: { frequency: 'daily', time: '04:00' }, - lastRun: { - startedAt: '2026-07-08T04:00:00', - durationSeconds: 1204, - status: 'success', - message: '3.218 Projekte importiert, 44 aktualisiert.', - }, - history: [ - { - startedAt: '2026-07-08T04:00:00', - durationSeconds: 1204, - status: 'success', - message: '3.218 Projekte importiert, 44 aktualisiert.', - }, - ], - }, - { - id: 'patents', - name: 'Patente-Index', - description: - 'Verarbeitet EPO- und USPTO-Patentdaten und verknüpft Erfinder:innen mit Personen.', - targetIndex: 'epo_index_1.0, uspto_patents_3.0, org_patents', - status: 'failed', - enabled: true, - schedule: { frequency: 'weekly', weekday: 0, time: '01:30' }, - lastRun: { - startedAt: '2026-07-06T01:30:00', - durationSeconds: 233, - status: 'failed', - message: 'Verbindung zum USPTO-Endpunkt fehlgeschlagen.', - }, - history: [ - { - startedAt: '2026-07-06T01:30:00', - durationSeconds: 233, - status: 'failed', - message: 'Verbindung zum USPTO-Endpunkt fehlgeschlagen.', - }, - { - startedAt: '2026-06-29T01:30:00', - durationSeconds: 1988, - status: 'success', - message: '9.104 Patente verarbeitet.', - }, - ], - }, - { - id: 'works', - name: 'Publikationen-Index', - description: 'Aktualisiert Publikationsdaten und Autor:innen-Zuordnungen.', - targetIndex: 'openalex-works', - status: 'success', - enabled: true, - schedule: { frequency: 'daily', time: '03:30' }, - lastRun: { - startedAt: '2026-07-08T03:30:00', - durationSeconds: 1523, - status: 'success', - message: '52.011 Publikationen aktualisiert.', - }, - history: [ - { - startedAt: '2026-07-08T03:30:00', - durationSeconds: 1523, - status: 'success', - message: '52.011 Publikationen aktualisiert.', - }, - ], - }, - { - id: 'news', - name: 'News-Aufbereitung', - description: - 'Übernimmt Artikel aus dem „aktuell“-Index und fügt Relevanz, Personenzuordnungen und Schlagwörter hinzu.', - targetIndex: 'aktuell_postproc', - status: 'running', - enabled: true, - schedule: { frequency: 'hourly' }, - lastRun: { - startedAt: '2026-07-08T18:00:00', - durationSeconds: 96, - status: 'success', - message: '214 neue Artikel indiziert.', - }, - history: [ - { - startedAt: '2026-07-08T18:00:00', - durationSeconds: 96, - status: 'success', - message: '214 neue Artikel indiziert.', - }, - { - startedAt: '2026-07-08T17:00:00', - durationSeconds: 88, - status: 'success', - message: '187 neue Artikel indiziert.', - }, - ], - }, - { - id: 'topics', - name: 'Themen-Vektoren', - description: - 'Liest Themen aus „openalex-topics“, berechnet Embeddings und schreibt sie in den Vektor-Index „topicvectors“.', - targetIndex: 'topicvectors', - status: 'idle', - enabled: false, - schedule: { frequency: 'manual' }, - history: [], - }, -]; diff --git a/webapp/src/app/modules/preprocessing/task-schedule-dialog/task-schedule-dialog.component.html b/webapp/src/app/modules/preprocessing/task-schedule-dialog/task-schedule-dialog.component.html deleted file mode 100644 index 40d2ca2e..00000000 --- a/webapp/src/app/modules/preprocessing/task-schedule-dialog/task-schedule-dialog.component.html +++ /dev/null @@ -1,99 +0,0 @@ -

{{ data.task.name }}

- - -

{{ data.task.description }}

- -
- - - - Häufigkeit - - @for (option of frequencyOptions; track option.value) { - {{ option.label }} - } - - - - @if ( - form.controls.frequency.value === 'daily' || - form.controls.frequency.value === 'weekly' - ) { - - Uhrzeit - - - } - - @if (form.controls.frequency.value === 'weekly') { - - Wochentag - - @for (day of weekdays; track day; let i = $index) { - {{ day }} - } - - - } - - @if (form.controls.frequency.value === 'cron') { - - Cron-Ausdruck - - @if (form.controls.cronExpression.hasError('required')) { - Cron-Ausdruck ist erforderlich. - } - - } -
- -
-

Letzte Läufe

- @if (recentHistory.length === 0) { -

Für diesen Task liegt noch kein Lauf vor.

- } @else { -
    - @for (run of recentHistory; track run.startedAt) { -
  • - - {{ run.status === 'success' ? 'check_circle' : 'error' }} - -
    - {{ - run.startedAt | date: 'dd.MM.yyyy HH:mm' - }} - {{ run.message }} -
    - {{ run.durationSeconds }} s -
  • - } -
- } -
-
- - - - - diff --git a/webapp/src/app/modules/preprocessing/task-schedule-dialog/task-schedule-dialog.component.ts b/webapp/src/app/modules/preprocessing/task-schedule-dialog/task-schedule-dialog.component.ts deleted file mode 100644 index caebde91..00000000 --- a/webapp/src/app/modules/preprocessing/task-schedule-dialog/task-schedule-dialog.component.ts +++ /dev/null @@ -1,125 +0,0 @@ -import { CommonModule } from '@angular/common'; -import { Component, inject } from '@angular/core'; -import { - FormControl, - FormGroup, - ReactiveFormsModule, - Validators, -} from '@angular/forms'; -import { MatButtonModule } from '@angular/material/button'; -import { - MAT_DIALOG_DATA, - MatDialogModule, - MatDialogRef, -} from '@angular/material/dialog'; -import { MatFormFieldModule } from '@angular/material/form-field'; -import { MatIconModule } from '@angular/material/icon'; -import { MatInputModule } from '@angular/material/input'; -import { MatSelectModule } from '@angular/material/select'; -import { - PreprocessingTask, - ScheduleFrequency, - TaskSchedule, - WEEKDAYS, -} from '../preprocessing.models'; - -export interface TaskScheduleDialogData { - task: PreprocessingTask; -} - -export interface TaskScheduleDialogResult { - taskId: string; - enabled: boolean; - schedule: TaskSchedule; -} - -@Component({ - selector: 'app-task-schedule-dialog', - imports: [ - CommonModule, - ReactiveFormsModule, - MatButtonModule, - MatDialogModule, - MatFormFieldModule, - MatIconModule, - MatInputModule, - MatSelectModule, - ], - templateUrl: './task-schedule-dialog.component.html', - styleUrl: './task-schedule-dialog.component.scss', - standalone: true, -}) -export class TaskScheduleDialogComponent { - private readonly dialogRef = - inject< - MatDialogRef< - TaskScheduleDialogComponent, - TaskScheduleDialogResult | undefined - > - >(MatDialogRef); - protected readonly data = inject(MAT_DIALOG_DATA); - - protected readonly weekdays = WEEKDAYS; - - protected readonly frequencyOptions: { - value: ScheduleFrequency; - label: string; - }[] = [ - { value: 'manual', label: 'Nur manuell' }, - { value: 'hourly', label: 'Stündlich' }, - { value: 'daily', label: 'Täglich' }, - { value: 'weekly', label: 'Wöchentlich' }, - { value: 'cron', label: 'Cron-Ausdruck' }, - ]; - - protected readonly form = new FormGroup({ - enabled: new FormControl(this.data.task.enabled, { nonNullable: true }), - frequency: new FormControl( - this.data.task.schedule.frequency, - { nonNullable: true }, - ), - time: new FormControl(this.data.task.schedule.time ?? '03:00', { - nonNullable: true, - }), - weekday: new FormControl(this.data.task.schedule.weekday ?? 0, { - nonNullable: true, - }), - cronExpression: new FormControl( - this.data.task.schedule.cronExpression ?? '', - { nonNullable: true, validators: [] }, - ), - }); - - protected readonly recentHistory = this.data.task.history.slice(0, 5); - - protected submit(): void { - const value = this.form.getRawValue(); - - if (value.frequency === 'cron' && !value.cronExpression.trim()) { - this.form.controls.cronExpression.setErrors({ required: true }); - this.form.controls.cronExpression.markAsTouched(); - return; - } - - const schedule: TaskSchedule = { frequency: value.frequency }; - if (value.frequency === 'daily' || value.frequency === 'weekly') { - schedule.time = value.time; - } - if (value.frequency === 'weekly') { - schedule.weekday = value.weekday; - } - if (value.frequency === 'cron') { - schedule.cronExpression = value.cronExpression.trim(); - } - - this.dialogRef.close({ - taskId: this.data.task.id, - enabled: value.enabled, - schedule, - }); - } - - protected close(): void { - this.dialogRef.close(); - } -} diff --git a/webapp/src/app/resolvers/background-job-tasks.resolver.ts b/webapp/src/app/resolvers/background-job-tasks.resolver.ts new file mode 100644 index 00000000..dd3652e0 --- /dev/null +++ b/webapp/src/app/resolvers/background-job-tasks.resolver.ts @@ -0,0 +1,9 @@ +import { inject } from '@angular/core'; +import { ResolveFn } from '@angular/router'; +import { BackgroundJobsService, BackgroundJobTask } from '../api'; + +export const backgroundJobTasksResolver: ResolveFn< + BackgroundJobTask[] +> = () => { + return inject(BackgroundJobsService).getBackgroundJobTasks(); +}; diff --git a/webapp/src/app/resolvers/background-jobs-docker-health.resolver.ts b/webapp/src/app/resolvers/background-jobs-docker-health.resolver.ts new file mode 100644 index 00000000..5a8e1a94 --- /dev/null +++ b/webapp/src/app/resolvers/background-jobs-docker-health.resolver.ts @@ -0,0 +1,9 @@ +import { inject } from '@angular/core'; +import { ResolveFn } from '@angular/router'; +import { BackgroundJobsService, DockerHealth } from '../api'; + +export const backgroundJobsDockerHealthResolver: ResolveFn< + DockerHealth +> = () => { + return inject(BackgroundJobsService).getBackgroundJobsDockerHealth(); +}; diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts index 28a9cc9c..67fd9f37 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts @@ -143,9 +143,9 @@ export class AppMenuComponent { superAdminOnly: true, }, { - label: 'Preprocessing', + label: 'Jobs', icon: 'sync', - route: '/preprocessing', + route: '/jobs', disabled: false, superAdminOnly: true, }, -- 2.56.1 From e5f28f21436f33d234f8e222463bf8c838cd423f Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 14 Jul 2026 05:42:04 +0200 Subject: [PATCH 11/60] add short demo jobs for demos and parallel testing --- background-jobs/app/demo.py | 16 +++++++++ background-jobs/entrypoint.sh | 13 ++++++-- .../src/main/inse/background_jobs/model.py | 3 ++ service/src/main/inse/background_jobs/seed.py | 33 +++++++++++++++++++ webapp/src/app/api/model/backgroundJobName.ts | 6 ++-- 5 files changed, 66 insertions(+), 5 deletions(-) create mode 100644 background-jobs/app/demo.py diff --git a/background-jobs/app/demo.py b/background-jobs/app/demo.py new file mode 100644 index 00000000..a89e6dd0 --- /dev/null +++ b/background-jobs/app/demo.py @@ -0,0 +1,16 @@ +import sys +import time + + +def main() -> None: + seconds = int(sys.argv[1]) if len(sys.argv) > 1 else 20 + print(f"Demo job started, running for {seconds} seconds.", flush=True) + for elapsed in range(1, seconds + 1): + time.sleep(1) + if elapsed % 5 == 0: + print(f"Progress: {elapsed}/{seconds} seconds.", flush=True) + print("Demo job finished successfully.", flush=True) + + +if __name__ == "__main__": + main() diff --git a/background-jobs/entrypoint.sh b/background-jobs/entrypoint.sh index 4cfaa044..10b790e1 100644 --- a/background-jobs/entrypoint.sh +++ b/background-jobs/entrypoint.sh @@ -14,12 +14,21 @@ case "$JOB" in # Print counts for the aktuell / aktuell_postproc indices (read-only). exec python sync.py --stats ;; + demo-a) + exec python demo.py 20 + ;; + demo-b) + exec python demo.py 25 + ;; + demo-c) + exec python demo.py 30 + ;; "") - echo "No job given. Available jobs: news, news-stats" >&2 + echo "No job given. Available jobs: news, news-stats, demo-a, demo-b, demo-c" >&2 exit 2 ;; *) - echo "Unknown job: $JOB. Available jobs: news, news-stats" >&2 + echo "Unknown job: $JOB. Available jobs: news, news-stats, demo-a, demo-b, demo-c" >&2 exit 2 ;; esac diff --git a/service/src/main/inse/background_jobs/model.py b/service/src/main/inse/background_jobs/model.py index 7d470890..cb46d07d 100644 --- a/service/src/main/inse/background_jobs/model.py +++ b/service/src/main/inse/background_jobs/model.py @@ -13,6 +13,9 @@ from sqlmodel import Field, SQLModel class BackgroundJobName(StrEnum): NEWS = "news" NEWS_STATS = "news-stats" + DEMO_A = "demo-a" + DEMO_B = "demo-b" + DEMO_C = "demo-c" class JobRunStatus(StrEnum): diff --git a/service/src/main/inse/background_jobs/seed.py b/service/src/main/inse/background_jobs/seed.py index 6a4a42d9..3ced610e 100644 --- a/service/src/main/inse/background_jobs/seed.py +++ b/service/src/main/inse/background_jobs/seed.py @@ -33,6 +33,39 @@ PREDEFINED_JOB_DEFINITIONS: list[dict] = [ "schedule": None, "enabled": True, }, + { + "name": "Demo-Job A", + "description": ( + "Testjob für Demos: läuft ca. 20 Sekunden, schreibt Fortschritt " + "ins Log und verändert nichts." + ), + "target_index": "-", + "job": BackgroundJobName.DEMO_A, + "schedule": None, + "enabled": True, + }, + { + "name": "Demo-Job B", + "description": ( + "Testjob für Demos: läuft ca. 25 Sekunden, schreibt Fortschritt " + "ins Log und verändert nichts." + ), + "target_index": "-", + "job": BackgroundJobName.DEMO_B, + "schedule": None, + "enabled": True, + }, + { + "name": "Demo-Job C", + "description": ( + "Testjob für Demos: läuft ca. 30 Sekunden, schreibt Fortschritt " + "ins Log und verändert nichts." + ), + "target_index": "-", + "job": BackgroundJobName.DEMO_C, + "schedule": None, + "enabled": True, + }, ] diff --git a/webapp/src/app/api/model/backgroundJobName.ts b/webapp/src/app/api/model/backgroundJobName.ts index 2c65eba1..0a0f4555 100644 --- a/webapp/src/app/api/model/backgroundJobName.ts +++ b/webapp/src/app/api/model/backgroundJobName.ts @@ -8,12 +8,12 @@ * Do not edit the class manually. */ -/** - * Jobs known to the background-jobs image\'s entrypoint.sh dispatcher. - */ export const BackgroundJobName = { News: 'news', NewsStats: 'news-stats', + DemoA: 'demo-a', + DemoB: 'demo-b', + DemoC: 'demo-c', } as const; export type BackgroundJobName = (typeof BackgroundJobName)[keyof typeof BackgroundJobName]; -- 2.56.1 From 3b4d0b33394792d27f3148c59c2c93495caa308c Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 14 Jul 2026 06:27:26 +0200 Subject: [PATCH 12/60] allow superadmins to create and delete whitelisted job schedules --- .../src/main/inse/background_jobs/model.py | 9 + .../src/main/inse/background_jobs/router.py | 31 ++- .../src/main/inse/background_jobs/service.py | 65 +++++ webapp/src/app/api/.openapi-generator/FILES | 1 + .../src/app/api/api/backgroundJobs.service.ts | 247 ++++++++++++++++++ .../api/model/jobDefinitionCreateRequest.ts | 19 ++ webapp/src/app/api/model/models.ts | 1 + 7 files changed, 372 insertions(+), 1 deletion(-) create mode 100644 webapp/src/app/api/model/jobDefinitionCreateRequest.ts diff --git a/service/src/main/inse/background_jobs/model.py b/service/src/main/inse/background_jobs/model.py index cb46d07d..5931a946 100644 --- a/service/src/main/inse/background_jobs/model.py +++ b/service/src/main/inse/background_jobs/model.py @@ -83,6 +83,15 @@ class JobRun(SQLModel, table=True): ) +class JobDefinitionCreateRequest(BaseModel): + name: str + job: BackgroundJobName + description: str = "" + target_index: str = "" + schedule: Optional[str] = None + enabled: bool = True + + class JobDefinitionUpdateRequest(BaseModel): schedule: Optional[str] = None diff --git a/service/src/main/inse/background_jobs/router.py b/service/src/main/inse/background_jobs/router.py index 046a09f2..e6d76bff 100644 --- a/service/src/main/inse/background_jobs/router.py +++ b/service/src/main/inse/background_jobs/router.py @@ -1,4 +1,4 @@ -from fastapi import APIRouter, Depends, Query +from fastapi import APIRouter, Depends, Query, Response, status from sqlmodel import Session from inse.auth import service as auth_service @@ -10,6 +10,7 @@ from . import service from .model import ( BackgroundJobTask, DockerHealth, + JobDefinitionCreateRequest, JobDefinitionUpdateRequest, JobRun, JobRunLogs, @@ -30,6 +31,34 @@ async def get_tasks( return service.get_tasks(session, access_token) +@router.post( + "/tasks", + operation_id="createBackgroundJobTask", + response_model=BackgroundJobTask, + status_code=status.HTTP_201_CREATED, +) +async def create_task( + payload: JobDefinitionCreateRequest, + session: Session = Depends(get_session), + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, +) -> BackgroundJobTask: + return service.create_task(session, access_token, payload) + + +@router.delete( + "/tasks/{task_id}", + operation_id="deleteBackgroundJobTask", + status_code=status.HTTP_204_NO_CONTENT, +) +async def delete_task( + task_id: int, + session: Session = Depends(get_session), + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, +) -> Response: + service.delete_task(session, access_token, task_id) + return Response(status_code=status.HTTP_204_NO_CONTENT) + + @router.patch( "/tasks/{task_id}", operation_id="updateBackgroundJobTask", diff --git a/service/src/main/inse/background_jobs/service.py b/service/src/main/inse/background_jobs/service.py index 2b772483..2f0a1aad 100644 --- a/service/src/main/inse/background_jobs/service.py +++ b/service/src/main/inse/background_jobs/service.py @@ -16,6 +16,7 @@ from .model import ( BackgroundJobTask, DockerHealth, JobDefinition, + JobDefinitionCreateRequest, JobDefinitionUpdateRequest, JobRun, JobRunLogs, @@ -97,6 +98,70 @@ def get_tasks( return [_to_task(session, definition) for definition in definitions] +def create_task( + session: Session, + access_token: AccessTokenMetadata, + payload: JobDefinitionCreateRequest, +) -> BackgroundJobTask: + _require_super_admin(access_token) + name = payload.name.strip() + if not name: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="Task name must not be empty.", + ) + if payload.schedule is not None and not croniter.is_valid(payload.schedule): + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail=f"Invalid cron expression: '{payload.schedule}'.", + ) + if session.exec(select(JobDefinition).where(JobDefinition.name == name)).first(): + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail=f"A task named '{name}' already exists.", + ) + + definition = JobDefinition( + name=name, + job=payload.job, + description=payload.description, + target_index=payload.target_index, + schedule=payload.schedule, + enabled=payload.enabled, + ) + if definition.enabled and definition.schedule: + definition.next_run_at = runner.compute_next_run(definition.schedule) + session.add(definition) + session.commit() + session.refresh(definition) + logger.info("Created background job task '%s' (job=%s).", name, payload.job) + return _to_task(session, definition) + + +def delete_task( + session: Session, access_token: AccessTokenMetadata, definition_id: int +) -> None: + _require_super_admin(access_token) + definition = _get_definition(session, definition_id) + if runner.has_running_run(session, definition.id): + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail=f"'{definition.name}' is running. Stop the run first.", + ) + runs = session.exec( + select(JobRun).where(JobRun.definition_id == definition.id) + ).all() + for run in runs: + session.delete(run) + session.delete(definition) + session.commit() + logger.info( + "Deleted background job task '%s' (%d runs removed).", + definition.name, + len(runs), + ) + + def update_task( session: Session, access_token: AccessTokenMetadata, diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index cacf423b..053eee66 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -144,6 +144,7 @@ model/institutionNetworkNode.ts model/institutionPage.ts model/institutionsListResponse.ts model/ipcClassification.ts +model/jobDefinitionCreateRequest.ts model/jobDefinitionUpdateRequest.ts model/jobRun.ts model/jobRunLogs.ts diff --git a/webapp/src/app/api/api/backgroundJobs.service.ts b/webapp/src/app/api/api/backgroundJobs.service.ts index 871707eb..7a838c18 100644 --- a/webapp/src/app/api/api/backgroundJobs.service.ts +++ b/webapp/src/app/api/api/backgroundJobs.service.ts @@ -29,6 +29,8 @@ import { DockerHealth } from '../model/dockerHealth'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; // @ts-ignore +import { JobDefinitionCreateRequest } from '../model/jobDefinitionCreateRequest'; +// @ts-ignore import { JobDefinitionUpdateRequest } from '../model/jobDefinitionUpdateRequest'; // @ts-ignore import { JobRun } from '../model/jobRun'; @@ -52,6 +54,251 @@ export class BackgroundJobsService extends BaseService { super(basePath, configuration); } + /** + * Create Task + * @endpoint post /api/background-jobs/tasks + * @param jobDefinitionCreateRequest + * @param secureFgpAcc + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createBackgroundJobTask( + jobDefinitionCreateRequest: JobDefinitionCreateRequest, + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public createBackgroundJobTask( + jobDefinitionCreateRequest: JobDefinitionCreateRequest, + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public createBackgroundJobTask( + jobDefinitionCreateRequest: JobDefinitionCreateRequest, + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public createBackgroundJobTask( + jobDefinitionCreateRequest: JobDefinitionCreateRequest, + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if ( + jobDefinitionCreateRequest === null || + jobDefinitionCreateRequest === undefined + ) { + throw new Error( + 'Required parameter jobDefinitionCreateRequest was null or undefined when calling createBackgroundJobTask.', + ); + } + + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + // to determine the Content-Type header + const consumes: string[] = ['application/json']; + const httpContentTypeSelected: string | undefined = + this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Content-Type', + httpContentTypeSelected, + ); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/background-jobs/tasks`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'post', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: jobDefinitionCreateRequest, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + + /** + * Delete Task + * @endpoint delete /api/background-jobs/tasks/{task_id} + * @param taskId + * @param secureFgpAcc + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deleteBackgroundJobTask( + taskId: number, + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public deleteBackgroundJobTask( + taskId: number, + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public deleteBackgroundJobTask( + taskId: number, + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public deleteBackgroundJobTask( + taskId: number, + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if (taskId === null || taskId === undefined) { + throw new Error( + 'Required parameter taskId was null or undefined when calling deleteBackgroundJobTask.', + ); + } + + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/background-jobs/tasks/${this.configuration.encodeParam({ name: 'taskId', value: taskId, in: 'path', style: 'simple', explode: false, dataType: 'number', dataFormat: undefined })}`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'delete', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + /** * Get Run Logs * @endpoint get /api/background-jobs/runs/{run_id}/logs diff --git a/webapp/src/app/api/model/jobDefinitionCreateRequest.ts b/webapp/src/app/api/model/jobDefinitionCreateRequest.ts new file mode 100644 index 00000000..7a8eeba0 --- /dev/null +++ b/webapp/src/app/api/model/jobDefinitionCreateRequest.ts @@ -0,0 +1,19 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { BackgroundJobName } from './backgroundJobName'; + +export interface JobDefinitionCreateRequest { + name: string; + job: BackgroundJobName; + description?: string; + target_index?: string; + schedule?: string | null; + enabled?: boolean; +} diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 88bb2e6c..d5953c8a 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -115,6 +115,7 @@ export * from './institutionNetworkNode'; export * from './institutionPage'; export * from './institutionsListResponse'; export * from './ipcClassification'; +export * from './jobDefinitionCreateRequest'; export * from './jobDefinitionUpdateRequest'; export * from './jobRun'; export * from './jobRunLogs'; -- 2.56.1 From bee19dfa39758ae9e6060a5db7a9f7c63114b4ca Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Wed, 15 Jul 2026 20:49:57 +0200 Subject: [PATCH 13/60] backgroundjobs: let superadmins define image, command and env per job --- .../src/main/inse/background_jobs/model.py | 39 +++++---- .../src/main/inse/background_jobs/runner.py | 25 +++++- service/src/main/inse/background_jobs/seed.py | 81 ------------------- .../src/main/inse/background_jobs/service.py | 11 ++- service/src/main/inse/main.py | 2 - webapp/src/app/api/.openapi-generator/FILES | 1 - webapp/src/app/api/model/backgroundJobName.ts | 19 ----- webapp/src/app/api/model/backgroundJobTask.ts | 4 +- .../api/model/jobDefinitionCreateRequest.ts | 6 +- .../api/model/jobDefinitionUpdateRequest.ts | 6 +- webapp/src/app/api/model/models.ts | 1 - webapp/src/app/app.routes.ts | 2 +- 12 files changed, 64 insertions(+), 133 deletions(-) delete mode 100644 service/src/main/inse/background_jobs/seed.py delete mode 100644 webapp/src/app/api/model/backgroundJobName.ts diff --git a/service/src/main/inse/background_jobs/model.py b/service/src/main/inse/background_jobs/model.py index 5931a946..a45ac3ab 100644 --- a/service/src/main/inse/background_jobs/model.py +++ b/service/src/main/inse/background_jobs/model.py @@ -7,15 +7,7 @@ from enum import StrEnum from typing import Optional from pydantic import BaseModel -from sqlmodel import Field, SQLModel - - -class BackgroundJobName(StrEnum): - NEWS = "news" - NEWS_STATS = "news-stats" - DEMO_A = "demo-a" - DEMO_B = "demo-b" - DEMO_C = "demo-c" +from sqlmodel import JSON, Column, Field, SQLModel class JobRunStatus(StrEnum): @@ -45,8 +37,20 @@ class JobDefinition(SQLModel, table=True): target_index: str = Field( default="", description="Elasticsearch index the job writes to (UI info)." ) - job: BackgroundJobName = Field( - description="Job argument passed to the background-jobs image's entrypoint." + image: Optional[str] = Field( + default=None, + description="Docker image to run. Null falls back to the configured " + "background-jobs image.", + ) + command: Optional[str] = Field( + default=None, + description="Command passed to the image. Null uses the job name (for " + "known jobs) or the image's default entrypoint.", + ) + env: dict[str, str] = Field( + default_factory=dict, + sa_column=Column(JSON), + description="Extra environment variables passed to the container.", ) schedule: Optional[str] = Field( default=None, @@ -85,7 +89,9 @@ class JobRun(SQLModel, table=True): class JobDefinitionCreateRequest(BaseModel): name: str - job: BackgroundJobName + image: Optional[str] = None + command: Optional[str] = None + env: dict[str, str] = {} description: str = "" target_index: str = "" schedule: Optional[str] = None @@ -93,7 +99,11 @@ class JobDefinitionCreateRequest(BaseModel): class JobDefinitionUpdateRequest(BaseModel): - + image: Optional[str] = None + command: Optional[str] = None + env: Optional[dict[str, str]] = None + description: Optional[str] = None + target_index: Optional[str] = None schedule: Optional[str] = None enabled: Optional[bool] = None @@ -103,8 +113,9 @@ class BackgroundJobTask(BaseModel): name: str description: str target_index: str - job: BackgroundJobName image: str + command: Optional[str] + env: dict[str, str] schedule: Optional[str] enabled: bool next_run_at: Optional[datetime] diff --git a/service/src/main/inse/background_jobs/runner.py b/service/src/main/inse/background_jobs/runner.py index d2b568cc..0b7fb413 100644 --- a/service/src/main/inse/background_jobs/runner.py +++ b/service/src/main/inse/background_jobs/runner.py @@ -55,6 +55,23 @@ def job_environment() -> dict[str, str]: return {key: value for key, value in environment.items() if value} +def resolve_image(definition: JobDefinition) -> str: + return definition.image or settings.background_jobs_image + + +def resolve_command(definition: JobDefinition): + return definition.command or None + + +def resolve_environment(definition: JobDefinition) -> dict[str, str]: + base = ( + job_environment() + if resolve_image(definition) == settings.background_jobs_image + else {} + ) + return {**base, **(definition.env or {})} + + def start_run( session: Session, definition: JobDefinition, triggered_by: JobTriggeredBy ) -> JobRun: @@ -65,11 +82,11 @@ def start_run( try: container = get_docker_client().containers.run( - image=settings.background_jobs_image, - command=[definition.job.value], - environment=job_environment(), + image=resolve_image(definition), + command=resolve_command(definition), + environment=resolve_environment(definition), detach=True, - name=f"background-job-{definition.job.value}-run-{run.id}", + name=f"background-job-{definition.id}-run-{run.id}", remove=False, ) run.container_id = container.id diff --git a/service/src/main/inse/background_jobs/seed.py b/service/src/main/inse/background_jobs/seed.py deleted file mode 100644 index 3ced610e..00000000 --- a/service/src/main/inse/background_jobs/seed.py +++ /dev/null @@ -1,81 +0,0 @@ -""" -Seeding of the whitelisted background job definitions. -""" - -import logging - -from sqlmodel import Session, select - -from .model import BackgroundJobName, JobDefinition - -logger = logging.getLogger(__name__) - -PREDEFINED_JOB_DEFINITIONS: list[dict] = [ - { - "name": "News-Aufbereitung", - "description": ( - "Übernimmt neue Artikel aus dem „aktuell“-Index und fügt Relevanz, " - "Personenzuordnungen und Schlagwörter hinzu (Delta-Sync per LLM)." - ), - "target_index": "aktuell_postproc", - "job": BackgroundJobName.NEWS, - "schedule": None, - "enabled": True, - }, - { - "name": "News-Statistik", - "description": ( - "Zählt die Einträge in „aktuell“ und „aktuell_postproc“ (read-only, " - "verändert nichts) — nützlich als Verbindungstest." - ), - "target_index": "aktuell_postproc", - "job": BackgroundJobName.NEWS_STATS, - "schedule": None, - "enabled": True, - }, - { - "name": "Demo-Job A", - "description": ( - "Testjob für Demos: läuft ca. 20 Sekunden, schreibt Fortschritt " - "ins Log und verändert nichts." - ), - "target_index": "-", - "job": BackgroundJobName.DEMO_A, - "schedule": None, - "enabled": True, - }, - { - "name": "Demo-Job B", - "description": ( - "Testjob für Demos: läuft ca. 25 Sekunden, schreibt Fortschritt " - "ins Log und verändert nichts." - ), - "target_index": "-", - "job": BackgroundJobName.DEMO_B, - "schedule": None, - "enabled": True, - }, - { - "name": "Demo-Job C", - "description": ( - "Testjob für Demos: läuft ca. 30 Sekunden, schreibt Fortschritt " - "ins Log und verändert nichts." - ), - "target_index": "-", - "job": BackgroundJobName.DEMO_C, - "schedule": None, - "enabled": True, - }, -] - - -def create_predefined_job_definitions(session: Session) -> None: - for entry in PREDEFINED_JOB_DEFINITIONS: - existing = session.exec( - select(JobDefinition).where(JobDefinition.job == entry["job"]) - ).first() - if existing: - continue - session.add(JobDefinition(**entry)) - logger.info("Seeded background job definition '%s'.", entry["name"]) - session.commit() diff --git a/service/src/main/inse/background_jobs/service.py b/service/src/main/inse/background_jobs/service.py index 2f0a1aad..93da0e2e 100644 --- a/service/src/main/inse/background_jobs/service.py +++ b/service/src/main/inse/background_jobs/service.py @@ -78,8 +78,9 @@ def _to_task(session: Session, definition: JobDefinition) -> BackgroundJobTask: name=definition.name, description=definition.description, target_index=definition.target_index, - job=definition.job, - image=settings.background_jobs_image, + image=runner.resolve_image(definition), + command=definition.command, + env=definition.env or {}, schedule=definition.schedule, enabled=definition.enabled, next_run_at=definition.next_run_at, @@ -123,7 +124,9 @@ def create_task( definition = JobDefinition( name=name, - job=payload.job, + image=payload.image, + command=payload.command, + env=payload.env or {}, description=payload.description, target_index=payload.target_index, schedule=payload.schedule, @@ -134,7 +137,7 @@ def create_task( session.add(definition) session.commit() session.refresh(definition) - logger.info("Created background job task '%s' (job=%s).", name, payload.job) + logger.info("Created background job task '%s'.", name) return _to_task(session, definition) diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index 1b0eacea..8454a2d1 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -46,7 +46,6 @@ from inse.database import create_db_and_tables, get_session from inse.auth.service import create_predefined_accounts from inse.background_jobs.router import router as background_jobs_router from inse.background_jobs.runner import scheduler_loop as background_jobs_scheduler_loop -from inse.background_jobs.seed import create_predefined_job_definitions from . import config from .service import router as service_router @@ -73,7 +72,6 @@ async def lifespan(app: FastAPI): create_db_and_tables() with contextmanager(get_session)() as session: create_predefined_accounts(session, "../data/predefined_accounts.json") - create_predefined_job_definitions(session) background_jobs_scheduler_task = None if settings.background_jobs_scheduler_enabled: diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index 053eee66..6c89c8d7 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -52,7 +52,6 @@ model/autocompleteResponse.ts model/autocompleteResponseMeta.ts model/autocompleteResponseResultsInner.ts model/award.ts -model/backgroundJobName.ts model/backgroundJobTask.ts model/bodyChangePassword.ts model/bodyGetAccessToken.ts diff --git a/webapp/src/app/api/model/backgroundJobName.ts b/webapp/src/app/api/model/backgroundJobName.ts deleted file mode 100644 index 0a0f4555..00000000 --- a/webapp/src/app/api/model/backgroundJobName.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Innovation Search Engine API - * - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -export const BackgroundJobName = { - News: 'news', - NewsStats: 'news-stats', - DemoA: 'demo-a', - DemoB: 'demo-b', - DemoC: 'demo-c', -} as const; -export type BackgroundJobName = - (typeof BackgroundJobName)[keyof typeof BackgroundJobName]; diff --git a/webapp/src/app/api/model/backgroundJobTask.ts b/webapp/src/app/api/model/backgroundJobTask.ts index 0f413e88..e6072ba8 100644 --- a/webapp/src/app/api/model/backgroundJobTask.ts +++ b/webapp/src/app/api/model/backgroundJobTask.ts @@ -7,7 +7,6 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { BackgroundJobName } from './backgroundJobName'; import { JobRun } from './jobRun'; export interface BackgroundJobTask { @@ -15,8 +14,9 @@ export interface BackgroundJobTask { name: string; description: string; target_index: string; - job: BackgroundJobName; image: string; + command: string | null; + env: { [key: string]: string }; schedule: string | null; enabled: boolean; next_run_at: string | null; diff --git a/webapp/src/app/api/model/jobDefinitionCreateRequest.ts b/webapp/src/app/api/model/jobDefinitionCreateRequest.ts index 7a8eeba0..b171e1d8 100644 --- a/webapp/src/app/api/model/jobDefinitionCreateRequest.ts +++ b/webapp/src/app/api/model/jobDefinitionCreateRequest.ts @@ -7,11 +7,11 @@ * https://openapi-generator.tech * Do not edit the class manually. */ -import { BackgroundJobName } from './backgroundJobName'; - export interface JobDefinitionCreateRequest { name: string; - job: BackgroundJobName; + image?: string | null; + command?: string | null; + env?: { [key: string]: string }; description?: string; target_index?: string; schedule?: string | null; diff --git a/webapp/src/app/api/model/jobDefinitionUpdateRequest.ts b/webapp/src/app/api/model/jobDefinitionUpdateRequest.ts index faaec21c..33e96f6a 100644 --- a/webapp/src/app/api/model/jobDefinitionUpdateRequest.ts +++ b/webapp/src/app/api/model/jobDefinitionUpdateRequest.ts @@ -7,8 +7,12 @@ * https://openapi-generator.tech * Do not edit the class manually. */ - export interface JobDefinitionUpdateRequest { + image?: string | null; + command?: string | null; + env?: { [key: string]: string } | null; + description?: string | null; + target_index?: string | null; schedule?: string | null; enabled?: boolean | null; } diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index d5953c8a..64fdfcca 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -23,7 +23,6 @@ export * from './autocompleteResponse'; export * from './autocompleteResponseMeta'; export * from './autocompleteResponseResultsInner'; export * from './award'; -export * from './backgroundJobName'; export * from './backgroundJobTask'; export * from './bodyChangePassword'; export * from './bodyGetAccessToken'; diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index a421ab0e..c1286933 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -227,7 +227,7 @@ export const routes: Routes = [ }, { path: 'jobs', - canActivate: [superAdminGuard], + canActivate: [roleGuard([UserRole.SuperAdmin])], loadComponent: () => import('./modules/jobs/jobs.component').then((mod) => mod.JobsComponent), resolve: { -- 2.56.1 From 5d721407588f07545934b5bab9cf899c04f426c5 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Wed, 15 Jul 2026 23:50:27 +0200 Subject: [PATCH 14/60] backgroundjobs: pull job image from registry before each run --- service/src/main/inse/background_jobs/runner.py | 17 ++++++++++++++++- service/src/main/inse/config.py | 4 ++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/service/src/main/inse/background_jobs/runner.py b/service/src/main/inse/background_jobs/runner.py index 0b7fb413..20894f3c 100644 --- a/service/src/main/inse/background_jobs/runner.py +++ b/service/src/main/inse/background_jobs/runner.py @@ -72,6 +72,18 @@ def resolve_environment(definition: JobDefinition) -> dict[str, str]: return {**base, **(definition.env or {})} +def pull_image(image: str) -> None: + try: + get_docker_client().images.pull(image) + logger.info("Pulled image '%s' from the registry.", image) + except Exception: + logger.warning( + "Could not pull image '%s'; using the local copy if present.", + image, + exc_info=True, + ) + + def start_run( session: Session, definition: JobDefinition, triggered_by: JobTriggeredBy ) -> JobRun: @@ -80,9 +92,12 @@ def start_run( session.commit() session.refresh(run) + image = resolve_image(definition) try: + if settings.background_jobs_pull_before_run: + pull_image(image) container = get_docker_client().containers.run( - image=resolve_image(definition), + image=image, command=resolve_command(definition), environment=resolve_environment(definition), detach=True, diff --git a/service/src/main/inse/config.py b/service/src/main/inse/config.py index b435009e..97441423 100644 --- a/service/src/main/inse/config.py +++ b/service/src/main/inse/config.py @@ -47,6 +47,10 @@ class Settings(BaseSettings): background_jobs_image: str = "docker.nes.uni-due.de/inse/background-jobs:latest" background_jobs_scheduler_enabled: bool = True background_jobs_tick_seconds: int = 5 + # Pull the job image from the registry before each run so an updated tag + # (e.g. :latest) is picked up. Disable for local image development, where + # a locally built image would otherwise be overwritten by the registry. + background_jobs_pull_before_run: bool = False # Sentence Transformers config sentence_transformers_model_name: str = "intfloat/multilingual-e5-base" -- 2.56.1 From e92b450e5b33e274326b682bfd6d71e5ef8eed3c Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Wed, 15 Jul 2026 23:57:43 +0200 Subject: [PATCH 15/60] backgroundjobs: add demo jobs at startup --- service/src/main/inse/background_jobs/seed.py | 47 +++++++++++++++++++ service/src/main/inse/main.py | 2 + 2 files changed, 49 insertions(+) create mode 100644 service/src/main/inse/background_jobs/seed.py diff --git a/service/src/main/inse/background_jobs/seed.py b/service/src/main/inse/background_jobs/seed.py new file mode 100644 index 00000000..0b72a369 --- /dev/null +++ b/service/src/main/inse/background_jobs/seed.py @@ -0,0 +1,47 @@ +""" +Seeding of the demo background job definitions. +""" + +import logging + +from sqlmodel import Session, select + +from .model import JobDefinition + +logger = logging.getLogger(__name__) + +PREDEFINED_DEMO_JOBS: list[dict] = [ + { + "name": "Demo-Job A", + "description": "Testjob für Demos: läuft ca. 20 Sekunden, schreibt " + "Fortschritt ins Log und verändert nichts.", + "target_index": "-", + "command": "demo-a", + }, + { + "name": "Demo-Job B", + "description": "Testjob für Demos: läuft ca. 25 Sekunden, schreibt " + "Fortschritt ins Log und verändert nichts.", + "target_index": "-", + "command": "demo-b", + }, + { + "name": "Demo-Job C", + "description": "Testjob für Demos: läuft ca. 30 Sekunden, schreibt " + "Fortschritt ins Log und verändert nichts.", + "target_index": "-", + "command": "demo-c", + }, +] + + +def create_demo_job_definitions(session: Session) -> None: + for entry in PREDEFINED_DEMO_JOBS: + existing = session.exec( + select(JobDefinition).where(JobDefinition.name == entry["name"]) + ).first() + if existing: + continue + session.add(JobDefinition(**entry)) + logger.info("Seeded demo job definition '%s'.", entry["name"]) + session.commit() diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index 8454a2d1..b8f27b07 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -46,6 +46,7 @@ from inse.database import create_db_and_tables, get_session from inse.auth.service import create_predefined_accounts from inse.background_jobs.router import router as background_jobs_router from inse.background_jobs.runner import scheduler_loop as background_jobs_scheduler_loop +from inse.background_jobs.seed import create_demo_job_definitions from . import config from .service import router as service_router @@ -72,6 +73,7 @@ async def lifespan(app: FastAPI): create_db_and_tables() with contextmanager(get_session)() as session: create_predefined_accounts(session, "../data/predefined_accounts.json") + create_demo_job_definitions(session) background_jobs_scheduler_task = None if settings.background_jobs_scheduler_enabled: -- 2.56.1 From 2566fa920809112d2922bd9eb25c9c37f99b1933 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Thu, 16 Jul 2026 20:41:42 +0200 Subject: [PATCH 16/60] feat(jobs): add news-crawler, bund-crawler and topic-mapper jobs --- .dockerignore | 18 ++++++++ background-jobs/Dockerfile | 22 ++++++++-- background-jobs/entrypoint.sh | 23 +++++++++- background-jobs/requirements.txt | 6 +++ service/scripts/news/ude/run_pipeline.py | 39 ++++++++++++++--- service/scripts/projects/bund/gpc.data.py | 32 +++++++++++--- .../src/main/inse/background_jobs/runner.py | 3 ++ service/src/main/inse/background_jobs/seed.py | 43 ++++++++++++++++--- service/src/main/inse/config.py | 2 +- service/src/main/inse/main.py | 4 +- 10 files changed, 165 insertions(+), 27 deletions(-) create mode 100644 .dockerignore diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..14be7b5c --- /dev/null +++ b/.dockerignore @@ -0,0 +1,18 @@ +* +!background-jobs +!service +service/* +!service/scripts +service/scripts/* +!service/scripts/news +!service/scripts/projects +service/scripts/projects/* +!service/scripts/projects/topic_mapper +!service/scripts/projects/bund + +**/__pycache__ +**/*.pyc +**/.venv +**/.env +**/.env.* +**/out diff --git a/background-jobs/Dockerfile b/background-jobs/Dockerfile index c3d7e8ab..68f19974 100644 --- a/background-jobs/Dockerfile +++ b/background-jobs/Dockerfile @@ -3,15 +3,31 @@ FROM python:3.13-slim WORKDIR /app +# Headless Chrome for the bund foerderportal crawler (Selenium). +RUN apt-get update \ + && apt-get install -y --no-install-recommends chromium chromium-driver \ + && rm -rf /var/lib/apt/lists/* +ENV CHROME_BIN=/usr/bin/chromium \ + CHROMEDRIVER_PATH=/usr/bin/chromedriver + # Install dependencies first so this layer is cached when only code changes. -COPY requirements.txt . +COPY background-jobs/requirements.txt . RUN pip install --no-cache-dir -r requirements.txt # Copy the job code. No secrets here, config is read from env vars at runtime. -COPY app/ ./ +COPY background-jobs/app/ ./ + +# The UDE news crawler is maintained under service/scripts and copied in as-is. +COPY service/scripts/news/ude/ ./news/ude/ + +# The project topic-mapper keeps its package path so its absolute import resolves. +COPY service/scripts/projects/topic_mapper/ ./service/scripts/projects/topic_mapper/ + +# The bund foerderportal crawler (runs with its own dir as cwd for its JSON configs). +COPY service/scripts/projects/bund/ ./projects/bund/ # Small dispatcher that maps a job name to the right command. -COPY entrypoint.sh /entrypoint.sh +COPY background-jobs/entrypoint.sh /entrypoint.sh RUN chmod +x /entrypoint.sh ENTRYPOINT ["/entrypoint.sh"] diff --git a/background-jobs/entrypoint.sh b/background-jobs/entrypoint.sh index 10b790e1..5f1f4d52 100644 --- a/background-jobs/entrypoint.sh +++ b/background-jobs/entrypoint.sh @@ -14,6 +14,25 @@ case "$JOB" in # Print counts for the aktuell / aktuell_postproc indices (read-only). exec python sync.py --stats ;; + news-crawl) + # Crawl UDE 'aktuell' into JSON only. --skip-upload keeps Elasticsearch untouched. + exec python news/ude/run_pipeline.py --skip-upload --max-items "${NEWS_CRAWL_MAX_ITEMS:-5}" + ;; + bund-crawl) + # Crawl the bund foerderportal export via headless Chrome. --skip-upload keeps ES untouched. + cd projects/bund || exit 1 + exec python gpc.data.py --skip-upload + ;; + project-topics) + # Map bund-project keywords to OpenAlex topics. --dry-run reads only, writes nothing. + exec python -m service.scripts.projects.topic_mapper.map_project_topics \ + --dry-run \ + --max-docs "${PROJECT_TOPICS_MAX_DOCS:-50}" \ + --source-index projects_bund_v1 \ + --text-field Leistungsplansystematik_fullname \ + --output-index projects_bund_openalex_topics \ + --api-base-url "${PROJECT_TOPICS_API_BASE_URL:-http://host.docker.internal:8000}" + ;; demo-a) exec python demo.py 20 ;; @@ -24,11 +43,11 @@ case "$JOB" in exec python demo.py 30 ;; "") - echo "No job given. Available jobs: news, news-stats, demo-a, demo-b, demo-c" >&2 + echo "No job given. Available jobs: news, news-stats, news-crawl, project-topics, bund-crawl, demo-a, demo-b, demo-c" >&2 exit 2 ;; *) - echo "Unknown job: $JOB. Available jobs: news, news-stats, demo-a, demo-b, demo-c" >&2 + echo "Unknown job: $JOB. Available jobs: news, news-stats, news-crawl, project-topics, bund-crawl, demo-a, demo-b, demo-c" >&2 exit 2 ;; esac diff --git a/background-jobs/requirements.txt b/background-jobs/requirements.txt index d5f8a74c..6d1122cd 100644 --- a/background-jobs/requirements.txt +++ b/background-jobs/requirements.txt @@ -1,3 +1,9 @@ requests~=2.32 openai~=2.41 python-dotenv~=1.0 +scrapy>=2.11,<2.13 +Twisted>=22.10,<24.7 +httpx~=0.27 +selenium~=4.20 +pandas~=2.2 +elasticsearch>=7.17,<8 diff --git a/service/scripts/news/ude/run_pipeline.py b/service/scripts/news/ude/run_pipeline.py index abd86228..75f9e4b6 100644 --- a/service/scripts/news/ude/run_pipeline.py +++ b/service/scripts/news/ude/run_pipeline.py @@ -3,6 +3,7 @@ import sys import os import shutil import time +import argparse def run_command(command, cwd=None): """Run a shell command and exit if it fails.""" @@ -17,6 +18,22 @@ def run_command(command, cwd=None): sys.exit(result.returncode) if __name__ == "__main__": + parser = argparse.ArgumentParser( + description="Crawl the UDE 'aktuell' news pages and upload the articles to Elasticsearch." + ) + parser.add_argument( + "--skip-upload", + action="store_true", + help="Only crawl into out/*.json and never connect to Elasticsearch", + ) + parser.add_argument( + "--max-items", + type=int, + default=None, + help="Stop each spider after N items (for short test runs)", + ) + args = parser.parse_args() + start_time = time.time() base_dir = os.path.dirname(os.path.abspath(__file__)) @@ -31,19 +48,27 @@ if __name__ == "__main__": output_file_meta = os.path.join(out_dir, "meta.json") + limit = f" -s CLOSESPIDER_ITEMCOUNT={args.max_items}" if args.max_items else "" + print("Running Scrapy link crawler...") - run_command(f"scrapy crawl aktuell-links -O \"{output_file_links}\"", cwd=crawler_dir) + run_command(f"scrapy crawl aktuell-links -O \"{output_file_links}\"{limit}", cwd=crawler_dir) print("Running Scrapy meta crawler...") - run_command(f"scrapy crawl aktuell-metadata -O \"{output_file_meta}\"", cwd=crawler_dir) + run_command(f"scrapy crawl aktuell-metadata -O \"{output_file_meta}\"{limit}", cwd=crawler_dir) - print("Running upload script") - run_command(f"{sys.executable} upload_aktuell.py {output_file_meta}", cwd=base_dir) + if args.skip_upload: + print("Skipping upload (--skip-upload): Elasticsearch was not contacted.") + else: + print("Running upload script") + run_command(f"{sys.executable} upload_aktuell.py {output_file_meta}", cwd=base_dir) end_time = time.time() runtime_seconds = end_time - start_time - runtime_hours = runtime_seconds / 3600 - + runtime_hours = runtime_seconds / 3600 + print(f"Runtime: {runtime_hours:.2f} hours") - print("Finished crawling and uploading UDE news articles.") + if args.skip_upload: + print("Finished crawling UDE news articles (no upload).") + else: + print("Finished crawling and uploading UDE news articles.") diff --git a/service/scripts/projects/bund/gpc.data.py b/service/scripts/projects/bund/gpc.data.py index 56b77702..4cba5952 100644 --- a/service/scripts/projects/bund/gpc.data.py +++ b/service/scripts/projects/bund/gpc.data.py @@ -16,6 +16,7 @@ from elasticsearch import Elasticsearch, helpers from elasticsearch.helpers import bulk,BulkIndexError import os import hashlib +import argparse download_path=os.path.abspath(os.getcwd()) @@ -233,7 +234,10 @@ def setup_chrome_driver(download_path): "download.directory_upgrade": True, "plugins.always_open_pdf_externally": True, }) - chromedriver_path = "/home/inse/miniconda3/envs/airflow/bin/chromedriver" + chrome_bin = os.getenv("CHROME_BIN") + if chrome_bin: + options.binary_location = chrome_bin + chromedriver_path = os.getenv("CHROMEDRIVER_PATH", "/usr/bin/chromedriver") service = Service(executable_path=chromedriver_path) driver = webdriver.Chrome(service=service, options=options) return driver @@ -241,6 +245,16 @@ def setup_chrome_driver(download_path): # main - entry point if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="Crawl the bund foerderportal project export and upload it to Elasticsearch." + ) + parser.add_argument( + "--skip-upload", + action="store_true", + help="Only crawl and format the export; never connect to Elasticsearch", + ) + args = parser.parse_args() + print("Starting") file_path = os.path.join(os.path.abspath(os.getcwd()), 'Suchliste.csv') if not os.path.exists(file_path): @@ -249,14 +263,18 @@ if __name__ == '__main__': crawl_data(link_to_crawl,driver) wait_for_file_complete(download_path, "Suchliste.csv") driver.close() - - + + file = pd.read_csv(file_path,encoding = "latin1",sep=";") df = pd.DataFrame(file) df_formatted = format_data(df) - + index_name = "projects_bund_test" #test indices to make sure everything works before uploading to the real index, ps. you lack rights to push to the real index, please contact the admin if you want to push to the real index - check_elastic_online() - upload_data(df_formatted,index_name) - os.remove(file_path) + if args.skip_upload: + print(f"Skipping upload (--skip-upload): Elasticsearch was not contacted. " + f"Formatted {len(df_formatted)} rows.") + else: + check_elastic_online() + upload_data(df_formatted,index_name) + os.remove(file_path) \ No newline at end of file diff --git a/service/src/main/inse/background_jobs/runner.py b/service/src/main/inse/background_jobs/runner.py index 20894f3c..e05af513 100644 --- a/service/src/main/inse/background_jobs/runner.py +++ b/service/src/main/inse/background_jobs/runner.py @@ -51,6 +51,9 @@ def job_environment() -> dict[str, str]: "INSE_LLM_BASE_URL": settings.llm_api_url, "INSE_LLM_API_KEY": settings.llm_api_key, "INSE_LLM_MODEL": settings.llm_model, + "ELASTICSEARCH_INSE_URL": settings.elasticsearch_inse_url, + "ELASTICSEARCH_INSE_API_KEY": settings.elasticsearch_inse_api_key, + "SENTENCE_TRANSFORMERS_MODEL_NAME": settings.sentence_transformers_model_name, } return {key: value for key, value in environment.items() if value} diff --git a/service/src/main/inse/background_jobs/seed.py b/service/src/main/inse/background_jobs/seed.py index 0b72a369..2b26d3f8 100644 --- a/service/src/main/inse/background_jobs/seed.py +++ b/service/src/main/inse/background_jobs/seed.py @@ -1,5 +1,5 @@ """ -Seeding of the demo background job definitions. +Seeding of the predefined background job definitions. """ import logging @@ -10,7 +10,40 @@ from .model import JobDefinition logger = logging.getLogger(__name__) -PREDEFINED_DEMO_JOBS: list[dict] = [ +PREDEFINED_JOBS: list[dict] = [ + { + "name": "News-Crawler (Testlauf, ohne Upload)", + "description": ( + "Crawlt die UDE-„aktuell“-Seiten mit Scrapy und legt die Artikel nur " + "als JSON im Container ab. Der Upload-Schritt ist abgeschaltet, es " + "wird nichts nach Elasticsearch geschrieben. Begrenzt auf wenige " + "Artikel, da ein vollständiger Crawl mehrere Stunden dauert." + ), + "target_index": "-", + "command": "news-crawl", + }, + { + "name": "Projekt-Themen-Mapping (Testlauf, Dry-Run)", + "description": ( + "Ordnet die Schlagwörter der Bund-Projekte über die Topic-Vektorsuche " + "des Backends OpenAlex-Themen zu. Läuft als Dry-Run (--dry-run): liest " + "nur aus dem Quellindex und schreibt nichts nach Elasticsearch. " + "Benötigt ein erreichbares Backend und INSE-Elasticsearch-Zugang." + ), + "target_index": "-", + "command": "project-topics", + }, + { + "name": "Bund-Crawler (Testlauf, ohne Upload)", + "description": ( + "Lädt den Projekt-Export des Bund-Förderportals via Headless-Chrome " + "herunter und formatiert ihn. Läuft mit --skip-upload: es wird nichts " + "nach Elasticsearch geschrieben. Startet einen echten Browser-Crawl " + "von foerderportal.bund.de und kann daher länger dauern." + ), + "target_index": "-", + "command": "bund-crawl", + }, { "name": "Demo-Job A", "description": "Testjob für Demos: läuft ca. 20 Sekunden, schreibt " @@ -35,13 +68,13 @@ PREDEFINED_DEMO_JOBS: list[dict] = [ ] -def create_demo_job_definitions(session: Session) -> None: - for entry in PREDEFINED_DEMO_JOBS: +def create_predefined_job_definitions(session: Session) -> None: + for entry in PREDEFINED_JOBS: existing = session.exec( select(JobDefinition).where(JobDefinition.name == entry["name"]) ).first() if existing: continue session.add(JobDefinition(**entry)) - logger.info("Seeded demo job definition '%s'.", entry["name"]) + logger.info("Seeded background job definition '%s'.", entry["name"]) session.commit() diff --git a/service/src/main/inse/config.py b/service/src/main/inse/config.py index 97441423..30f8f3e1 100644 --- a/service/src/main/inse/config.py +++ b/service/src/main/inse/config.py @@ -50,7 +50,7 @@ class Settings(BaseSettings): # Pull the job image from the registry before each run so an updated tag # (e.g. :latest) is picked up. Disable for local image development, where # a locally built image would otherwise be overwritten by the registry. - background_jobs_pull_before_run: bool = False + background_jobs_pull_before_run: bool = True # Sentence Transformers config sentence_transformers_model_name: str = "intfloat/multilingual-e5-base" diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index b8f27b07..1b0eacea 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -46,7 +46,7 @@ from inse.database import create_db_and_tables, get_session from inse.auth.service import create_predefined_accounts from inse.background_jobs.router import router as background_jobs_router from inse.background_jobs.runner import scheduler_loop as background_jobs_scheduler_loop -from inse.background_jobs.seed import create_demo_job_definitions +from inse.background_jobs.seed import create_predefined_job_definitions from . import config from .service import router as service_router @@ -73,7 +73,7 @@ async def lifespan(app: FastAPI): create_db_and_tables() with contextmanager(get_session)() as session: create_predefined_accounts(session, "../data/predefined_accounts.json") - create_demo_job_definitions(session) + create_predefined_job_definitions(session) background_jobs_scheduler_task = None if settings.background_jobs_scheduler_enabled: -- 2.56.1 From a76789f34b86832de41c4fa8dc21002ab9428a23 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Thu, 16 Jul 2026 22:21:04 +0200 Subject: [PATCH 17/60] fix(config): load .env relative to config.py --- service/src/main/inse/config.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/service/src/main/inse/config.py b/service/src/main/inse/config.py index 30f8f3e1..e85488dd 100644 --- a/service/src/main/inse/config.py +++ b/service/src/main/inse/config.py @@ -7,6 +7,7 @@ that can be adjusted via environment variables. from functools import lru_cache import logging +from pathlib import Path from typing import Dict, List, Literal, Optional from pydantic_settings import BaseSettings, SettingsConfigDict from dotenv import load_dotenv @@ -14,7 +15,10 @@ from dotenv import load_dotenv logger = logging.getLogger(__name__) -load_dotenv() +# Anchor the .env to this file's directory so it loads regardless of the +# process working directory. +ENV_FILE = Path(__file__).resolve().parent / ".env" +load_dotenv(ENV_FILE) class Settings(BaseSettings): @@ -61,7 +65,7 @@ class Settings(BaseSettings): elasticsearch_inse_url: Optional[str] = None elasticsearch_inse_api_key: Optional[str] = None - model_config = SettingsConfigDict(env_file=".env") + model_config = SettingsConfigDict(env_file=str(ENV_FILE)) allowed_origins: List[str] = ["http://localhost:4200"] -- 2.56.1 From 93481bf9c5692e7bebe464f3063fba9bb99b0171 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Thu, 16 Jul 2026 22:22:11 +0200 Subject: [PATCH 18/60] feat(jobs): authenticate registry image pulls --- service/src/main/inse/background_jobs/runner.py | 14 +++++++++++++- service/src/main/inse/config.py | 5 +++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/service/src/main/inse/background_jobs/runner.py b/service/src/main/inse/background_jobs/runner.py index e05af513..beb20ccd 100644 --- a/service/src/main/inse/background_jobs/runner.py +++ b/service/src/main/inse/background_jobs/runner.py @@ -75,9 +75,21 @@ def resolve_environment(definition: JobDefinition) -> dict[str, str]: return {**base, **(definition.env or {})} +def registry_auth() -> Optional[dict[str, str]]: + if ( + settings.background_jobs_registry_username + and settings.background_jobs_registry_password + ): + return { + "username": settings.background_jobs_registry_username, + "password": settings.background_jobs_registry_password, + } + return None + + def pull_image(image: str) -> None: try: - get_docker_client().images.pull(image) + get_docker_client().images.pull(image, auth_config=registry_auth()) logger.info("Pulled image '%s' from the registry.", image) except Exception: logger.warning( diff --git a/service/src/main/inse/config.py b/service/src/main/inse/config.py index e85488dd..aebc16c6 100644 --- a/service/src/main/inse/config.py +++ b/service/src/main/inse/config.py @@ -55,6 +55,11 @@ class Settings(BaseSettings): # (e.g. :latest) is picked up. Disable for local image development, where # a locally built image would otherwise be overwritten by the registry. background_jobs_pull_before_run: bool = True + # Credentials for pulling the job image from a private registry (e.g. the + # Nexus at docker.nes.uni-due.de). Needed because the runner pulls via the + # Docker SDK inside the service container, which has no `docker login` creds. + background_jobs_registry_username: Optional[str] = None + background_jobs_registry_password: Optional[str] = None # Sentence Transformers config sentence_transformers_model_name: str = "intfloat/multilingual-e5-base" -- 2.56.1 From 8583f6622efd0380856689e7f9c1c3c1ad34ec75 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Thu, 16 Jul 2026 23:16:55 +0200 Subject: [PATCH 19/60] feat(jobs): cap logs at last 200 lines --- .../src/main/inse/background_jobs/service.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/service/src/main/inse/background_jobs/service.py b/service/src/main/inse/background_jobs/service.py index 93da0e2e..2909b568 100644 --- a/service/src/main/inse/background_jobs/service.py +++ b/service/src/main/inse/background_jobs/service.py @@ -225,6 +225,16 @@ def get_task_runs( ).all() +LOG_TAIL_LINES = 200 + + +def _tail_log_lines(text: str, limit: int = LOG_TAIL_LINES) -> str: + lines = text.splitlines() + if len(lines) <= limit: + return text + return "\n".join(lines[-limit:]) + + def get_run_logs( session: Session, access_token: AccessTokenMetadata, run_id: int ) -> JobRunLogs: @@ -236,11 +246,15 @@ def get_run_logs( return JobRunLogs( run_id=run_id, status=run.status, - logs=container.logs().decode("utf-8", errors="replace"), + logs=container.logs(tail=LOG_TAIL_LINES).decode( + "utf-8", errors="replace" + ), ) except Exception: # noqa: BLE001 pass - return JobRunLogs(run_id=run_id, status=run.status, logs=run.logs or "") + return JobRunLogs( + run_id=run_id, status=run.status, logs=_tail_log_lines(run.logs or "") + ) def stop_run( -- 2.56.1 From 53155d4e532aa6fe5f6723e60e229c423285d556 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Fri, 17 Jul 2026 00:23:40 +0200 Subject: [PATCH 20/60] feat(logs): add run dropdown, visible scrollbar and download button --- .../job-logs-dialog.component.html | 48 +++++++++++--- .../job-logs-dialog.component.scss | 38 +++++++++++ .../job-logs-dialog.component.ts | 63 +++++++++++++++++-- 3 files changed, 135 insertions(+), 14 deletions(-) diff --git a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html index 01122184..acc03651 100644 --- a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html +++ b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html @@ -1,12 +1,29 @@

Logs · {{ data.task.name }}

- @if (runId == null) { + @if (runs().length === 0 && !runsLoading()) {

Für diesen Job liegt noch kein Lauf vor.

} @else { + + Lauf auswählen + + @for (run of runs(); track run.id) { + + #{{ run.id }} · {{ statusMeta(run.status!).label }} · + {{ run.started_at | date: 'dd.MM.yyyy HH:mm' }} + @if (run.exit_code != null) { + · Exit {{ run.exit_code }} + } + + } + + +
- Letzter Lauf #{{ runId }} + Lauf #{{ selectedRunId() }} @if (runStatus()) { } + zeigt letzte 200 Zeilen +
+
+ +
-
diff --git a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.scss b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.scss index bf9a2c60..850f22b0 100644 --- a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.scss +++ b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.scss @@ -19,6 +19,12 @@ color: #64748b; } +.logs-actions { + display: flex; + gap: 8px; + flex-shrink: 0; +} + .task-status { display: inline-flex; align-items: center; @@ -61,6 +67,28 @@ min-height: 120px; max-height: 55vh; overflow: auto; + scrollbar-width: thin; + scrollbar-color: #64748b #1e293b; + + &::-webkit-scrollbar { + width: 12px; + height: 12px; + } + + &::-webkit-scrollbar-track { + background: #1e293b; + border-radius: 6px; + } + + &::-webkit-scrollbar-thumb { + background: #64748b; + border-radius: 6px; + border: 3px solid #0f172a; + } + + &::-webkit-scrollbar-thumb:hover { + background: #94a3b8; + } pre { margin: 0; @@ -84,6 +112,16 @@ font-size: 13px; } +.run-select { + width: 100%; + margin-top: 8px; +} + +.logs-hint { + color: #94a3b8; + font-size: 12px; +} + @media (max-width: 640px) { .logs-header { flex-direction: column; diff --git a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts index 62cf0903..d618bb9f 100644 --- a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts +++ b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts @@ -6,9 +6,11 @@ import { MatDialogModule, MatDialogRef, } from '@angular/material/dialog'; +import { MatFormFieldModule } from '@angular/material/form-field'; import { MatIconModule } from '@angular/material/icon'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; -import { BackgroundJobsService, BackgroundJobTask } from '../../../api'; +import { MatSelectModule } from '@angular/material/select'; +import { BackgroundJobsService, BackgroundJobTask, JobRun } from '../../../api'; import { statusMeta } from '../jobs.utils'; export interface JobLogsDialogData { @@ -21,8 +23,10 @@ export interface JobLogsDialogData { CommonModule, MatButtonModule, MatDialogModule, + MatFormFieldModule, MatIconModule, MatProgressSpinnerModule, + MatSelectModule, ], templateUrl: './job-logs-dialog.component.html', styleUrl: './job-logs-dialog.component.scss', @@ -34,8 +38,12 @@ export class JobLogsDialogComponent implements OnInit { protected readonly data = inject(MAT_DIALOG_DATA); protected readonly statusMeta = statusMeta; - protected readonly runId = this.data.task.last_run?.id ?? null; + protected readonly runs = signal([]); + protected readonly runsLoading = signal(false); + protected readonly selectedRunId = signal( + this.data.task.last_run?.id ?? null, + ); protected readonly loading = signal(false); protected readonly logs = signal(''); protected readonly runStatus = signal( @@ -43,14 +51,46 @@ export class JobLogsDialogComponent implements OnInit { ); ngOnInit(): void { + this.loadRuns(); + if (this.selectedRunId() != null) { + this.loadLogs(); + } + } + + protected loadRuns(): void { + this.runsLoading.set(true); + this.backgroundJobsService + .getBackgroundJobTaskRuns(this.data.task.id, 50) + .subscribe({ + next: (runs) => { + this.runs.set(runs); + this.runsLoading.set(false); + if (this.selectedRunId() == null && runs.length > 0) { + this.selectRun(runs[0]); + } + }, + error: () => this.runsLoading.set(false), + }); + } + + protected selectRun(run: JobRun): void { + if (run.id == null) return; + this.selectedRunId.set(run.id); + this.runStatus.set(run.status ?? null); this.loadLogs(); } + protected onRunSelected(runId: number): void { + const run = this.runs().find((item) => item.id === runId); + if (run) this.selectRun(run); + } + protected loadLogs(): void { - if (this.runId == null) return; + const runId = this.selectedRunId(); + if (runId == null) return; this.loading.set(true); - this.backgroundJobsService.getBackgroundJobRunLogs(this.runId).subscribe({ + this.backgroundJobsService.getBackgroundJobRunLogs(runId).subscribe({ next: (result) => { this.logs.set(result.logs || 'Keine Logs vorhanden.'); this.runStatus.set(result.status); @@ -63,6 +103,21 @@ export class JobLogsDialogComponent implements OnInit { }); } + protected downloadLogs(): void { + const runId = this.selectedRunId(); + if (runId == null) return; + + const run = this.runs().find((item) => item.id === runId); + const text = run?.logs ?? this.logs(); + const blob = new Blob([text], { type: 'text/plain;charset=utf-8' }); + const url = URL.createObjectURL(blob); + const anchor = document.createElement('a'); + anchor.href = url; + anchor.download = `${this.data.task.command ?? 'job'}-run-${runId}.log`; + anchor.click(); + URL.revokeObjectURL(url); + } + protected close(): void { this.dialogRef.close(); } -- 2.56.1 From b39daba5616a8d3278cf5acba1aa696c9079f916 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Fri, 17 Jul 2026 00:50:07 +0200 Subject: [PATCH 21/60] feat(jobs): add stop button --- .../src/main/inse/background_jobs/service.py | 26 ++++++++++++++----- .../src/app/modules/jobs/jobs.component.html | 9 +++++++ webapp/src/app/modules/jobs/jobs.component.ts | 20 ++++++++++++++ 3 files changed, 49 insertions(+), 6 deletions(-) diff --git a/service/src/main/inse/background_jobs/service.py b/service/src/main/inse/background_jobs/service.py index 2909b568..224ce05d 100644 --- a/service/src/main/inse/background_jobs/service.py +++ b/service/src/main/inse/background_jobs/service.py @@ -22,6 +22,7 @@ from .model import ( JobRunLogs, JobRunStatus, JobTriggeredBy, + utcnow, ) logger = logging.getLogger(__name__) @@ -267,13 +268,26 @@ def stop_run( status_code=status.HTTP_409_CONFLICT, detail=f"Run {run_id} is not running.", ) + + run.status = JobRunStatus.STOPPED + run.finished_at = utcnow() + session.add(run) + session.commit() + session.refresh(run) + try: - runner.get_docker_client().containers.get(run.container_id).stop() - except Exception as error: # noqa: BLE001 - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=f"Failed to stop container: {error}", - ) + container = runner.get_docker_client().containers.get(run.container_id) + container.stop() + container.reload() + run.logs = container.logs().decode("utf-8", errors="replace") + run.exit_code = container.attrs["State"]["ExitCode"] + container.remove() + session.add(run) + session.commit() + session.refresh(run) + except Exception: # noqa: BLE001 + logger.warning("Cleanup after stopping run %s failed.", run_id, exc_info=True) + return run diff --git a/webapp/src/app/modules/jobs/jobs.component.html b/webapp/src/app/modules/jobs/jobs.component.html index c0056af5..330e71c1 100644 --- a/webapp/src/app/modules/jobs/jobs.component.html +++ b/webapp/src/app/modules/jobs/jobs.component.html @@ -115,6 +115,15 @@ (click)="runNow(row)"> play_arrow + diff --git a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.scss b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.scss index 850f22b0..f4b9b0ca 100644 --- a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.scss +++ b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.scss @@ -3,6 +3,22 @@ margin: 0; } +.runs-loading { + display: flex; + align-items: center; + gap: 10px; + min-height: 120px; + color: #64748b; +} + +.logs-error { + margin: 0; + padding: 16px; + border-radius: 6px; + background: #fef2f2; + color: #991b1b; +} + .logs-header { display: flex; align-items: center; diff --git a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts index d618bb9f..815bd458 100644 --- a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts +++ b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts @@ -10,6 +10,7 @@ import { MatFormFieldModule } from '@angular/material/form-field'; import { MatIconModule } from '@angular/material/icon'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { MatSelectModule } from '@angular/material/select'; +import { finalize } from 'rxjs'; import { BackgroundJobsService, BackgroundJobTask, JobRun } from '../../../api'; import { statusMeta } from '../jobs.utils'; @@ -41,35 +42,42 @@ export class JobLogsDialogComponent implements OnInit { protected readonly runs = signal([]); protected readonly runsLoading = signal(false); - protected readonly selectedRunId = signal( - this.data.task.last_run?.id ?? null, - ); + protected readonly runsError = signal(null); + protected readonly selectedRunId = signal(null); protected readonly loading = signal(false); protected readonly logs = signal(''); - protected readonly runStatus = signal( - this.data.task.last_run?.status ?? null, - ); + protected readonly runStatus = signal(null); ngOnInit(): void { - this.loadRuns(); - if (this.selectedRunId() != null) { - this.loadLogs(); - } + this.loadRuns(true); } - protected loadRuns(): void { + protected loadRuns(selectLatest = false): void { this.runsLoading.set(true); + this.runsError.set(null); this.backgroundJobsService - .getBackgroundJobTaskRuns(this.data.task.id, 50) + .getBackgroundJobTaskRuns( + this.data.task.id, + 50, + undefined, + 'body', + false, + { transferCache: false }, + ) + .pipe(finalize(() => this.runsLoading.set(false))) .subscribe({ next: (runs) => { this.runs.set(runs); - this.runsLoading.set(false); - if (this.selectedRunId() == null && runs.length > 0) { - this.selectRun(runs[0]); + const selected = selectLatest + ? runs[0] + : (runs.find((run) => run.id === this.selectedRunId()) ?? runs[0]); + if (selected) { + this.selectRun(selected); } }, - error: () => this.runsLoading.set(false), + error: () => { + this.runsError.set('Läufe konnten nicht geladen werden.'); + }, }); } @@ -90,17 +98,24 @@ export class JobLogsDialogComponent implements OnInit { if (runId == null) return; this.loading.set(true); - this.backgroundJobsService.getBackgroundJobRunLogs(runId).subscribe({ - next: (result) => { - this.logs.set(result.logs || 'Keine Logs vorhanden.'); - this.runStatus.set(result.status); - this.loading.set(false); - }, - error: () => { - this.logs.set('Logs konnten nicht geladen werden.'); - this.loading.set(false); - }, - }); + this.backgroundJobsService + .getBackgroundJobRunLogs(runId, undefined, 'body', false, { + transferCache: false, + }) + .pipe(finalize(() => this.loading.set(false))) + .subscribe({ + next: (result) => { + if (!result) { + this.logs.set('Die Log-Anfrage hat keine Daten zurückgegeben.'); + return; + } + this.logs.set(result.logs || 'Keine Logs vorhanden.'); + this.runStatus.set(result.status); + }, + error: () => { + this.logs.set('Logs konnten nicht geladen werden.'); + }, + }); } protected downloadLogs(): void { diff --git a/webapp/src/app/modules/jobs/jobs.component.html b/webapp/src/app/modules/jobs/jobs.component.html index 330e71c1..e87d3850 100644 --- a/webapp/src/app/modules/jobs/jobs.component.html +++ b/webapp/src/app/modules/jobs/jobs.component.html @@ -78,7 +78,7 @@ - @if (row.status === 'running') { + @if (row.status === 'running' || row.status === 'stopping') { @@ -111,7 +111,8 @@ type="button" aria-label="Jetzt ausführen" matTooltip="Jetzt ausführen" - [disabled]="row.status === 'running'" + matTooltipPosition="above" + [disabled]="row.status === 'running' || row.status === 'stopping'" (click)="runNow(row)"> play_arrow @@ -120,6 +121,7 @@ type="button" aria-label="Stoppen" matTooltip="Stoppen" + matTooltipPosition="above" [disabled]="row.status !== 'running'" (click)="stopNow(row)"> stop @@ -129,6 +131,7 @@ type="button" aria-label="Logs anzeigen" matTooltip="Logs anzeigen" + matTooltipPosition="above" [disabled]="!row.last_run" (click)="openLogsDialog(row)"> description @@ -138,6 +141,7 @@ type="button" aria-label="Zeitplan bearbeiten" matTooltip="Zeitplan bearbeiten" + matTooltipPosition="above" (click)="openScheduleDialog(row)"> edit_calendar diff --git a/webapp/src/app/modules/jobs/jobs.component.scss b/webapp/src/app/modules/jobs/jobs.component.scss index 547f1b1d..5c5d6aa3 100644 --- a/webapp/src/app/modules/jobs/jobs.component.scss +++ b/webapp/src/app/modules/jobs/jobs.component.scss @@ -83,6 +83,19 @@ mat-paginator { vertical-align: middle; } +:host ::ng-deep .mat-mdc-header-cell { + text-align: center; +} + +:host ::ng-deep .mat-mdc-cell:not(:last-child), +:host ::ng-deep .mat-mdc-header-cell:not(:last-child) { + border-right: 1px solid var(--sg-border); +} + +:host ::ng-deep .mat-mdc-cell.mat-column-lastRun { + text-align: center; +} + .task-name-cell { display: flex; flex-direction: column; @@ -167,6 +180,7 @@ mat-paginator { .last-run-cell { display: flex; flex-direction: column; + align-items: center; gap: 2px; font-size: 13px; } diff --git a/webapp/src/app/modules/jobs/jobs.component.ts b/webapp/src/app/modules/jobs/jobs.component.ts index e965908e..d18b8b89 100644 --- a/webapp/src/app/modules/jobs/jobs.component.ts +++ b/webapp/src/app/modules/jobs/jobs.component.ts @@ -17,7 +17,7 @@ import { MatIconModule } from '@angular/material/icon'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; import { MatTooltipModule } from '@angular/material/tooltip'; -import { interval, switchMap, takeWhile, take } from 'rxjs'; +import { EMPTY, Subject, catchError, merge, switchMap, timer } from 'rxjs'; import { BackgroundJobsService, BackgroundJobTask, @@ -84,10 +84,31 @@ export class JobsComponent implements OnInit { private readonly taskActionsTmp = viewChild.required>('taskActionsTmp'); + private readonly taskRefreshTrigger = new Subject(); + private readonly pendingStopTaskIds = new Set(); + ngOnInit(): void { this.tasks.set(this.tasksInput()); this.dockerHealth.set(this.dockerHealthInput()); + merge(timer(0, 5000), this.taskRefreshTrigger) + .pipe( + switchMap(() => + this.backgroundJobsService + .getBackgroundJobTasks(undefined, 'body', false, { + transferCache: false, + }) + .pipe( + catchError(() => { + this.showError('Tasks konnten nicht aktualisiert werden.'); + return EMPTY; + }), + ), + ), + takeUntilDestroyed(this.destroyRef), + ) + .subscribe((tasks) => this.setTasksPreservingPendingStops(tasks)); + this.taskColumns = [ { id: 'name', @@ -120,17 +141,10 @@ export class JobsComponent implements OnInit { cellTemplate: this.taskActionsTmp(), }, ]; - - if (this.tasks().some((task) => task.status === 'running')) { - this.pollWhileRunning(); - } } protected refreshTasks(): void { - this.backgroundJobsService.getBackgroundJobTasks().subscribe({ - next: (tasks) => this.tasks.set(tasks), - error: () => this.showError('Tasks konnten nicht aktualisiert werden.'), - }); + this.taskRefreshTrigger.next(); } protected refreshDockerHealth(): void { @@ -148,7 +162,7 @@ export class JobsComponent implements OnInit { } protected runNow(task: BackgroundJobTask): void { - if (task.status === 'running') return; + if (['running', 'stopping'].includes(task.status)) return; this.backgroundJobsService.runBackgroundJobTask(task.id).subscribe({ next: (run) => { @@ -159,8 +173,10 @@ export class JobsComponent implements OnInit { })); this.snackBar.open(`„${task.name}“ wurde gestartet.`, 'OK', { duration: 3000, + horizontalPosition: 'right', + verticalPosition: 'top', }); - this.pollWhileRunning(); + this.refreshTasks(); }, error: (error) => this.showError( @@ -175,19 +191,44 @@ export class JobsComponent implements OnInit { const runId = task.last_run?.id; if (task.status !== 'running' || runId == null) return; + this.pendingStopTaskIds.add(task.id); + this.updateTask(task.id, (current) => ({ + ...current, + status: 'stopping', + })); + this.backgroundJobsService.stopBackgroundJobRun(runId).subscribe({ - next: () => { - this.snackBar.open(`„${task.name}“ wird gestoppt.`, 'OK', { + next: (run) => { + this.pendingStopTaskIds.delete(task.id); + this.updateTask(task.id, (current) => ({ + ...current, + status: run.status ?? 'running', + last_run: run, + })); + const message = + run.status === 'stopped' + ? `„${task.name}“ wurde gestoppt.` + : `„${task.name}“ war bereits beendet.`; + this.snackBar.open(message, 'OK', { duration: 3000, + horizontalPosition: 'right', + verticalPosition: 'top', }); - this.pollWhileRunning(); + this.refreshTasks(); }, - error: (error) => + error: (error) => { + this.pendingStopTaskIds.delete(task.id); + this.updateTask(task.id, (current) => ({ + ...current, + status: 'running', + })); this.showError( error.status === 409 ? `„${task.name}“ läuft nicht.` : `„${task.name}“ konnte nicht gestoppt werden.`, - ), + ); + this.refreshTasks(); + }, }); } @@ -228,6 +269,8 @@ export class JobsComponent implements OnInit { this.updateTask(result.taskId, () => updatedTask); this.snackBar.open('Zeitplan wurde gespeichert.', 'OK', { duration: 3000, + horizontalPosition: 'right', + verticalPosition: 'top', }); }, error: (error) => @@ -239,20 +282,6 @@ export class JobsComponent implements OnInit { }); } - private pollWhileRunning(): void { - interval(5000) - .pipe( - switchMap(() => this.backgroundJobsService.getBackgroundJobTasks()), - take(24), - takeWhile( - (tasks) => tasks.some((task) => task.status === 'running'), - true, - ), - takeUntilDestroyed(this.destroyRef), - ) - .subscribe((tasks) => this.tasks.set(tasks)); - } - private updateTask( id: number, updater: (task: BackgroundJobTask) => BackgroundJobTask, @@ -262,7 +291,21 @@ export class JobsComponent implements OnInit { ); } + private setTasksPreservingPendingStops(tasks: BackgroundJobTask[]): void { + this.tasks.set( + tasks.map((task) => + this.pendingStopTaskIds.has(task.id) + ? { ...task, status: 'stopping' } + : task, + ), + ); + } + private showError(message: string): void { - this.snackBar.open(message, 'OK', { duration: 5000 }); + this.snackBar.open(message, 'OK', { + duration: 5000, + horizontalPosition: 'right', + verticalPosition: 'top', + }); } } diff --git a/webapp/src/app/modules/jobs/jobs.utils.ts b/webapp/src/app/modules/jobs/jobs.utils.ts index 599b95ab..0ddc57dd 100644 --- a/webapp/src/app/modules/jobs/jobs.utils.ts +++ b/webapp/src/app/modules/jobs/jobs.utils.ts @@ -8,6 +8,11 @@ export interface StatusMeta { const STATUS_META: Record = { running: { label: 'Läuft', icon: 'sync', cssClass: 'task-status--running' }, + stopping: { + label: 'Wird gestoppt', + icon: 'stop_circle', + cssClass: 'task-status--running', + }, succeeded: { label: 'Erfolgreich', icon: 'check_circle', diff --git a/webapp/src/app/resolvers/background-job-tasks.resolver.ts b/webapp/src/app/resolvers/background-job-tasks.resolver.ts index dd3652e0..e32575bc 100644 --- a/webapp/src/app/resolvers/background-job-tasks.resolver.ts +++ b/webapp/src/app/resolvers/background-job-tasks.resolver.ts @@ -5,5 +5,10 @@ import { BackgroundJobsService, BackgroundJobTask } from '../api'; export const backgroundJobTasksResolver: ResolveFn< BackgroundJobTask[] > = () => { - return inject(BackgroundJobsService).getBackgroundJobTasks(); + return inject(BackgroundJobsService).getBackgroundJobTasks( + undefined, + 'body', + false, + { transferCache: false }, + ); }; -- 2.56.1 From d005162a80ed528484026f447a05a50ec242bb89 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Fri, 17 Jul 2026 13:54:59 +0200 Subject: [PATCH 23/60] fix(jobs): auto-refresh logs and improve job table layout --- .../job-logs-dialog/job-logs-dialog.component.html | 2 +- .../jobs/job-logs-dialog/job-logs-dialog.component.ts | 10 ++++++++-- webapp/src/app/modules/jobs/jobs.component.scss | 6 ++++++ webapp/src/app/modules/jobs/jobs.component.ts | 4 ++-- 4 files changed, 17 insertions(+), 5 deletions(-) diff --git a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html index 06bcbcd9..8448a217 100644 --- a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html +++ b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html @@ -55,7 +55,7 @@
diff --git a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts index f022e806..d6ccbcb8 100644 --- a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts +++ b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts @@ -11,6 +11,7 @@ import { MatFormFieldModule } from '@angular/material/form-field'; import { MatIconModule } from '@angular/material/icon'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { MatSelectModule } from '@angular/material/select'; +import { MatTooltipModule } from '@angular/material/tooltip'; import { finalize, timer } from 'rxjs'; import { BackgroundJobsService, BackgroundJobTask, JobRun } from '../../../api'; import { statusMeta } from '../jobs.utils'; @@ -29,6 +30,7 @@ export interface JobLogsDialogData { MatIconModule, MatProgressSpinnerModule, MatSelectModule, + MatTooltipModule, ], templateUrl: './job-logs-dialog.component.html', styleUrl: './job-logs-dialog.component.scss', diff --git a/webapp/src/app/modules/jobs/jobs.component.html b/webapp/src/app/modules/jobs/jobs.component.html index e87d3850..5c8926e9 100644 --- a/webapp/src/app/modules/jobs/jobs.component.html +++ b/webapp/src/app/modules/jobs/jobs.component.html @@ -43,12 +43,6 @@ -
- -
@@ -104,6 +98,21 @@ } + +
+ Aktionen + +
+
+
- - Cron-Ausdruck (UTC) - - Leer lassen für nur manuelle Ausführung. - @if (form.controls.cronExpression.hasError('invalidCron')) { - Ungültiger Cron-Ausdruck, z. B. „0 3 * * *“. - } + Ausführung + + Nur manuell + Stündlich + Täglich + Wöchentlich + Monatlich + Erweiterter Cron-Ausdruck + - @if (data.task.next_run_at) { + @switch (form.controls.mode.value) { + @case ('hourly') { + + Minute der Stunde + + Angabe in UTC, zwischen 0 und 59. + @if (form.controls.minute.invalid) { + Bitte eine Minute zwischen 0 und 59 eingeben. + } + + } + @case ('daily') { + + } + @case ('weekly') { +
+ + Wochentag + + @for (weekday of weekdays; track weekday.value) { + + {{ weekday.label }} + + } + + + +
+ } + @case ('monthly') { +
+ + Tag des Monats + + @if (form.controls.monthDay.invalid) { + Bitte einen Tag zwischen 1 und 31 eingeben. + } + + +
+

+ In kürzeren Monaten wird ein nicht vorhandener Tag übersprungen. +

+ } + @case ('advanced') { + + Cron-Ausdruck (UTC) + + Minute · Stunde · Tag · Monat · Wochentag + @if (form.controls.cronExpression.hasError('invalidCron')) { + Ungültiger Cron-Ausdruck, z. B. „0 3 * * *“. + } + + } + } + + @if (form.controls.mode.value !== 'manual') { + + } + + @if (data.task.next_run_at && form.controls.mode.value !== 'manual') {

Nächster geplanter Lauf: - {{ data.task.next_run_at | date: 'dd.MM.yyyy HH:mm' }} Uhr + {{ formatNextRun(data.task.next_run_at) }} Uhr UTC

} + + + + Uhrzeit (UTC) + + @if (form.controls.time.invalid) { + Bitte eine gültige Uhrzeit eingeben. + } + + diff --git a/webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.scss b/webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.scss index 7fa6ba05..a684f79b 100644 --- a/webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.scss +++ b/webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.scss @@ -10,6 +10,22 @@ min-width: 360px; } +.schedule-fields { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 12px; +} + +.field-hint { + margin: -6px 0 0; + color: #64748b; + font-size: 12px; +} + +::ng-deep .schedule-mode-panel.mat-mdc-select-panel { + max-height: 360px; +} + .enabled-toggle { display: inline-flex; align-items: center; @@ -73,4 +89,9 @@ .schedule-form { min-width: 0; } + + .schedule-fields { + grid-template-columns: 1fr; + gap: 0; + } } diff --git a/webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.ts b/webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.ts index d8526b3a..fd0e08e2 100644 --- a/webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.ts +++ b/webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.ts @@ -1,6 +1,11 @@ import { CommonModule } from '@angular/common'; import { Component, inject } from '@angular/core'; -import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms'; +import { + FormControl, + FormGroup, + ReactiveFormsModule, + Validators, +} from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; import { MAT_DIALOG_DATA, @@ -10,6 +15,7 @@ import { import { MatFormFieldModule } from '@angular/material/form-field'; import { MatIconModule } from '@angular/material/icon'; import { MatInputModule } from '@angular/material/input'; +import { MatSelectModule } from '@angular/material/select'; import { BackgroundJobTask } from '../../../api'; export interface TaskScheduleDialogData { @@ -22,7 +28,86 @@ export interface TaskScheduleDialogResult { schedule: string | null; } +type ScheduleMode = + | 'manual' + | 'hourly' + | 'daily' + | 'weekly' + | 'monthly' + | 'advanced'; + +interface ScheduleValues { + mode: ScheduleMode; + minute: number; + time: string; + weekday: number; + monthDay: number; +} + const CRON_PATTERN = /^\S+\s+\S+\s+\S+\s+\S+\s+\S+$/; +const TIME_PATTERN = /^([01]\d|2[0-3]):([0-5]\d)$/; + +const WEEKDAYS = [ + { value: 1, label: 'Montag' }, + { value: 2, label: 'Dienstag' }, + { value: 3, label: 'Mittwoch' }, + { value: 4, label: 'Donnerstag' }, + { value: 5, label: 'Freitag' }, + { value: 6, label: 'Samstag' }, + { value: 0, label: 'Sonntag' }, +]; + +function parseSchedule(schedule: string | null): ScheduleValues { + const defaults: ScheduleValues = { + mode: 'manual', + minute: 0, + time: '03:00', + weekday: 1, + monthDay: 1, + }; + + if (!schedule) return defaults; + + let match = schedule.match(/^(\d{1,2}) \* \* \* \*$/); + if (match && Number(match[1]) <= 59) { + return { ...defaults, mode: 'hourly', minute: Number(match[1]) }; + } + + match = schedule.match(/^(\d{1,2}) (\d{1,2}) \* \* \*$/); + if (match && Number(match[1]) <= 59 && Number(match[2]) <= 23) { + return { + ...defaults, + mode: 'daily', + time: toTime(match[2], match[1]), + }; + } + + match = schedule.match(/^(\d{1,2}) (\d{1,2}) \* \* ([0-6])$/); + if (match && Number(match[1]) <= 59 && Number(match[2]) <= 23) { + return { + ...defaults, + mode: 'weekly', + time: toTime(match[2], match[1]), + weekday: Number(match[3]), + }; + } + + match = schedule.match(/^(\d{1,2}) (\d{1,2}) ([1-9]|[12]\d|3[01]) \* \*$/); + if (match && Number(match[1]) <= 59 && Number(match[2]) <= 23) { + return { + ...defaults, + mode: 'monthly', + time: toTime(match[2], match[1]), + monthDay: Number(match[3]), + }; + } + + return { ...defaults, mode: 'advanced' }; +} + +function toTime(hour: string, minute: string): string { + return `${hour.padStart(2, '0')}:${minute.padStart(2, '0')}`; +} @Component({ selector: 'app-task-schedule-dialog', @@ -34,6 +119,7 @@ const CRON_PATTERN = /^\S+\s+\S+\s+\S+\s+\S+\s+\S+$/; MatFormFieldModule, MatIconModule, MatInputModule, + MatSelectModule, ], templateUrl: './task-schedule-dialog.component.html', styleUrl: './task-schedule-dialog.component.scss', @@ -48,9 +134,30 @@ export class TaskScheduleDialogComponent { > >(MatDialogRef); protected readonly data = inject(MAT_DIALOG_DATA); + protected readonly weekdays = WEEKDAYS; + + private readonly initialSchedule = parseSchedule(this.data.task.schedule); protected readonly form = new FormGroup({ enabled: new FormControl(this.data.task.enabled, { nonNullable: true }), + mode: new FormControl(this.initialSchedule.mode, { + nonNullable: true, + }), + minute: new FormControl(this.initialSchedule.minute, { + nonNullable: true, + validators: [Validators.min(0), Validators.max(59)], + }), + time: new FormControl(this.initialSchedule.time, { + nonNullable: true, + validators: [Validators.pattern(TIME_PATTERN)], + }), + weekday: new FormControl(this.initialSchedule.weekday, { + nonNullable: true, + }), + monthDay: new FormControl(this.initialSchedule.monthDay, { + nonNullable: true, + validators: [Validators.min(1), Validators.max(31)], + }), cronExpression: new FormControl(this.data.task.schedule ?? '', { nonNullable: true, }), @@ -58,22 +165,70 @@ export class TaskScheduleDialogComponent { protected submit(): void { const value = this.form.getRawValue(); - const cron = value.cronExpression.trim(); + const schedule = this.buildSchedule(value); - if (cron && !CRON_PATTERN.test(cron)) { - this.form.controls.cronExpression.setErrors({ invalidCron: true }); - this.form.controls.cronExpression.markAsTouched(); - return; - } + if (schedule === undefined) return; this.dialogRef.close({ taskId: this.data.task.id, enabled: value.enabled, - schedule: cron || null, + schedule, }); } protected close(): void { this.dialogRef.close(); } + + protected formatNextRun(value: string): string { + const utcValue = /(?:Z|[+-]\d{2}:\d{2})$/.test(value) ? value : `${value}Z`; + return new Intl.DateTimeFormat('de-DE', { + day: '2-digit', + month: '2-digit', + year: 'numeric', + hour: '2-digit', + minute: '2-digit', + hour12: false, + timeZone: 'UTC', + }).format(new Date(utcValue)); + } + + private buildSchedule( + value: ReturnType, + ): string | null | undefined { + if (value.mode === 'manual') return null; + + if (value.mode === 'hourly') { + if (this.form.controls.minute.invalid) { + this.form.controls.minute.markAsTouched(); + return undefined; + } + return `${value.minute} * * * *`; + } + + if (['daily', 'weekly', 'monthly'].includes(value.mode)) { + if (this.form.controls.time.invalid) { + this.form.controls.time.markAsTouched(); + return undefined; + } + const [hour, minute] = value.time.split(':').map(Number); + if (value.mode === 'daily') return `${minute} ${hour} * * *`; + if (value.mode === 'weekly') { + return `${minute} ${hour} * * ${value.weekday}`; + } + if (this.form.controls.monthDay.invalid) { + this.form.controls.monthDay.markAsTouched(); + return undefined; + } + return `${minute} ${hour} ${value.monthDay} * *`; + } + + const cron = value.cronExpression.trim(); + if (!CRON_PATTERN.test(cron)) { + this.form.controls.cronExpression.setErrors({ invalidCron: true }); + this.form.controls.cronExpression.markAsTouched(); + return undefined; + } + return cron; + } } diff --git a/webapp/src/app/shared/ui/data-table/data-table.component.html b/webapp/src/app/shared/ui/data-table/data-table.component.html index babc2916..7a66be7b 100644 --- a/webapp/src/app/shared/ui/data-table/data-table.component.html +++ b/webapp/src/app/shared/ui/data-table/data-table.component.html @@ -7,7 +7,11 @@ multiTemplateDataRows> @for (col of columns(); track col.id) { - @if (col.type === 'accessor') { + @if (col.headerTemplate) { + + + + } @else if (col.type === 'accessor') { {{ col.header }} diff --git a/webapp/src/app/shared/ui/data-table/data-table.component.ts b/webapp/src/app/shared/ui/data-table/data-table.component.ts index 6fa71428..6be5c79e 100644 --- a/webapp/src/app/shared/ui/data-table/data-table.component.ts +++ b/webapp/src/app/shared/ui/data-table/data-table.component.ts @@ -25,6 +25,7 @@ export interface BaseColumn { id: string; header: string; type: 'accessor' | 'display' | 'group'; + headerTemplate?: TemplateRef; cellTemplate?: TemplateRef; } -- 2.56.1 From b9c4067250040d75659aa7aa052e08c78be53960 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Fri, 17 Jul 2026 14:35:20 +0200 Subject: [PATCH 25/60] fix(jobs): display UTC timestamps in local time --- .../job-logs-dialog.component.html | 2 +- .../job-logs-dialog/job-logs-dialog.component.ts | 3 ++- webapp/src/app/modules/jobs/jobs.component.html | 8 ++++---- webapp/src/app/modules/jobs/jobs.component.ts | 7 ++++++- webapp/src/app/modules/jobs/jobs.utils.ts | 13 +++++++++++++ .../task-schedule-dialog.component.html | 2 +- .../task-schedule-dialog.component.ts | 15 ++------------- 7 files changed, 29 insertions(+), 21 deletions(-) diff --git a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html index e4ed8771..663e69b8 100644 --- a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html +++ b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html @@ -21,7 +21,7 @@ @for (run of runs(); track run.id) { #{{ run.id }} · {{ statusMeta(run.status!).label }} · - {{ run.started_at | date: 'dd.MM.yyyy HH:mm' }} + {{ formatUtcDateAsLocal(run.started_at) }} @if (run.exit_code != null) { · Exit {{ run.exit_code }} } diff --git a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts index d6ccbcb8..78f5d948 100644 --- a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts +++ b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts @@ -14,7 +14,7 @@ import { MatSelectModule } from '@angular/material/select'; import { MatTooltipModule } from '@angular/material/tooltip'; import { finalize, timer } from 'rxjs'; import { BackgroundJobsService, BackgroundJobTask, JobRun } from '../../../api'; -import { statusMeta } from '../jobs.utils'; +import { formatUtcDateAsLocal, statusMeta } from '../jobs.utils'; export interface JobLogsDialogData { task: BackgroundJobTask; @@ -43,6 +43,7 @@ export class JobLogsDialogComponent implements OnInit { protected readonly data = inject(MAT_DIALOG_DATA); protected readonly statusMeta = statusMeta; + protected readonly formatUtcDateAsLocal = formatUtcDateAsLocal; protected readonly runs = signal([]); protected readonly runsLoading = signal(false); diff --git a/webapp/src/app/modules/jobs/jobs.component.html b/webapp/src/app/modules/jobs/jobs.component.html index 5c8926e9..2ecae548 100644 --- a/webapp/src/app/modules/jobs/jobs.component.html +++ b/webapp/src/app/modules/jobs/jobs.component.html @@ -60,9 +60,9 @@
{{ formatScheduleCron(row.schedule) }} @if (row.next_run_at) { - Nächster Lauf: {{ row.next_run_at | date: 'dd.MM.yyyy HH:mm' }} + + Nächster Lauf: {{ formatUtcDateAsLocal(row.next_run_at) }} + } {{ row.enabled ? 'Aktiv' : 'Inaktiv' }} @@ -86,7 +86,7 @@ @if (row.last_run) {
- {{ row.last_run.started_at | date: 'dd.MM.yyyy HH:mm' }} + {{ formatUtcDateAsLocal(row.last_run.started_at) }} @if (row.last_run.exit_code != null) { Exit-Code {{ row.last_run.exit_code }}[] = []; diff --git a/webapp/src/app/modules/jobs/jobs.utils.ts b/webapp/src/app/modules/jobs/jobs.utils.ts index 0ddc57dd..b3bc6a7f 100644 --- a/webapp/src/app/modules/jobs/jobs.utils.ts +++ b/webapp/src/app/modules/jobs/jobs.utils.ts @@ -39,6 +39,19 @@ export function formatScheduleCron(schedule: string | null): string { return schedule ? `Cron: ${schedule}` : 'Nur manuell'; } +export function formatUtcDateAsLocal(value: string | null | undefined): string { + if (!value) return ''; + const utcValue = /(?:Z|[+-]\d{2}:\d{2})$/.test(value) ? value : `${value}Z`; + return new Intl.DateTimeFormat('de-DE', { + day: '2-digit', + month: '2-digit', + year: 'numeric', + hour: '2-digit', + minute: '2-digit', + hour12: false, + }).format(new Date(utcValue)); +} + export function formatRunDuration(run: JobRun): string | null { if (!run.started_at || !run.finished_at) return null; const seconds = Math.max( diff --git a/webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.html b/webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.html index 7908c2f9..670be803 100644 --- a/webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.html +++ b/webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.html @@ -104,7 +104,7 @@ @if (data.task.next_run_at && form.controls.mode.value !== 'manual') {

Nächster geplanter Lauf: - {{ formatNextRun(data.task.next_run_at) }} Uhr UTC + {{ formatUtcDateAsLocal(data.task.next_run_at) }} Uhr

} diff --git a/webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.ts b/webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.ts index fd0e08e2..75549038 100644 --- a/webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.ts +++ b/webapp/src/app/modules/jobs/task-schedule-dialog/task-schedule-dialog.component.ts @@ -17,6 +17,7 @@ import { MatIconModule } from '@angular/material/icon'; import { MatInputModule } from '@angular/material/input'; import { MatSelectModule } from '@angular/material/select'; import { BackgroundJobTask } from '../../../api'; +import { formatUtcDateAsLocal } from '../jobs.utils'; export interface TaskScheduleDialogData { task: BackgroundJobTask; @@ -135,6 +136,7 @@ export class TaskScheduleDialogComponent { >(MatDialogRef); protected readonly data = inject(MAT_DIALOG_DATA); protected readonly weekdays = WEEKDAYS; + protected readonly formatUtcDateAsLocal = formatUtcDateAsLocal; private readonly initialSchedule = parseSchedule(this.data.task.schedule); @@ -180,19 +182,6 @@ export class TaskScheduleDialogComponent { this.dialogRef.close(); } - protected formatNextRun(value: string): string { - const utcValue = /(?:Z|[+-]\d{2}:\d{2})$/.test(value) ? value : `${value}Z`; - return new Intl.DateTimeFormat('de-DE', { - day: '2-digit', - month: '2-digit', - year: 'numeric', - hour: '2-digit', - minute: '2-digit', - hour12: false, - timeZone: 'UTC', - }).format(new Date(utcValue)); - } - private buildSchedule( value: ReturnType, ): string | null | undefined { -- 2.56.1 From b22f16809db669e7fafbea841aa2403000ffef41 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Fri, 17 Jul 2026 14:45:46 +0200 Subject: [PATCH 26/60] feat(jobs): add job deletion with confirmation --- .../src/app/modules/jobs/jobs.component.html | 21 +++++ .../src/app/modules/jobs/jobs.component.scss | 4 + webapp/src/app/modules/jobs/jobs.component.ts | 81 +++++++++++++++++-- .../confirmation-dialog.component.scss | 2 + 4 files changed, 100 insertions(+), 8 deletions(-) diff --git a/webapp/src/app/modules/jobs/jobs.component.html b/webapp/src/app/modules/jobs/jobs.component.html index 2ecae548..dd974e7b 100644 --- a/webapp/src/app/modules/jobs/jobs.component.html +++ b/webapp/src/app/modules/jobs/jobs.component.html @@ -154,5 +154,26 @@ (click)="openScheduleDialog(row)"> edit_calendar +
diff --git a/webapp/src/app/modules/jobs/jobs.component.scss b/webapp/src/app/modules/jobs/jobs.component.scss index a7f3598b..ca8c94e5 100644 --- a/webapp/src/app/modules/jobs/jobs.component.scss +++ b/webapp/src/app/modules/jobs/jobs.component.scss @@ -200,6 +200,10 @@ mat-paginator { gap: 4px; } +.delete-action:not(:disabled) { + color: #b91c1c; +} + .actions-header { display: grid; grid-template-columns: 40px 1fr 40px; diff --git a/webapp/src/app/modules/jobs/jobs.component.ts b/webapp/src/app/modules/jobs/jobs.component.ts index ed047dd3..3c0058cf 100644 --- a/webapp/src/app/modules/jobs/jobs.component.ts +++ b/webapp/src/app/modules/jobs/jobs.component.ts @@ -71,6 +71,7 @@ export class JobsComponent implements OnInit { protected readonly tasks = signal([]); protected readonly dockerHealth = signal(null); protected readonly dockerHealthLoading = signal(false); + protected readonly deletingTaskIds = signal>(new Set()); protected readonly statusMeta = statusMeta; protected readonly formatScheduleCron = formatScheduleCron; @@ -182,8 +183,8 @@ export class JobsComponent implements OnInit { })); this.snackBar.open(`„${task.name}“ wurde gestartet.`, 'OK', { duration: 3000, - horizontalPosition: 'right', - verticalPosition: 'top', + horizontalPosition: 'center', + verticalPosition: 'bottom', }); this.refreshTasks(); }, @@ -220,8 +221,8 @@ export class JobsComponent implements OnInit { : `„${task.name}“ war bereits beendet.`; this.snackBar.open(message, 'OK', { duration: 3000, - horizontalPosition: 'right', - verticalPosition: 'top', + horizontalPosition: 'center', + verticalPosition: 'bottom', }); this.refreshTasks(); }, @@ -278,8 +279,8 @@ export class JobsComponent implements OnInit { this.updateTask(result.taskId, () => updatedTask); this.snackBar.open('Zeitplan wurde gespeichert.', 'OK', { duration: 3000, - horizontalPosition: 'right', - verticalPosition: 'top', + horizontalPosition: 'center', + verticalPosition: 'bottom', }); }, error: (error) => @@ -291,6 +292,34 @@ export class JobsComponent implements OnInit { }); } + protected confirmDeleteTask(task: BackgroundJobTask): void { + if ( + ['running', 'stopping'].includes(task.status) || + this.deletingTaskIds().has(task.id) + ) { + return; + } + + import('../../shared/ui/confirmation-dialog/confirmation-dialog.component').then( + ({ ConfirmationDialogComponent }) => { + const dialogRef = this.dialog.open(ConfirmationDialogComponent, { + width: '520px', + maxWidth: 'calc(100vw - 32px)', + data: { + title: 'Job löschen', + message: `Möchtest Du „${task.name}“ wirklich löschen? Alle Laufdaten und gespeicherten Logs werden dauerhaft gelöscht.`, + confirmText: 'Löschen', + cancelText: 'Abbrechen', + }, + }); + + dialogRef.afterClosed().subscribe((confirmed) => { + if (confirmed) this.deleteTask(task); + }); + }, + ); + } + private updateTask( id: number, updater: (task: BackgroundJobTask) => BackgroundJobTask, @@ -300,6 +329,42 @@ export class JobsComponent implements OnInit { ); } + private deleteTask(task: BackgroundJobTask): void { + this.deletingTaskIds.update((ids) => new Set(ids).add(task.id)); + + this.backgroundJobsService.deleteBackgroundJobTask(task.id).subscribe({ + next: () => { + this.finishDeletingTask(task.id); + this.tasks.update((tasks) => + tasks.filter((current) => current.id !== task.id), + ); + this.snackBar.open(`„${task.name}“ wurde gelöscht.`, 'OK', { + duration: 3000, + horizontalPosition: 'center', + verticalPosition: 'bottom', + }); + this.refreshTasks(); + }, + error: (error) => { + this.finishDeletingTask(task.id); + this.showError( + error.status === 409 + ? `„${task.name}“ läuft noch und kann nicht gelöscht werden.` + : `„${task.name}“ konnte nicht gelöscht werden.`, + ); + this.refreshTasks(); + }, + }); + } + + private finishDeletingTask(taskId: number): void { + this.deletingTaskIds.update((ids) => { + const updated = new Set(ids); + updated.delete(taskId); + return updated; + }); + } + private setTasksPreservingPendingStops(tasks: BackgroundJobTask[]): void { this.tasks.set( tasks.map((task) => @@ -313,8 +378,8 @@ export class JobsComponent implements OnInit { private showError(message: string): void { this.snackBar.open(message, 'OK', { duration: 5000, - horizontalPosition: 'right', - verticalPosition: 'top', + horizontalPosition: 'center', + verticalPosition: 'bottom', }); } } diff --git a/webapp/src/app/shared/ui/confirmation-dialog/confirmation-dialog.component.scss b/webapp/src/app/shared/ui/confirmation-dialog/confirmation-dialog.component.scss index 1dd84db8..a459ffda 100644 --- a/webapp/src/app/shared/ui/confirmation-dialog/confirmation-dialog.component.scss +++ b/webapp/src/app/shared/ui/confirmation-dialog/confirmation-dialog.component.scss @@ -1,4 +1,6 @@ .action { + justify-content: center; + button { min-width: 150px; } -- 2.56.1 From 4bd4a015f16145cf9bb3ccea925f344e6f6bc68a Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 20 Jul 2026 22:17:31 +0200 Subject: [PATCH 27/60] refactor(jobs): remove job definition seeding --- service/src/main/inse/background_jobs/seed.py | 80 ------------------- service/src/main/inse/main.py | 2 - 2 files changed, 82 deletions(-) delete mode 100644 service/src/main/inse/background_jobs/seed.py diff --git a/service/src/main/inse/background_jobs/seed.py b/service/src/main/inse/background_jobs/seed.py deleted file mode 100644 index 2b26d3f8..00000000 --- a/service/src/main/inse/background_jobs/seed.py +++ /dev/null @@ -1,80 +0,0 @@ -""" -Seeding of the predefined background job definitions. -""" - -import logging - -from sqlmodel import Session, select - -from .model import JobDefinition - -logger = logging.getLogger(__name__) - -PREDEFINED_JOBS: list[dict] = [ - { - "name": "News-Crawler (Testlauf, ohne Upload)", - "description": ( - "Crawlt die UDE-„aktuell“-Seiten mit Scrapy und legt die Artikel nur " - "als JSON im Container ab. Der Upload-Schritt ist abgeschaltet, es " - "wird nichts nach Elasticsearch geschrieben. Begrenzt auf wenige " - "Artikel, da ein vollständiger Crawl mehrere Stunden dauert." - ), - "target_index": "-", - "command": "news-crawl", - }, - { - "name": "Projekt-Themen-Mapping (Testlauf, Dry-Run)", - "description": ( - "Ordnet die Schlagwörter der Bund-Projekte über die Topic-Vektorsuche " - "des Backends OpenAlex-Themen zu. Läuft als Dry-Run (--dry-run): liest " - "nur aus dem Quellindex und schreibt nichts nach Elasticsearch. " - "Benötigt ein erreichbares Backend und INSE-Elasticsearch-Zugang." - ), - "target_index": "-", - "command": "project-topics", - }, - { - "name": "Bund-Crawler (Testlauf, ohne Upload)", - "description": ( - "Lädt den Projekt-Export des Bund-Förderportals via Headless-Chrome " - "herunter und formatiert ihn. Läuft mit --skip-upload: es wird nichts " - "nach Elasticsearch geschrieben. Startet einen echten Browser-Crawl " - "von foerderportal.bund.de und kann daher länger dauern." - ), - "target_index": "-", - "command": "bund-crawl", - }, - { - "name": "Demo-Job A", - "description": "Testjob für Demos: läuft ca. 20 Sekunden, schreibt " - "Fortschritt ins Log und verändert nichts.", - "target_index": "-", - "command": "demo-a", - }, - { - "name": "Demo-Job B", - "description": "Testjob für Demos: läuft ca. 25 Sekunden, schreibt " - "Fortschritt ins Log und verändert nichts.", - "target_index": "-", - "command": "demo-b", - }, - { - "name": "Demo-Job C", - "description": "Testjob für Demos: läuft ca. 30 Sekunden, schreibt " - "Fortschritt ins Log und verändert nichts.", - "target_index": "-", - "command": "demo-c", - }, -] - - -def create_predefined_job_definitions(session: Session) -> None: - for entry in PREDEFINED_JOBS: - existing = session.exec( - select(JobDefinition).where(JobDefinition.name == entry["name"]) - ).first() - if existing: - continue - session.add(JobDefinition(**entry)) - logger.info("Seeded background job definition '%s'.", entry["name"]) - session.commit() diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index 51f6d805..c725edec 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -46,7 +46,6 @@ from inse.database import create_db_and_tables, get_session from inse.auth.service import create_predefined_accounts from inse.background_jobs.router import router as background_jobs_router from inse.background_jobs.runner import scheduler_loop as background_jobs_scheduler_loop -from inse.background_jobs.seed import create_predefined_job_definitions from . import config from .service import router as service_router @@ -72,7 +71,6 @@ async def lifespan(app: FastAPI): create_db_and_tables() with contextmanager(get_session)() as session: create_predefined_accounts(session, "../data/predefined_accounts.json") - create_predefined_job_definitions(session) background_jobs_scheduler_task = None if settings.background_jobs_scheduler_enabled: -- 2.56.1 From 755f83f65ae2733dfa3e3e57a4f67aba0729819d Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 20 Jul 2026 22:17:35 +0200 Subject: [PATCH 28/60] refactor(jobs): simplify create-dialog to free-text command --- .../src/app/modules/jobs/jobs.component.html | 8 ++ webapp/src/app/modules/jobs/jobs.component.ts | 24 ++++ .../task-create-dialog.component.html | 74 ++++++++++++ .../task-create-dialog.component.scss | 32 +++++ .../task-create-dialog.component.ts | 112 ++++++++++++++++++ 5 files changed, 250 insertions(+) create mode 100644 webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.html create mode 100644 webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.scss create mode 100644 webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.ts diff --git a/webapp/src/app/modules/jobs/jobs.component.html b/webapp/src/app/modules/jobs/jobs.component.html index dd974e7b..4909b602 100644 --- a/webapp/src/app/modules/jobs/jobs.component.html +++ b/webapp/src/app/modules/jobs/jobs.component.html @@ -7,6 +7,14 @@ ausführen oder per Cron-Zeitplan automatisieren.

+ diff --git a/webapp/src/app/modules/jobs/jobs.component.ts b/webapp/src/app/modules/jobs/jobs.component.ts index 3c0058cf..9a97abfb 100644 --- a/webapp/src/app/modules/jobs/jobs.component.ts +++ b/webapp/src/app/modules/jobs/jobs.component.ts @@ -41,6 +41,7 @@ import { JobLogsDialogComponent, JobLogsDialogData, } from './job-logs-dialog/job-logs-dialog.component'; +import { TaskCreateDialogComponent } from './task-create-dialog/task-create-dialog.component'; @Component({ selector: 'app-jobs', @@ -255,6 +256,29 @@ export class JobsComponent implements OnInit { ); } + protected openCreateDialog(): void { + const dialogRef = this.dialog.open< + TaskCreateDialogComponent, + void, + BackgroundJobTask | undefined + >(TaskCreateDialogComponent, { + width: '560px', + maxWidth: 'calc(100vw - 32px)', + }); + + dialogRef.afterClosed().subscribe((task) => { + if (!task) return; + + this.tasks.update((tasks) => [...tasks, task]); + this.snackBar.open(`„${task.name}“ wurde angelegt.`, 'OK', { + duration: 3000, + horizontalPosition: 'center', + verticalPosition: 'bottom', + }); + this.refreshTasks(); + }); + } + protected openScheduleDialog(task: BackgroundJobTask): void { const dialogRef = this.dialog.open< TaskScheduleDialogComponent, diff --git a/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.html b/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.html new file mode 100644 index 00000000..b58885f6 --- /dev/null +++ b/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.html @@ -0,0 +1,74 @@ +

Neuer Job

+ + +
+ + Name + + @if (form.controls.name.invalid) { + Bitte einen Namen eingeben. + } + + + + Befehl (optional) + + Der Befehl, den der Container ausführt. Leer = Standard-Entrypoint des + Images. + + + + Image (optional) + + Docker-Image (Standard: + docker.nes.uni-due.de/inse/background-jobs:latest). + + + + Beschreibung + + + + + Ziel-Index (optional) + + Elasticsearch-Index, in den der Job schreibt (Anzeige). + + + + Umgebungsvariablen (optional) + + Eine Variable pro Zeile im Format KEY=value. + @if (form.controls.env.hasError('invalidEnv')) { + Ungültige Zeile — Format: KEY=value. + } + +
+ + @if (serverError()) { +

{{ serverError() }}

+ } +
+ + + + + diff --git a/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.scss b/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.scss new file mode 100644 index 00000000..dc8f0bda --- /dev/null +++ b/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.scss @@ -0,0 +1,32 @@ +.create-form { + display: flex; + flex-direction: column; + gap: 12px; + min-width: 400px; +} + +.commands-loading { + display: flex; + align-items: center; + gap: 8px; + color: #64748b; + font-size: 14px; +} + +.field-hint { + margin: -6px 0 0; + color: #64748b; + font-size: 12px; +} + +.server-error { + margin: 8px 0 0; + color: #b3261e; + font-size: 14px; +} + +@media (max-width: 640px) { + .create-form { + min-width: 0; + } +} diff --git a/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.ts b/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.ts new file mode 100644 index 00000000..a48d43ba --- /dev/null +++ b/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.ts @@ -0,0 +1,112 @@ +import { CommonModule } from '@angular/common'; +import { Component, inject, signal } from '@angular/core'; +import { + FormControl, + FormGroup, + ReactiveFormsModule, + Validators, +} from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { MatDialogModule, MatDialogRef } from '@angular/material/dialog'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatIconModule } from '@angular/material/icon'; +import { MatInputModule } from '@angular/material/input'; +import { BackgroundJobTask, BackgroundJobsService } from '../../../api'; + +const ENV_LINE_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*=.*$/; + +@Component({ + selector: 'app-task-create-dialog', + imports: [ + CommonModule, + ReactiveFormsModule, + MatButtonModule, + MatDialogModule, + MatFormFieldModule, + MatIconModule, + MatInputModule, + ], + templateUrl: './task-create-dialog.component.html', + styleUrl: './task-create-dialog.component.scss', + standalone: true, +}) +export class TaskCreateDialogComponent { + private readonly dialogRef = + inject< + MatDialogRef + >(MatDialogRef); + private readonly backgroundJobsService = inject(BackgroundJobsService); + + protected readonly creating = signal(false); + protected readonly serverError = signal(''); + + protected readonly form = new FormGroup({ + name: new FormControl('', { + nonNullable: true, + validators: [Validators.required], + }), + description: new FormControl('', { nonNullable: true }), + targetIndex: new FormControl('', { nonNullable: true }), + command: new FormControl('', { nonNullable: true }), + image: new FormControl('', { nonNullable: true }), + env: new FormControl('', { nonNullable: true }), + }); + + protected submit(): void { + this.serverError.set(''); + const value = this.form.getRawValue(); + + const name = value.name.trim(); + if (!name) { + this.form.controls.name.markAsTouched(); + return; + } + + const command = value.command.trim() || null; + const env = this.parseEnv(value.env); + if (env === undefined) return; + + this.creating.set(true); + this.backgroundJobsService + .createBackgroundJobTask({ + name, + description: value.description.trim(), + target_index: value.targetIndex.trim(), + image: value.image.trim() || null, + command, + env, + }) + .subscribe({ + next: (task) => this.dialogRef.close(task), + error: (error) => { + this.creating.set(false); + const detail = error?.error?.detail; + this.serverError.set( + typeof detail === 'string' + ? detail + : 'Der Job konnte nicht angelegt werden.', + ); + }, + }); + } + + protected close(): void { + this.dialogRef.close(); + } + + private parseEnv(text: string): { [key: string]: string } | undefined { + const env: { [key: string]: string } = {}; + for (const line of text.split('\n')) { + const trimmed = line.trim(); + if (!trimmed) continue; + if (!ENV_LINE_PATTERN.test(trimmed)) { + this.form.controls.env.setErrors({ invalidEnv: true }); + this.form.controls.env.markAsTouched(); + return undefined; + } + const separatorIndex = trimmed.indexOf('='); + env[trimmed.slice(0, separatorIndex)] = trimmed.slice(separatorIndex + 1); + } + return env; + } +} -- 2.56.1 From cb5a887d12b8eb3a7844d7bd47cfa03109a696ea Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 20 Jul 2026 22:17:37 +0200 Subject: [PATCH 29/60] docs(background-jobs): update readme --- background-jobs/README.md | 92 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 background-jobs/README.md diff --git a/background-jobs/README.md b/background-jobs/README.md new file mode 100644 index 00000000..47d714ba --- /dev/null +++ b/background-jobs/README.md @@ -0,0 +1,92 @@ +# Background Jobs + +Background Jobs sind Docker-Container, die regelmäßig oder manuell Elasticsearch-Daten verarbeiten. Sie werden vom Backend über den Docker-Socket gestartet. + +**Wichtig:** Jobs sind in der **Datenbank**, nicht im Image. Das Image enthält nur die ausführbaren Skripte. + +## Jobs anlegen + +**Frontend** (`/jobs`): + +- "Neuer Job" → Name + Command + optionales Image + Zeitplan + +**API**: + +```bash +curl -X POST -H "Authorization: Bearer $TOKEN" \ + -d '{"name": "Sync", "command": "python sync.py --sync-delta", "schedule": "0 3 * * *"}' \ + http://localhost:8000/api/background-jobs/tasks +``` + +Command-Beispiele: + +``` +python sync.py --sync-delta +python news/ude/run_pipeline.py --skip-upload +python -m service.scripts.projects.topic_mapper.map_project_topics --dry-run +``` + +**Neue Jobs = kein Image-Rebuild.** Die Skripte sind bereits im Image; der Command wird direkt an Docker übergeben. + +## Image & Dockerfile + +Das [Dockerfile](./Dockerfile) enthält die Skripte (sync.py, news/, projects/, etc.) und hat keine ENTRYPOINT. Der Backend startet Container direkt: + +```python +docker.run(image="...", command="python sync.py --sync-delta") +``` + +**Nur Skripte hinzufügen?** → Image neu bauen + pushen: + +```bash +docker build -f background-jobs/Dockerfile -t docker.nes.uni-due.de/inse/background-jobs:latest . +docker push docker.nes.uni-due.de/inse/background-jobs:latest +``` + +Lokal testen ohne Pull: + +```bash +export INSE_BACKGROUND_JOBS_PULL_BEFORE_RUN=false +``` + +## Scheduling + +Job mit `schedule: "0 3 * * *"` und `enabled: true` läuft automatisch täglich um 3:00 UTC. Manuell starten: "Jetzt ausführen" Button oder API. + +## Logs + +Während Laufzeit: Live vom Container. Nach Beendigung: Letzte 200 Zeilen in der DB. Frontend: "Logs anzeigen" Button. + +## Docker-Socket (Deployment) + +```yaml +# docker-compose +backend: + volumes: + - /var/run/docker.sock:/var/run/docker.sock +``` + +Ohne Socket-Mount funktioniert nichts. + +## Env-Variablen + +Standard-Image erhält automatisch: + +- `INSE_ELASTIC_URL`, `INSE_ELASTIC_API_KEY` +- `INSE_LLM_*`, `ELASTICSEARCH_INSE_*`, `SENTENCE_TRANSFORMERS_MODEL_NAME` + +Plus `env` aus der Job-Definition. + +**Eigene Images** bekommen nur die `env`-Variablen (Sicherheit). + +## API + +- `GET /api/background-jobs/tasks` — Jobs auflisten +- `POST /api/background-jobs/tasks` — Job anlegen +- `DELETE /api/background-jobs/tasks/{id}` — Job löschen +- `POST /api/background-jobs/tasks/{id}/run` — Run starten +- `PATCH /api/background-jobs/tasks/{id}` — Schedule ändern +- `GET /api/background-jobs/runs/{id}/logs` — Logs abrufen +- `POST /api/background-jobs/runs/{id}/stop` — Run stoppen + +Alle Endpoints erfordern Superadmin-Auth. -- 2.56.1 From 712fcbb7499c3f726d204e282ff147686e475a30 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Mon, 20 Jul 2026 22:17:52 +0200 Subject: [PATCH 30/60] refactor(background-jobs): remove entrypoint.sh and discovery --- background-jobs/Dockerfile | 6 ---- background-jobs/entrypoint.sh | 53 ----------------------------------- 2 files changed, 59 deletions(-) delete mode 100644 background-jobs/entrypoint.sh diff --git a/background-jobs/Dockerfile b/background-jobs/Dockerfile index 68f19974..540a7397 100644 --- a/background-jobs/Dockerfile +++ b/background-jobs/Dockerfile @@ -25,9 +25,3 @@ COPY service/scripts/projects/topic_mapper/ ./service/scripts/projects/topic_map # The bund foerderportal crawler (runs with its own dir as cwd for its JSON configs). COPY service/scripts/projects/bund/ ./projects/bund/ - -# Small dispatcher that maps a job name to the right command. -COPY background-jobs/entrypoint.sh /entrypoint.sh -RUN chmod +x /entrypoint.sh - -ENTRYPOINT ["/entrypoint.sh"] diff --git a/background-jobs/entrypoint.sh b/background-jobs/entrypoint.sh deleted file mode 100644 index 5f1f4d52..00000000 --- a/background-jobs/entrypoint.sh +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env sh -# Job dispatcher for the preprocessing worker. -# Usage: e.g. docker run news -set -eu - -JOB="${1:-}" - -case "$JOB" in - news) - # Enrich new 'aktuell' articles into 'aktuell_postproc' (relevance, authors, keywords). - exec python sync.py --sync-delta - ;; - news-stats) - # Print counts for the aktuell / aktuell_postproc indices (read-only). - exec python sync.py --stats - ;; - news-crawl) - # Crawl UDE 'aktuell' into JSON only. --skip-upload keeps Elasticsearch untouched. - exec python news/ude/run_pipeline.py --skip-upload --max-items "${NEWS_CRAWL_MAX_ITEMS:-5}" - ;; - bund-crawl) - # Crawl the bund foerderportal export via headless Chrome. --skip-upload keeps ES untouched. - cd projects/bund || exit 1 - exec python gpc.data.py --skip-upload - ;; - project-topics) - # Map bund-project keywords to OpenAlex topics. --dry-run reads only, writes nothing. - exec python -m service.scripts.projects.topic_mapper.map_project_topics \ - --dry-run \ - --max-docs "${PROJECT_TOPICS_MAX_DOCS:-50}" \ - --source-index projects_bund_v1 \ - --text-field Leistungsplansystematik_fullname \ - --output-index projects_bund_openalex_topics \ - --api-base-url "${PROJECT_TOPICS_API_BASE_URL:-http://host.docker.internal:8000}" - ;; - demo-a) - exec python demo.py 20 - ;; - demo-b) - exec python demo.py 25 - ;; - demo-c) - exec python demo.py 30 - ;; - "") - echo "No job given. Available jobs: news, news-stats, news-crawl, project-topics, bund-crawl, demo-a, demo-b, demo-c" >&2 - exit 2 - ;; - *) - echo "Unknown job: $JOB. Available jobs: news, news-stats, news-crawl, project-topics, bund-crawl, demo-a, demo-b, demo-c" >&2 - exit 2 - ;; -esac -- 2.56.1 From 8db323d605b0f274817be368c18b6799e03fc528 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Mon, 20 Jul 2026 23:43:33 +0200 Subject: [PATCH 31/60] feat(news): store matched topics in aktuell_postproc and switch to topic batch mapping --- service/src/main/inse/news/logic.py | 122 +++++++++++++++++++--------- 1 file changed, 85 insertions(+), 37 deletions(-) diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index 3ced9bf5..42eedb57 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -12,7 +12,7 @@ from inse.exceptions import ElasticsearchException from ..integrations import elasticsearch, llm from ..persons.logic import find_ude_author_by_name, get_author_name_by_id -from ..topics.logic import vector_search_topics +from ..topics.logic import vector_search_topics_batch from .model import MatchedTopic, MentionedPerson, NewsArticle, NewsArticleDetail, NewsPage logger = logging.getLogger(__name__) @@ -21,7 +21,6 @@ TOPIC_LIMIT = 4 TOPIC_QUERY_CONTENT_CHARS = 300 TOPIC_NUM_CANDIDATES = 100 TOPIC_SIMILARITY = 0.5 -TOPIC_MATCHES_PER_KEYWORD = 1 KEYWORD_LIMIT = 6 KEYWORD_CONTENT_CHARS = 4000 @@ -252,15 +251,17 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail: source = response.get("_source", {}) - relevant, authors, cached_keywords, postproc_id = await _get_postproc_labels(news_id) - keywords = await _get_article_keywords( + relevant, authors, cached_keywords, cached_topics, postproc_id = await _get_postproc_labels( + news_id + ) + keywords, postproc_id = await _get_article_keywords( news_id, postproc_id, cached_keywords, source.get("maintitle"), source.get("full_content"), ) - topics = await _match_topics_for_keywords(keywords) + topics = await _get_article_topics(news_id, postproc_id, cached_topics, keywords) return NewsArticleDetail( id=response.get("_id"), @@ -282,15 +283,15 @@ async def _get_article_keywords( cached_keywords: list, maintitle: str | None, full_content: str | None, -) -> list: +) -> tuple[list, str | None]: if cached_keywords: - return cached_keywords + return cached_keywords, postproc_id text = " ".join( part for part in (maintitle, (full_content or "")[:KEYWORD_CONTENT_CHARS]) if part ).strip() if not text: - return [] + return [], postproc_id raw = llm.call( system_prompt=KEYWORD_SYSTEM_PROMPT, @@ -300,9 +301,26 @@ async def _get_article_keywords( keywords = _parse_keywords(raw) if keywords: - await _store_keywords(news_id, postproc_id, keywords) + postproc_id = await _store_keywords(news_id, postproc_id, keywords) - return keywords + return keywords, postproc_id + + +async def _get_article_topics( + news_id: str, + postproc_id: str | None, + cached_topics: list, + keywords: list, +) -> list: + if cached_topics: + return [MatchedTopic(**topic) for topic in cached_topics] + + topics = await _match_topics_for_keywords(keywords) + + if topics: + await _store_topics(news_id, postproc_id, topics) + + return topics def _parse_keywords(raw: str) -> list: @@ -330,7 +348,8 @@ def _parse_keywords(raw: str) -> list: return keywords[:KEYWORD_LIMIT] -async def _store_keywords(news_id: str, postproc_id: str | None, keywords: list) -> None: +async def _store_keywords(news_id: str, postproc_id: str | None, keywords: list) -> str | None: + """Caches the keywords and returns the postproc document id they landed in.""" try: if postproc_id: await elasticsearch.update( @@ -339,42 +358,70 @@ async def _store_keywords(news_id: str, postproc_id: str | None, keywords: list) doc={"keywords": keywords}, cluster="inse", ) + return postproc_id + + await elasticsearch.index_doc( + index="aktuell_postproc", + doc_id=news_id, + document={"news_id": news_id, "keywords": keywords}, + cluster="inse", + ) + return news_id + except Exception: + logger.exception(f"Failed to cache keywords for {news_id}.") + return postproc_id + + +async def _store_topics(news_id: str, postproc_id: str | None, topics: list) -> None: + documents = [topic.model_dump() for topic in topics] + + try: + if postproc_id: + await elasticsearch.update( + index="aktuell_postproc", + doc_id=postproc_id, + doc={"topics": documents}, + cluster="inse", + ) else: await elasticsearch.index_doc( index="aktuell_postproc", doc_id=news_id, - document={"news_id": news_id, "keywords": keywords}, + document={"news_id": news_id, "topics": documents}, cluster="inse", ) except Exception: - logger.exception(f"Failed to cache keywords for {news_id}.") + logger.exception(f"Failed to cache topics for {news_id}.") async def _match_topics_for_keywords(keywords: list) -> list: + if not keywords: + return [] + + try: + response = await vector_search_topics_batch(keywords=keywords) + except Exception: + logger.exception(f"Topic-Matching fuer {len(keywords)} Keywords fehlgeschlagen.") + return [] + matched = [] seen_ids = set() - for keyword in keywords: - try: - response = await vector_search_topics(query=keyword, limit=TOPIC_MATCHES_PER_KEYWORD) - except Exception: - logger.exception(f"Topic-Matching fuer Keyword '{keyword}' fehlgeschlagen.") + for match in response.results or []: + topic = match.topic + if not topic or not topic.id or topic.id in seen_ids: continue - - for topic in response.results or []: - if not topic.id or topic.id in seen_ids: - continue - seen_ids.add(topic.id) - matched.append( - MatchedTopic( - id=topic.id, - display_name=topic.display_name, - subfield_name=topic.subfield.display_name if topic.subfield else None, - field_name=topic.var_field.display_name if topic.var_field else None, - domain_name=topic.domain.display_name if topic.domain else None, - source_keyword=keyword, - ) + seen_ids.add(topic.id) + matched.append( + MatchedTopic( + id=topic.id, + display_name=topic.display_name, + subfield_name=topic.subfield.display_name if topic.subfield else None, + field_name=topic.var_field.display_name if topic.var_field else None, + domain_name=topic.domain.display_name if topic.domain else None, + source_keyword=match.keyword, ) + ) return matched @@ -428,30 +475,31 @@ async def _build_mentioned_persons(author_names: list) -> list: return ude_persons + other_persons -async def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, str | None]: +async def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, list, str | None]: try: response = await elasticsearch.search( index="aktuell_postproc", query={"term": {"news_id.keyword": news_id}}, - source=["relevant", "authors", "keywords"], + source=["relevant", "authors", "keywords", "topics"], size=1, cluster="inse", ) except Exception: logger.exception(f"Postproc-Lookup for {news_id} failed.") - return None, [], [], None + return None, [], [], [], None hits = response.get("hits", {}).get("hits", []) if not hits: - return None, [], [], None + return None, [], [], [], None hit = hits[0] postproc_source = hit.get("_source", {}) relevant = bool(postproc_source.get("relevant", 0)) authors = postproc_source.get("authors") or [] keywords = postproc_source.get("keywords") or [] + topics = postproc_source.get("topics") or [] - return relevant, authors, keywords, hit.get("_id") + return relevant, authors, keywords, topics, hit.get("_id") async def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict: -- 2.56.1 From 807adbd6e410f1ce2812fe0f876933cfda720d3b Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Tue, 21 Jul 2026 00:28:18 +0200 Subject: [PATCH 32/60] feat(jobs): add news topic-mapping as background job --- background-jobs/Dockerfile | 3 + background-jobs/entrypoint.sh | 19 +- service/scripts/news/topic_mapper/README.md | 79 +++++ .../news/topic_mapper/map_news_topics.py | 329 ++++++++++++++++++ .../scripts/news/topic_mapper/news_mapping.py | 30 ++ .../news/topic_mapper/requirements.txt | 2 + service/src/main/inse/background_jobs/seed.py | 24 +- 7 files changed, 483 insertions(+), 3 deletions(-) create mode 100644 service/scripts/news/topic_mapper/README.md create mode 100644 service/scripts/news/topic_mapper/map_news_topics.py create mode 100644 service/scripts/news/topic_mapper/news_mapping.py create mode 100644 service/scripts/news/topic_mapper/requirements.txt diff --git a/background-jobs/Dockerfile b/background-jobs/Dockerfile index 68f19974..e80b739f 100644 --- a/background-jobs/Dockerfile +++ b/background-jobs/Dockerfile @@ -23,6 +23,9 @@ COPY service/scripts/news/ude/ ./news/ude/ # The project topic-mapper keeps its package path so its absolute import resolves. COPY service/scripts/projects/topic_mapper/ ./service/scripts/projects/topic_mapper/ +# The news topic-mapper imports the project topic-mapper, so it keeps its path too. +COPY service/scripts/news/topic_mapper/ ./service/scripts/news/topic_mapper/ + # The bund foerderportal crawler (runs with its own dir as cwd for its JSON configs). COPY service/scripts/projects/bund/ ./projects/bund/ diff --git a/background-jobs/entrypoint.sh b/background-jobs/entrypoint.sh index 5f1f4d52..8eebef41 100644 --- a/background-jobs/entrypoint.sh +++ b/background-jobs/entrypoint.sh @@ -33,6 +33,21 @@ case "$JOB" in --output-index projects_bund_openalex_topics \ --api-base-url "${PROJECT_TOPICS_API_BASE_URL:-http://host.docker.internal:8000}" ;; + news-keywords) + # Extract news keywords with the LLM. Writes to the docker test index, so + # 'aktuell_postproc' stays untouched. + exec python sync.py --update-keywords \ + --target-index "${NEWS_KEYWORDS_TARGET_INDEX:-docker-job_test}" \ + --limit "${NEWS_KEYWORDS_LIMIT:-50}" \ + --threads "${NEWS_KEYWORDS_THREADS:-4}" + ;; + news-topics) + # Map the keywords of enriched news articles to OpenAlex topics. + exec python -m service.scripts.news.topic_mapper.map_news_topics \ + --output-index "${NEWS_TOPICS_OUTPUT_INDEX:-docker-job_test}" \ + --max-docs "${NEWS_TOPICS_MAX_DOCS:-50}" \ + --api-base-url "${PROJECT_TOPICS_API_BASE_URL:-http://host.docker.internal:8000}" + ;; demo-a) exec python demo.py 20 ;; @@ -43,11 +58,11 @@ case "$JOB" in exec python demo.py 30 ;; "") - echo "No job given. Available jobs: news, news-stats, news-crawl, project-topics, bund-crawl, demo-a, demo-b, demo-c" >&2 + echo "No job given. Available jobs: news, news-stats, news-crawl, news-keywords, news-topics, project-topics, bund-crawl, demo-a, demo-b, demo-c" >&2 exit 2 ;; *) - echo "Unknown job: $JOB. Available jobs: news, news-stats, news-crawl, project-topics, bund-crawl, demo-a, demo-b, demo-c" >&2 + echo "Unknown job: $JOB. Available jobs: news, news-stats, news-crawl, news-keywords, news-topics, project-topics, bund-crawl, demo-a, demo-b, demo-c" >&2 exit 2 ;; esac diff --git a/service/scripts/news/topic_mapper/README.md b/service/scripts/news/topic_mapper/README.md new file mode 100644 index 00000000..213df178 --- /dev/null +++ b/service/scripts/news/topic_mapper/README.md @@ -0,0 +1,79 @@ +# News → OpenAlex topic mapping + +Batch counterpart to `news.logic._match_topics_for_keywords`, which matches an +article's keywords on every detail request without persisting the result. This +script maps the LLM-extracted `keywords` of the enriched articles in +`aktuell_postproc` to OpenAlex topics via the backend's +`/api/topics/vector-search` endpoint, and persists one document per +(article, keyword) pair into an output index with the explicit mapping from +`news_mapping.py`: + +```json +{ + "news_id": "...", + "keyword": "", + "source_index": "aktuell_postproc", + "source_field": "keywords", + "topic_matches": [ + { + "rank": 1, + "topic_id": "...", + "topic_display_name": "...", + "subfield": "...", + "field": "...", + "domain": "...", + "match_score": null + } + ], + "match_method": "sentence_transformer", + "model_name": "...", + "built_at": "..." +} +``` + +`match_score` is `null` because the endpoint does not expose Elasticsearch +scores; `rank` preserves the search result order. + +This script only ever **reads** `aktuell_postproc` and writes into the separate test index. Caching the topics back into `aktuell_postproc` is done by the news detail endpoint (`news/logic.py`), not here. + +Keywords are **not** extracted here. `background-jobs/app/sync.py` (job `news`) +writes them into `aktuell_postproc` first, the same way the bund projects +already carry their keyword field before `map_project_topics.py` runs. + +The Elasticsearch plumbing (point-in-time scan, batched topic search, bulk +indexing, retries) is imported from +`service/scripts/projects/topic_mapper/map_project_topics.py` rather than +duplicated — that directory must stay next to this one. + +## Setup + +```bash +pip install -r requirements.txt +``` + +Credentials are read from `service/src/main/inse/.env` by default (override +with `--env-file`), and the backend must be running (e.g. `./gradlew serve`) +because the topic search goes through its API. + +## Usage + +```bash +python map_news_topics.py --output-index docker-job_test +``` + +Test run against a few articles without writing anything: + +```bash +python map_news_topics.py --output-index docker-job_test --dry-run --max-docs 50 +``` + +Runs are resumable: (article, keyword) pairs already present in the output +index are skipped, and each unique keyword is searched only once across all +articles that use it. Pairs whose search failed are left unwritten so the next +run retries them. + +## As a background job + +Registered in `background-jobs/entrypoint.sh` as `news-topics`, writing into +the test index `docker-job_test` and capped at a few articles. Both are +overridable via `NEWS_TOPICS_OUTPUT_INDEX` and `NEWS_TOPICS_MAX_DOCS`. diff --git a/service/scripts/news/topic_mapper/map_news_topics.py b/service/scripts/news/topic_mapper/map_news_topics.py new file mode 100644 index 00000000..f34dc42e --- /dev/null +++ b/service/scripts/news/topic_mapper/map_news_topics.py @@ -0,0 +1,329 @@ +#!/usr/bin/env python3 +""" +map_news_topics.py — Map news keywords to OpenAlex topics. + +Batch counterpart to news.logic._match_topics_for_keywords. This script streams +the enriched articles from aktuell_postproc, reads their LLM-extracted +'keywords', matches every unique keyword against OpenAlex topics and persists +one document per (article, keyword) pair into a separate output index: + + {news_id, keyword, source_index, source_field, topic_matches[], + match_method, model_name, built_at} + +The source index is only ever read. Writing the topics back into +aktuell_postproc is the job of the news detail endpoint, not of this script. + +Keywords are not extracted here — sync.py (job 'news') writes them into +aktuell_postproc, the same way the bund projects already carry their keyword +field before map_project_topics.py runs. + +The run is resumable: (article, keyword) pairs already present in the output +index are skipped, so an interrupted run can simply be restarted. Each unique +keyword is searched only once, across all articles that use it. + +Usage: + python map_news_topics.py --output-index docker-job_test + +Requires ELASTICSEARCH_INSE_URL/ELASTICSEARCH_INSE_API_KEY in the environment +or in the service .env, plus a running backend serving +/api/topics/vector-search (e.g. ./gradlew serve). +""" +from __future__ import annotations + +import argparse +import asyncio +import hashlib +import json +import logging +import os +import sys +from datetime import datetime, timezone +from pathlib import Path + +from dotenv import load_dotenv + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "projects" / "topic_mapper")) +import map_project_topics as base + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from news_mapping import NEWS_TOPICS_MAPPING + +logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") +logger = logging.getLogger(__name__) + +SOURCE_INDEX = "aktuell_postproc" +KEYWORD_FIELD = "keywords" +NEWS_ID_FIELD = "news_id" + + +async def ensure_index(index: str, cluster: str) -> None: + """Creates the output index with the explicit mapping if it does not exist.""" + url, headers = base.es_headers(cluster) + client = base.get_http_client() + + response = await client.head(f"{url}/{index}", headers=headers) + if response.status_code == 200: + logger.info("Output index '%s' already exists.", index) + return + + response = await client.put( + f"{url}/{index}", json={"mappings": NEWS_TOPICS_MAPPING}, headers=headers + ) + response.raise_for_status() + logger.info("Created output index '%s' with explicit mapping.", index) + + +def output_doc_id(news_id: str, keyword: str) -> str: + """Stable id per (article, keyword) pair. + + Derived from news_id rather than the aktuell_postproc document id, so a + reindex of the postproc index does not duplicate the mappings. + """ + digest = hashlib.sha1(keyword.encode("utf-8")).hexdigest()[:12] + return f"{news_id}::{digest}" + + +async def fetch_source_entries(cluster: str, max_docs: int | None) -> dict[str, tuple[str, str]]: + """Returns output_doc_id -> (news_id, keyword) for every enriched article.""" + entries: dict[str, tuple[str, str]] = {} + total = 0 + docs_with_keywords = 0 + + async for hit in base.scan( + index=SOURCE_INDEX, + cluster=cluster, + query={"exists": {"field": KEYWORD_FIELD}}, + source=[NEWS_ID_FIELD, KEYWORD_FIELD], + ): + total += 1 + doc_source = hit.get("_source", {}) + keywords = base.extract_text_values(doc_source, KEYWORD_FIELD) + news_id = doc_source.get(NEWS_ID_FIELD) + if keywords and news_id: + docs_with_keywords += 1 + for keyword in keywords: + entries[output_doc_id(news_id, keyword)] = (news_id, keyword) + if total % 50000 == 0: + logger.info("Scanned %d source documents...", total) + if max_docs and total >= max_docs: + logger.info("Stopping scan at --max-docs=%d.", max_docs) + break + + logger.info( + "Scanned %d documents from '%s', %d with non-empty '%s' (%d article/keyword pairs).", + total, + SOURCE_INDEX, + docs_with_keywords, + KEYWORD_FIELD, + len(entries), + ) + return entries + + +async def run(args: argparse.Namespace) -> None: + built_at = datetime.now(timezone.utc).isoformat() + model_name = os.getenv("SENTENCE_TRANSFORMERS_MODEL_NAME") + + await base.check_backend(args.api_base_url) + + if not args.dry_run: + await ensure_index(index=args.output_index, cluster=args.output_cluster) + + entries = await fetch_source_entries(cluster=args.source_cluster, max_docs=args.max_docs) + if not entries: + logger.warning("No keywords in '%s' — run the 'news' job first.", SOURCE_INDEX) + return + + if args.overwrite: + logger.info("--overwrite: re-mapping every pair, existing documents are replaced.") + covered = set() + else: + covered = await base.fetch_covered_doc_ids( + index=args.output_index, cluster=args.output_cluster + ) + pending = {doc_id: entry for doc_id, entry in entries.items() if doc_id not in covered} + logger.info( + "Coverage: %d/%d pairs already in '%s', %d still to be processed.", + len(entries) - len(pending), + len(entries), + args.output_index, + len(pending), + ) + if not pending: + logger.info("Nothing left to process.") + return + + docs_by_keyword: dict[str, list[tuple[str, str]]] = {} + for doc_id, (news_id, keyword) in pending.items(): + docs_by_keyword.setdefault(keyword, []).append((doc_id, news_id)) + unique_keywords = sorted(docs_by_keyword) + logger.info( + "%d unique keywords cover the %d pending pairs.", len(unique_keywords), len(pending) + ) + + backup_docs: list[dict] = [] + docs_done = 0 + keywords_done = 0 + + for start in range(0, len(unique_keywords), args.text_batch_size): + chunk = unique_keywords[start : start + args.text_batch_size] + matches_by_keyword = await base.match_keywords( + chunk, + api_base_url=args.api_base_url, + top_k=args.top_k, + search_type=args.search_type, + ) + + documents = [] + for keyword in chunk: + if keyword not in matches_by_keyword: + continue # search failed — left for the next run + for doc_id, news_id in docs_by_keyword[keyword]: + documents.append( + ( + doc_id, + { + "news_id": news_id, + "keyword": keyword, + "source_index": SOURCE_INDEX, + "source_field": KEYWORD_FIELD, + "topic_matches": matches_by_keyword[keyword], + "match_method": base.MATCH_METHOD, + "model_name": model_name, + "built_at": built_at, + }, + ) + ) + + if documents and not args.dry_run: + await base.bulk_index( + index=args.output_index, cluster=args.output_cluster, documents=documents + ) + if args.output: + backup_docs.extend(doc for _, doc in documents) + + keywords_done += len(chunk) + docs_done += len(documents) + logger.info( + "Progress: %d/%d keywords, %d/%d pending pairs indexed into '%s'.", + keywords_done, + len(unique_keywords), + docs_done, + len(pending), + args.output_index, + ) + + skipped = len(pending) - docs_done + if skipped: + logger.warning( + "%d pairs were NOT indexed due to failed searches — rerun the script to retry.", + skipped, + ) + + if args.output: + output_path = Path(args.output) + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text( + json.dumps(backup_docs, indent=2, ensure_ascii=False), encoding="utf-8" + ) + logger.info("Wrote local JSON backup (%d documents) to %s", len(backup_docs), output_path) + + logger.info( + "Done. %d documents indexed this run, %d covered in total.", + docs_done, + len(covered) + docs_done, + ) + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Map the keywords of enriched news articles to OpenAlex topics.", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=( + "Examples:\n" + " python map_news_topics.py --output-index docker-job_test\n" + " python map_news_topics.py --output-index docker-job_test --dry-run --max-docs 50" + ), + ) + parser.add_argument( + "--output-index", required=True, help="Index to persist the topic mappings into" + ) + parser.add_argument( + "--source-cluster", + default="inse", + choices=["inse", "nes"], + help=f"Cluster holding '{SOURCE_INDEX}' (default: inse)", + ) + parser.add_argument( + "--output-cluster", + default="inse", + choices=["inse", "nes"], + help="Cluster of the output index (default: inse)", + ) + parser.add_argument( + "--api-base-url", + default=base.DEFAULT_API_BASE_URL, + help=f"Base URL of the running backend (default: {base.DEFAULT_API_BASE_URL})", + ) + parser.add_argument( + "--top-k", + type=int, + default=1, + help=( + "Number of topic matches per keyword (default: 1, matching the single " + "match the news detail endpoint shows). Only truncates the result list; " + "ranking is unaffected." + ), + ) + parser.add_argument( + "--search-type", + default="hybrid", + choices=["hybrid", "semantic"], + help="Topic search type, mirrors vector_search_topics (default: hybrid)", + ) + parser.add_argument( + "--text-batch-size", + type=int, + default=base.TEXT_BATCH_SIZE, + help=f"Unique keywords searched per chunk (default: {base.TEXT_BATCH_SIZE})", + ) + parser.add_argument( + "--env-file", + default=str(base.DEFAULT_ENV_FILE), + help=f"Path to a .env with Elasticsearch credentials (default: {base.DEFAULT_ENV_FILE})", + ) + parser.add_argument( + "--max-docs", + type=int, + default=None, + help=f"Stop scanning '{SOURCE_INDEX}' after N documents (for test runs)", + ) + parser.add_argument( + "--output", + default=None, + help="Optional path for a local JSON backup of the documents built this run", + ) + parser.add_argument( + "--overwrite", + action="store_true", + help=( + "Re-map pairs that are already in the output index instead of skipping " + "them; document ids are deterministic, so they are replaced in place " + "(use after changing --top-k or --search-type)" + ), + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="Build the mapping without creating/writing the output index", + ) + args = parser.parse_args() + + if args.env_file and Path(args.env_file).exists(): + load_dotenv(dotenv_path=args.env_file) + + asyncio.run(run(args)) + + +if __name__ == "__main__": + main() diff --git a/service/scripts/news/topic_mapper/news_mapping.py b/service/scripts/news/topic_mapper/news_mapping.py new file mode 100644 index 00000000..28a6d909 --- /dev/null +++ b/service/scripts/news/topic_mapper/news_mapping.py @@ -0,0 +1,30 @@ +"""Elasticsearch mapping for news -> OpenAlex topic mapping indices. + +One document per (news article, keyword) pair. Articles in aktuell_postproc +carry up to KEYWORD_LIMIT keywords each, so an article normally yields +several documents. +""" + +NEWS_TOPICS_MAPPING = { + "properties": { + "news_id": {"type": "keyword"}, + "keyword": {"type": "text", "fields": {"keyword": {"type": "keyword"}}}, + "source_index": {"type": "keyword"}, + "source_field": {"type": "keyword"}, + "topic_matches": { + "type": "nested", + "properties": { + "rank": {"type": "integer"}, + "topic_id": {"type": "keyword"}, + "topic_display_name": {"type": "keyword"}, + "subfield": {"type": "keyword"}, + "field": {"type": "keyword"}, + "domain": {"type": "keyword"}, + "match_score": {"type": "float"}, + }, + }, + "match_method": {"type": "keyword"}, + "model_name": {"type": "keyword"}, + "built_at": {"type": "date"}, + } +} diff --git a/service/scripts/news/topic_mapper/requirements.txt b/service/scripts/news/topic_mapper/requirements.txt new file mode 100644 index 00000000..7507eb03 --- /dev/null +++ b/service/scripts/news/topic_mapper/requirements.txt @@ -0,0 +1,2 @@ +httpx>=0.27 +python-dotenv>=1.0 diff --git a/service/src/main/inse/background_jobs/seed.py b/service/src/main/inse/background_jobs/seed.py index 2b26d3f8..bcadaa17 100644 --- a/service/src/main/inse/background_jobs/seed.py +++ b/service/src/main/inse/background_jobs/seed.py @@ -28,11 +28,33 @@ PREDEFINED_JOBS: list[dict] = [ "Ordnet die Schlagwörter der Bund-Projekte über die Topic-Vektorsuche " "des Backends OpenAlex-Themen zu. Läuft als Dry-Run (--dry-run): liest " "nur aus dem Quellindex und schreibt nichts nach Elasticsearch. " - "Benötigt ein erreichbares Backend und INSE-Elasticsearch-Zugang." ), "target_index": "-", "command": "project-topics", }, + { + "name": "News-Schlagwort-Extraktion (Testlauf)", + "description": ( + "Extrahiert per LLM die Schlagwörter aus den News-Artikeln und legt sie " + "im Testindex „docker-job_test“ ab. „aktuell_postproc“ bleibt dabei " + "unverändert. Begrenzt auf wenige Artikel; da nichts im Quellindex " + "markiert wird, verarbeitet jeder Lauf erneut die ersten Artikel." + ), + "target_index": "docker-job_test", + "command": "news-keywords", + }, + { + "name": "News-Themen-Mapping (Testlauf)", + "description": ( + "Ordnet die per LLM extrahierten Schlagwörter der angereicherten " + "News-Artikel („aktuell_postproc“) über die Topic-Vektorsuche des " + "Backends OpenAlex-Themen zu und schreibt je Artikel-Schlagwort-Paar " + "ein Dokument in den Testindex „docker-job_test“. Begrenzt auf wenige " + "Artikel; erneute Läufe überspringen bereits gemappte Paare." + ), + "target_index": "docker-job_test", + "command": "news-topics", + }, { "name": "Bund-Crawler (Testlauf, ohne Upload)", "description": ( -- 2.56.1 From 83ed0bcaee60d785d45db2fccf1a4994aae7e62e Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Tue, 21 Jul 2026 00:29:59 +0200 Subject: [PATCH 33/60] fix(jobs): don't count empty keyword extractions as successful --- background-jobs/app/sync.py | 56 ++++++++++++++++++++++++++++++++----- 1 file changed, 49 insertions(+), 7 deletions(-) diff --git a/background-jobs/app/sync.py b/background-jobs/app/sync.py index 72f330b4..c0cf185e 100644 --- a/background-jobs/app/sync.py +++ b/background-jobs/app/sync.py @@ -6,6 +6,8 @@ import time import threading from concurrent.futures import ThreadPoolExecutor, as_completed +POSTPROC_INDEX = "aktuell_postproc" + def print_pretty_json(data): print(json.dumps(data, indent=2)) @@ -34,15 +36,32 @@ def sync_single_news(news_id, max_retries=3): print(f"Error: {news_id} - {error}") return False -def update_keywords_single(postproc_entry, max_retries=3): +def update_keywords_single(postproc_entry, target_index=POSTPROC_INDEX, max_retries=3): doc_id = postproc_entry["_id"] - news_id = postproc_entry["_source"]["news_id"] + source = postproc_entry["_source"] + news_id = source["news_id"] attempt = 0 while attempt < max_retries: try: news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"] keywords = llm_client.extract_keywords(news_text) - es_client.update_entry("aktuell_postproc", doc_id, {"keywords": keywords}) + if not keywords: + # Empty article or unparseable LLM answer: writing an empty list + # would look like a success and block a later retry. + print(f"Skipped {news_id}: no keywords extracted.") + return False + if target_index == POSTPROC_INDEX: + es_client.update_entry(POSTPROC_INDEX, doc_id, {"keywords": keywords}) + else: + es_client.add_entry( + target_index, + { + "news_id": news_id, + "relevant": source.get("relevant", 0), + "authors": source.get("authors", []), + "keywords": keywords, + }, + ) return True except Exception as error: attempt += 1 @@ -100,6 +119,16 @@ def main(): help="Process at most this many entries (used by --update-keywords, e.g. for a smoke test).", ) + parser.add_argument( + "--target-index", + default=POSTPROC_INDEX, + help=( + f"Index that --update-keywords writes to (default: {POSTPROC_INDEX}). Any other " + "index gets new documents instead of in-place updates, and every entry is " + "re-extracted rather than only those missing keywords." + ), + ) + args = parser.parse_args() if args.delete_all: @@ -143,10 +172,20 @@ def main(): if args.update_keywords: start_time = time.time() - postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["news_id", "keywords"]) + postproc_entries = es_client.get_all_entries( + POSTPROC_INDEX, fields=["news_id", "keywords", "relevant", "authors"] + ) - pending = [entry for entry in postproc_entries if not entry["_source"].get("keywords")] - print(f"Number of entries without keywords: {len(pending)}") + if args.target_index == POSTPROC_INDEX: + pending = [entry for entry in postproc_entries if not entry["_source"].get("keywords")] + print(f"Number of entries without keywords: {len(pending)}") + else: + # Writing elsewhere never marks the postproc entries, so the "missing + # keywords" filter would select the same entries on every run. Pick + # entries that already have keywords instead: those are known to come + # from articles with actual content, unlike the empty archive stubs. + pending = [entry for entry in postproc_entries if entry["_source"].get("keywords")] + print(f"Re-extracting keywords into '{args.target_index}': {len(pending)} candidates.") if args.limit is not None: pending = pending[:args.limit] @@ -159,7 +198,10 @@ def main(): progress_lock = threading.Lock() with ThreadPoolExecutor(max_workers=args.threads) as executor: - futures = [executor.submit(update_keywords_single, entry) for entry in pending] + futures = [ + executor.submit(update_keywords_single, entry, args.target_index) + for entry in pending + ] for future in as_completed(futures): was_successful = future.result() with progress_lock: -- 2.56.1 From 5323797c710087ce603b644e3064af857a9ab6ee Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 21 Jul 2026 06:12:41 +0200 Subject: [PATCH 34/60] refactor(background-jobs): move image definition to service/scripts/jobs-image --- .dockerignore | 1 + background-jobs/README.md | 4 ++-- {background-jobs => service/scripts/jobs-image}/Dockerfile | 5 +++-- .../scripts/jobs-image}/requirements.txt | 0 4 files changed, 6 insertions(+), 4 deletions(-) rename {background-jobs => service/scripts/jobs-image}/Dockerfile (83%) rename {background-jobs => service/scripts/jobs-image}/requirements.txt (100%) diff --git a/.dockerignore b/.dockerignore index 14be7b5c..ec522120 100644 --- a/.dockerignore +++ b/.dockerignore @@ -4,6 +4,7 @@ service/* !service/scripts service/scripts/* +!service/scripts/jobs-image !service/scripts/news !service/scripts/projects service/scripts/projects/* diff --git a/background-jobs/README.md b/background-jobs/README.md index 47d714ba..0fe7121b 100644 --- a/background-jobs/README.md +++ b/background-jobs/README.md @@ -30,7 +30,7 @@ python -m service.scripts.projects.topic_mapper.map_project_topics --dry-run ## Image & Dockerfile -Das [Dockerfile](./Dockerfile) enthält die Skripte (sync.py, news/, projects/, etc.) und hat keine ENTRYPOINT. Der Backend startet Container direkt: +Das [Dockerfile](../service/scripts/jobs-image/Dockerfile) enthält die Skripte (sync.py, news/, projects/, etc.) und hat keine ENTRYPOINT. Der Backend startet Container direkt: ```python docker.run(image="...", command="python sync.py --sync-delta") @@ -39,7 +39,7 @@ docker.run(image="...", command="python sync.py --sync-delta") **Nur Skripte hinzufügen?** → Image neu bauen + pushen: ```bash -docker build -f background-jobs/Dockerfile -t docker.nes.uni-due.de/inse/background-jobs:latest . +docker build -f service/scripts/jobs-image/Dockerfile -t docker.nes.uni-due.de/inse/background-jobs:latest . docker push docker.nes.uni-due.de/inse/background-jobs:latest ``` diff --git a/background-jobs/Dockerfile b/service/scripts/jobs-image/Dockerfile similarity index 83% rename from background-jobs/Dockerfile rename to service/scripts/jobs-image/Dockerfile index 1e144425..6cce38f7 100644 --- a/background-jobs/Dockerfile +++ b/service/scripts/jobs-image/Dockerfile @@ -1,4 +1,5 @@ -# Preprocessing worker, news enrichment job (v1) +# Background-jobs worker image. Build from the repo root: +# docker build -f service/scripts/jobs-image/Dockerfile -t docker.nes.uni-due.de/inse/background-jobs:latest . FROM python:3.13-slim WORKDIR /app @@ -11,7 +12,7 @@ ENV CHROME_BIN=/usr/bin/chromium \ CHROMEDRIVER_PATH=/usr/bin/chromedriver # Install dependencies first so this layer is cached when only code changes. -COPY background-jobs/requirements.txt . +COPY service/scripts/jobs-image/requirements.txt . RUN pip install --no-cache-dir -r requirements.txt # Copy the job code. No secrets here, config is read from env vars at runtime. diff --git a/background-jobs/requirements.txt b/service/scripts/jobs-image/requirements.txt similarity index 100% rename from background-jobs/requirements.txt rename to service/scripts/jobs-image/requirements.txt -- 2.56.1 From 0b3be358854c8ba5730ebaa53414db23cf4ce1b8 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 21 Jul 2026 06:24:58 +0200 Subject: [PATCH 35/60] feat(jobs): prefill default image and add field tooltips in create-dialog --- .../task-create-dialog.component.html | 53 ++++++++++++++----- .../task-create-dialog.component.scss | 5 ++ .../task-create-dialog.component.ts | 12 ++++- 3 files changed, 56 insertions(+), 14 deletions(-) diff --git a/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.html b/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.html index b58885f6..0c6178a3 100644 --- a/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.html +++ b/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.html @@ -5,39 +5,62 @@ Name + info_outline @if (form.controls.name.invalid) { Bitte einen Namen eingeben. } - Befehl (optional) - - Der Befehl, den der Container ausführt. Leer = Standard-Entrypoint des - Images.Befehl + + info_outline - Image (optional) + Image - Docker-Image (Standard: - docker.nes.uni-due.de/inse/background-jobs:latest).info_outline + Im Normalfall unverändert lassen. - Beschreibung + Beschreibung (optional) + info_outline Ziel-Index (optional) - Elasticsearch-Index, in den der Job schreibt (Anzeige).info_outline @@ -48,6 +71,12 @@ rows="3" formControlName="env" placeholder="KEY=value"> + info_outline Eine Variable pro Zeile im Format KEY=value. @if (form.controls.env.hasError('invalidEnv')) { Ungültige Zeile — Format: KEY=value. diff --git a/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.scss b/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.scss index dc8f0bda..51c04f90 100644 --- a/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.scss +++ b/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.scss @@ -19,6 +19,11 @@ font-size: 12px; } +.field-info { + color: #94a3b8; + cursor: help; +} + .server-error { margin: 8px 0 0; color: #b3261e; diff --git a/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.ts b/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.ts index a48d43ba..4cf49752 100644 --- a/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.ts +++ b/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.ts @@ -11,10 +11,13 @@ import { MatDialogModule, MatDialogRef } from '@angular/material/dialog'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatIconModule } from '@angular/material/icon'; import { MatInputModule } from '@angular/material/input'; +import { MatTooltipModule } from '@angular/material/tooltip'; import { BackgroundJobTask, BackgroundJobsService } from '../../../api'; const ENV_LINE_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*=.*$/; +const DEFAULT_JOB_IMAGE = 'docker.nes.uni-due.de/inse/background-jobs:latest'; + @Component({ selector: 'app-task-create-dialog', imports: [ @@ -25,6 +28,7 @@ const ENV_LINE_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*=.*$/; MatFormFieldModule, MatIconModule, MatInputModule, + MatTooltipModule, ], templateUrl: './task-create-dialog.component.html', styleUrl: './task-create-dialog.component.scss', @@ -48,7 +52,7 @@ export class TaskCreateDialogComponent { description: new FormControl('', { nonNullable: true }), targetIndex: new FormControl('', { nonNullable: true }), command: new FormControl('', { nonNullable: true }), - image: new FormControl('', { nonNullable: true }), + image: new FormControl(DEFAULT_JOB_IMAGE, { nonNullable: true }), env: new FormControl('', { nonNullable: true }), }); @@ -66,13 +70,17 @@ export class TaskCreateDialogComponent { const env = this.parseEnv(value.env); if (env === undefined) return; + // The default image is stored as null so jobs keep following the + // backend-configured image if it ever changes. + const image = value.image.trim(); + this.creating.set(true); this.backgroundJobsService .createBackgroundJobTask({ name, description: value.description.trim(), target_index: value.targetIndex.trim(), - image: value.image.trim() || null, + image: !image || image === DEFAULT_JOB_IMAGE ? null : image, command, env, }) -- 2.56.1 From 762e3f9a15fbcb126691076de62d02c9203fadb6 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 21 Jul 2026 08:05:03 +0200 Subject: [PATCH 36/60] refactor(background-jobs): copy full script tree into image and move demo job --- .dockerignore | 10 +++------- background-jobs/README.md | 9 ++++++--- .../app => service/scripts/demo}/demo.py | 0 service/scripts/jobs-image/Dockerfile | 14 +++----------- 4 files changed, 12 insertions(+), 21 deletions(-) rename {background-jobs/app => service/scripts/demo}/demo.py (100%) diff --git a/.dockerignore b/.dockerignore index ec522120..888e85bd 100644 --- a/.dockerignore +++ b/.dockerignore @@ -3,13 +3,9 @@ !service service/* !service/scripts -service/scripts/* -!service/scripts/jobs-image -!service/scripts/news -!service/scripts/projects -service/scripts/projects/* -!service/scripts/projects/topic_mapper -!service/scripts/projects/bund + +# Data-only folders that do not belong in the job image. +service/scripts/multipliers **/__pycache__ **/*.pyc diff --git a/background-jobs/README.md b/background-jobs/README.md index 0fe7121b..e1bb7396 100644 --- a/background-jobs/README.md +++ b/background-jobs/README.md @@ -21,22 +21,25 @@ curl -X POST -H "Authorization: Bearer $TOKEN" \ Command-Beispiele: ``` +python service/scripts/demo/demo.py 20 python sync.py --sync-delta -python news/ude/run_pipeline.py --skip-upload +python service/scripts/news/ude/run_pipeline.py --skip-upload --max-items 5 +python -m service.scripts.news.topic_mapper.map_news_topics --output-index docker-job_test --max-docs 50 python -m service.scripts.projects.topic_mapper.map_project_topics --dry-run +sh -c "cd service/scripts/projects/bund && python gpc.data.py --skip-upload" ``` **Neue Jobs = kein Image-Rebuild.** Die Skripte sind bereits im Image; der Command wird direkt an Docker übergeben. ## Image & Dockerfile -Das [Dockerfile](../service/scripts/jobs-image/Dockerfile) enthält die Skripte (sync.py, news/, projects/, etc.) und hat keine ENTRYPOINT. Der Backend startet Container direkt: +Das [Dockerfile](../service/scripts/jobs-image/Dockerfile) kopiert den kompletten `service/scripts/`-Baum (Pfade im Container = Pfade im Repo) plus `background-jobs/app/` (sync.py) und hat keinen ENTRYPOINT. Neue Skripte unter `service/scripts` landen automatisch im nächsten Build — ohne Dockerfile-Änderung. Der Backend startet Container direkt: ```python docker.run(image="...", command="python sync.py --sync-delta") ``` -**Nur Skripte hinzufügen?** → Image neu bauen + pushen: +**Skripte hinzugefügt oder geändert?** → Image neu bauen + pushen: ```bash docker build -f service/scripts/jobs-image/Dockerfile -t docker.nes.uni-due.de/inse/background-jobs:latest . diff --git a/background-jobs/app/demo.py b/service/scripts/demo/demo.py similarity index 100% rename from background-jobs/app/demo.py rename to service/scripts/demo/demo.py diff --git a/service/scripts/jobs-image/Dockerfile b/service/scripts/jobs-image/Dockerfile index 6cce38f7..c270a2eb 100644 --- a/service/scripts/jobs-image/Dockerfile +++ b/service/scripts/jobs-image/Dockerfile @@ -18,14 +18,6 @@ RUN pip install --no-cache-dir -r requirements.txt # Copy the job code. No secrets here, config is read from env vars at runtime. COPY background-jobs/app/ ./ -# The UDE news crawler is maintained under service/scripts and copied in as-is. -COPY service/scripts/news/ude/ ./news/ude/ - -# The project topic-mapper keeps its package path so its absolute import resolves. -COPY service/scripts/projects/topic_mapper/ ./service/scripts/projects/topic_mapper/ - -# The news topic-mapper imports the project topic-mapper, so it keeps its path too. -COPY service/scripts/news/topic_mapper/ ./service/scripts/news/topic_mapper/ - -# The bund foerderportal crawler (runs with its own dir as cwd for its JSON configs). -COPY service/scripts/projects/bund/ ./projects/bund/ +# The complete script tree: new scripts are picked up by the next build without +# any Dockerfile change. Data-only folders are excluded via the root .dockerignore. +COPY service/scripts/ ./service/scripts/ -- 2.56.1 From fb44e9db3c1bfd42ddc07998958bcd7b5d43a26d Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 21 Jul 2026 08:26:07 +0200 Subject: [PATCH 37/60] style(background-jobs): trim Dockerfile comments --- service/scripts/jobs-image/Dockerfile | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/service/scripts/jobs-image/Dockerfile b/service/scripts/jobs-image/Dockerfile index c270a2eb..44a70636 100644 --- a/service/scripts/jobs-image/Dockerfile +++ b/service/scripts/jobs-image/Dockerfile @@ -11,13 +11,11 @@ RUN apt-get update \ ENV CHROME_BIN=/usr/bin/chromium \ CHROMEDRIVER_PATH=/usr/bin/chromedriver -# Install dependencies first so this layer is cached when only code changes. +# Install dependencies COPY service/scripts/jobs-image/requirements.txt . RUN pip install --no-cache-dir -r requirements.txt -# Copy the job code. No secrets here, config is read from env vars at runtime. +# Copy the job code. COPY background-jobs/app/ ./ -# The complete script tree: new scripts are picked up by the next build without -# any Dockerfile change. Data-only folders are excluded via the root .dockerignore. COPY service/scripts/ ./service/scripts/ -- 2.56.1 From afaa840d48e655fec4035444e4d7e08f6bac83e8 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 21 Jul 2026 08:33:41 +0200 Subject: [PATCH 38/60] feat(jobs): add edit dialog with hover pencil in the name column --- .../src/app/modules/jobs/jobs.component.html | 18 ++- .../src/app/modules/jobs/jobs.component.scss | 42 +++++- webapp/src/app/modules/jobs/jobs.component.ts | 29 ++++ .../task-edit-dialog.component.html | 91 +++++++++++++ .../task-edit-dialog.component.scss | 29 ++++ .../task-edit-dialog.component.ts | 126 ++++++++++++++++++ 6 files changed, 331 insertions(+), 4 deletions(-) create mode 100644 webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.html create mode 100644 webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.scss create mode 100644 webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.ts diff --git a/webapp/src/app/modules/jobs/jobs.component.html b/webapp/src/app/modules/jobs/jobs.component.html index 4909b602..f1863d32 100644 --- a/webapp/src/app/modules/jobs/jobs.component.html +++ b/webapp/src/app/modules/jobs/jobs.component.html @@ -58,9 +58,21 @@
- {{ row.name }} - {{ row.description }} - {{ row.target_index }} + +
+ {{ row.name }} + {{ row.description }} + {{ row.target_index }} +
diff --git a/webapp/src/app/modules/jobs/jobs.component.scss b/webapp/src/app/modules/jobs/jobs.component.scss index ca8c94e5..137b4f24 100644 --- a/webapp/src/app/modules/jobs/jobs.component.scss +++ b/webapp/src/app/modules/jobs/jobs.component.scss @@ -95,10 +95,50 @@ mat-paginator { } .task-name-cell { + display: flex; + flex-direction: row; + align-items: center; + gap: 6px; + min-width: 220px; +} + +.task-name-text { display: flex; flex-direction: column; gap: 2px; - min-width: 220px; +} + +.edit-name-action { + flex: 0 0 auto; + display: inline-flex; + align-items: center; + justify-content: center; + width: 22px; + height: 22px; + padding: 0; + border: none; + background: none; + cursor: pointer; + color: #64748b; + opacity: 0; + transition: opacity 0.15s ease; + + .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + line-height: 18px; + } +} + +.task-name-cell:hover .edit-name-action, +.edit-name-action:focus-visible { + opacity: 1; +} + +.edit-name-action[disabled] { + cursor: not-allowed; + color: #cbd5e1; } .task-description { diff --git a/webapp/src/app/modules/jobs/jobs.component.ts b/webapp/src/app/modules/jobs/jobs.component.ts index 9a97abfb..0d0bd51b 100644 --- a/webapp/src/app/modules/jobs/jobs.component.ts +++ b/webapp/src/app/modules/jobs/jobs.component.ts @@ -42,6 +42,10 @@ import { JobLogsDialogData, } from './job-logs-dialog/job-logs-dialog.component'; import { TaskCreateDialogComponent } from './task-create-dialog/task-create-dialog.component'; +import { + TaskEditDialogComponent, + TaskEditDialogData, +} from './task-edit-dialog/task-edit-dialog.component'; @Component({ selector: 'app-jobs', @@ -279,6 +283,31 @@ export class JobsComponent implements OnInit { }); } + protected openEditDialog(task: BackgroundJobTask): void { + if (['running', 'stopping'].includes(task.status)) return; + + const dialogRef = this.dialog.open< + TaskEditDialogComponent, + TaskEditDialogData, + BackgroundJobTask | undefined + >(TaskEditDialogComponent, { + width: '560px', + maxWidth: 'calc(100vw - 32px)', + data: { task }, + }); + + dialogRef.afterClosed().subscribe((updatedTask) => { + if (!updatedTask) return; + + this.updateTask(updatedTask.id, () => updatedTask); + this.snackBar.open(`„${updatedTask.name}“ wurde gespeichert.`, 'OK', { + duration: 3000, + horizontalPosition: 'center', + verticalPosition: 'bottom', + }); + }); + } + protected openScheduleDialog(task: BackgroundJobTask): void { const dialogRef = this.dialog.open< TaskScheduleDialogComponent, diff --git a/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.html b/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.html new file mode 100644 index 00000000..8f7d8b18 --- /dev/null +++ b/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.html @@ -0,0 +1,91 @@ +

Job bearbeiten

+ + +

{{ data.task.name }}

+ +
+ + Befehl + + info_outline + + + + Image + + info_outline + Im Normalfall unverändert lassen. + + + + Beschreibung (optional) + + info_outline + + + + Ziel-Index (optional) + + info_outline + + + + Umgebungsvariablen (optional) + + info_outline + Eine Variable pro Zeile im Format KEY=value. + @if (form.controls.env.hasError('invalidEnv')) { + Ungültige Zeile — Format: KEY=value. + } + +
+ + @if (serverError()) { +

{{ serverError() }}

+ } +
+ + + + + diff --git a/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.scss b/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.scss new file mode 100644 index 00000000..d02bdb7e --- /dev/null +++ b/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.scss @@ -0,0 +1,29 @@ +.edit-name { + margin: 0 0 16px; + font-weight: 600; + color: var(--sg-text, #101a3d); +} + +.edit-form { + display: flex; + flex-direction: column; + gap: 12px; + min-width: 400px; +} + +.field-info { + color: #94a3b8; + cursor: help; +} + +.server-error { + margin: 8px 0 0; + color: #b3261e; + font-size: 14px; +} + +@media (max-width: 640px) { + .edit-form { + min-width: 0; + } +} diff --git a/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.ts b/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.ts new file mode 100644 index 00000000..782cd05d --- /dev/null +++ b/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.ts @@ -0,0 +1,126 @@ +import { CommonModule } from '@angular/common'; +import { Component, inject, signal } from '@angular/core'; +import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { + MAT_DIALOG_DATA, + MatDialogModule, + MatDialogRef, +} from '@angular/material/dialog'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatIconModule } from '@angular/material/icon'; +import { MatInputModule } from '@angular/material/input'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { BackgroundJobTask, BackgroundJobsService } from '../../../api'; + +const ENV_LINE_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*=.*$/; + +const DEFAULT_JOB_IMAGE = 'docker.nes.uni-due.de/inse/background-jobs:latest'; + +export interface TaskEditDialogData { + task: BackgroundJobTask; +} + +@Component({ + selector: 'app-task-edit-dialog', + imports: [ + CommonModule, + ReactiveFormsModule, + MatButtonModule, + MatDialogModule, + MatFormFieldModule, + MatIconModule, + MatInputModule, + MatTooltipModule, + ], + templateUrl: './task-edit-dialog.component.html', + styleUrl: './task-edit-dialog.component.scss', + standalone: true, +}) +export class TaskEditDialogComponent { + private readonly dialogRef = + inject< + MatDialogRef + >(MatDialogRef); + private readonly backgroundJobsService = inject(BackgroundJobsService); + protected readonly data = inject(MAT_DIALOG_DATA); + + protected readonly saving = signal(false); + protected readonly serverError = signal(''); + + protected readonly form = new FormGroup({ + description: new FormControl(this.data.task.description, { + nonNullable: true, + }), + targetIndex: new FormControl(this.data.task.target_index, { + nonNullable: true, + }), + command: new FormControl(this.data.task.command ?? '', { + nonNullable: true, + }), + image: new FormControl(this.data.task.image, { nonNullable: true }), + env: new FormControl(this.envToText(this.data.task.env), { + nonNullable: true, + }), + }); + + protected submit(): void { + this.serverError.set(''); + const value = this.form.getRawValue(); + + const env = this.parseEnv(value.env); + if (env === undefined) return; + + // The default image is stored as null so the job keeps following the + // backend-configured image if it ever changes. + const image = value.image.trim(); + + this.saving.set(true); + this.backgroundJobsService + .updateBackgroundJobTask(this.data.task.id, { + description: value.description.trim(), + target_index: value.targetIndex.trim(), + image: !image || image === DEFAULT_JOB_IMAGE ? null : image, + command: value.command.trim() || null, + env, + }) + .subscribe({ + next: (task) => this.dialogRef.close(task), + error: (error) => { + this.saving.set(false); + const detail = error?.error?.detail; + this.serverError.set( + typeof detail === 'string' + ? detail + : 'Der Job konnte nicht gespeichert werden.', + ); + }, + }); + } + + protected close(): void { + this.dialogRef.close(); + } + + private envToText(env: { [key: string]: string }): string { + return Object.entries(env) + .map(([key, value]) => `${key}=${value}`) + .join('\n'); + } + + private parseEnv(text: string): { [key: string]: string } | undefined { + const env: { [key: string]: string } = {}; + for (const line of text.split('\n')) { + const trimmed = line.trim(); + if (!trimmed) continue; + if (!ENV_LINE_PATTERN.test(trimmed)) { + this.form.controls.env.setErrors({ invalidEnv: true }); + this.form.controls.env.markAsTouched(); + return undefined; + } + const separatorIndex = trimmed.indexOf('='); + env[trimmed.slice(0, separatorIndex)] = trimmed.slice(separatorIndex + 1); + } + return env; + } +} -- 2.56.1 From c47d5ee17092fbbfee997deea7a3a6e747ec54d7 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 21 Jul 2026 09:43:39 +0200 Subject: [PATCH 39/60] fix(jobs): keep new-job button on one line, unclip name label, make command/image fields resizable --- webapp/src/app/modules/jobs/jobs.component.html | 1 + webapp/src/app/modules/jobs/jobs.component.scss | 5 +++++ .../task-create-dialog.component.html | 12 +++++++++--- .../task-create-dialog.component.scss | 17 +++++++++++++++++ .../task-edit-dialog.component.html | 12 +++++++++--- .../task-edit-dialog.component.scss | 13 +++++++++++++ 6 files changed, 54 insertions(+), 6 deletions(-) diff --git a/webapp/src/app/modules/jobs/jobs.component.html b/webapp/src/app/modules/jobs/jobs.component.html index f1863d32..dd5f8788 100644 --- a/webapp/src/app/modules/jobs/jobs.component.html +++ b/webapp/src/app/modules/jobs/jobs.component.html @@ -11,6 +11,7 @@ mat-flat-button color="primary" type="button" + class="new-job-button" (click)="openCreateDialog()"> add Neuer Job diff --git a/webapp/src/app/modules/jobs/jobs.component.scss b/webapp/src/app/modules/jobs/jobs.component.scss index 137b4f24..8da0d2a5 100644 --- a/webapp/src/app/modules/jobs/jobs.component.scss +++ b/webapp/src/app/modules/jobs/jobs.component.scss @@ -12,6 +12,11 @@ gap: 16px; } +.new-job-button { + flex-shrink: 0; + white-space: nowrap; +} + h1, p { margin: 0; diff --git a/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.html b/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.html index 0c6178a3..c0d9b080 100644 --- a/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.html +++ b/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.html @@ -18,10 +18,12 @@ Befehl - + placeholder="python sync.py --stats"> Image - + Befehl - + placeholder="python sync.py --stats"> Image - + Date: Tue, 21 Jul 2026 09:52:19 +0200 Subject: [PATCH 40/60] fix(jobs): keep log scroll position on refresh --- .../job-logs-dialog.component.html | 4 +- .../job-logs-dialog.component.ts | 41 ++++++++++++++++++- 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html index 663e69b8..f0ebaeb7 100644 --- a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html +++ b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html @@ -65,8 +65,8 @@
-
- @if (loading()) { +
+ @if (loading() && !logs()) {
(''); protected readonly runStatus = signal(null); + private readonly logsPanel = viewChild>('logsPanel'); + + // Follow the tail (auto-scroll to the newest lines) as long as the user is at + // the bottom. Once they scroll up to read, this turns false and their scroll + // position is left untouched on the next refresh. + private followTail = true; + private readonly followThresholdPx = 24; + ngOnInit(): void { this.loadRuns(true); timer(5000, 5000) @@ -99,7 +115,27 @@ export class JobLogsDialogComponent implements OnInit { protected onRunSelected(runId: number): void { const run = this.runs().find((item) => item.id === runId); - if (run) this.selectRun(run); + if (run) { + // A run the user just picked should open at its newest output. + this.followTail = true; + this.selectRun(run); + } + } + + protected onLogsScroll(): void { + const panel = this.logsPanel()?.nativeElement; + if (!panel) return; + const distanceFromBottom = + panel.scrollHeight - panel.scrollTop - panel.clientHeight; + this.followTail = distanceFromBottom <= this.followThresholdPx; + } + + private scrollToBottom(): void { + // Defer until the new log content has been rendered. + setTimeout(() => { + const panel = this.logsPanel()?.nativeElement; + if (panel) panel.scrollTop = panel.scrollHeight; + }); } protected loadLogs(): void { @@ -120,6 +156,7 @@ export class JobLogsDialogComponent implements OnInit { } this.logs.set(result.logs || 'Keine Logs vorhanden.'); this.runStatus.set(result.status); + if (this.followTail) this.scrollToBottom(); }, error: () => { this.logs.set('Logs konnten nicht geladen werden.'); -- 2.56.1 From ff322fc29bbbc1df854f5dd9b2209d6181430a61 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 21 Jul 2026 10:08:28 +0200 Subject: [PATCH 41/60] feat(jobs): show run duration and live elapsed time --- .../job-logs-dialog.component.html | 12 ++++++ .../job-logs-dialog.component.scss | 5 +++ .../job-logs-dialog.component.ts | 19 +++++++- .../src/app/modules/jobs/jobs.component.html | 7 +++ webapp/src/app/modules/jobs/jobs.component.ts | 10 +++++ webapp/src/app/modules/jobs/jobs.utils.ts | 43 ++++++++++++++----- 6 files changed, 85 insertions(+), 11 deletions(-) diff --git a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html index f0ebaeb7..13917cdf 100644 --- a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html +++ b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.html @@ -25,6 +25,9 @@ @if (run.exit_code != null) { · Exit {{ run.exit_code }} } + @if (formatRunDuration(run); as dur) { + · {{ dur }} + } } @@ -41,6 +44,15 @@ {{ statusMeta(runStatus()!).label }} } + @if (selectedRun(); as run) { + @if (runStatus() === 'running' || runStatus() === 'stopping') { + @if (formatRunElapsed(run, nowMs()); as elapsed) { + läuft seit {{ elapsed }} + } + } @else if (formatRunDuration(run); as dur) { + Dauer: {{ dur }} + } + } zeigt letzte 200 Zeilen
diff --git a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.scss b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.scss index f4b9b0ca..b65b114c 100644 --- a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.scss +++ b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.scss @@ -138,6 +138,11 @@ font-size: 12px; } +.run-duration { + font-size: 13px; + color: #475569; +} + @media (max-width: 640px) { .logs-header { flex-direction: column; diff --git a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts index 68c40815..7965cb9e 100644 --- a/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts +++ b/webapp/src/app/modules/jobs/job-logs-dialog/job-logs-dialog.component.ts @@ -4,6 +4,7 @@ import { DestroyRef, ElementRef, OnInit, + computed, inject, signal, viewChild, @@ -22,7 +23,12 @@ import { MatSelectModule } from '@angular/material/select'; import { MatTooltipModule } from '@angular/material/tooltip'; import { finalize, timer } from 'rxjs'; import { BackgroundJobsService, BackgroundJobTask, JobRun } from '../../../api'; -import { formatUtcDateAsLocal, statusMeta } from '../jobs.utils'; +import { + formatRunDuration, + formatRunElapsed, + formatUtcDateAsLocal, + statusMeta, +} from '../jobs.utils'; export interface JobLogsDialogData { task: BackgroundJobTask; @@ -52,6 +58,8 @@ export class JobLogsDialogComponent implements OnInit { protected readonly statusMeta = statusMeta; protected readonly formatUtcDateAsLocal = formatUtcDateAsLocal; + protected readonly formatRunDuration = formatRunDuration; + protected readonly formatRunElapsed = formatRunElapsed; protected readonly runs = signal([]); protected readonly runsLoading = signal(false); @@ -60,6 +68,11 @@ export class JobLogsDialogComponent implements OnInit { protected readonly loading = signal(false); protected readonly logs = signal(''); protected readonly runStatus = signal(null); + protected readonly nowMs = signal(Date.now()); + + protected readonly selectedRun = computed( + () => this.runs().find((run) => run.id === this.selectedRunId()) ?? null, + ); private readonly logsPanel = viewChild>('logsPanel'); @@ -74,6 +87,10 @@ export class JobLogsDialogComponent implements OnInit { timer(5000, 5000) .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe(() => this.loadRuns()); + // Ticks the live "läuft seit …" duration every second. + timer(1000, 1000) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(() => this.nowMs.set(Date.now())); } protected loadRuns(selectLatest = false): void { diff --git a/webapp/src/app/modules/jobs/jobs.component.html b/webapp/src/app/modules/jobs/jobs.component.html index dd5f8788..18a32526 100644 --- a/webapp/src/app/modules/jobs/jobs.component.html +++ b/webapp/src/app/modules/jobs/jobs.component.html @@ -108,6 +108,13 @@ @if (row.last_run) {
{{ formatUtcDateAsLocal(row.last_run.started_at) }} + @if (row.status === 'running' || row.status === 'stopping') { + @if (formatRunElapsed(row.last_run, nowMs()); as elapsed) { + läuft seit {{ elapsed }} + } + } @else if (formatRunDuration(row.last_run); as duration) { + Dauer: {{ duration }} + } @if (row.last_run.exit_code != null) { Exit-Code {{ row.last_run.exit_code }}(null); protected readonly dockerHealthLoading = signal(false); protected readonly deletingTaskIds = signal>(new Set()); + protected readonly nowMs = signal(Date.now()); protected readonly statusMeta = statusMeta; protected readonly formatScheduleCron = formatScheduleCron; protected readonly formatUtcDateAsLocal = formatUtcDateAsLocal; + protected readonly formatRunDuration = formatRunDuration; + protected readonly formatRunElapsed = formatRunElapsed; protected taskColumns: GenericColumn[] = []; @@ -123,6 +128,11 @@ export class JobsComponent implements OnInit { ) .subscribe((tasks) => this.setTasksPreservingPendingStops(tasks)); + // Ticks the live "läuft seit …" duration in the last-run column. + timer(1000, 1000) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(() => this.nowMs.set(Date.now())); + this.taskColumns = [ { id: 'name', diff --git a/webapp/src/app/modules/jobs/jobs.utils.ts b/webapp/src/app/modules/jobs/jobs.utils.ts index b3bc6a7f..8936ca77 100644 --- a/webapp/src/app/modules/jobs/jobs.utils.ts +++ b/webapp/src/app/modules/jobs/jobs.utils.ts @@ -39,9 +39,18 @@ export function formatScheduleCron(schedule: string | null): string { return schedule ? `Cron: ${schedule}` : 'Nur manuell'; } +// Backend timestamps are naive UTC without a timezone suffix, so add a "Z" +// before parsing to keep them comparable with the (UTC-based) wall clock. +function appendUtcZ(value: string): string { + return /(?:Z|[+-]\d{2}:\d{2})$/.test(value) ? value : `${value}Z`; +} + +function toUtcMs(value: string): number { + return new Date(appendUtcZ(value)).getTime(); +} + export function formatUtcDateAsLocal(value: string | null | undefined): string { if (!value) return ''; - const utcValue = /(?:Z|[+-]\d{2}:\d{2})$/.test(value) ? value : `${value}Z`; return new Intl.DateTimeFormat('de-DE', { day: '2-digit', month: '2-digit', @@ -49,18 +58,32 @@ export function formatUtcDateAsLocal(value: string | null | undefined): string { hour: '2-digit', minute: '2-digit', hour12: false, - }).format(new Date(utcValue)); + }).format(new Date(appendUtcZ(value))); } +// Compact clock format: "00:05 min", "02:28 min", and "1:01:30 h" past an hour. +export function formatDurationSeconds(totalSeconds: number): string { + const s = Math.max(0, Math.round(totalSeconds)); + const pad = (n: number) => n.toString().padStart(2, '0'); + const hours = Math.floor(s / 3600); + const minutes = Math.floor((s % 3600) / 60); + const seconds = s % 60; + if (hours > 0) { + return `${hours}:${pad(minutes)}:${pad(seconds)} h`; + } + return `${pad(minutes)}:${pad(seconds)} min`; +} + +// Duration of a finished run, or null while it is still running. export function formatRunDuration(run: JobRun): string | null { if (!run.started_at || !run.finished_at) return null; - const seconds = Math.max( - 0, - Math.round( - (new Date(run.finished_at).getTime() - - new Date(run.started_at).getTime()) / - 1000, - ), + return formatDurationSeconds( + (toUtcMs(run.finished_at) - toUtcMs(run.started_at)) / 1000, ); - return `${seconds} s`; +} + +// Live elapsed time since the run started, relative to the given "now" (ms). +export function formatRunElapsed(run: JobRun, nowMs: number): string | null { + if (!run.started_at) return null; + return formatDurationSeconds((nowMs - toUtcMs(run.started_at)) / 1000); } -- 2.56.1 From 292c02cac8cc7f15b09b02ea3ef8915a43db6ee5 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Tue, 21 Jul 2026 10:28:20 +0200 Subject: [PATCH 42/60] feat(jobs): allow renaming a job in the edit dialog --- .../src/main/inse/background_jobs/model.py | 1 + .../src/main/inse/background_jobs/service.py | 20 +++++++++++++++++++ .../api/model/jobDefinitionUpdateRequest.ts | 1 + .../task-edit-dialog.component.html | 16 +++++++++++++-- .../task-edit-dialog.component.scss | 10 ++++------ .../task-edit-dialog.component.ts | 18 ++++++++++++++++- 6 files changed, 57 insertions(+), 9 deletions(-) diff --git a/service/src/main/inse/background_jobs/model.py b/service/src/main/inse/background_jobs/model.py index a45ac3ab..880218c1 100644 --- a/service/src/main/inse/background_jobs/model.py +++ b/service/src/main/inse/background_jobs/model.py @@ -99,6 +99,7 @@ class JobDefinitionCreateRequest(BaseModel): class JobDefinitionUpdateRequest(BaseModel): + name: Optional[str] = None image: Optional[str] = None command: Optional[str] = None env: Optional[dict[str, str]] = None diff --git a/service/src/main/inse/background_jobs/service.py b/service/src/main/inse/background_jobs/service.py index e6947edb..4522f19c 100644 --- a/service/src/main/inse/background_jobs/service.py +++ b/service/src/main/inse/background_jobs/service.py @@ -183,6 +183,26 @@ def update_task( detail=f"Invalid cron expression: '{changes['schedule']}'.", ) + if "name" in changes: + name = (changes["name"] or "").strip() + if not name: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="Task name must not be empty.", + ) + duplicate = session.exec( + select(JobDefinition).where( + JobDefinition.name == name, + JobDefinition.id != definition_id, + ) + ).first() + if duplicate: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail=f"A task named '{name}' already exists.", + ) + changes["name"] = name + definition = _get_definition(session, definition_id) for key, value in changes.items(): setattr(definition, key, value) diff --git a/webapp/src/app/api/model/jobDefinitionUpdateRequest.ts b/webapp/src/app/api/model/jobDefinitionUpdateRequest.ts index 33e96f6a..efd8d096 100644 --- a/webapp/src/app/api/model/jobDefinitionUpdateRequest.ts +++ b/webapp/src/app/api/model/jobDefinitionUpdateRequest.ts @@ -8,6 +8,7 @@ * Do not edit the class manually. */ export interface JobDefinitionUpdateRequest { + name?: string | null; image?: string | null; command?: string | null; env?: { [key: string]: string } | null; diff --git a/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.html b/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.html index d0ca14f1..dc75d179 100644 --- a/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.html +++ b/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.html @@ -1,9 +1,21 @@

Job bearbeiten

-

{{ data.task.name }}

-
+ + Name + + info_outline + @if (form.controls.name.invalid) { + Bitte einen Namen eingeben. + } + + Befehl + formControlName="image" + [matAutocomplete]="imageAuto" /> + + @for (image of filteredImages(); track image) { + {{ image }} + } + info_outline - Im Normalfall unverändert lassen. + @if (form.controls.image.invalid && form.controls.image.touched) { + Bitte ein Image auswählen oder eingeben. + } + Aus Nexus wählen oder eigenes Image eingeben. diff --git a/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.ts b/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.ts index 50858c76..ee841c3f 100644 --- a/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.ts +++ b/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.ts @@ -1,11 +1,13 @@ import { CommonModule } from '@angular/common'; -import { Component, inject, signal } from '@angular/core'; +import { Component, OnInit, computed, inject, signal } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; import { FormControl, FormGroup, ReactiveFormsModule, Validators, } from '@angular/forms'; +import { MatAutocompleteModule } from '@angular/material/autocomplete'; import { MatButtonModule } from '@angular/material/button'; import { MatDialogModule, MatDialogRef } from '@angular/material/dialog'; import { MatFormFieldModule } from '@angular/material/form-field'; @@ -23,6 +25,7 @@ const DEFAULT_JOB_IMAGE = 'docker.nes.uni-due.de/inse/background-jobs:latest'; imports: [ CommonModule, ReactiveFormsModule, + MatAutocompleteModule, MatButtonModule, MatDialogModule, MatFormFieldModule, @@ -34,7 +37,7 @@ const DEFAULT_JOB_IMAGE = 'docker.nes.uni-due.de/inse/background-jobs:latest'; styleUrl: './task-create-dialog.component.scss', standalone: true, }) -export class TaskCreateDialogComponent { +export class TaskCreateDialogComponent implements OnInit { private readonly dialogRef = inject< MatDialogRef @@ -43,6 +46,7 @@ export class TaskCreateDialogComponent { protected readonly creating = signal(false); protected readonly serverError = signal(''); + protected readonly images = signal([]); protected readonly form = new FormGroup({ name: new FormControl('', { @@ -52,10 +56,33 @@ export class TaskCreateDialogComponent { description: new FormControl('', { nonNullable: true }), targetIndex: new FormControl('', { nonNullable: true }), command: new FormControl('', { nonNullable: true }), - image: new FormControl(DEFAULT_JOB_IMAGE, { nonNullable: true }), + image: new FormControl(DEFAULT_JOB_IMAGE, { + nonNullable: true, + validators: [Validators.required], + }), env: new FormControl('', { nonNullable: true }), }); + private readonly imageQuery = toSignal( + this.form.controls.image.valueChanges, + { + initialValue: this.form.controls.image.value, + }, + ); + + protected readonly filteredImages = computed(() => { + const query = (this.imageQuery() ?? '').toLowerCase().trim(); + const all = this.images(); + if (!query) return all; + return all.filter((image) => image.toLowerCase().includes(query)); + }); + + ngOnInit(): void { + this.backgroundJobsService + .getBackgroundJobAvailableImages() + .subscribe({ next: (result) => this.images.set(result.images ?? []) }); + } + protected submit(): void { this.serverError.set(''); const value = this.form.getRawValue(); @@ -66,19 +93,23 @@ export class TaskCreateDialogComponent { return; } + const image = value.image.trim(); + if (!image) { + this.form.controls.image.markAsTouched(); + return; + } + const command = value.command.trim() || null; const env = this.parseEnv(value.env); if (env === undefined) return; - const image = value.image.trim(); - this.creating.set(true); this.backgroundJobsService .createBackgroundJobTask({ name, description: value.description.trim(), target_index: value.targetIndex.trim(), - image: !image || image === DEFAULT_JOB_IMAGE ? null : image, + image, command, env, }) diff --git a/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.html b/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.html index dc75d179..59f0b31f 100644 --- a/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.html +++ b/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.html @@ -34,18 +34,26 @@ Image - + formControlName="image" + [matAutocomplete]="imageAuto" /> + + @for (image of filteredImages(); track image) { + {{ image }} + } + info_outline - Im Normalfall unverändert lassen. + @if (form.controls.image.invalid && form.controls.image.touched) { + Bitte ein Image auswählen oder eingeben. + } + Aus Nexus wählen oder eigenes Image eingeben. diff --git a/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.ts b/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.ts index 776749a9..87f52cdd 100644 --- a/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.ts +++ b/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.ts @@ -1,11 +1,13 @@ import { CommonModule } from '@angular/common'; -import { Component, inject, signal } from '@angular/core'; +import { Component, OnInit, computed, inject, signal } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; import { FormControl, FormGroup, ReactiveFormsModule, Validators, } from '@angular/forms'; +import { MatAutocompleteModule } from '@angular/material/autocomplete'; import { MatButtonModule } from '@angular/material/button'; import { MAT_DIALOG_DATA, @@ -20,8 +22,6 @@ import { BackgroundJobTask, BackgroundJobsService } from '../../../api'; const ENV_LINE_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*=.*$/; -const DEFAULT_JOB_IMAGE = 'docker.nes.uni-due.de/inse/background-jobs:latest'; - export interface TaskEditDialogData { task: BackgroundJobTask; } @@ -31,6 +31,7 @@ export interface TaskEditDialogData { imports: [ CommonModule, ReactiveFormsModule, + MatAutocompleteModule, MatButtonModule, MatDialogModule, MatFormFieldModule, @@ -42,7 +43,7 @@ export interface TaskEditDialogData { styleUrl: './task-edit-dialog.component.scss', standalone: true, }) -export class TaskEditDialogComponent { +export class TaskEditDialogComponent implements OnInit { private readonly dialogRef = inject< MatDialogRef @@ -52,6 +53,7 @@ export class TaskEditDialogComponent { protected readonly saving = signal(false); protected readonly serverError = signal(''); + protected readonly images = signal([]); protected readonly form = new FormGroup({ name: new FormControl(this.data.task.name, { @@ -67,12 +69,35 @@ export class TaskEditDialogComponent { command: new FormControl(this.data.task.command ?? '', { nonNullable: true, }), - image: new FormControl(this.data.task.image, { nonNullable: true }), + image: new FormControl(this.data.task.image ?? '', { + nonNullable: true, + validators: [Validators.required], + }), env: new FormControl(this.envToText(this.data.task.env), { nonNullable: true, }), }); + private readonly imageQuery = toSignal( + this.form.controls.image.valueChanges, + { + initialValue: this.form.controls.image.value, + }, + ); + + protected readonly filteredImages = computed(() => { + const query = (this.imageQuery() ?? '').toLowerCase().trim(); + const all = this.images(); + if (!query) return all; + return all.filter((image) => image.toLowerCase().includes(query)); + }); + + ngOnInit(): void { + this.backgroundJobsService + .getBackgroundJobAvailableImages() + .subscribe({ next: (result) => this.images.set(result.images ?? []) }); + } + protected submit(): void { this.serverError.set(''); const value = this.form.getRawValue(); @@ -83,18 +108,22 @@ export class TaskEditDialogComponent { return; } + const image = value.image.trim(); + if (!image) { + this.form.controls.image.markAsTouched(); + return; + } + const env = this.parseEnv(value.env); if (env === undefined) return; - const image = value.image.trim(); - this.saving.set(true); this.backgroundJobsService .updateBackgroundJobTask(this.data.task.id, { name, description: value.description.trim(), target_index: value.targetIndex.trim(), - image: !image || image === DEFAULT_JOB_IMAGE ? null : image, + image, command: value.command.trim() || null, env, }) -- 2.56.1 From ee98b589c98100b0a25a6846b102b366be37f8da Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Thu, 23 Jul 2026 12:13:49 +0200 Subject: [PATCH 49/60] add Nexus registry credentials for job image listing --- service/src/main/inse/.env | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/service/src/main/inse/.env b/service/src/main/inse/.env index a5a055f2..36f353cf 100644 --- a/service/src/main/inse/.env +++ b/service/src/main/inse/.env @@ -16,4 +16,8 @@ ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FM SENTENCE_TRANSFORMERS_MODEL_NAME=intfloat/multilingual-e5-base TOKEN_ISSUER_ID=inse -TOKEN_HMAC_KEY=9dd09c80dd0796fa24bd2007f4cf57fc28c9a38909b7e83bb2d73121c5bc69c7 \ No newline at end of file +TOKEN_HMAC_KEY=9dd09c80dd0796fa24bd2007f4cf57fc28c9a38909b7e83bb2d73121c5bc69c7 + +# Docker-Registry-Login für Background-Jobs (Nexus, nes.uni-due.de) +BACKGROUND_JOBS_REGISTRY_USERNAME=student +BACKGROUND_JOBS_REGISTRY_PASSWORD=nes-student! \ No newline at end of file -- 2.56.1 From ddbf000213ed478ab8d6a0feda133a889694d169 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Thu, 23 Jul 2026 13:38:15 +0200 Subject: [PATCH 50/60] feat(jobs): fix table to not go out-of-bounds anymore during window resizing --- .../src/app/shared/ui/data-table/data-table.component.html | 5 ++++- .../src/app/shared/ui/data-table/data-table.component.scss | 4 ++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/webapp/src/app/shared/ui/data-table/data-table.component.html b/webapp/src/app/shared/ui/data-table/data-table.component.html index 7a66be7b..c7a62547 100644 --- a/webapp/src/app/shared/ui/data-table/data-table.component.html +++ b/webapp/src/app/shared/ui/data-table/data-table.component.html @@ -1,4 +1,7 @@ -
+
Date: Thu, 23 Jul 2026 22:59:06 +0200 Subject: [PATCH 51/60] feat(jobs): add per-job dockerfiles and requirements and unify logging format --- background-jobs/README.md | 2 +- background-jobs/app/elastic/client.py | 14 + background-jobs/app/sync.py | 59 ++-- service/scripts/demo/demo.py | 10 +- service/scripts/jobs-image/README.md | 65 +++++ .../scripts/jobs-image/bund-crawl/Dockerfile | 28 ++ .../jobs-image/bund-crawl/requirements.txt | 3 + service/scripts/jobs-image/demo-a/Dockerfile | 10 + service/scripts/jobs-image/demo-b/Dockerfile | 10 + service/scripts/jobs-image/demo-c/Dockerfile | 10 + .../scripts/jobs-image/news-crawl/Dockerfile | 21 ++ .../jobs-image/news-crawl/requirements.txt | 3 + .../jobs-image/news-keywords/Dockerfile | 21 ++ .../jobs-image/news-keywords/requirements.txt | 3 + .../scripts/jobs-image/news-topics/Dockerfile | 24 ++ .../jobs-image/news-topics/requirements.txt | 2 + .../jobs-image/project-topics/Dockerfile | 25 ++ .../project-topics/requirements.txt | 2 + service/scripts/news/ude/run_pipeline.py | 23 +- service/scripts/news/ude/upload_aktuell.py | 254 +++--------------- service/scripts/projects/bund/gpc.data.py | 196 ++++++-------- .../preprocessing.component.html | 204 ++++++++++++++ 22 files changed, 613 insertions(+), 376 deletions(-) create mode 100644 service/scripts/jobs-image/README.md create mode 100644 service/scripts/jobs-image/bund-crawl/Dockerfile create mode 100644 service/scripts/jobs-image/bund-crawl/requirements.txt create mode 100644 service/scripts/jobs-image/demo-a/Dockerfile create mode 100644 service/scripts/jobs-image/demo-b/Dockerfile create mode 100644 service/scripts/jobs-image/demo-c/Dockerfile create mode 100644 service/scripts/jobs-image/news-crawl/Dockerfile create mode 100644 service/scripts/jobs-image/news-crawl/requirements.txt create mode 100644 service/scripts/jobs-image/news-keywords/Dockerfile create mode 100644 service/scripts/jobs-image/news-keywords/requirements.txt create mode 100644 service/scripts/jobs-image/news-topics/Dockerfile create mode 100644 service/scripts/jobs-image/news-topics/requirements.txt create mode 100644 service/scripts/jobs-image/project-topics/Dockerfile create mode 100644 service/scripts/jobs-image/project-topics/requirements.txt create mode 100644 webapp/src/app/modules/preprocessing-mock-backup/preprocessing.component.html diff --git a/background-jobs/README.md b/background-jobs/README.md index e1bb7396..000e414c 100644 --- a/background-jobs/README.md +++ b/background-jobs/README.md @@ -49,7 +49,7 @@ docker push docker.nes.uni-due.de/inse/background-jobs:latest Lokal testen ohne Pull: ```bash -export INSE_BACKGROUND_JOBS_PULL_BEFORE_RUN=false +export BACKGROUND_JOBS_PULL_BEFORE_RUN=false ``` ## Scheduling diff --git a/background-jobs/app/elastic/client.py b/background-jobs/app/elastic/client.py index a3c06382..1ef0c6dc 100644 --- a/background-jobs/app/elastic/client.py +++ b/background-jobs/app/elastic/client.py @@ -57,6 +57,20 @@ def add_entry(index: str, entry: dict): return created_id +def index_entry(index: str, document_id: str, entry: dict): + + encoded_document_id = quote(document_id, safe="") + endpoint = f"{INSE_URL}/{index}/_doc/{encoded_document_id}" + + document_body = { + "news_id": entry["news_id"], + "relevant": int(entry["relevant"]), + "authors": entry["authors"], + "keywords": entry.get("keywords", []), + } + + return _send_es_request("PUT", endpoint, payload=document_body) + def update_entry(index: str, document_id: str, partial_doc: dict): encoded_document_id = quote(document_id, safe="") diff --git a/background-jobs/app/sync.py b/background-jobs/app/sync.py index c0cf185e..7c1fed29 100644 --- a/background-jobs/app/sync.py +++ b/background-jobs/app/sync.py @@ -3,13 +3,17 @@ import llm.client as llm_client import json import argparse import time +import logging import threading from concurrent.futures import ThreadPoolExecutor, as_completed +logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") +logger = logging.getLogger(__name__) + POSTPROC_INDEX = "aktuell_postproc" def print_pretty_json(data): - print(json.dumps(data, indent=2)) + logger.info(json.dumps(data, indent=2)) def sync_single_news(news_id, max_retries=3): attempt = 0 @@ -29,11 +33,11 @@ def sync_single_news(news_id, max_retries=3): return True except Exception as error: attempt += 1 - print(f"Warning syncing news_id {news_id} (Attempt {attempt}/{max_retries})") + logger.warning(f"Warning syncing news_id {news_id} (Attempt {attempt}/{max_retries})") if attempt < max_retries: time.sleep(1) else: - print(f"Error: {news_id} - {error}") + logger.error(f"Error: {news_id} - {error}") return False def update_keywords_single(postproc_entry, target_index=POSTPROC_INDEX, max_retries=3): @@ -48,13 +52,16 @@ def update_keywords_single(postproc_entry, target_index=POSTPROC_INDEX, max_retr if not keywords: # Empty article or unparseable LLM answer: writing an empty list # would look like a success and block a later retry. - print(f"Skipped {news_id}: no keywords extracted.") + logger.info(f"Skipped {news_id}: no keywords extracted.") return False if target_index == POSTPROC_INDEX: es_client.update_entry(POSTPROC_INDEX, doc_id, {"keywords": keywords}) else: - es_client.add_entry( + # Key the target doc on news_id so re-runs update it in place + # instead of piling up a new document each time. + es_client.index_entry( target_index, + news_id, { "news_id": news_id, "relevant": source.get("relevant", 0), @@ -65,11 +72,11 @@ def update_keywords_single(postproc_entry, target_index=POSTPROC_INDEX, max_retr return True except Exception as error: attempt += 1 - print(f"Warning updating keywords for news_id {news_id} (Attempt {attempt}/{max_retries})") + logger.warning(f"Warning updating keywords for news_id {news_id} (Attempt {attempt}/{max_retries})") if attempt < max_retries: time.sleep(1) else: - print(f"Error: {news_id} - {error}") + logger.error(f"Error: {news_id} - {error}") return False def main(): @@ -136,7 +143,7 @@ def main(): if args.reset_keywords: result = es_client.remove_field_all("aktuell_postproc", "keywords") - print(f"Removed 'keywords' from {result.get('updated', 0)} entries.") + logger.info(f"Removed 'keywords' from {result.get('updated', 0)} entries.") if args.sync_delta: start_time = time.time() @@ -147,7 +154,7 @@ def main(): target_ids = set(entry["_source"]["news_id"] for entry in postproc_ids_raw) missing_ids = source_ids - target_ids - print(f"Number of missing IDs: {len(missing_ids)}") + logger.info(f"Number of missing IDs: {len(missing_ids)}") missing_ids = list(missing_ids) total = len(missing_ids) @@ -164,11 +171,11 @@ def main(): processed += 1 if was_successful: succeeded += 1 - print(f"Sync: {processed} / {total}") + logger.info(f"Sync: {processed} / {total}") end_time = time.time() - print(f"Sync DONE: {succeeded} entries synced.") - print(f"Time taken: {end_time - start_time} seconds.") + logger.info(f"Sync DONE: {succeeded} entries synced.") + logger.info(f"Time taken: {end_time - start_time} seconds.") if args.update_keywords: start_time = time.time() @@ -178,20 +185,20 @@ def main(): if args.target_index == POSTPROC_INDEX: pending = [entry for entry in postproc_entries if not entry["_source"].get("keywords")] - print(f"Number of entries without keywords: {len(pending)}") + logger.info(f"Number of entries without keywords: {len(pending)}") else: # Writing elsewhere never marks the postproc entries, so the "missing # keywords" filter would select the same entries on every run. Pick # entries that already have keywords instead: those are known to come # from articles with actual content, unlike the empty archive stubs. pending = [entry for entry in postproc_entries if entry["_source"].get("keywords")] - print(f"Re-extracting keywords into '{args.target_index}': {len(pending)} candidates.") + logger.info(f"Re-extracting keywords into '{args.target_index}': {len(pending)} candidates.") if args.limit is not None: pending = pending[:args.limit] total = len(pending) - print(f"Processing {total} entries.") + logger.info(f"Processing {total} entries.") processed = 0 succeeded = 0 @@ -208,15 +215,15 @@ def main(): processed += 1 if was_successful: succeeded += 1 - print(f"Update keywords: {processed} / {total}") + logger.info(f"Update keywords: {processed} / {total}") end_time = time.time() - print(f"Update keywords DONE: {succeeded} entries updated.") - print(f"Time taken: {end_time - start_time} seconds.") + logger.info(f"Update keywords DONE: {succeeded} entries updated.") + logger.info(f"Time taken: {end_time - start_time} seconds.") if args.stats: aktuell_entries = es_client.get_all_entries("aktuell", fields=["_id"]) - print(f"Total entries in 'aktuell': {len(aktuell_entries)}") + logger.info(f"Total entries in 'aktuell': {len(aktuell_entries)}") postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["_id", "news_id", "relevant", "authors", "keywords"]) total_entries = len(postproc_entries) @@ -227,13 +234,13 @@ def main(): news_with_keywords = sum(1 for entry in postproc_entries if entry["_source"].get("keywords")) news_without_keywords = total_entries - news_with_keywords - print(f"Total entries in 'aktuell_postproc': {total_entries}") - print(f"Relevant entries: {relevant_count}") - print(f"Irrelevant entries: {irrelevant_count}") - print(f"Entries with extracted names: {news_with_extracted_names}") - print(f"Entries without extracted names: {news_without_extracted_names}") - print(f"Entries with keywords: {news_with_keywords}") - print(f"Entries without keywords: {news_without_keywords}") + logger.info(f"Total entries in 'aktuell_postproc': {total_entries}") + logger.info(f"Relevant entries: {relevant_count}") + logger.info(f"Irrelevant entries: {irrelevant_count}") + logger.info(f"Entries with extracted names: {news_with_extracted_names}") + logger.info(f"Entries without extracted names: {news_without_extracted_names}") + logger.info(f"Entries with keywords: {news_with_keywords}") + logger.info(f"Entries without keywords: {news_without_keywords}") if __name__ == "__main__": main() diff --git a/service/scripts/demo/demo.py b/service/scripts/demo/demo.py index a89e6dd0..5e505495 100644 --- a/service/scripts/demo/demo.py +++ b/service/scripts/demo/demo.py @@ -1,15 +1,19 @@ import sys import time +import logging + +logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") +logger = logging.getLogger(__name__) def main() -> None: seconds = int(sys.argv[1]) if len(sys.argv) > 1 else 20 - print(f"Demo job started, running for {seconds} seconds.", flush=True) + logger.info(f"Demo job started, running for {seconds} seconds.") for elapsed in range(1, seconds + 1): time.sleep(1) if elapsed % 5 == 0: - print(f"Progress: {elapsed}/{seconds} seconds.", flush=True) - print("Demo job finished successfully.", flush=True) + logger.info(f"Progress: {elapsed}/{seconds} seconds.") + logger.info("Demo job finished successfully.") if __name__ == "__main__": diff --git a/service/scripts/jobs-image/README.md b/service/scripts/jobs-image/README.md new file mode 100644 index 00000000..9135c57c --- /dev/null +++ b/service/scripts/jobs-image/README.md @@ -0,0 +1,65 @@ +# Per-Job Images + +One distinct Docker image per background job. Each image installs only its own +dependencies and bakes the job's command as its `ENTRYPOINT`, so a job runs with +no `command` override in the database — the job definition just points `image` at +the matching tag. + +This is deliberately different from the single shared-image model described in +[background-jobs/README.md](../../../background-jobs/README.md): here every job is +self-contained, at the cost of maintaining one Dockerfile per job. + +## Images + +| Job (DB name) | Image | Entrypoint | Notes | +| -------------------------- | --------------------- | ---------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| News-Crawler | `jobs/news-crawl` | `run_pipeline.py` | scrapy<2.13, Twisted<24.7; uploads to `NEWS_UPLOAD_INDEX` | +| Bund-Crawler | `jobs/bund-crawl` | `gpc.data.py --max-rows 200` | headless Chrome; uploads to `BUND_UPLOAD_INDEX`; capped, full export is ~300k rows | +| Projekt-Themen-Mapping | `jobs/project-topics` | `map_project_topics --output-index docker-job_test` | reads projects_bund_v1; needs host backend | +| News-Themen-Mapping | `jobs/news-topics` | `map_news_topics --output-index docker-job_test` | bundles both topic_mapper pkgs; needs host backend | +| News-Schlagwort-Extraktion | `jobs/news-keywords` | `sync.py --update-keywords --target-index docker-job_test` | ES + LLM creds; writes to test index | +| Demo-Job A / B / C | `jobs/demo-a/b/c` | `demo.py 20 / 25 / 30` | no dependencies | + +Each job is its own repository under the `jobs/` path namespace, prefixed +`docker.nes.uni-due.de/inse/` (e.g. `docker.nes.uni-due.de/inse/jobs/news-crawl:latest`). + +The entrypoints carry no run limits: anything set in the job's `command` field is +appended to the entrypoint, so limits (`--max-items`, `--max-docs`, `--limit`) are +passed per run from the UI. The one exception is the Bund-Crawler, which keeps a +`--max-rows` cap in the image because its full export is ~300k rows. + +## Build + +From the repo root (the build context must be the repo root so the Dockerfiles +can copy `service/scripts/…` and `background-jobs/app/`): + +```bash +docker build -f service/scripts/jobs-image/news-crawl/Dockerfile \ + -t docker.nes.uni-due.de/inse/jobs/news-crawl:latest . +docker push docker.nes.uni-due.de/inse/jobs/news-crawl:latest +``` + +Each job's Dockerfile header lists its own build command. + +## Running locally without pushing + +The backend tries to pull each image before a run. If the image isn't in the +registry, the pull fails softly and the local copy is used — so building locally +is enough for local runs. To skip the pull attempt entirely: + +```bash +export BACKGROUND_JOBS_PULL_BEFORE_RUN=false +``` + +## Env vars + +Because every tag lives under the `docker.nes.uni-due.de` registry host, the +backend treats these as registry images and injects the INSE Elasticsearch / LLM +credentials automatically (plus any per-job `env`). + +No image writes to a production index by default: the crawlers upload into the +index named by `NEWS_UPLOAD_INDEX` / `BUND_UPLOAD_INDEX` (both baked to +`docker-job_test` in their Dockerfile), and the mappers and the keyword +extraction write to `docker-job_test` via `--output-index` / `--target-index`. +To not contact Elasticsearch at all, pass `--skip-upload` (crawlers) or +`--dry-run` (mappers) through the job's command field. diff --git a/service/scripts/jobs-image/bund-crawl/Dockerfile b/service/scripts/jobs-image/bund-crawl/Dockerfile new file mode 100644 index 00000000..dcbebcbb --- /dev/null +++ b/service/scripts/jobs-image/bund-crawl/Dockerfile @@ -0,0 +1,28 @@ +# Bund-Crawler (foerderportal export via headless Chrome). Build from the repo root: +# docker build -f service/scripts/jobs-image/bund-crawl/Dockerfile -t docker.nes.uni-due.de/inse/jobs/bund-crawl:latest . +FROM python:3.13-slim + +WORKDIR /app +ENV PYTHONUNBUFFERED=1 +# Upload the crawled projects into the shared test index (gpc.data.py reads +# ELASTICSEARCH_INSE_* creds + BUND_UPLOAD_INDEX from the env). +ENV BUND_UPLOAD_INDEX=docker-job_test + +# Headless Chrome for the Selenium crawler. +RUN apt-get update \ + && apt-get install -y --no-install-recommends chromium chromium-driver \ + && rm -rf /var/lib/apt/lists/* +ENV CHROME_BIN=/usr/bin/chromium \ + CHROMEDRIVER_PATH=/usr/bin/chromedriver + +COPY service/scripts/jobs-image/bund-crawl/requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY service/scripts/projects/bund/ ./service/scripts/projects/bund/ + +WORKDIR /app/service/scripts/projects/bund + +# Capped on purpose: the full export is ~300k rows, so an uncapped run would +# write that entire volume into BUND_UPLOAD_INDEX. Raise or drop the cap by +# passing --max-rows N through the job's command field. +ENTRYPOINT ["python", "gpc.data.py", "--max-rows", "200"] diff --git a/service/scripts/jobs-image/bund-crawl/requirements.txt b/service/scripts/jobs-image/bund-crawl/requirements.txt new file mode 100644 index 00000000..f660d056 --- /dev/null +++ b/service/scripts/jobs-image/bund-crawl/requirements.txt @@ -0,0 +1,3 @@ +selenium~=4.20 +pandas~=2.2 +requests~=2.32 diff --git a/service/scripts/jobs-image/demo-a/Dockerfile b/service/scripts/jobs-image/demo-a/Dockerfile new file mode 100644 index 00000000..34fa453b --- /dev/null +++ b/service/scripts/jobs-image/demo-a/Dockerfile @@ -0,0 +1,10 @@ +# Demo-Job A. Build from the repo root: +# docker build -f service/scripts/jobs-image/demo-a/Dockerfile -t docker.nes.uni-due.de/inse/jobs/demo-a:latest . +FROM python:3.13-slim + +WORKDIR /app +ENV PYTHONUNBUFFERED=1 + +COPY service/scripts/demo/demo.py ./demo.py + +ENTRYPOINT ["python", "demo.py", "20"] diff --git a/service/scripts/jobs-image/demo-b/Dockerfile b/service/scripts/jobs-image/demo-b/Dockerfile new file mode 100644 index 00000000..7533c877 --- /dev/null +++ b/service/scripts/jobs-image/demo-b/Dockerfile @@ -0,0 +1,10 @@ +# Demo-Job B. Build from the repo root: +# docker build -f service/scripts/jobs-image/demo-b/Dockerfile -t docker.nes.uni-due.de/inse/jobs/demo-b:latest . +FROM python:3.13-slim + +WORKDIR /app +ENV PYTHONUNBUFFERED=1 + +COPY service/scripts/demo/demo.py ./demo.py + +ENTRYPOINT ["python", "demo.py", "25"] diff --git a/service/scripts/jobs-image/demo-c/Dockerfile b/service/scripts/jobs-image/demo-c/Dockerfile new file mode 100644 index 00000000..60896d34 --- /dev/null +++ b/service/scripts/jobs-image/demo-c/Dockerfile @@ -0,0 +1,10 @@ +# Demo-Job C. Build from the repo root: +# docker build -f service/scripts/jobs-image/demo-c/Dockerfile -t docker.nes.uni-due.de/inse/jobs/demo-c:latest . +FROM python:3.13-slim + +WORKDIR /app +ENV PYTHONUNBUFFERED=1 + +COPY service/scripts/demo/demo.py ./demo.py + +ENTRYPOINT ["python", "demo.py", "30"] diff --git a/service/scripts/jobs-image/news-crawl/Dockerfile b/service/scripts/jobs-image/news-crawl/Dockerfile new file mode 100644 index 00000000..86101794 --- /dev/null +++ b/service/scripts/jobs-image/news-crawl/Dockerfile @@ -0,0 +1,21 @@ +# News-Crawler (UDE 'aktuell'). Build from the repo root: +# docker build -f service/scripts/jobs-image/news-crawl/Dockerfile -t docker.nes.uni-due.de/inse/jobs/news-crawl:latest . +# +# scrapy<2.13 + Twisted<24.7 are load-bearing: the spiders use the removed +# start_requests() hook, and newer versions silently crawl 0 items. +FROM python:3.13-slim + +WORKDIR /app +ENV PYTHONUNBUFFERED=1 +# Upload the crawled articles into the shared test index (see upload_aktuell.py, +# which reads ELASTICSEARCH_INSE_* creds + NEWS_UPLOAD_INDEX from the env). +ENV NEWS_UPLOAD_INDEX=docker-job_test + +COPY service/scripts/jobs-image/news-crawl/requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY service/scripts/news/ude/ ./service/scripts/news/ude/ + +# Uncapped: crawls every article and uploads to NEWS_UPLOAD_INDEX. Limit a run by +# passing --max-items N through the job's command field. +ENTRYPOINT ["python", "service/scripts/news/ude/run_pipeline.py"] diff --git a/service/scripts/jobs-image/news-crawl/requirements.txt b/service/scripts/jobs-image/news-crawl/requirements.txt new file mode 100644 index 00000000..394c2a2d --- /dev/null +++ b/service/scripts/jobs-image/news-crawl/requirements.txt @@ -0,0 +1,3 @@ +scrapy>=2.11,<2.13 +Twisted>=22.10,<24.7 +requests~=2.32 diff --git a/service/scripts/jobs-image/news-keywords/Dockerfile b/service/scripts/jobs-image/news-keywords/Dockerfile new file mode 100644 index 00000000..e8059947 --- /dev/null +++ b/service/scripts/jobs-image/news-keywords/Dockerfile @@ -0,0 +1,21 @@ +# News keyword extraction (LLM keyword extraction into docker-job_test). +# Build from the repo root: +# docker build -f service/scripts/jobs-image/news-keywords/Dockerfile -t docker.nes.uni-due.de/inse/jobs/news-keywords:latest . +# +# Needs Elasticsearch + LLM creds (injected as env vars by the backend for +# registry images). Calls the LLM once per entry. +FROM python:3.13-slim + +WORKDIR /app +ENV PYTHONUNBUFFERED=1 + +COPY service/scripts/jobs-image/news-keywords/requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY background-jobs/app/ ./ + +# Writes into docker-job_test, leaving production aktuell_postproc untouched. +# A non-postproc target re-extracts entries that already have keywords (real +# content) and updates them in place, keyed on news_id (re-runs overwrite, no +# duplicates). Cap a run by appending --limit N via the job's command field. +ENTRYPOINT ["python", "sync.py", "--update-keywords", "--target-index", "docker-job_test"] diff --git a/service/scripts/jobs-image/news-keywords/requirements.txt b/service/scripts/jobs-image/news-keywords/requirements.txt new file mode 100644 index 00000000..d5f8a74c --- /dev/null +++ b/service/scripts/jobs-image/news-keywords/requirements.txt @@ -0,0 +1,3 @@ +requests~=2.32 +openai~=2.41 +python-dotenv~=1.0 diff --git a/service/scripts/jobs-image/news-topics/Dockerfile b/service/scripts/jobs-image/news-topics/Dockerfile new file mode 100644 index 00000000..0c14852e --- /dev/null +++ b/service/scripts/jobs-image/news-topics/Dockerfile @@ -0,0 +1,24 @@ +# News-Topic-Mapping (news keywords -> OpenAlex topics). Build from the repo root: +# docker build -f service/scripts/jobs-image/news-topics/Dockerfile -t docker.nes.uni-due.de/inse/jobs/news-topics:latest . +# +# map_news_topics imports map_project_topics as its "base", so both topic_mapper +# packages must be present. Needs a reachable backend and Elasticsearch creds +# (injected as env vars by the backend for registry images). +FROM python:3.13-slim + +WORKDIR /app +ENV PYTHONUNBUFFERED=1 + +COPY service/scripts/jobs-image/news-topics/requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY service/scripts/news/topic_mapper/ ./service/scripts/news/topic_mapper/ +COPY service/scripts/projects/topic_mapper/ ./service/scripts/projects/topic_mapper/ + +# Writes topic mappings into docker-job_test. Only maps (article, keyword) pairs +# not already present in the output index; pass --overwrite to re-map all. +# Uncapped: limit a run by passing --max-docs N through the job's command field. +# host.docker.internal reaches the host backend for vector search. +ENTRYPOINT ["python", "-m", "service.scripts.news.topic_mapper.map_news_topics", \ + "--output-index", "docker-job_test", \ + "--api-base-url", "http://host.docker.internal:8000"] diff --git a/service/scripts/jobs-image/news-topics/requirements.txt b/service/scripts/jobs-image/news-topics/requirements.txt new file mode 100644 index 00000000..7507eb03 --- /dev/null +++ b/service/scripts/jobs-image/news-topics/requirements.txt @@ -0,0 +1,2 @@ +httpx>=0.27 +python-dotenv>=1.0 diff --git a/service/scripts/jobs-image/project-topics/Dockerfile b/service/scripts/jobs-image/project-topics/Dockerfile new file mode 100644 index 00000000..f8a46a05 --- /dev/null +++ b/service/scripts/jobs-image/project-topics/Dockerfile @@ -0,0 +1,25 @@ +# Projekt-Topic-Mapping (bund keywords -> OpenAlex topics). Build from the repo root: +# docker build -f service/scripts/jobs-image/project-topics/Dockerfile -t docker.nes.uni-due.de/inse/jobs/project-topics:latest . +# +# Needs a reachable backend (vector search) and Elasticsearch creds. The creds +# arrive as env vars injected by the backend for registry images. +FROM python:3.13-slim + +WORKDIR /app +ENV PYTHONUNBUFFERED=1 + +COPY service/scripts/jobs-image/project-topics/requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY service/scripts/projects/topic_mapper/ ./service/scripts/projects/topic_mapper/ + +# Writes topic mappings into docker-job_test. Only maps (project, keyword) pairs +# not already present in the output index, so an interrupted run can be resumed. +# There is no overwrite flag: to re-map all, point --output-index at a fresh index. +# Uncapped: limit a run by passing --max-docs N through the job's command field. +# host.docker.internal reaches the host backend for vector search. +ENTRYPOINT ["python", "-m", "service.scripts.projects.topic_mapper.map_project_topics", \ + "--source-index", "projects_bund_v1", \ + "--text-field", "Leistungsplansystematik_fullname", \ + "--output-index", "docker-job_test", \ + "--api-base-url", "http://host.docker.internal:8000"] diff --git a/service/scripts/jobs-image/project-topics/requirements.txt b/service/scripts/jobs-image/project-topics/requirements.txt new file mode 100644 index 00000000..7507eb03 --- /dev/null +++ b/service/scripts/jobs-image/project-topics/requirements.txt @@ -0,0 +1,2 @@ +httpx>=0.27 +python-dotenv>=1.0 diff --git a/service/scripts/news/ude/run_pipeline.py b/service/scripts/news/ude/run_pipeline.py index 75f9e4b6..5f54229c 100644 --- a/service/scripts/news/ude/run_pipeline.py +++ b/service/scripts/news/ude/run_pipeline.py @@ -4,6 +4,11 @@ import os import shutil import time import argparse +import logging + +logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") +logger = logging.getLogger(__name__) + def run_command(command, cwd=None): """Run a shell command and exit if it fails.""" @@ -13,8 +18,8 @@ def run_command(command, cwd=None): #capture_output=True, #supresses output from subprocess text=True) if result.returncode != 0: - print(f"Command failed: {command}") - print("Error output:\n", result.stderr) + logger.error(f"Command failed: {command}") + logger.error(f"Error output:\n{result.stderr}") sys.exit(result.returncode) if __name__ == "__main__": @@ -50,25 +55,25 @@ if __name__ == "__main__": limit = f" -s CLOSESPIDER_ITEMCOUNT={args.max_items}" if args.max_items else "" - print("Running Scrapy link crawler...") + logger.info("Running Scrapy link crawler...") run_command(f"scrapy crawl aktuell-links -O \"{output_file_links}\"{limit}", cwd=crawler_dir) - print("Running Scrapy meta crawler...") + logger.info("Running Scrapy meta crawler...") run_command(f"scrapy crawl aktuell-metadata -O \"{output_file_meta}\"{limit}", cwd=crawler_dir) if args.skip_upload: - print("Skipping upload (--skip-upload): Elasticsearch was not contacted.") + logger.info("Skipping upload (--skip-upload): Elasticsearch was not contacted.") else: - print("Running upload script") + logger.info("Running upload script") run_command(f"{sys.executable} upload_aktuell.py {output_file_meta}", cwd=base_dir) end_time = time.time() runtime_seconds = end_time - start_time runtime_hours = runtime_seconds / 3600 - print(f"Runtime: {runtime_hours:.2f} hours") + logger.info(f"Runtime: {runtime_hours:.2f} hours") if args.skip_upload: - print("Finished crawling UDE news articles (no upload).") + logger.info("Finished crawling UDE news articles (no upload).") else: - print("Finished crawling and uploading UDE news articles.") + logger.info("Finished crawling and uploading UDE news articles.") diff --git a/service/scripts/news/ude/upload_aktuell.py b/service/scripts/news/ude/upload_aktuell.py index 72a9654e..c97bcb3e 100644 --- a/service/scripts/news/ude/upload_aktuell.py +++ b/service/scripts/news/ude/upload_aktuell.py @@ -1,231 +1,39 @@ -from elasticsearch import Elasticsearch import sys import os import json -from datetime import datetime import time +import logging +from urllib.parse import quote -# elasticsearch-connection should be adjusted -# uni-server -es = Elasticsearch() +import requests -index_name = "aktuell-test" #test indices to make sure everything works before uploading to the real index, ps. you lack rights to push to the real index, please contact the admin if you want to push to the real index +logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") +logger = logging.getLogger(__name__) +# The INSE key is index-scoped and can't hit cluster endpoints (e.g. GET /), so +# the elasticsearch client's ping/product-check would 403. We talk to the index +# endpoint directly over HTTP with the ApiKey header, like the other jobs do. +ES_URL = os.getenv("ELASTICSEARCH_INSE_URL", "http://localhost:9200").rstrip("/") +ES_API_KEY = os.getenv("ELASTICSEARCH_INSE_API_KEY") +# Default is a test index — you lack rights to push to the production index; +# contact the ES admin for that. Override via NEWS_UPLOAD_INDEX. +# The target index is never created here: an index that doesn't exist yet gets +# ES dynamic mapping, without the searchabilityAnalyzer the search relies on. +# Create it with the proper mapping before pointing a run at a new index. +INDEX_NAME = os.getenv("NEWS_UPLOAD_INDEX", "aktuell-test") -# checks if elastic is up and creates the index if not already done -def check_elastic(): - if not es.ping(): - sys.exit("No connection to Elasticsearch") +_session = requests.Session() +_session.headers.update({"Content-Type": "application/json"}) +if ES_API_KEY: + _session.headers.update({"Authorization": f"ApiKey {ES_API_KEY}"}) - if not es.indices.exists(index=index_name): - settings = { - "analysis": { - "analyzer": { - "searchabilityAnalyzer": { - "type": "custom", - "tokenizer": "standard", - "filter": [ - "lowercase", - "asciifolding" - ] - } - } - } - } - mappings = { - "properties": { - "subtitle": { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 - } - } - }, - "maintitle": { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 - } - } - }, - "author": { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 - } - } - }, - "date": { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 - } - } - }, - "date_year": { - "type": "long", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 - } - } - }, - "date_full": { - "type": "long", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 - } - } - }, - "intro_content": { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 - } - } - }, - "main_content": { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 - } - } - }, - "further_content": { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 - } - } - }, - "redaktion": { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 - } - } - }, - "full_content": { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 - } - } - }, - "tags": { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 - } - } - }, - "tags_nested": { - "type": "nested", - "properties": { - "tag": { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 250 - } - } - } - } - }, - #"links": { - # "type": "text", - # "analyzer": "searchabilityAnalyzer", - # "search_analyzer": "searchabilityAnalyzer", - # "fields": { - # "keyword": { - # "type": "keyword", - # "ignore_above": 256 - # } - # } - #}, - "links_nested": { - "type": "nested", - "properties": { - "url": { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 250 - } - } - }, - "text": { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 250 - } - } - } - } - }, - } - } - es.indices.create(index=index_name, mappings=mappings, settings=settings) def upload(path): - with open(path, "r", encoding='utf-8') as json_file: - + with open(path, "r", encoding="utf-8") as json_file: try: json_loaded = json.load(json_file) + uploaded = 0 for news in json_loaded: time.sleep(10 / 1000) id = (str(news["date"]) + "_" + str(news["author"]) + "_" + str(news["maintitle"])).replace(" ", "").replace("/", "").replace("ö", "").replace("ä", "").replace("ü", "").replace("Ö", "").replace("Ä", "").replace("Ü", "").replace(".", "").replace("?", "") @@ -241,7 +49,7 @@ def upload(path): for p in range(len(tags)): tags_nested.append({"tag": tags[p]}) - dict = { + document = { "subtitle": news["subtitle"], "maintitle": news["maintitle"], "tags": news["tags"], @@ -255,21 +63,25 @@ def upload(path): "tags_nested": tags_nested, "date_year": news["date_year"], "date_full": news["date_full"], - #"links": news["links"], "links_nested": links_nested, "url": news["url"] } - es.index(index=index_name, id=id, document=dict) + response = _session.put( + f"{ES_URL}/{INDEX_NAME}/_doc/{quote(id, safe='')}", + json=document, + ) + response.raise_for_status() + uploaded += 1 + + logger.info(f"Uploaded {uploaded} news articles to '{INDEX_NAME}'.") except Exception as e: - print("--- Failed to upload news.") - print(e) + logger.error(f"Failed to upload news: {e}") + # main - entry point if __name__ == '__main__': - check_elastic() - if len(sys.argv) != 2: sys.exit("No path given.") upload(sys.argv[1]) diff --git a/service/scripts/projects/bund/gpc.data.py b/service/scripts/projects/bund/gpc.data.py index 4cba5952..2d538982 100644 --- a/service/scripts/projects/bund/gpc.data.py +++ b/service/scripts/projects/bund/gpc.data.py @@ -12,15 +12,34 @@ import pandas as pd import json from datetime import datetime import sys -from elasticsearch import Elasticsearch, helpers -from elasticsearch.helpers import bulk,BulkIndexError import os +import math +import requests import hashlib import argparse +import logging + +logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") +logger = logging.getLogger(__name__) download_path=os.path.abspath(os.getcwd()) -es = Elasticsearch() + +# The INSE key is index-scoped and can't hit cluster endpoints (e.g. GET /), so +# the elasticsearch client's ping/product-check would 403. We POST to _bulk +# directly over HTTP with the ApiKey header, like the other jobs do. +ES_URL = os.getenv("ELASTICSEARCH_INSE_URL", "http://localhost:9200").rstrip("/") +ES_API_KEY = os.getenv("ELASTICSEARCH_INSE_API_KEY") +# Default is a test index — you lack rights to push to the production index; +# contact the ES admin for that. Override via BUND_UPLOAD_INDEX. +# The target index is never created here: an index that doesn't exist yet gets +# ES dynamic mapping, without the searchabilityAnalyzer the search relies on. +# Create it with the proper mapping before pointing a run at a new index. +INDEX_NAME = os.getenv("BUND_UPLOAD_INDEX", "projects_bund_test") + +_session = requests.Session() +if ES_API_KEY: + _session.headers.update({"Authorization": f"ApiKey {ES_API_KEY}"}) def crawl_data(link,driver): driver.get(link) @@ -42,123 +61,61 @@ def crawl_data(link,driver): time.sleep(2) # Switch to the alert and Clicks the "OK" button Alert(driver).accept() - print("downloading data") + logger.info("downloading data") else: # The element is likely a honeypot, do not interact - print("Honeypot detected, skipping interaction") + logger.info("Honeypot detected, skipping interaction") -def check_elastic_online(): - if not es.ping(): - sys.exit("No connection to Elasticsearch") - else : - print("Elasticsearch connection established") -def check_elastic_index(df, index_name): - - if not es.indices.exists(index=index_name): - print(index_name + " index wasn't found. Creating a new one..") - settings = { - "analysis": { - "analyzer": { - "searchabilityAnalyzer": { - "type": "custom", - "tokenizer": "standard", - "filter": [ - "lowercase", - "asciifolding" - ] - } - } - } - } - mappings = {} - properties = {} +def _clean(value): + # pandas/numpy scalars -> native python; NaN -> None (ES rejects NaN in JSON). + if hasattr(value, "item"): + value = value.item() + if isinstance(value, float) and math.isnan(value): + return None + return value - for key in list(df.columns): - if key in ("funding_start", "funding_end", "datum"): - properties[key] = { - "type": "date", - "format": "dd.MM.yyyy" - } - elif key == "Publikationsdatum": - properties[key] = { - "type": "date", - "format": "yyyy" - } - elif key == "unix_timestamp": - properties[key] = { - "type": "long" - } - elif key == "Fördersumme": - properties[key] = { - "type": "float" - } - elif key == "new": - properties[key] = { - "type": "boolean" - } - else: - properties[key] = { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 - } - } - } - - mappings["properties"] = properties - es.indices.create(index=index_name, mappings=mappings, settings=settings) - es.indices.refresh(index=index_name) - print("The new index '"+index_name+"' has been created") - else: - print(index_name + " already exists. Uploading data...") +def upload_data(df, index_name): + logger.info("Uploading data...") -def upload_data(df,index_name): - def fill_docs_to_upload(row): + docs = [] + for _, row in df.iterrows(): doc_id = hashlib.sha256(str(row['Förderkennzeichen']).encode('utf-8')).hexdigest() - doc = { - "_op_type": "update", # Update existing documents - "_index": index_name, - "_id": doc_id, - "doc": { - "new":False - }, - "upsert":{ - **row.to_dict(), - "new":True - } - } + source = {key: _clean(val) for key, val in row.to_dict().items()} + source["new"] = True + docs.append((doc_id, source)) - docs_to_upload.append(doc) - print("Uploading data...") - - try: - check_elastic_index(df, index_name) - except Exception as e: - print("Error while creating index") - print(e) - - docs_to_upload = [] - df.apply(fill_docs_to_upload,axis=1) - def bulk_docs(docs,data_rate): - response_sum = 0 - for i in range(0, len(docs), data_rate): - try: - response = helpers.bulk(es,docs[i:i + data_rate]) - response_sum = response_sum + response[0] - except BulkIndexError as e: - print(f"{len(e.errors)} document(s) failed to index.") - for error in e.errors: - print("Error details:", error) - print ("Upload is completed. "+ str(response_sum) +" documents have been uploaded." ) data_rate = 200 - bulk_docs(docs_to_upload,data_rate) + uploaded = 0 + for i in range(0, len(docs), data_rate): + batch = docs[i:i + data_rate] + lines = [] + for doc_id, source in batch: + # update + upsert: flag an existing project as not-new, or create an + # unseen one from the row (with new=True). + lines.append(json.dumps({"update": {"_index": index_name, "_id": doc_id}})) + lines.append(json.dumps({"doc": {"new": False}, "upsert": source}, default=str)) + payload = ("\n".join(lines) + "\n").encode("utf-8") + response = _session.post( + f"{ES_URL}/_bulk", + data=payload, + headers={"Content-Type": "application/x-ndjson"}, + ) + response.raise_for_status() + result = response.json() + if result.get("errors"): + failed = [item for item in result["items"] + if next(iter(item.values())).get("status", 200) >= 300] + logger.error(f"{len(failed)} document(s) failed to index.") + for item in failed[:5]: + logger.error(f"Error details: {item}") + uploaded += len(batch) - len(failed) + else: + uploaded += len(batch) + + logger.info(f"Upload is completed. {uploaded} documents have been uploaded to '{index_name}'.") @@ -171,7 +128,7 @@ def wait_for_file_complete(download_path,file_name): fname.endswith(".part") or fname.endswith(".crdownload") for fname in os.listdir(download_path) ): - print(f"Download complete: {file_name}") + logger.info(f"Download complete: {file_name}") return True if any(fname.endswith((".part", ".crdownload")) for fname in os.listdir(download_path)): time.sleep(1) @@ -181,7 +138,7 @@ def wait_for_file_complete(download_path,file_name): def format_data(df): - print("Formattind data...") + logger.info("Formatting data...") df.drop(list(df.filter(regex='.1|Unnamed')), axis=1, inplace=True) def clean_format(text): if isinstance(text, str): @@ -253,9 +210,15 @@ if __name__ == '__main__': action="store_true", help="Only crawl and format the export; never connect to Elasticsearch", ) + parser.add_argument( + "--max-rows", + type=int, + default=None, + help="Keep at most this many rows of the formatted export (e.g. for a smoke test).", + ) args = parser.parse_args() - print("Starting") + logger.info("Starting") file_path = os.path.join(os.path.abspath(os.getcwd()), 'Suchliste.csv') if not os.path.exists(file_path): driver = setup_chrome_driver(download_path) @@ -269,12 +232,13 @@ if __name__ == '__main__': df = pd.DataFrame(file) df_formatted = format_data(df) - index_name = "projects_bund_test" #test indices to make sure everything works before uploading to the real index, ps. you lack rights to push to the real index, please contact the admin if you want to push to the real index + if args.max_rows: + df_formatted = df_formatted.head(args.max_rows) + if args.skip_upload: - print(f"Skipping upload (--skip-upload): Elasticsearch was not contacted. " + logger.info(f"Skipping upload (--skip-upload): Elasticsearch was not contacted. " f"Formatted {len(df_formatted)} rows.") else: - check_elastic_online() - upload_data(df_formatted,index_name) + upload_data(df_formatted, INDEX_NAME) os.remove(file_path) \ No newline at end of file diff --git a/webapp/src/app/modules/preprocessing-mock-backup/preprocessing.component.html b/webapp/src/app/modules/preprocessing-mock-backup/preprocessing.component.html new file mode 100644 index 00000000..b13eb6f3 --- /dev/null +++ b/webapp/src/app/modules/preprocessing-mock-backup/preprocessing.component.html @@ -0,0 +1,204 @@ +
+ + + + +
+ + +
+ {{ containerStatus().name }} +
+ {{ containerStatus().image }} + {{ + containerStatus().imageDigest + }} + @switch (containerStatus().state) { + @case ('running') { + Läuft{{ + containerStatus().uptime + ? ' · seit ' + containerStatus().uptime + : '' + }} + } + @case ('stopped') { + Gestoppt + } + @case ('restarting') { + Wird neu gestartet … + } + } + @if (containerStatus().updateAvailable) { + + upgrade + Neue Version verfügbar + + } +
+
+
+ +
+ @if (containerStatus().updateAvailable) { + + } + @if (containerStatus().state === 'running') { + + + } @else { + + } +
+
+
+ + + + + + +
+ + +
+ {{ row.name }} + {{ row.description }} + {{ row.targetIndex }} +
+
+ + +
+ {{ formatSchedule(row.schedule) }} + +
+
+ + + @switch (row.status) { + @case ('running') { + + + Läuft + + } + @case ('success') { + + check_circle + Erfolgreich + + } + @case ('failed') { + + error + Fehlgeschlagen + + } + @default { + + schedule + Bereit + + } + } + + + + @if (row.lastRun) { +
+ {{ row.lastRun.startedAt | date: 'dd.MM.yyyy HH:mm' }} + {{ row.lastRun.message }} +
+ } @else { + Noch nicht ausgeführt + } +
+ + +
+ + +
+
-- 2.56.1 From 9d24c0a9bb660b4d740920c19db30ab2efcce7ba Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Fri, 24 Jul 2026 13:20:12 +0200 Subject: [PATCH 52/60] fix(jobs): start the new-job image field empty instead of prefilled --- .../jobs/task-create-dialog/task-create-dialog.component.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.ts b/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.ts index ee841c3f..d4d1ae50 100644 --- a/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.ts +++ b/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.ts @@ -18,8 +18,6 @@ import { BackgroundJobTask, BackgroundJobsService } from '../../../api'; const ENV_LINE_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*=.*$/; -const DEFAULT_JOB_IMAGE = 'docker.nes.uni-due.de/inse/background-jobs:latest'; - @Component({ selector: 'app-task-create-dialog', imports: [ @@ -56,7 +54,7 @@ export class TaskCreateDialogComponent implements OnInit { description: new FormControl('', { nonNullable: true }), targetIndex: new FormControl('', { nonNullable: true }), command: new FormControl('', { nonNullable: true }), - image: new FormControl(DEFAULT_JOB_IMAGE, { + image: new FormControl('', { nonNullable: true, validators: [Validators.required], }), -- 2.56.1 From f0caacd69604ffff929cb3d4191c4919f0fdd1a2 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Fri, 24 Jul 2026 14:05:37 +0200 Subject: [PATCH 53/60] feat(jobs): show Nexus registry reachability next to the Docker daemon --- .../src/main/inse/background_jobs/model.py | 6 + .../src/main/inse/background_jobs/router.py | 12 ++ .../src/main/inse/background_jobs/runner.py | 17 +++ .../src/main/inse/background_jobs/service.py | 9 ++ webapp/src/app/api/.openapi-generator/FILES | 1 + .../src/app/api/api/backgroundJobs.service.ts | 106 +++++++++++++++++ webapp/src/app/api/model/models.ts | 1 + webapp/src/app/api/model/registryHealth.ts | 15 +++ .../src/app/modules/jobs/jobs.component.html | 107 +++++++++++++----- .../src/app/modules/jobs/jobs.component.scss | 53 ++++++--- webapp/src/app/modules/jobs/jobs.component.ts | 41 +++++++ 11 files changed, 326 insertions(+), 42 deletions(-) create mode 100644 webapp/src/app/api/model/registryHealth.ts diff --git a/service/src/main/inse/background_jobs/model.py b/service/src/main/inse/background_jobs/model.py index 0cc7d37e..2a19fbef 100644 --- a/service/src/main/inse/background_jobs/model.py +++ b/service/src/main/inse/background_jobs/model.py @@ -135,6 +135,12 @@ class DockerHealth(BaseModel): detail: str +class RegistryHealth(BaseModel): + reachable: bool + detail: str + host: str + + class AvailableImages(BaseModel): images: list[str] detail: str = "" diff --git a/service/src/main/inse/background_jobs/router.py b/service/src/main/inse/background_jobs/router.py index 4a3b7d41..57b3704b 100644 --- a/service/src/main/inse/background_jobs/router.py +++ b/service/src/main/inse/background_jobs/router.py @@ -11,6 +11,7 @@ from .model import ( AvailableImages, BackgroundJobTask, DockerHealth, + RegistryHealth, JobDefinitionCreateRequest, JobDefinitionUpdateRequest, JobRun, @@ -147,3 +148,14 @@ async def docker_health( access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> DockerHealth: return service.docker_health(access_token) + + +@router.get( + "/registry-health", + operation_id="getBackgroundJobsRegistryHealth", + response_model=RegistryHealth, +) +async def registry_health( + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, +) -> RegistryHealth: + return service.registry_health(access_token) diff --git a/service/src/main/inse/background_jobs/runner.py b/service/src/main/inse/background_jobs/runner.py index 89a1c8f8..60d13a3c 100644 --- a/service/src/main/inse/background_jobs/runner.py +++ b/service/src/main/inse/background_jobs/runner.py @@ -45,6 +45,23 @@ def docker_reachable() -> tuple[bool, str]: return False, str(error) +def registry_reachable() -> tuple[bool, str]: + username = settings.background_jobs_registry_username + password = settings.background_jobs_registry_password + auth = (username, password) if username and password else None + host = registry_host() + try: + with httpx.Client(timeout=8.0, auth=auth) as client: + response = client.get(f"https://{host}/v2/") + if response.status_code == 200: + return True, "ok" + if response.status_code == 401: + return False, "authentication failed (401)" + return False, f"unexpected status {response.status_code}" + except Exception as error: # noqa: BLE001 + return False, str(error) + + def compute_next_run(schedule: str) -> datetime: return croniter(schedule, utcnow()).get_next(datetime) diff --git a/service/src/main/inse/background_jobs/service.py b/service/src/main/inse/background_jobs/service.py index 581557d9..9f27b30e 100644 --- a/service/src/main/inse/background_jobs/service.py +++ b/service/src/main/inse/background_jobs/service.py @@ -17,6 +17,7 @@ from .model import ( AvailableImages, BackgroundJobTask, DockerHealth, + RegistryHealth, JobDefinition, JobDefinitionCreateRequest, JobDefinitionUpdateRequest, @@ -390,3 +391,11 @@ def docker_health(access_token: AccessTokenMetadata) -> DockerHealth: _require_super_admin(access_token) reachable, detail = runner.docker_reachable() return DockerHealth(reachable=reachable, detail=detail) + + +def registry_health(access_token: AccessTokenMetadata) -> RegistryHealth: + _require_super_admin(access_token) + reachable, detail = runner.registry_reachable() + return RegistryHealth( + reachable=reachable, detail=detail, host=runner.registry_host() + ) diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index ded62dd1..edff19a7 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -192,6 +192,7 @@ model/publicationIdsByAuthorPosition.ts model/publicationsByAuthorResponse.ts model/rankingResponse.ts model/rebuildResponse.ts +model/registryHealth.ts model/score.ts model/sortDirection.ts model/tokenType.ts diff --git a/webapp/src/app/api/api/backgroundJobs.service.ts b/webapp/src/app/api/api/backgroundJobs.service.ts index 2617efd6..8df591c2 100644 --- a/webapp/src/app/api/api/backgroundJobs.service.ts +++ b/webapp/src/app/api/api/backgroundJobs.service.ts @@ -38,6 +38,8 @@ import { JobDefinitionUpdateRequest } from '../model/jobDefinitionUpdateRequest' import { JobRun } from '../model/jobRun'; // @ts-ignore import { JobRunLogs } from '../model/jobRunLogs'; +// @ts-ignore +import { RegistryHealth } from '../model/registryHealth'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; @@ -856,6 +858,110 @@ export class BackgroundJobsService extends BaseService { ); } + /** + * Registry Health + * @endpoint get /api/background-jobs/registry-health + * @param secureFgpAcc + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getBackgroundJobsRegistryHealth( + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getBackgroundJobsRegistryHealth( + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getBackgroundJobsRegistryHealth( + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getBackgroundJobsRegistryHealth( + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/background-jobs/registry-health`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + /** * Run Task * @endpoint post /api/background-jobs/tasks/{task_id}/run diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index c07e9caa..9a5c1383 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -162,6 +162,7 @@ export * from './publicationIdsByAuthorPosition'; export * from './publicationsByAuthorResponse'; export * from './rankingResponse'; export * from './rebuildResponse'; +export * from './registryHealth'; export * from './score'; export * from './sortDirection'; export * from './tokenType'; diff --git a/webapp/src/app/api/model/registryHealth.ts b/webapp/src/app/api/model/registryHealth.ts new file mode 100644 index 00000000..dc9411bd --- /dev/null +++ b/webapp/src/app/api/model/registryHealth.ts @@ -0,0 +1,15 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +export interface RegistryHealth { + reachable: boolean; + detail: string; + host: string; +} diff --git a/webapp/src/app/modules/jobs/jobs.component.html b/webapp/src/app/modules/jobs/jobs.component.html index 429e494c..40e432be 100644 --- a/webapp/src/app/modules/jobs/jobs.component.html +++ b/webapp/src/app/modules/jobs/jobs.component.html @@ -18,37 +18,86 @@ - - -
- - -
- Docker-Daemon -
- {{ dockerHealth()?.reachable ? 'Erreichbar' : 'Nicht erreichbar' }} - @if (dockerHealth()?.detail) { - · {{ dockerHealth()?.detail }} - } +
+ + +
+ + +
+ Docker-Daemon +
+ {{ + dockerHealth()?.reachable ? 'Erreichbar' : 'Nicht erreichbar' + }} + @if (dockerHealth()?.detail) { + · {{ dockerHealth()?.detail }} + } +
-
- - - + + + + + + +
+ + +
+
+ Nexus-Registry + @if (registryHealth()?.host) { + {{ registryHealth()?.host }} + } +
+
+ @if (registryHealthLoading() && !registryHealth()) { + Wird geprüft … + } @else { + {{ + registryHealth()?.reachable + ? 'Erreichbar' + : 'Nicht erreichbar' + }} + @if (registryHealth()?.detail) { + · {{ registryHealth()?.detail }} + } + } +
+
+
+ +
+
+
diff --git a/webapp/src/app/modules/jobs/jobs.component.scss b/webapp/src/app/modules/jobs/jobs.component.scss index b131ba42..817af734 100644 --- a/webapp/src/app/modules/jobs/jobs.component.scss +++ b/webapp/src/app/modules/jobs/jobs.component.scss @@ -37,20 +37,35 @@ mat-paginator { background-color: var(--sg-background); } -.docker-health-content { +.health-cards { display: flex; - align-items: center; - justify-content: space-between; - gap: 16px; -} - -.docker-health-info { - display: flex; - align-items: flex-start; gap: 12px; } -.docker-state-dot { +.health-card { + flex: 1 1 0; + min-width: 0; +} + +.health-content { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} + +.health-info { + display: flex; + align-items: flex-start; + gap: 12px; + min-width: 0; +} + +.health-text { + min-width: 0; +} + +.state-dot { margin-top: 6px; width: 10px; height: 10px; @@ -67,11 +82,24 @@ mat-paginator { } } -.docker-health-detail { +.health-detail { font-size: 12px; color: #64748b; } +.health-title { + display: flex; + align-items: baseline; + gap: 8px; + flex-wrap: wrap; +} + +.health-host { + font-size: 11px; + color: #64748b; + word-break: break-all; +} + :host ::ng-deep .mat-mdc-row { height: 96px; } @@ -283,8 +311,7 @@ mat-paginator { flex-direction: column; } - .docker-health-content { + .health-cards { flex-direction: column; - align-items: flex-start; } } diff --git a/webapp/src/app/modules/jobs/jobs.component.ts b/webapp/src/app/modules/jobs/jobs.component.ts index f7bdb907..ccf3e90c 100644 --- a/webapp/src/app/modules/jobs/jobs.component.ts +++ b/webapp/src/app/modules/jobs/jobs.component.ts @@ -30,6 +30,7 @@ import { BackgroundJobsService, BackgroundJobTask, DockerHealth, + RegistryHealth, } from '../../api'; import { DataTableComponent, @@ -89,6 +90,8 @@ export class JobsComponent implements OnInit { protected readonly tasks = signal([]); protected readonly dockerHealth = signal(null); protected readonly dockerHealthLoading = signal(false); + protected readonly registryHealth = signal(null); + protected readonly registryHealthLoading = signal(false); protected readonly deletingTaskIds = signal>(new Set()); protected readonly nowMs = signal(Date.now()); @@ -123,6 +126,7 @@ export class JobsComponent implements OnInit { ngOnInit(): void { this.tasks.set(this.tasksInput()); this.dockerHealth.set(this.dockerHealthInput()); + this.refreshRegistryHealth(); merge(this.pollNow, this.taskRefreshTrigger) .pipe( @@ -249,6 +253,39 @@ export class JobsComponent implements OnInit { }); } + protected refreshRegistryHealth(): void { + this.registryHealthLoading.set(true); + this.backgroundJobsService + .getBackgroundJobsRegistryHealth() + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe({ + next: (health) => { + this.registryHealth.set(health); + this.registryHealthLoading.set(false); + }, + error: () => { + this.registryHealthLoading.set(false); + this.showError('Nexus-Status konnte nicht abgerufen werden.'); + }, + }); + } + + private notifyIfRegistryDown(): void { + this.backgroundJobsService + .getBackgroundJobsRegistryHealth() + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe({ + next: (health) => { + this.registryHealth.set(health); + if (!health.reachable) { + this.showError( + `Nexus-Registry nicht erreichbar: ${health.detail}. Die Image-Auswahl bleibt leer.`, + ); + } + }, + }); + } + protected runNow(task: BackgroundJobTask): void { if (['running', 'stopping'].includes(task.status)) return; @@ -334,6 +371,8 @@ export class JobsComponent implements OnInit { } protected openCreateDialog(): void { + this.notifyIfRegistryDown(); + const dialogRef = this.dialog.open< TaskCreateDialogComponent, void, @@ -359,6 +398,8 @@ export class JobsComponent implements OnInit { protected openEditDialog(task: BackgroundJobTask): void { if (['running', 'stopping'].includes(task.status)) return; + this.notifyIfRegistryDown(); + const dialogRef = this.dialog.open< TaskEditDialogComponent, TaskEditDialogData, -- 2.56.1 From e8b5dcfd5b649db4960f446646a58ea6b9418aad Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Fri, 24 Jul 2026 14:12:22 +0200 Subject: [PATCH 54/60] feat(jobs): fail the run when a registry image can't be pulled instead of using a local copy --- .../src/main/inse/background_jobs/runner.py | 25 +++++++++++-------- webapp/src/app/modules/jobs/jobs.component.ts | 20 ++++++++++----- 2 files changed, 28 insertions(+), 17 deletions(-) diff --git a/service/src/main/inse/background_jobs/runner.py b/service/src/main/inse/background_jobs/runner.py index 60d13a3c..e0892ad2 100644 --- a/service/src/main/inse/background_jobs/runner.py +++ b/service/src/main/inse/background_jobs/runner.py @@ -151,15 +151,8 @@ def registry_auth() -> Optional[dict[str, str]]: def pull_image(image: str) -> None: - try: - get_docker_client().images.pull(image, auth_config=registry_auth()) - logger.info("Pulled image '%s' from the registry.", image) - except Exception: - logger.warning( - "Could not pull image '%s'; using the local copy if present.", - image, - exc_info=True, - ) + get_docker_client().images.pull(image, auth_config=registry_auth()) + logger.info("Pulled image '%s' from the registry.", image) def start_run( @@ -180,9 +173,19 @@ def start_run( session.refresh(run) return run - try: - if settings.background_jobs_pull_before_run: + if settings.background_jobs_pull_before_run and is_registry_image(image): + try: pull_image(image) + except Exception as error: # noqa: BLE001 + run.status = JobRunStatus.FAILED + run.finished_at = utcnow() + run.logs = f"failed to pull image '{image}': {error}" + session.add(run) + session.commit() + session.refresh(run) + return run + + try: container = get_docker_client().containers.run( image=image, command=resolve_command(definition), diff --git a/webapp/src/app/modules/jobs/jobs.component.ts b/webapp/src/app/modules/jobs/jobs.component.ts index ccf3e90c..97a53644 100644 --- a/webapp/src/app/modules/jobs/jobs.component.ts +++ b/webapp/src/app/modules/jobs/jobs.component.ts @@ -291,16 +291,24 @@ export class JobsComponent implements OnInit { this.backgroundJobsService.runBackgroundJobTask(task.id).subscribe({ next: (run) => { + const status = run.status ?? 'running'; this.updateTask(task.id, (current) => ({ ...current, - status: 'running', + status, last_run: run, })); - this.snackBar.open(`„${task.name}“ wurde gestartet.`, 'OK', { - duration: 3000, - horizontalPosition: 'center', - verticalPosition: 'bottom', - }); + if (status === 'failed') { + this.showError( + `„${task.name}“ ist fehlgeschlagen — Details in den Logs.`, + ); + this.refreshRegistryHealth(); + } else { + this.snackBar.open(`„${task.name}“ wurde gestartet.`, 'OK', { + duration: 3000, + horizontalPosition: 'center', + verticalPosition: 'bottom', + }); + } this.refreshTasks(); }, error: (error) => -- 2.56.1 From 467f40a625d34275f4d0fa27f41fa3469bfba3a7 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Fri, 24 Jul 2026 14:27:04 +0200 Subject: [PATCH 55/60] feat(jobs): name job containers after the job instead of its id --- service/src/main/inse/background_jobs/runner.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/service/src/main/inse/background_jobs/runner.py b/service/src/main/inse/background_jobs/runner.py index e0892ad2..288b9fb8 100644 --- a/service/src/main/inse/background_jobs/runner.py +++ b/service/src/main/inse/background_jobs/runner.py @@ -5,6 +5,7 @@ periodic schedule/reconcile loop. import asyncio import logging +import re from datetime import datetime from threading import RLock from typing import Optional @@ -129,6 +130,18 @@ def is_registry_image(image: Optional[str]) -> bool: return bool(image) and image.split("/", 1)[0] == registry_host() +def container_name(definition: JobDefinition, run: JobRun) -> str: + slug = definition.name.lower() + slug = ( + slug.replace("ä", "ae") + .replace("ö", "oe") + .replace("ü", "ue") + .replace("ß", "ss") + ) + slug = re.sub(r"[^a-z0-9]+", "-", slug).strip("-")[:40].strip("-") + return f"{slug or 'job'}-run-{run.id}" + + def resolve_command(definition: JobDefinition): return definition.command or None @@ -191,7 +204,7 @@ def start_run( command=resolve_command(definition), environment=resolve_environment(definition), detach=True, - name=f"background-job-{definition.id}-run-{run.id}", + name=container_name(definition, run), remove=False, ) run.container_id = container.id -- 2.56.1 From ceed96102f8c2c12a15dba8e67df46aeaebfabc8 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Fri, 24 Jul 2026 14:32:51 +0200 Subject: [PATCH 56/60] style(jobs): center and enlarge the health status dot --- webapp/src/app/modules/jobs/jobs.component.scss | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/webapp/src/app/modules/jobs/jobs.component.scss b/webapp/src/app/modules/jobs/jobs.component.scss index 817af734..1777b492 100644 --- a/webapp/src/app/modules/jobs/jobs.component.scss +++ b/webapp/src/app/modules/jobs/jobs.component.scss @@ -56,7 +56,7 @@ mat-paginator { .health-info { display: flex; - align-items: flex-start; + align-items: center; gap: 12px; min-width: 0; } @@ -66,9 +66,8 @@ mat-paginator { } .state-dot { - margin-top: 6px; - width: 10px; - height: 10px; + width: 12px; + height: 12px; border-radius: 50%; background: #94a3b8; flex-shrink: 0; -- 2.56.1 From 358a47bbf5005502753cc9b922ffd7937a0c44a0 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Fri, 24 Jul 2026 14:33:21 +0200 Subject: [PATCH 57/60] feat(jobs): remove individual demo image creation --- service/scripts/jobs-image/README.md | 34 +++++++++++--------- service/scripts/jobs-image/demo-a/Dockerfile | 10 ------ service/scripts/jobs-image/demo-b/Dockerfile | 10 ------ service/scripts/jobs-image/demo-c/Dockerfile | 10 ------ 4 files changed, 18 insertions(+), 46 deletions(-) delete mode 100644 service/scripts/jobs-image/demo-a/Dockerfile delete mode 100644 service/scripts/jobs-image/demo-b/Dockerfile delete mode 100644 service/scripts/jobs-image/demo-c/Dockerfile diff --git a/service/scripts/jobs-image/README.md b/service/scripts/jobs-image/README.md index 9135c57c..89b2fbaf 100644 --- a/service/scripts/jobs-image/README.md +++ b/service/scripts/jobs-image/README.md @@ -1,27 +1,29 @@ -# Per-Job Images +# Job Images -One distinct Docker image per background job. Each image installs only its own -dependencies and bakes the job's command as its `ENTRYPOINT`, so a job runs with -no `command` override in the database — the job definition just points `image` at -the matching tag. +One Docker image per job script. Each image installs only its own dependencies +and bakes its script as the `ENTRYPOINT`. Most jobs then run with no `command` +override — the job definition just points `image` at the matching tag. Where +several jobs share one script (the demos), they point at the same image and +differ only by their `command`. This is deliberately different from the single shared-image model described in -[background-jobs/README.md](../../../background-jobs/README.md): here every job is -self-contained, at the cost of maintaining one Dockerfile per job. +[background-jobs/README.md](../../../background-jobs/README.md): here every script +is self-contained, at the cost of maintaining one Dockerfile per script. ## Images -| Job (DB name) | Image | Entrypoint | Notes | -| -------------------------- | --------------------- | ---------------------------------------------------------- | ---------------------------------------------------------------------------------- | -| News-Crawler | `jobs/news-crawl` | `run_pipeline.py` | scrapy<2.13, Twisted<24.7; uploads to `NEWS_UPLOAD_INDEX` | -| Bund-Crawler | `jobs/bund-crawl` | `gpc.data.py --max-rows 200` | headless Chrome; uploads to `BUND_UPLOAD_INDEX`; capped, full export is ~300k rows | -| Projekt-Themen-Mapping | `jobs/project-topics` | `map_project_topics --output-index docker-job_test` | reads projects_bund_v1; needs host backend | -| News-Themen-Mapping | `jobs/news-topics` | `map_news_topics --output-index docker-job_test` | bundles both topic_mapper pkgs; needs host backend | -| News-Schlagwort-Extraktion | `jobs/news-keywords` | `sync.py --update-keywords --target-index docker-job_test` | ES + LLM creds; writes to test index | -| Demo-Job A / B / C | `jobs/demo-a/b/c` | `demo.py 20 / 25 / 30` | no dependencies | +| Job (DB name) | Image | Entrypoint | Notes | +| ----------------------- | --------------------- | ---------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| News-Crawler | `jobs/news-crawl` | `run_pipeline.py` | scrapy<2.13, Twisted<24.7; uploads to `NEWS_UPLOAD_INDEX` | +| Bund-Crawler | `jobs/bund-crawl` | `gpc.data.py --max-rows 200` | headless Chrome; uploads to `BUND_UPLOAD_INDEX`; capped, full export is ~300k rows | +| Project-Topic-Mapping | `jobs/project-topics` | `map_project_topics --output-index docker-job_test` | reads projects_bund_v1; needs host backend | +| News-Topic-Mapping | `jobs/news-topics` | `map_news_topics --output-index docker-job_test` | bundles both topic_mapper pkgs; needs host backend | +| News-Keyword-Extraction | `jobs/news-keywords` | `sync.py --update-keywords --target-index docker-job_test` | ES + LLM creds; writes to test index | +| Demo-Job A / B / C | `jobs/demo` | `demo.py` (seconds via command: `20` / `25` / `30`) | no dependencies; one image, three job rows | -Each job is its own repository under the `jobs/` path namespace, prefixed +Each image is its own repository under the `jobs/` path namespace, prefixed `docker.nes.uni-due.de/inse/` (e.g. `docker.nes.uni-due.de/inse/jobs/news-crawl:latest`). +The three demo jobs share the single `jobs/demo` repository. The entrypoints carry no run limits: anything set in the job's `command` field is appended to the entrypoint, so limits (`--max-items`, `--max-docs`, `--limit`) are diff --git a/service/scripts/jobs-image/demo-a/Dockerfile b/service/scripts/jobs-image/demo-a/Dockerfile deleted file mode 100644 index 34fa453b..00000000 --- a/service/scripts/jobs-image/demo-a/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -# Demo-Job A. Build from the repo root: -# docker build -f service/scripts/jobs-image/demo-a/Dockerfile -t docker.nes.uni-due.de/inse/jobs/demo-a:latest . -FROM python:3.13-slim - -WORKDIR /app -ENV PYTHONUNBUFFERED=1 - -COPY service/scripts/demo/demo.py ./demo.py - -ENTRYPOINT ["python", "demo.py", "20"] diff --git a/service/scripts/jobs-image/demo-b/Dockerfile b/service/scripts/jobs-image/demo-b/Dockerfile deleted file mode 100644 index 7533c877..00000000 --- a/service/scripts/jobs-image/demo-b/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -# Demo-Job B. Build from the repo root: -# docker build -f service/scripts/jobs-image/demo-b/Dockerfile -t docker.nes.uni-due.de/inse/jobs/demo-b:latest . -FROM python:3.13-slim - -WORKDIR /app -ENV PYTHONUNBUFFERED=1 - -COPY service/scripts/demo/demo.py ./demo.py - -ENTRYPOINT ["python", "demo.py", "25"] diff --git a/service/scripts/jobs-image/demo-c/Dockerfile b/service/scripts/jobs-image/demo-c/Dockerfile deleted file mode 100644 index 60896d34..00000000 --- a/service/scripts/jobs-image/demo-c/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -# Demo-Job C. Build from the repo root: -# docker build -f service/scripts/jobs-image/demo-c/Dockerfile -t docker.nes.uni-due.de/inse/jobs/demo-c:latest . -FROM python:3.13-slim - -WORKDIR /app -ENV PYTHONUNBUFFERED=1 - -COPY service/scripts/demo/demo.py ./demo.py - -ENTRYPOINT ["python", "demo.py", "30"] -- 2.56.1 From 18f661e3b4ad382d99e27388e03998ce9a55fabd Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Fri, 24 Jul 2026 14:55:24 +0200 Subject: [PATCH 58/60] docs(jobs): document the UI create/edit workflow --- service/scripts/jobs-image/README.md | 84 +++++++++++++++++++++++++--- 1 file changed, 77 insertions(+), 7 deletions(-) diff --git a/service/scripts/jobs-image/README.md b/service/scripts/jobs-image/README.md index 89b2fbaf..e3cb74e3 100644 --- a/service/scripts/jobs-image/README.md +++ b/service/scripts/jobs-image/README.md @@ -1,14 +1,78 @@ # Job Images +## Anlegen und Bearbeiten eines Jobs (UI) + +Ein Job im Frontend ist nur eine **Definition** in der Datenbank, die auf ein +Image zeigt. Der eigentliche Job-Code steckt im Image. Reihenfolge daher immer: +**erst das Image nach Nexus pushen, dann den Job in der UI anlegen.** + +### 1. Image bauen und pushen + +Aus dem Repo-Root (Build-Kontext = Root), Beispiel News-Crawler (jedes +Dockerfile nennt in seinem Kopf den eigenen Build-Befehl): + +```bash +docker build -f service/scripts/jobs-image/news-crawl/Dockerfile \ + -t docker.nes.uni-due.de/inse/jobs/news-crawl:latest . +docker push docker.nes.uni-due.de/inse/jobs/news-crawl:latest +``` + +Login zu Nexus vorher, falls nötig: `docker login docker.nes.uni-due.de` +(Zugangsdaten wie in der Backend-`.env`, `BACKGROUND_JOBS_REGISTRY_*`). + +Erst wenn Push erfolgreich war, taucht das Image in der Image-Auswahl der UI auf. + +### 2. Job anlegen + +1. Als **Superadmin** anmelden und die Seite **Jobs** öffnen. +2. Oben rechts prüfen, dass die Karten **Docker-Daemon** und **Nexus-Registry** + grün („Erreichbar") sind. Ist Nexus rot, bleibt die Image-Auswahl leer — + dann Registry/`.env` prüfen, bevor es weitergeht. +3. Auf **Neuer Job** klicken. Im Dialog: + - **Name** – Pflichtfeld, muss eindeutig sein (sonst 409). + - **Beschreibung**, **Ziel-Index** – optional, nur zur Anzeige. + - **Image** – Pflichtfeld. In das Feld tippen und aus der + Nexus-Autovervollständigung den passenden Tag wählen, z. B. + `docker.nes.uni-due.de/inse/jobs/news-crawl:latest`. Leer = Fehler. + - **Befehl** – optional. Wird an den `ENTRYPOINT` des Images **angehängt** + (z. B. `--max-items 50`). Leer lassen, wenn die Image-Defaults reichen. + - **Umgebungsvariablen** – optional, `KEY=VALUE` pro Zeile. Bei + Nexus-Images werden die INSE-Zugangsdaten (Elasticsearch/LLM) ohnehin + automatisch ergänzt; hier nur Zusätzliches/Overrides. +4. **Speichern**. Der Job erscheint in der Tabelle, zunächst ohne Zeitplan + (= nur manuell). + +### 3. Job ausführen und beobachten + +- **▶ Jetzt ausführen** startet einen Lauf. Das Backend pullt das Image und + startet einen Container namens `-run-`. +- **⏹ Stoppen** bricht einen laufenden Lauf ab. +- **🗎 Logs** zeigt die Container-Logs (live während des Laufs, danach die in der + DB gespeicherten letzten Zeilen) sowie Dauer bzw. „läuft seit". +- Schlägt der Pull fehl (Image gelöscht/nicht gepusht), wird der Lauf + **fehlgeschlagen** mit `failed to pull image …` im Log — dann Image neu pushen. + +### 4. Job bearbeiten + +- In der **Name**-Spalte erscheint beim Hovern ein **Stift**-Symbol → öffnet den + Bearbeiten-Dialog. Dort lassen sich **Name, Beschreibung, Ziel-Index, Image, + Befehl und Env** ändern (gleiche Validierung wie beim Anlegen). +- Das **Kalender**-Symbol in der Aktionsspalte öffnet den **Zeitplan**-Dialog: + Cron-Ausdruck setzen (5 Felder) und Job aktiv/inaktiv schalten. Ein Zeitplan + macht aus einem manuellen Job einen automatisch laufenden. +- Bearbeiten ist gesperrt, solange ein Lauf des Jobs läuft. + +### 5. Job löschen + +Das **Papierkorb**-Symbol entfernt die Job-Definition. Das Image in Nexus bleibt +davon unberührt (siehe unten zum Image-Löschen). + One Docker image per job script. Each image installs only its own dependencies and bakes its script as the `ENTRYPOINT`. Most jobs then run with no `command` override — the job definition just points `image` at the matching tag. Where several jobs share one script (the demos), they point at the same image and differ only by their `command`. - -This is deliberately different from the single shared-image model described in -[background-jobs/README.md](../../../background-jobs/README.md): here every script -is self-contained, at the cost of maintaining one Dockerfile per script. +here every script ## Images @@ -45,14 +109,20 @@ Each job's Dockerfile header lists its own build command. ## Running locally without pushing -The backend tries to pull each image before a run. If the image isn't in the -registry, the pull fails softly and the local copy is used — so building locally -is enough for local runs. To skip the pull attempt entirely: +Before each run the backend pulls the job's image from the registry when it is a +registry image (host `docker.nes.uni-due.de`). **There is no fallback to a local +copy:** if the pull fails, the run is marked _failed_ and the error is written to +the run log — a stale local image is never used silently. To run a locally built +image without pushing it, skip the pull attempt entirely: ```bash export BACKGROUND_JOBS_PULL_BEFORE_RUN=false ``` +With the pull disabled the backend uses whatever image with that tag exists on +the Docker host, so `docker build -t docker.nes.uni-due.de/inse/jobs/:latest .` +is enough for local runs. + ## Env vars Because every tag lives under the `docker.nes.uni-due.de` registry host, the -- 2.56.1 From 02b498f82998820a2272d47c9e7f5084c88b5371 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Fri, 24 Jul 2026 15:34:03 +0200 Subject: [PATCH 59/60] fix(jobs): write a clear system log message when a run fails to pull or start --- service/src/main/inse/background_jobs/runner.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/service/src/main/inse/background_jobs/runner.py b/service/src/main/inse/background_jobs/runner.py index 288b9fb8..8e964f5e 100644 --- a/service/src/main/inse/background_jobs/runner.py +++ b/service/src/main/inse/background_jobs/runner.py @@ -180,7 +180,7 @@ def start_run( if not image: run.status = JobRunStatus.FAILED run.finished_at = utcnow() - run.logs = "No image configured for this job." + run.logs = "[system] No image configured for this job." session.add(run) session.commit() session.refresh(run) @@ -192,7 +192,10 @@ def start_run( except Exception as error: # noqa: BLE001 run.status = JobRunStatus.FAILED run.finished_at = utcnow() - run.logs = f"failed to pull image '{image}': {error}" + run.logs = ( + f"[system] Failed to pull image '{image}' from the registry.\n" + f"[system] {error}" + ) session.add(run) session.commit() session.refresh(run) @@ -211,7 +214,10 @@ def start_run( except Exception as error: # noqa: BLE001 run.status = JobRunStatus.FAILED run.finished_at = utcnow() - run.logs = f"failed to start container: {error}" + run.logs = ( + f"[system] Failed to start the container for image '{image}'.\n" + f"[system] {error}" + ) session.add(run) session.commit() -- 2.56.1 From e5283543a1f6c0dfd479a1e19b1bd24d707cb28e Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Sat, 25 Jul 2026 13:48:57 +0200 Subject: [PATCH 60/60] feat(news): store matched OpenAlex topics in 'aktuell_openalex_topics' index --- service/scripts/jobs-image/README.md | 10 +- .../scripts/jobs-image/news-topics/Dockerfile | 6 +- service/scripts/news/topic_mapper/README.md | 7 +- service/src/main/inse/news/logic.py | 99 +++++++++++-------- 4 files changed, 68 insertions(+), 54 deletions(-) diff --git a/service/scripts/jobs-image/README.md b/service/scripts/jobs-image/README.md index e3cb74e3..dfe8da7e 100644 --- a/service/scripts/jobs-image/README.md +++ b/service/scripts/jobs-image/README.md @@ -72,7 +72,6 @@ and bakes its script as the `ENTRYPOINT`. Most jobs then run with no `command` override — the job definition just points `image` at the matching tag. Where several jobs share one script (the demos), they point at the same image and differ only by their `command`. -here every script ## Images @@ -81,7 +80,7 @@ here every script | News-Crawler | `jobs/news-crawl` | `run_pipeline.py` | scrapy<2.13, Twisted<24.7; uploads to `NEWS_UPLOAD_INDEX` | | Bund-Crawler | `jobs/bund-crawl` | `gpc.data.py --max-rows 200` | headless Chrome; uploads to `BUND_UPLOAD_INDEX`; capped, full export is ~300k rows | | Project-Topic-Mapping | `jobs/project-topics` | `map_project_topics --output-index docker-job_test` | reads projects_bund_v1; needs host backend | -| News-Topic-Mapping | `jobs/news-topics` | `map_news_topics --output-index docker-job_test` | bundles both topic_mapper pkgs; needs host backend | +| News-Topic-Mapping | `jobs/news-topics` | `map_news_topics --output-index aktuell_openalex_topics` | bundles both topic_mapper pkgs; needs host backend | | News-Keyword-Extraction | `jobs/news-keywords` | `sync.py --update-keywords --target-index docker-job_test` | ES + LLM creds; writes to test index | | Demo-Job A / B / C | `jobs/demo` | `demo.py` (seconds via command: `20` / `25` / `30`) | no dependencies; one image, three job rows | @@ -105,7 +104,7 @@ docker build -f service/scripts/jobs-image/news-crawl/Dockerfile \ docker push docker.nes.uni-due.de/inse/jobs/news-crawl:latest ``` -Each job's Dockerfile header lists its own build command. +Each image's Dockerfile header lists its own build command. ## Running locally without pushing @@ -129,9 +128,10 @@ Because every tag lives under the `docker.nes.uni-due.de` registry host, the backend treats these as registry images and injects the INSE Elasticsearch / LLM credentials automatically (plus any per-job `env`). -No image writes to a production index by default: the crawlers upload into the +Most images write to the test index by default: the crawlers upload into the index named by `NEWS_UPLOAD_INDEX` / `BUND_UPLOAD_INDEX` (both baked to -`docker-job_test` in their Dockerfile), and the mappers and the keyword +`docker-job_test` in their Dockerfile), and the project mapper and the keyword extraction write to `docker-job_test` via `--output-index` / `--target-index`. +The exception is News-Topic-Mapping, which writes to `aktuell_openalex_topics`. To not contact Elasticsearch at all, pass `--skip-upload` (crawlers) or `--dry-run` (mappers) through the job's command field. diff --git a/service/scripts/jobs-image/news-topics/Dockerfile b/service/scripts/jobs-image/news-topics/Dockerfile index 0c14852e..916a9d82 100644 --- a/service/scripts/jobs-image/news-topics/Dockerfile +++ b/service/scripts/jobs-image/news-topics/Dockerfile @@ -15,10 +15,10 @@ RUN pip install --no-cache-dir -r requirements.txt COPY service/scripts/news/topic_mapper/ ./service/scripts/news/topic_mapper/ COPY service/scripts/projects/topic_mapper/ ./service/scripts/projects/topic_mapper/ -# Writes topic mappings into docker-job_test. Only maps (article, keyword) pairs -# not already present in the output index; pass --overwrite to re-map all. +# Writes topic mappings into aktuell_openalex_topics. Only maps (article, keyword) +# pairs not already present in the output index; pass --overwrite to re-map all. # Uncapped: limit a run by passing --max-docs N through the job's command field. # host.docker.internal reaches the host backend for vector search. ENTRYPOINT ["python", "-m", "service.scripts.news.topic_mapper.map_news_topics", \ - "--output-index", "docker-job_test", \ + "--output-index", "aktuell_openalex_topics", \ "--api-base-url", "http://host.docker.internal:8000"] diff --git a/service/scripts/news/topic_mapper/README.md b/service/scripts/news/topic_mapper/README.md index 213df178..048058ec 100644 --- a/service/scripts/news/topic_mapper/README.md +++ b/service/scripts/news/topic_mapper/README.md @@ -74,6 +74,7 @@ run retries them. ## As a background job -Registered in `background-jobs/entrypoint.sh` as `news-topics`, writing into -the test index `docker-job_test` and capped at a few articles. Both are -overridable via `NEWS_TOPICS_OUTPUT_INDEX` and `NEWS_TOPICS_MAX_DOCS`. +Packaged as the `news-topics` registry image (see +`service/scripts/jobs-image/news-topics/Dockerfile`), writing into +`aktuell_openalex_topics`. The run is uncapped; limit a run by passing +`--max-docs N` through the job's command field. diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index 42eedb57..edb9197f 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -17,11 +17,14 @@ from .model import MatchedTopic, MentionedPerson, NewsArticle, NewsArticleDetail logger = logging.getLogger(__name__) -TOPIC_LIMIT = 4 -TOPIC_QUERY_CONTENT_CHARS = 300 TOPIC_NUM_CANDIDATES = 100 TOPIC_SIMILARITY = 0.5 +TOPICS_INDEX = "aktuell_openalex_topics" +TOPICS_INDEX_MAX_PAIRS = 100 + +_SESSION_TOPIC_CACHE: dict[str, list] = {} + KEYWORD_LIMIT = 6 KEYWORD_CONTENT_CHARS = 4000 KEYWORD_SYSTEM_PROMPT = """\ @@ -251,9 +254,7 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail: source = response.get("_source", {}) - relevant, authors, cached_keywords, cached_topics, postproc_id = await _get_postproc_labels( - news_id - ) + relevant, authors, cached_keywords, postproc_id = await _get_postproc_labels(news_id) keywords, postproc_id = await _get_article_keywords( news_id, postproc_id, @@ -261,7 +262,7 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail: source.get("maintitle"), source.get("full_content"), ) - topics = await _get_article_topics(news_id, postproc_id, cached_topics, keywords) + topics = await _get_article_topics(news_id, keywords) return NewsArticleDetail( id=response.get("_id"), @@ -306,23 +307,58 @@ async def _get_article_keywords( return keywords, postproc_id -async def _get_article_topics( - news_id: str, - postproc_id: str | None, - cached_topics: list, - keywords: list, -) -> list: - if cached_topics: - return [MatchedTopic(**topic) for topic in cached_topics] +async def _get_article_topics(news_id: str, keywords: list) -> list: + indexed = await get_article_topics_from_index(news_id) + if indexed: + return indexed + + if news_id in _SESSION_TOPIC_CACHE: + return _SESSION_TOPIC_CACHE[news_id] topics = await _match_topics_for_keywords(keywords) if topics: - await _store_topics(news_id, postproc_id, topics) + _SESSION_TOPIC_CACHE[news_id] = topics return topics +async def get_article_topics_from_index(news_id: str) -> list: + try: + response = await elasticsearch.search( + index=TOPICS_INDEX, + query={"term": {"news_id.keyword": news_id}}, + source=["keyword", "topic_matches"], + size=TOPICS_INDEX_MAX_PAIRS, + cluster="inse", + ) + except Exception: + logger.exception(f"Topic-index lookup for {news_id} failed.") + return [] + + matched = [] + seen_ids = set() + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + keyword = source.get("keyword") + for match in source.get("topic_matches") or []: + topic_id = match.get("topic_id") + if not topic_id or topic_id in seen_ids: + continue + seen_ids.add(topic_id) + matched.append( + MatchedTopic( + id=topic_id, + display_name=match.get("topic_display_name"), + subfield_name=match.get("subfield"), + field_name=match.get("field"), + domain_name=match.get("domain"), + source_keyword=keyword, + ) + ) + return matched + + def _parse_keywords(raw: str) -> list: raw = (raw or "").strip() @@ -372,28 +408,6 @@ async def _store_keywords(news_id: str, postproc_id: str | None, keywords: list) return postproc_id -async def _store_topics(news_id: str, postproc_id: str | None, topics: list) -> None: - documents = [topic.model_dump() for topic in topics] - - try: - if postproc_id: - await elasticsearch.update( - index="aktuell_postproc", - doc_id=postproc_id, - doc={"topics": documents}, - cluster="inse", - ) - else: - await elasticsearch.index_doc( - index="aktuell_postproc", - doc_id=news_id, - document={"news_id": news_id, "topics": documents}, - cluster="inse", - ) - except Exception: - logger.exception(f"Failed to cache topics for {news_id}.") - - async def _match_topics_for_keywords(keywords: list) -> list: if not keywords: return [] @@ -475,31 +489,30 @@ async def _build_mentioned_persons(author_names: list) -> list: return ude_persons + other_persons -async def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, list, str | None]: +async def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, str | None]: try: response = await elasticsearch.search( index="aktuell_postproc", query={"term": {"news_id.keyword": news_id}}, - source=["relevant", "authors", "keywords", "topics"], + source=["relevant", "authors", "keywords"], size=1, cluster="inse", ) except Exception: logger.exception(f"Postproc-Lookup for {news_id} failed.") - return None, [], [], [], None + return None, [], [], None hits = response.get("hits", {}).get("hits", []) if not hits: - return None, [], [], [], None + return None, [], [], None hit = hits[0] postproc_source = hit.get("_source", {}) relevant = bool(postproc_source.get("relevant", 0)) authors = postproc_source.get("authors") or [] keywords = postproc_source.get("keywords") or [] - topics = postproc_source.get("topics") or [] - return relevant, authors, keywords, topics, hit.get("_id") + return relevant, authors, keywords, hit.get("_id") async def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict: -- 2.56.1