Skip to content

Commit

Permalink
refactor(core): migrate momentjs functionality to luxon + date-fns (s…
Browse files Browse the repository at this point in the history
  • Loading branch information
anotherchrisberry authored Feb 25, 2019
1 parent a73071b commit 3e75815
Show file tree
Hide file tree
Showing 26 changed files with 193 additions and 140 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as moment from 'moment';
import { cloneDeep, uniq } from 'lodash';
import { module, noop } from 'angular';
import { Duration } from 'luxon';

import { ApplicationReader } from 'core/application/service/ApplicationReader';
import { AccountService } from 'core/account/AccountService';
Expand Down Expand Up @@ -31,7 +31,7 @@ export class CacheInitializerService {

private setConfigDefaults(key: string, config: ICacheConfig) {
config.version = config.version || 1;
config.maxAge = config.maxAge || moment.duration(2, 'days').asMilliseconds();
config.maxAge = config.maxAge || Duration.fromObject({ days: 2 }).as('milliseconds');
config.initializers = config.initializers || this.initializers[key] || ([] as any[]);
config.onReset = config.onReset || [noop];
}
Expand Down
8 changes: 4 additions & 4 deletions app/scripts/modules/core/src/cache/deckCacheFactory.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Cache, CacheFactory, CacheOptions, ItemInfo } from 'cachefactory';
import * as moment from 'moment';
import { Duration } from 'luxon';

import { SETTINGS } from 'core/config/settings';

Expand Down Expand Up @@ -154,7 +154,7 @@ export class DeckCacheFactory {

private static getStats(cache: Cache): IStats {
const keys = cache.keys();
let ageMin = moment.now(),
let ageMin = Date.now(),
ageMax = 0;

keys.forEach((key: string) => {
Expand All @@ -178,8 +178,8 @@ export class DeckCacheFactory {
DeckCacheFactory.clearPreviousVersions(namespace, cacheId, currentVersion, cacheFactory);
cacheFactory.createCache(key, {
deleteOnExpire: 'aggressive',
maxAge: cacheConfig.maxAge || moment.duration(2, 'days').asMilliseconds(),
recycleFreq: moment.duration(5, 'seconds').asMilliseconds(),
maxAge: cacheConfig.maxAge || Duration.fromObject({ days: 2 }).as('milliseconds'),
recycleFreq: Duration.fromObject({ seconds: 5 }).as('milliseconds'),
storageImpl: new SelfClearingLocalStorage(this.cacheProxy),
storageMode: 'localStorage',
storagePrefix: DeckCacheFactory.getStoragePrefix(key, currentVersion),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as moment from 'moment';
import { Duration } from 'luxon';

export interface IMaxAgeConfig {
maxAge: number;
Expand Down Expand Up @@ -36,16 +36,16 @@ export const INFRASTRUCTURE_CACHE_CONFIG: IInfrastructureCacheConfig = {
version: 2,
},
applications: {
maxAge: moment.duration(30, 'days').asMilliseconds(), // it gets refreshed every time the user goes to the application list, anyway
maxAge: Duration.fromObject({ days: 30 }).as('milliseconds'), // it gets refreshed every time the user goes to the application list, anyway
},
loadBalancers: {
maxAge: moment.duration(1, 'hour').asMilliseconds(),
maxAge: Duration.fromObject({ hours: 1 }).as('milliseconds'),
},
securityGroups: {
version: 2, // increment to force refresh of cache on next page load - can be added to any cache
},
instanceTypes: {
maxAge: moment.duration(7, 'days').asMilliseconds(),
maxAge: Duration.fromObject({ days: 7 }).as('milliseconds'),
version: 2,
},
healthChecks: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ import * as React from 'react';

import { HoverablePopover } from 'core/presentation';
import { IEntityTags } from 'core/domain';

import * as moment from 'moment';
import { relativeTime } from 'core/utils/timeFormatters';

export interface IEphemeralPopoverProps {
entity?: any;
Expand Down Expand Up @@ -36,7 +35,7 @@ export class EphemeralPopover extends React.Component<IEphemeralPopoverProps, IE
private PopoverContent = () => {
const { ttl } = this.state;
const isInPast = !!ttl && Date.now() > ttl;
const ttlPhrase = moment(ttl).fromNow();
const ttlPhrase = relativeTime(ttl);

return (
<div>
Expand Down
4 changes: 2 additions & 2 deletions app/scripts/modules/core/src/history/recentHistory.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { module } from 'angular';
import * as moment from 'moment';
import { Duration } from 'luxon';
import { omit, omitBy, isUndefined, sortBy, find } from 'lodash';

import { UUIDGenerator } from 'core/utils/uuid.service';
Expand Down Expand Up @@ -27,7 +27,7 @@ const MAX_ITEMS = 5;
export class RecentHistoryService {
private static cache: ICache = DeckCacheFactory.createCache('history', 'user', {
version: 3,
maxAge: moment.duration(90, 'days').asMilliseconds(),
maxAge: Duration.fromObject({ days: 90 }).as('milliseconds'),
});

public static getItems(type: any): IRecentHistoryEntry[] {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { duration } from 'moment';
import { distanceInWords } from 'date-fns';
import { $log } from 'ngimport';

import { IOrchestratedItem, IOrchestratedItemVariable, ITask, ITaskStep } from 'core/domain';
Expand Down Expand Up @@ -87,7 +87,11 @@ export class OrchestratedItemTransformer {
},
},
runningTime: {
get: () => duration(this.calculateRunningTime(item)()).humanize(),
get: () => {
const now = Date.now();
const start = new Date(now - this.calculateRunningTime(item)());
return distanceInWords(start, now, { includeSeconds: true });
},
configurable: true,
},
runningTimeInMs: {
Expand Down
17 changes: 9 additions & 8 deletions app/scripts/modules/core/src/pagerDuty/Pager.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { UISref } from '@uirouter/react';
import SearchApi from 'js-worker-search';
import { groupBy } from 'lodash';
import { Debounce } from 'lodash-decorators';
import * as moment from 'moment';
import { DateTime } from 'luxon';
import { Observable } from 'rxjs';
import {
AutoSizer,
Expand All @@ -20,6 +20,7 @@ import {
} from 'react-virtualized';

import { ApplicationReader, IApplicationSummary } from 'core/application';
import { relativeTime } from 'core/utils/timeFormatters';
import { IOnCall, IPagerDutyService, PagerDutyReader } from './pagerDuty.read.service';
import { ReactInjector } from 'core/reactShims';
import { SETTINGS } from 'core/config';
Expand All @@ -40,7 +41,7 @@ export interface IUserList {
export interface IOnCallsByService {
users?: IUserList;
applications: IApplicationSummary[];
last: moment.Moment;
last: DateTime;
service: IPagerDutyService;
searchString: string;
}
Expand Down Expand Up @@ -125,13 +126,13 @@ export class Pager extends React.Component<IPagerProps, IPagerState> {
return a.service.name.localeCompare(b.service.name);
}
if (sortBy === 'last') {
if (!a.last.isValid()) {
if (!a.last.isValid) {
return 1;
}
if (!b.last.isValid()) {
if (!b.last.isValid) {
return -1;
}
return a.last.isBefore(b.last) ? 1 : a.last.isAfter(b.last) ? -1 : 0;
return a.last.toMillis() < b.last.toMillis() ? 1 : a.last.toMillis() > b.last.toMillis() ? -1 : 0;
}
return 0;
}
Expand Down Expand Up @@ -256,7 +257,7 @@ export class Pager extends React.Component<IPagerProps, IPagerState> {
users,
applications: associatedApplications,
service,
last: moment((service as any).lastIncidentTimestamp),
last: DateTime.fromISO((service as any).lastIncidentTimestamp),
searchString: searchTokens.join(' '),
};
if (onCallsByService.service.integration_key) {
Expand Down Expand Up @@ -300,8 +301,8 @@ export class Pager extends React.Component<IPagerProps, IPagerState> {
};

private lastIncidentRenderer = (data: TableCellProps): React.ReactNode => {
const time: moment.Moment = data.cellData;
return <div style={paddingStyle}>{time.isValid() ? time.fromNow() : 'Never'}</div>;
const time: DateTime = data.cellData;
return <div style={paddingStyle}>{time.isValid ? relativeTime(time.toMillis()) : 'Never'}</div>;
};

private applicationRenderer = (data: TableCellProps): React.ReactNode => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';

import moment from 'moment';
import { Duration } from 'luxon';
import _ from 'lodash';

import { CloudProviderRegistry } from 'core/cloudProvider';
Expand Down Expand Up @@ -129,7 +129,8 @@ module.exports = angular
$scope.showWaitingMessage = true;
$scope.waitingForUpInstances = activeWaitTask.status === 'RUNNING';
const lastCapacity = stage.context.lastCapacityCheck;
const waitDurationExceeded = activeWaitTask.runningTimeInMs > moment.duration(5, 'minutes').asMilliseconds();
const waitDurationExceeded =
activeWaitTask.runningTimeInMs > Duration.fromObject({ minutes: 5 }).as('milliseconds');
lastCapacity.total =
lastCapacity.up +
lastCapacity.down +
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { IController, module } from 'angular';
import * as momentTimezone from 'moment-timezone';
import { has } from 'lodash';
import { Subject } from 'rxjs';

import { SETTINGS } from 'core/config/settings';
import { DateTime, Duration } from 'luxon';

interface IExecutionWindow {
displayStart: Date;
Expand Down Expand Up @@ -258,27 +258,29 @@ class ExecutionWindowAtlasGraphController implements IController {
}

private createWindow(window: IExecutionWindow, dayOffset: number): IWindowData {
const today = new Date();
const zone: string = SETTINGS.defaultTimeZone;

const start = momentTimezone
.tz(today, zone)
.hour(window.displayStart.getHours())
.minute(window.displayStart.getMinutes())
.seconds(window.displayStart.getSeconds())
.milliseconds(window.displayStart.getMilliseconds())
.subtract(dayOffset, 'days')
.toDate()
.getTime(),
end = momentTimezone
.tz(today, zone)
.hour(window.displayEnd.getHours())
.minute(window.displayEnd.getMinutes())
.seconds(window.displayEnd.getSeconds())
.milliseconds(window.displayEnd.getMilliseconds())
.subtract(dayOffset, 'days')
.toDate()
.getTime();
const { displayEnd, displayStart } = window;

const start = DateTime.local()
.setZone(zone)
.set({
hour: displayStart.getHours(),
minute: displayStart.getMinutes(),
second: displayStart.getSeconds(),
millisecond: displayStart.getMilliseconds(),
})
.minus(Duration.fromObject({ days: dayOffset }))
.toMillis(),
end = DateTime.local()
.setZone(zone)
.set({
hour: displayEnd.getHours(),
minute: displayEnd.getMinutes(),
second: displayEnd.getSeconds(),
millisecond: displayEnd.getMilliseconds(),
})
.minus(Duration.fromObject({ days: dayOffset }))
.toMillis();

return { start, end };
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { IController, IScope, module } from 'angular';
import { IModalService } from 'angular-ui-bootstrap';
import * as moment from 'moment';

import { Registry } from 'core/registry';
import { SETTINGS } from 'core/config/settings';
import { IgorService, BuildServiceType } from 'core/ci/igor.service';
import { IJobConfig, IParameterDefinitionList, IStage } from 'core/domain';
import { TravisExecutionLabel } from './TravisExecutionLabel';
import { Duration } from 'luxon';

export interface ITravisStageViewState {
mastersLoaded: boolean;
Expand Down Expand Up @@ -175,7 +175,7 @@ module(TRAVIS_STAGE, [])
const lines = stage.masterStage.context.buildInfo.number ? 1 : 0;
return lines + (stage.masterStage.context.buildInfo.testResults || []).length;
},
defaultTimeoutMs: moment.duration(2, 'hours').asMilliseconds(),
defaultTimeoutMs: Duration.fromObject({ hours: 2 }).as('milliseconds'),
validators: [{ type: 'requiredField', fieldName: 'job' }],
strategy: true,
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { IController, IScope, module } from 'angular';
import { IModalService } from 'angular-ui-bootstrap';
import * as moment from 'moment';

import { Registry } from 'core/registry';
import { IgorService, BuildServiceType } from 'core/ci/igor.service';
import { IJobConfig, IParameterDefinitionList, IStage } from 'core/domain';
import { SETTINGS } from 'core/config/settings';
import { WerckerExecutionLabel } from './WerckerExecutionLabel';
import { Duration } from 'luxon';

export interface IWerckerStageViewState {
mastersLoaded: boolean;
Expand Down Expand Up @@ -226,7 +226,7 @@ module(WERCKER_STAGE, [])
const lines = stage.masterStage.context.buildInfo.number ? 1 : 0;
return lines + (stage.masterStage.context.buildInfo.testResults || []).length;
},
defaultTimeoutMs: moment.duration(2, 'hours').asMilliseconds(),
defaultTimeoutMs: Duration.fromObject({ hours: 2 }).as('milliseconds'),
validators: [{ type: 'requiredField', fieldName: 'job' }],
strategy: true,
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { chain, compact, find, flattenDeep, forOwn, get, groupBy, includes, uniq } from 'lodash';
import { Debounce } from 'lodash-decorators';
import { Subject } from 'rxjs';
import * as moment from 'moment';
import { $log } from 'ngimport';
import { DateTime, Duration } from 'luxon';

import { Application } from 'core/application/application.model';
import { IExecution, IExecutionGroup, IPipeline } from 'core/domain';
Expand All @@ -11,25 +11,51 @@ import { FilterModelService, ISortFilter } from 'core/filterModel';
import { Registry } from 'core/registry';

const boundaries = [
{ name: 'Today', after: () => moment().startOf('day') },
{
name: 'Today',
after: () =>
DateTime.local()
.startOf('day')
.toMillis(),
},
{
name: 'Yesterday',
after: () =>
moment()
DateTime.local()
.startOf('day')
.subtract(1, 'days'),
.minus(Duration.fromObject({ days: 1 }))
.toMillis(),
},
{
name: 'This Week',
after: () =>
DateTime.local()
.startOf('week')
.toMillis(),
},
{ name: 'This Week', after: () => moment().startOf('week') },
{
name: 'Last Week',
after: () =>
moment()
DateTime.local()
.startOf('week')
.subtract(1, 'weeks'),
.minus(Duration.fromObject({ weeks: 1 }))
.toMillis(),
},
{
name: 'Last Month',
after: () =>
DateTime.local()
.startOf('month')
.toMillis(),
},
{
name: 'This Year',
after: () =>
DateTime.local()
.startOf('year')
.toMillis(),
},
{ name: 'Last Month', after: () => moment().startOf('month') },
{ name: 'This Year', after: () => moment().startOf('year') },
{ name: 'Prior Years', after: () => moment(0) },
{ name: 'Prior Years', after: () => 0 },
];

export class ExecutionFilterService {
Expand All @@ -43,9 +69,10 @@ export class ExecutionFilterService {
return groupBy(
executions,
execution =>
boundaries.find(boundary =>
// executions that were cancelled before ever starting will not have a startTime, just a buildTime
moment(execution.startTime || execution.buildTime).isAfter(boundary.after()),
boundaries.find(
boundary =>
// executions that were cancelled before ever starting will not have a startTime, just a buildTime
(execution.startTime || execution.buildTime) > boundary.after(),
).name,
);
}
Expand Down
Loading

0 comments on commit 3e75815

Please sign in to comment.