Skip to content

Commit

Permalink
chore(core): move to class impl
Browse files Browse the repository at this point in the history
  • Loading branch information
AgentEnder committed Dec 12, 2024
1 parent 93c4f22 commit 61b0965
Show file tree
Hide file tree
Showing 4 changed files with 157 additions and 105 deletions.
26 changes: 14 additions & 12 deletions packages/nx/src/daemon/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ import {
DaemonProjectGraphError,
ProjectGraphError,
} from '../../project-graph/error-types';
import * as ora from 'ora';
import { IS_WASM, NxWorkspaceFiles, TaskRun, TaskTarget } from '../../native';
import { HandleGlobMessage } from '../message-types/glob';
import {
Expand Down Expand Up @@ -78,6 +77,10 @@ import {
FLUSH_SYNC_GENERATOR_CHANGES_TO_DISK,
type HandleFlushSyncGeneratorChangesToDiskMessage,
} from '../message-types/flush-sync-generator-changes-to-disk';
import {
DelayedSpinner,
SHOULD_SHOW_SPINNERS,
} from '../../utils/delayed-spinner';

const DAEMON_ENV_SETTINGS = {
NX_PROJECT_GLOB_CACHE: 'false',
Expand Down Expand Up @@ -195,12 +198,16 @@ export class DaemonClient {
projectGraph: ProjectGraph;
sourceMaps: ConfigurationSourceMaps;
}> {
let spinner: ReturnType<typeof ora>, timeout: NodeJS.Timeout;
if (process.stdout.isTTY) {
let spinner: DelayedSpinner;
if (SHOULD_SHOW_SPINNERS) {
// If the graph takes a while to load, we want to show a spinner.
timeout = setTimeout(() => {
spinner = ora('Getting project graph from the Nx Daemon').start();
}, 500).unref();
spinner = new DelayedSpinner(
'Calculating the project graph on the Nx Daemon',
500
).scheduleMessageUpdate(
'Calculating the project graph on the Nx Daemon is taking longer than expected. Re-run with NX_DAEMON=false to see more details.',
30_000
);
}
try {
const response = await this.sendToDaemonViaQueue({
Expand All @@ -217,12 +224,7 @@ export class DaemonClient {
throw e;
}
} finally {
if (timeout) {
clearTimeout(timeout);
}
if (spinner) {
spinner.stop();
}
spinner?.cleanup();
}
}

Expand Down
111 changes: 49 additions & 62 deletions packages/nx/src/project-graph/build-project-graph.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import { workspaceRoot } from '../utils/workspace-root';
import { join } from 'path';
import { performance } from 'perf_hooks';
import * as ora from 'ora';
import type { Ora } from 'ora';
import { assertWorkspaceValidity } from '../utils/assert-workspace-validity';
import { FileData } from './file-utils';
import {
Expand Down Expand Up @@ -46,7 +44,7 @@ import {
ConfigurationSourceMaps,
mergeMetadata,
} from './utils/project-configuration-utils';
import { isOnDaemon } from '../daemon/is-on-daemon';
import { DelayedSpinner, SHOULD_SHOW_SPINNERS } from '../utils/delayed-spinner';

let storedFileMap: FileMap | null = null;
let storedAllWorkspaceFiles: FileData[] | null = null;
Expand Down Expand Up @@ -317,28 +315,31 @@ async function updateProjectGraphWithPlugins(
);
performance.mark('createDependencies:start');

let spinner: Ora,
timeout: NodeJS.Timeout,
spinnerUpdateInterval: NodeJS.Timeout;
let spinner: DelayedSpinner;
const inProgressPlugins = new Set<string>();

if (!isOnDaemon() && process.stdout.isTTY) {
timeout = setTimeout(() => {
spinner = ora(
'Waiting on dependency information from ' +
(inProgressPlugins.size > 1
? `${inProgressPlugins.size} plugins`
: inProgressPlugins.keys()[0])
).start();

spinnerUpdateInterval = setInterval(() => {
spinner.text =
'Waiting on dependency information from ' +
(inProgressPlugins.size > 1
? `${inProgressPlugins.size} plugins`
: inProgressPlugins.keys()[0]);
}, 50);
}, 500).unref();
function updateSpinner() {
if (!spinner) {
return;
}
if (inProgressPlugins.size === 1) {
return `Creating project graph dependencies with ${
inProgressPlugins.keys()[0]
}`;
} else if (process.env.NX_VERBOSE_LOGGING === 'true') {
return [
`Creating project graph dependencies with ${inProgressPlugins.size} plugins`,
...Array.from(inProgressPlugins).map((p) => ` - ${p}`),
].join('\n');
} else {
return `Creating project graph dependencies with ${inProgressPlugins.size} plugins`;
}
}

if (SHOULD_SHOW_SPINNERS) {
spinner = new DelayedSpinner(
`Creating project graph dependencies with ${plugins.length} plugins`
);
}

await Promise.all(
Expand All @@ -352,6 +353,7 @@ async function updateProjectGraphWithPlugins(
})
.finally(() => {
inProgressPlugins.delete(plugin.name);
updateSpinner();
});

for (const dep of dependencies) {
Expand Down Expand Up @@ -384,16 +386,7 @@ async function updateProjectGraphWithPlugins(
`createDependencies:start`,
`createDependencies:end`
);

if (timeout) {
clearTimeout(timeout);
}
if (spinnerUpdateInterval) {
clearInterval(spinnerUpdateInterval);
}
if (spinner) {
spinner.stop();
}
spinner?.cleanup();

const graphWithDeps = builder.getUpdatedProjectGraph();

Expand Down Expand Up @@ -438,28 +431,29 @@ export async function applyProjectMetadata(
const errors: CreateMetadataError[] = [];

performance.mark('createMetadata:start');
let timeout: NodeJS.Timeout,
spinner: Ora,
spinnerUpdateInterval: NodeJS.Timeout;
let spinner: DelayedSpinner;
const inProgressPlugins = new Set<string>();

if (!isOnDaemon() && process.stdout.isTTY) {
timeout = setTimeout(() => {
spinner = ora(
'Waiting on project metadata from ' +
(inProgressPlugins.size > 1
? `${inProgressPlugins.size} plugins`
: inProgressPlugins.keys()[0])
).start();

spinnerUpdateInterval = setInterval(() => {
spinner.text =
'Waiting on project metadata from ' +
(inProgressPlugins.size > 1
? `${inProgressPlugins.size} plugins`
: inProgressPlugins.keys()[0]);
}, 50);
}, 500).unref();
function updateSpinner() {
if (!spinner) {
return;
}
if (inProgressPlugins.size === 1) {
return `Creating project metadata with ${inProgressPlugins.keys()[0]}`;
} else if (process.env.NX_VERBOSE_LOGGING === 'true') {
return [
`Creating project metadata with ${inProgressPlugins.size} plugins`,
...Array.from(inProgressPlugins).map((p) => ` - ${p}`),
].join('\n');
} else {
return `Creating project metadata with ${inProgressPlugins.size} plugins`;
}
}

if (SHOULD_SHOW_SPINNERS) {
spinner = new DelayedSpinner(
`Creating project metadata with ${plugins.length} plugins`
);
}

const promises = plugins.map(async (plugin) => {
Expand All @@ -473,6 +467,7 @@ export async function applyProjectMetadata(
errors.push(new CreateMetadataError(e, plugin.name));
} finally {
inProgressPlugins.delete(plugin.name);
updateSpinner();
performance.mark(`${plugin.name}:createMetadata - end`);
performance.measure(
`${plugin.name}:createMetadata`,
Expand All @@ -485,15 +480,7 @@ export async function applyProjectMetadata(

await Promise.all(promises);

if (timeout) {
clearTimeout(timeout);
}
if (spinnerUpdateInterval) {
clearInterval(spinnerUpdateInterval);
}
if (spinner) {
spinner.stop();
}
spinner?.cleanup();

for (const { metadata: projectsMetadata, pluginName } of results) {
for (const project in projectsMetadata) {
Expand Down
60 changes: 29 additions & 31 deletions packages/nx/src/project-graph/utils/project-configuration-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ import { workspaceRoot } from '../../utils/workspace-root';
import { minimatch } from 'minimatch';
import { join } from 'path';
import { performance } from 'perf_hooks';
import * as ora from 'ora';
import type { Ora } from 'ora';

import { LoadedNxPlugin } from '../plugins/internal-api';
import {
Expand All @@ -34,6 +32,10 @@ import {
import { CreateNodesResult } from '../plugins/public-api';
import { isGlobPattern } from '../../utils/globs';
import { isOnDaemon } from '../../daemon/is-on-daemon';
import {
DelayedSpinner,
SHOULD_SHOW_SPINNERS,
} from '../../utils/delayed-spinner';

export type SourceInformation = [file: string | null, plugin: string];
export type ConfigurationSourceMaps = Record<
Expand Down Expand Up @@ -328,27 +330,30 @@ export async function createProjectConfigurations(
): Promise<ConfigurationResult> {
performance.mark('build-project-configs:start');

let spinner: Ora,
timeout: NodeJS.Timeout,
spinnerUpdateInterval: NodeJS.Timeout;
let spinner: DelayedSpinner;
const inProgressPlugins = new Set<string>();
if (!isOnDaemon() && process.stdout.isTTY) {
timeout = setTimeout(() => {
spinner = ora(
'Waiting on project information from ' +
(inProgressPlugins.size > 1
? `${inProgressPlugins.size} plugins`
: inProgressPlugins.values().next().value)
).start();

spinnerUpdateInterval = setInterval(() => {
spinner.text =
'Waiting on project information from ' +
(inProgressPlugins.size > 1
? `${inProgressPlugins.size} plugins`
: inProgressPlugins.values().next().value);
}, 50);
}, 500).unref();

function updateSpinner() {
if (!spinner) {
return;
}

if (inProgressPlugins.size === 1) {
return `Creating project graph nodes with ${inProgressPlugins.keys()[0]}`;
} else if (process.env.NX_VERBOSE_LOGGING === 'true') {
return [
`Creating project graph nodes with ${inProgressPlugins.size} plugins`,
...Array.from(inProgressPlugins).map((p) => ` - ${p}`),
].join('\n');
} else {
return `Creating project graph nodes with ${inProgressPlugins.size} plugins`;
}
}

if (SHOULD_SHOW_SPINNERS) {
spinner = new DelayedSpinner(
`Creating project graph nodes with ${plugins.length} plugins`
);
}

const results: Array<ReturnType<LoadedNxPlugin['createNodes'][1]>> = [];
Expand Down Expand Up @@ -419,21 +424,14 @@ export async function createProjectConfigurations(
})
.finally(() => {
inProgressPlugins.delete(pluginName);
updateSpinner();
});

results.push(r);
}

return Promise.all(results).then((results) => {
if (timeout) {
clearTimeout(timeout);
}
if (spinner) {
spinner.stop();
}
if (spinnerUpdateInterval) {
clearInterval(spinnerUpdateInterval);
}
spinner?.cleanup();

const { projectRootMap, externalNodes, rootMap, configurationSourceMaps } =
mergeCreateNodesResults(results, nxJson, errors);
Expand Down
65 changes: 65 additions & 0 deletions packages/nx/src/utils/delayed-spinner.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import * as ora from 'ora';

/**
* A class that allows to delay the creation of a spinner, as well
* as schedule updates to the message of the spinner. Useful for
* scenarios where one wants to only show a spinner if an operation
* takes longer than a certain amount of time.
*/
export class DelayedSpinner {
spinner: ora.Ora;
timeouts: NodeJS.Timeout[] = [];
initial: number = Date.now();

/**
* Constructs a new {@link DelayedSpinner} instance.
*
* @param message The message to display in the spinner
* @param ms The number of milliseconds to wait before creating the spinner
*/
constructor(message: string, ms: number = 500) {
this.timeouts.push(
setTimeout(() => {
this.spinner = ora(message);
}, ms).unref()
);
}

/**
* Sets the message to display in the spinner.
*
* @param message The message to display in the spinner
* @returns The {@link DelayedSpinner} instance
*/
setMessage(message: string) {
this.spinner.text = message;
return this;
}

/**
* Schedules an update to the message of the spinner. Useful for
* changing the message after a certain amount of time has passed.
*
* @param message The message to display in the spinner
* @param delay How long to wait before updating the message
* @returns The {@link DelayedSpinner} instance
*/
scheduleMessageUpdate(message: string, delay: number) {
this.timeouts.push(
setTimeout(() => {
this.spinner.text = message;
}, delay).unref()
);
return this;
}

/**
* Stops the spinner and cleans up any scheduled timeouts.
*/
cleanup() {
this.spinner.stop();
this.timeouts.forEach((t) => clearTimeout(t));
}
}

export const SHOULD_SHOW_SPINNERS = process.stdout.isTTY;

0 comments on commit 61b0965

Please sign in to comment.