Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NAS-114805 / 22.12 / NAS-114805: Refactoring scheduler component #6440

Merged
merged 14 commits into from
Mar 2, 2022
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const { pathsToModuleNameMapper } = require('ts-jest/utils');
const { compilerOptions } = require('./tsconfig');

require('jest-preset-angular/ngcc-jest-processor');
process.env.TZ = 'UTC';

module.exports = {
preset: 'jest-preset-angular',
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@
"chartist": "~0.11.4",
"core-js": "~3.6.4",
"cron-parser": "~4.2.1",
"croner": "~4.1.97",
"cronstrue": "~1.113.0",
"d3": "~5.16.0",
"d3-transition": "~1.2.0",
Expand Down
2 changes: 2 additions & 0 deletions src/app/interfaces/schedule.interface.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
export interface Schedule {
// TODO: Check question marks
minute?: string;
hour?: string;
dom?: string;
month?: string;
dow?: string;
// TODO: May not belong here.
begin?: string;
end?: string;
}
Original file line number Diff line number Diff line change
@@ -1,33 +1,34 @@
import { Overlay } from '@angular/cdk/overlay';
import {
Component, OnInit, ViewChild, ElementRef, Renderer2,
ChangeDetectorRef, AfterViewInit, AfterViewChecked,
AfterViewChecked,
AfterViewInit,
ChangeDetectorRef,
Component,
ElementRef,
OnInit,
Renderer2,
ViewChild,
} from '@angular/core';
import { FormGroup, FormControl, AbstractControl } from '@angular/forms';
import { AbstractControl, FormControl, FormGroup } from '@angular/forms';
import { MatMonthView } from '@angular/material/datepicker';
import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy';
import { Store } from '@ngrx/store';
import { TranslateService } from '@ngx-translate/core';
import { CronDate } from 'cron-parser';
import * as parser from 'cron-parser';
import { CronDate } from 'cron-parser';
import { CronExpression } from 'cron-parser/types';
import * as dateFns from 'date-fns';
import * as dateFnsTz from 'date-fns-tz';
import globalHelptext from 'app/helptext/global-helptext';
import { FormSchedulerConfig } from 'app/modules/entity/entity-form/models/field-config.interface';
import { Field } from 'app/modules/entity/entity-form/models/field.interface';
import { EntityUtils } from 'app/modules/entity/utils';
import { CronPreset } from 'app/modules/scheduler/interfaces/cron-preset.interface';
import { LocaleService } from 'app/services/locale.service';
import { WebSocketService } from 'app/services/ws.service';
import { AppState } from 'app/store';
import { selectTimezone } from 'app/store/system-config/system-config.selectors';

interface CronPreset {
label: string;
value: string;
description?: string;
}

@UntilDestroy()
@Component({
selector: 'form-scheduler',
Expand Down Expand Up @@ -228,22 +229,6 @@ export class FormSchedulerComponent implements Field, OnInit, AfterViewInit, Aft
},
];

get textInput(): string {
return this._textInput;
}

set textInput(val: string) {
this._textInput = val;
}

get colorProxy(): string {
return this.group.value[this.config.name];
}

set colorProxy(val: string) {
this.group.controls[this.config.name].setValue(val);
}

private _preset: CronPreset;

get preset(): CronPreset {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ export interface FormRadioOption {
}

export interface FormSchedulerConfig<P = unknown> extends BaseFieldConfig<P> {
options?: string[];
options?: [startTime: string, endTime: string];
noMinutes?: boolean;
onChangeOption?(data: { event: Event }): void;
type: 'scheduler';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ export class IxInputComponent implements ControlValueAccessor {
}
this.formatted = formatted;
this.value = value;
this.cdr.markForCheck();
}

input(ixInput: HTMLInputElement): void {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { IxFormControlHarness } from 'app/modules/ix-forms/interfaces/ix-form-co
import { getErrorText } from '../../utils/harness.utils';

export interface IxSelectHarnessFilters extends SelectHarnessFilters {
label: string;
label?: string;
}

export class IxSelectHarness extends ComponentHarness implements IxFormControlHarness {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,14 @@ describe('JobsPanelComponent', () => {
it('loads jobs when adminUiInitialized is dispatched', () => {
spectator.inject(Store).dispatch(adminUiInitialized());

expect(websocket.call).toHaveBeenCalledWith('core.get_jobs');
expect(websocket.call).toHaveBeenCalledWith(
'core.get_jobs',
[[['state', '!=', JobState.Success]]],
);
expect(websocket.call).toHaveBeenCalledWith(
'core.get_jobs',
[[['state', '=', JobState.Success]], { limit: 30, order_by: ['-id'] }],
);
});

it('checks component header is present', () => {
Expand Down
15 changes: 12 additions & 3 deletions src/app/modules/jobs/store/job.effects.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { TranslateService } from '@ngx-translate/core';
import { of } from 'rxjs';
import { forkJoin, of } from 'rxjs';
import {
catchError, filter, map, switchMap,
} from 'rxjs/operators';
import { ApiEventMessage } from 'app/enums/api-event-message.enum';
import { JobState } from 'app/enums/job-state.enum';
import {
abortJobPressed, jobAdded, jobChanged, jobRemoved, jobsLoaded, jobsNotLoaded,
} from 'app/modules/jobs/store/job.actions';
Expand All @@ -18,8 +19,16 @@ export class JobEffects {
loadJobs$ = createEffect(() => this.actions$.pipe(
ofType(adminUiInitialized),
switchMap(() => {
return this.ws.call('core.get_jobs').pipe(
map((jobs) => jobsLoaded({ jobs })),
const getNotCompletedJobs$ = this.ws.call('core.get_jobs', [[['state', '!=', JobState.Success]]]);
const getCompletedJobs$ = this.ws.call('core.get_jobs', [[['state', '=', JobState.Success]], { order_by: ['-id'], limit: 30 }]);

return forkJoin([
getNotCompletedJobs$,
getCompletedJobs$,
]).pipe(
map(([notCompletedJobs, recentlyCompletedJobs]) => {
return jobsLoaded({ jobs: [...notCompletedJobs, ...recentlyCompletedJobs] });
}),
catchError((error) => {
console.error(error);
// TODO: See if it would make sense to parse middleware error.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import Cron from 'croner';
import {
addDays,
endOfMonth,
getDate, getMonth, isBefore, isWithinInterval,
setHours,
setMinutes,
subMinutes,
} from 'date-fns';
import { toDate, utcToZonedTime, zonedTimeToUtc } from 'date-fns-tz';

export interface CronSchedulerPreviewOptions {
crontab: string;
timezone: string;
startTime?: string;
endTime?: string;
}

export class CronSchedulePreview {
private readonly cron: Cron;
private readonly timezone: string;

constructor(private options: CronSchedulerPreviewOptions) {
this.timezone = this.options.timezone;
this.cron = new Cron(this.options.crontab, {
timezone: this.timezone,
});
}

/**
* Returns next {limit} dates from startDate to the end of month.
* startDate is specified in target timezone.
* Returned dates are in local time, but stored in UTC (ordinary JS way).
* @param startDate Starting date.
* @param limit
*/
listNextRunsInMonth(startDate: string, limit: number): Date[] {
const nextRuns: Date[] = [];
let previousDate: Date = this.getZonedStartDate(startDate);
const zonedEndDate = this.getZoneEndDate(startDate);

for (let i = 0; i < limit;) {
const exampleDate = this.cron.next(previousDate);
previousDate = exampleDate;

if (!exampleDate || !isBefore(exampleDate, zonedEndDate)) {
break;
}

if (!this.isWithinTimeConstrains(exampleDate)) {
continue;
}

nextRuns.push(exampleDate);
i = i + 1;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not have this in the for loop declaration? for (let i = 0; i < limit; i++)

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because there is a continue condition that doesn't actually need it.

}

return nextRuns;
}

getNextDaysInMonthWithRuns(startDate: string): Set<number> {
const monthDaysWithRuns = new Set<number>([]);

let previousDate = toDate(startDate, { timeZone: 'UTC' });
const startingMonth = getMonth(previousDate);

do {
const zonedPreviousDate = zonedTimeToUtc(previousDate, this.timezone);
const zonedNextRun = this.cron.next(subMinutes(zonedPreviousDate, 1));
const nextRun = utcToZonedTime(zonedNextRun, this.timezone);

if (!nextRun || getMonth(nextRun) !== startingMonth) {
break;
}

if (!this.isWithinTimeConstrains(nextRun)) {
previousDate = nextRun;
continue;
}

previousDate = addDays(previousDate, 1);

const dayNumber = getDate(nextRun);
monthDaysWithRuns.add(dayNumber);
} while (getMonth(previousDate) === startingMonth);

return monthDaysWithRuns;
}

private getZonedStartDate(forMonth: string): Date {
const zonedForMonth = toDate(forMonth, { timeZone: this.timezone });
return subMinutes(zonedForMonth, 1);
}

private getZoneEndDate(forMonth: string): Date {
const zonedForMonth = toDate(forMonth, { timeZone: 'UTC' });
const endDate = endOfMonth(zonedForMonth);
return zonedTimeToUtc(endDate, this.timezone);
}

private isWithinTimeConstrains(date: Date): boolean {
return true;
// TODO: Will be implemented later.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why later?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because I got tired :) It's an edge case feature that I will address in coming PRs soon.

if (!this.options.startTime || !this.options.endTime) {
return true;
}

const [startHour, startMinutes] = this.options.startTime.split(':');
const [endHour, endMinutes] = this.options.endTime.split(':');

const startDate = setMinutes(setHours(date, Number(startHour)), Number(startMinutes));
const endDate = setMinutes(setHours(date, Number(endHour)), Number(endMinutes));

return isWithinInterval(date, { start: startDate, end: endDate });
}
}
Loading